text
stringlengths
20
1.01M
url
stringlengths
14
1.25k
dump
stringlengths
9
15
lang
stringclasses
4 values
source
stringclasses
4 values
You have learned how to run an image classification model on ARM microcontroller and the basics of the CMSIS-NN framework. This post shows how you may train and deploy a new model from scratch. Keras was my favorite when came to picking a deep learning framework since its simplicity and elegance, however this time we are going with Caffe as the ARM's team has released two useful scripts to generate the code for us which was built for Caffe models. No worry if you are new to Caffe like me. The model structure and training parameters are all defined in easy to understand text file format. Caffe installation can be challenging especially for beginners, that's why I build this runnable Google Colab notebook with Caffe installation and code of the tutorial included. The Caffe image classification model is defined in file cifar10_m4_train_test_small.prototxt, with its model structure graph shown below. It contains three convolutional layers interspersed by ReLU activation and max-pooling layers, followed by a fully-connected layer at the end to generate classification result into one of the ten output classes. In the cifar10_m4_train_test_small.prototxt model definition file, data label lr_mults InnerProduct layer { // ...layer definition... include: { phase: TRAIN } } In the above example, this layer will be included only TRAIN Finally running the script train_small_colab.sh will start the training, when it's finished the weights will be saved. In our case, the script runs two solver files, the learning rate is reduced by a factor of 10 for the last 1000 training iterations as defined in the second solver file. The final trained weights will be saved to file cifar10_small_iter_5000.caffemodel.h5 means the model has been trained for 5000 iterations. If you come from Keras or other different deep learning framework background, one iteration here doesn't say the model has been trained with the entire training dataset once but a batch of training data with size 100 as defined in cifar10_m4_train_test_small.prototxt. Quite simple right? No coding is needed to build and train a Caffe model. Quick facts about quantization, As the weights are fixed after the training, and we know their min/max range. They are quantized or discretized to 256 levels using their ranges. Here is a quick demo to quantize the weights to fixed point numbers. Assume a layer's weights only contains 5 floating point numbers initially. import numpy as np weight = np.array([-31.63, -6.54, 0.45, 0.90, 31]) min_wt = weight.min() max_wt = weight.max() #find number of integer bits to represent this range int_bits = int(np.ceil(np.log2(max(abs(min_wt),abs(max_wt))))) # 31.63 --> 5 bits frac_bits = 7-int_bits #remaining bits are fractional bits (1-bit for sign), 7-5 = 2 bits #floating point weights are scaled and rounded to [-128,127], which are used in #the fixed-point operations on the actual hardware (i.e., microcontroller) quant_weight = np.round(weight*(2**frac_bits)) # 31 * 2^(2 bits frac) = 124 #To quantify the impact of quantized weights, scale them back to # original range to run inference using quantized weights recovered_weight = quant_weight/(2**frac_bits) print('quantization format: \t Q'+str(int_bits)+'.'+str(frac_bits)) print('Orginal weights: ', weight) print('Quantized weights:', quant_weight) print('Recovered weights:', recovered_weight) It outputs, quantization format: Q5.2 Orginal weights: [-31.63 -6.54 0.45 0.9 31. ] Quantized weights: [-127. -26. 2. 4. 124. ] Recovered weights: [-31.75 -6.5 0.5 1. 31. ] In this demo, the weights are quantized to Q5.2 fixed point number format, means to represent a signed floating point number in 8 bits, Qm.n format's weight = np.array([-31.63, -6.54, 0.45, 0.90, 31, 200]) If you rerun the previous script with this new weights values, the recovered weight as quantization Q8,-1 will look like below, not so good, small weights values are lost! array([-32., -6., 0., 0., 32., 200.]) That is why the ARM team developed a helper script to do the weight quantizing with minimal loss in accuracy on the test dataset which means it also runs the model to search for the best Q The nn_quantizer.py script takes the model definition (cifar10_m4_train_test_small.prototxt) file and the trained model file (cifar10_small_iter_5000.caffemodel.h5) then does three things iteratively layer-by-layer. The script finally dumps the network graph connectivity, quantization parameters into a pickle file for the next step. Who needs to write code if there is a "Code generator"? code_gen.py gets the quantization parameters and network graph connectivity from the previous step and generates the code consisting of NN function calls. It currently supports the following layers: Convolution, InnerProduct(Fully connected), Pooling (max/average) and ReLu. It generates three files weights.h parameter.h: quantization ranges, as of bias and output shift values computed from the Qm,n format of weights, bias, and activations main.cpp The generator is quite sophisticated, and it picks the best layer implementation based on various constraints as discussed in the previous post. If the model structure is unchanged, we only need to update those data weights.h parameter.h arm_nnexamples_cifar10_weights.h Naming for some definitions are slightly different, but it's easy to sort out. Now, build and run it on a microcontroller! So far you are running the neural network with purely pre-defined input data which is no fun when considering variety choices of sensors, to name a few, camera, microphone, accelerometer all can be easily integrated with the microcontroller to acquire real-time data from the environment. There are endless possibilities when this neural network framework is leveraged to process those data and extract useful information. Let's discuss what application you want to build with this technology. Don't forget to check out this runnable Google Colab notebook for this tutorial.Share on Twitter Share on Facebook
https://www.dlology.com/blog/how-to-run-deep-learning-model-on-microcontroller-with-cmsis-nn-part-3/
CC-MAIN-2018-43
en
refinedweb
Creating a App using JScript .NET and Windows Forms Working with Windows Forms Controls The sample application includes a number of controls, all of which are easy to work with. When you start the sample application (you can download the sample's source code using the link at the end of this article), the tab strip control starts with the tree view control visible, as shown in Figure 1. The tree view control organizes information using a hierarchal structure - you can access lower-level members by clicking on the plus symbol next to the root nodes. When you select a node and click the "Show Current Node" button, a message box pops (see Figure 2) describing the currently selected node and its full path. Here's the code that handles the button's click event: // The following line appears elsewhere in the class... private var treeView1 : System.Windows.Forms.TreeView; // This function handles the "Show Current Node" // button's click event function btnCurrentNode_OnClick( source:Object, e: EventArgs ) { if(treeView1.SelectedNode==null) MessageBox.Show("No currently selected node\n\nPlease select a node and try again", "Note", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1); else MessageBox.Show("Selected \"" + treeView1.SelectedNode.Text + "\"\nLocated at: \"" + treeView1.SelectedNode.FullPath+"\"", "Selected Node", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1); } If the user does not select a node, the tree view's SelectedNode is null, otherwise, it refers to TreeNode object that describes the currently selected node. The current node's Text property has the display text shown in the tree view control, while the FullPath property contains the complete path (starting form the root node) to the currently selected node. The FullPath property is useful when you want to, for example, perform an operation on a particular file in a directory listing. You can add nodes to the tree view control using its Add or AddRange methods - see the source code for details. The tab strip control contains a Month Calendar control under the Month Calendar tab. The control allows users to select a date based on a calendar metaphor that's easy to use and understand. The control offers a number of customization features that you can access using the control's properties. For example, the month calendar control has a FirstDayOfWeek property that allows you to specify the first day of the week (the day of the week that appears on the left side of each week in the month) - the sample application sets the FirstDayOfWeek property to Monday. The last control the tab strip control hosts is the Checked List Box control, which is similar to a regular List Box control except that each item has a check box next to it. When the user clicks the "Checked Items" button, the following event handler executes, which also causes a message box to pop up (see Figure 3): function btnCheckedItems_OnClick( source:Object, e: EventArgs ) { var i:int; var msg:StringBuilder = new StringBuilder("Checked items:\n"); if(checkedListBox1.CheckedItems.Count==0) msg.Append("\nNone!"); else for(i=0;i< checkedListBox1.CheckedItems.Count;i++) { msg.Append("* "); msg.Append(checkedListBox1.CheckedItems.Item(i).ToString()); msg.Append("\n"); } MessageBox.Show(msg.ToString(), "Checked Items", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1); } Figure 3 - Displaying checked items The function uses a StringBuilder object to compose a string that contains a list of the currently selected items. A StringBuilder (from the System.Text namespace) is a dynamic string that's well suited for building strings, as this function does, at runtime and is recommended instead of the System.String object, which is considered to be an immutable object. The only thing you need to watch out for is that you call the StringBuilder object's ToString method when you want to refer to its String representation, otherwise you'll get a compile-time error about a type mismatch whenever a method (like the MessageBox's Show method) requires a String object as part of its list of parameters that it accepts. The checked list box control represents checked items as a collection, which exposes a Count property making it easy to iterate over the items the user selects as shown in the listing. Page 2<<
https://www.developer.com/net/asp/article.php/10917_979251_2/Creating-a-App-using-JScript-NET-and-Windows-Forms.htm
CC-MAIN-2018-43
en
refinedweb
In the last lesson, we mapped out a plan for the structure of our online store application: The application will contain multiple routes. Depending on the route to which the user navigates, the URL in the browser and the child component displayed in the root component (between the <router-outlet> tags) will change. In this lesson, we'll walk through the process of creating a router and implementing it in an Angular application. We'll create a route to display the WelcomeComponent we described in the last lesson. In most MVCs, including Angular, we can create multiple-page applications by using a router. In terms of the MVC architecture, a router is responsible for navigating between different views in an application. As the user clicks navigational links within our app or uses the 'back' and 'forward' browser buttons in our application, a new URL is produced. This invokes the router, which matches the path of the URL with the defined route that matches that path. It then loads the components and other content that route requires. We'll need to have a special tag called a base tag in our index.html file. Angular CLI has already added this base tag for us. Look below the <title> tags to find the line <base href="/">: <> The base tag enables an HTML 5 feature called pushState routing, which Angular's own routing depends on. This allows us to make our in-app URL paths look the way we choose (ie: localhost:4200/about). You're not required to know the details of this for our course. If you'd like to explore this concept further, check out the Mozilla Developer Network entry on pushState() and the Angular Documentation on Base Tags Next we need to create the router itself. It will reside in a file known as the routes or router file. We'll create this now. In the app directory, create a file named app.routing.ts. This file name is special. All route files should be named app.routing.ts. (Note: At the time of this writing, the Angular CLI tool has disabled route creation directly from the command line. Check the Generating a Route section of their documentation in the future for updates regarding when/whether this feature will be available again.) Within our router file, we'll import two important pieces of the Angular framework: import { ModuleWithProviders } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; The ModuleWithProviders package from the Angular core helps provide our router to the rest of the application. We'll learn about "providers" in detail in an upcoming lesson when we discuss something called dependency injection. Routes and RouterModule contain code that will help us render specific components when specific URLs are provided to the router. They're not part of the Angular core by default, so we must import them here. appRoutes Next, we'll define an array called appRoutes. It will contain the master list of all available routes in our application: import { ModuleWithProviders } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; const appRoutes: Routes = [ ]; Let's walk through what's going on here: Notice appRoutes has been declared as the Routes data type. This file has access to Routes because we've imported { Routes, RouterModule }. Also note that the keyword const precedes our new appRoutes array. Including const before declaring a property or variable makes something a constant. A constant is a value that other code in our application cannot change. It's a read-only reference that cannot be redefined. Check out the Mozilla Developer Network's const entry for more details. We don't want to risk any other portion of our application altering our appRoutes array, so we declare it a constant. Additionally, keep in mind that all routes must be included in the appRoutes list. That means we'll have to manually update appRoutes to include each new route we create. Next, our file needs to export our routes to the rest of the application. We do this by passing our appRoutes variable into the forRoot() method of the RouterModule we imported, like this: import { ModuleWithProviders } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; const appRoutes: Routes = [ ]; export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes); The return value of forRoot() method is passed into the new variable called routing. Our routing object is a ModuleWithProviders data type. This is simply a special type of module that includes something called providers to help make information (like our routes) available to the rest of the application. Again, we'll learn about providers in an upcoming lesson on dependency injection. Notice that routing is being exported with the export keyword and that it's a constant. This makes our appRoutes list of routes available to our root module in app.module.ts. We'll also update our root module before the end of this lesson. At the end of the lesson, our application structure will look like this: Let's create a WelcomeComponent and a route to it. First, generate the new component: ng g component welcome Don't worry about adding content to this component yet. Next, let's add the route. Each route in an Angular application is actually a special type of object with code that looks like this: { path: '', component: WelcomeComponent }, Note: The code above is only for demonstration purposes. Don't worry about adding this to your application yet! Every route has path and component properties. path refers to the URL segment that should correspond with this route. For instance, if we wanted to create a route users could navigate to by visiting localhost:4200/super-crazy-route, the path property in our route object would read super-crazy-route. If a route has a blank string as its path property, as seen above, that means it's the index path located at localhost:4200. component refers to the primary component for a route. That is, the component that should be rendered when the user navigates to this route. The route object above will ensure the WelcomeComponent is displayed when the user visits the application's root path URL at. Let's add this first Route object into our app.routing.ts router file. First, we'll need to import any components our new route will need: ... import { WelcomeComponent } from './welcome/welcome.component'; ... We'll also add the new route object to our appRoutes array: import { ModuleWithProviders } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { WelcomeComponent } from './welcome/welcome.component'; const appRoutes: Routes = [ { path: '', component: WelcomeComponent } ]; export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes); Next, we need to add our routes file and any components it loads to our root module. (Angular CLI should have imported our WelcomeComponent when we generated it, but always make sure to double-check.) First, we import them: ... import { WelcomeComponent } from './welcome/welcome.component'; import { routing } from './app.routing'; ... routing refers to the constant being exported at the bottom of our routes file: ... export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes); We'll also need to add the routing constant to our root module's imports array: ... imports: [ BrowserModule, FormsModule, HttpModule, routing ], ... The imports array is used to import other modules into the current module. Note that this differs from the import statements at the top of our files. (The ones that look like import { WelcomeComponent } from './welcome/welcome.component';. Import statements simply import other modules' code into a single file. Finally, we need to update our root AppComponent. We must designate where the router should load content for our different routes. For instance, we told our router to load the WelcomeComponent when the user visits the root path at localhost:4200/. We need to tell Angular where the WelcomeComponent should be rendered. We do this with a special tag called <router-outlet>. This tag denotes exactly where a route's components will be rendered. Let's place <router-outlet></router-outlet> tags in our root component's template now. <h1>{{title}}</h1> <router-outlet></router-outlet> Let's go ahead and add a div and page title to our root component: <div class="container"> <h1>{{title}}</h1> <router-outlet></router-outlet> </div> Let's change the title property in our AppComponent class: ... export class AppComponent { title = 'Epicodus Tunes'; } And the template of our WelcomeComponent: <h2>Welcome to our store!</h2> Launch the application with the $ ng serve command and the WelcomeComponent will be displayed at the default root path: Now that we have a router and our very first route, we'll discuss how to navigate between routes and manage multiple routes in an Angular application in the next lesson. We'll also create our remaining About, Marketplace and Album Detail pages.
https://www.learnhowtoprogram.com/javascript/angular-extended/implementing-a-router
CC-MAIN-2018-43
en
refinedweb
A program includes many identifiers defined in different scopes. Sometimes a variable of one scope will "overlap" (i.e., collide) with a variable of the same name in a different scope, possibly creating a naming conflict. Such overlapping can occur at many levels. Identifier overlapping occurs frequently in third-party libraries that happen to use the same names for global identifiers (such as functions). This can cause compiler errors. The C++ standard attempts to solve this problem with namespaces. Each namespace defines a scope in which identifiers and variables are placed. To use a namespace member, either the member's name must be qualified with the namespace name and the binary scope resolution operator (::), as in MyNameSpace::member or a using declaration or using directive must appear before the name is used in the program. Typically, such using statements are placed at the beginning of the file in which members of the namespace are used. For example, placing the following using directive at the beginning of a source-code file using namespace MyNameSpace A using declaration (e.g., using std::cout;) brings one name into the scope where the declaration appears. A using directive (e.g., using namespace std;) brings all the names from the specified namespace into the scope where the directive appears. Not all namespaces are guaranteed to be unique. Two third-party vendors might inadvertently use the same identifiers for their namespace names. The following code segment illustrates the user of Namespace. 1 // programming-techniques tutorial on Namespace2 // Demonstrating namespaces.3 #include <iostream>4 using namespace std; // use std namespace56 int integer1 = 98; // global variable78 // create namespace Example9 namespace Example10 {11 // declare two constants and one variable12 const double PI = 3.14159;13 const double E = 2.71828;14 int integer1 = 8;1516 void printValues(); // prototype1718 // nested namespace19 namespace Inner20 {21 // define enumeration22 enum Years { FISCAL1 = 1990, FISCAL2, FISCAL3 };23 } // end Inner namespace24 } // end Example namespace2526 // create unnamed namespace27 namespace28 {29 double doubleInUnnamed = 88.22; // declare variable30 } // end unnamed namespace3132 int main()33 {34 // output value doubleInUnnamed of unnamed namespace35 cout << "doubleInUnnamed = " << doubleInUnnamed;3637 // output global variable38 cout << "\n(global) integer1 = " << integer1;3940 // output values of Example namespace41 cout << "\nPI = " << Example::PI << "\nE = " << Example::E42 << "\ninteger1 = " << Example::integer1 << "\nFISCAL3 = "43 << Example::Inner::FISCAL3 << endl;4445 Example::printValues(); // invoke printValues function46 return 0;47 } // end main4849 // display variable and constant values50 void Example::printValues()51 {52 cout << "\nIn printValues:\ninteger1 = " << integer1 << "\nPI = "53 << PI << "\nE = " << E << "\ndoubleInUnnamed = "54 << doubleInUnnamed << "\n(global) integer1 = " << ::integer155 << "\nFISCAL3 = " << Inner::FISCAL3 << endl;56 } // end printValues Using the std Namespace Line 4 informs the compiler that namespace std is being used. The contents of header file <iostream> are all defined as part of namespace std. [Note: Most C++ programmers consider it poor practice to write a using directive such as line 4 because the entire contents of the namespace are included, thus increasing the likelihood of a naming conflict.] The using namespace directive specifies that the members of a namespace will be used frequently throughout a program. This allows the programmer to access all the members of the namespace and to write more concise statements such as cout << "double1 = " << double1; rather than std::cout << "double1 = " << double1; Without line 4, either every cout and endl in above code would have to be qualified with std::, or individual using declarations must be included for cout and endl as in: using std::cout; using std::endl; The using namespace directive can be used for predefined namespaces (e.g., std) or programmer-defined namespaces. Defining Namespace Lines 9, 4 use the keyword namespace to define namespace Example. The body of a namespace is delimited by braces ({}). Namespace Example's members consist of two constants (PI and E at lines 1213), an int (integer1 at line 14), a function (printValues at line 16) and a nested namespace (Inner at lines 1923). Notice that member integer1 has the same name as global variable integer1 (line 6). Variables that have the same name must have different scopesotherwise compilation errors occur. A namespace can contain constants, data, classes, nested namespaces, functions, etc. Definitions of namespaces must occupy the global scope or be nested within other namespaces. Lines 27, 30 create an unnamed namespace containing the member doubleInUnnamed. The unnamed namespace has an implicit using directive, so its members appear to occupy the global namespace, are accessible directly and do not have to be qualified with a namespace name. Global variables are also part of the global namespace and are accessible in all scopes following the declaration in the file. Accessing Namespace Members with Qualified Names Line 35 outputs the value of variable doubleInUnnamed, which is directly accessible as part of the unnamed namespace. Line 38 outputs the value of global variable integer1. For both of these variables, the compiler first attempts to locate a local declaration of the variables in main. Since there are no local declarations, the compiler assumes those variables are in the global namespace. Lines 41, 43 output the values of PI, E, integer1 and FISCAL3 from namespace Example. Notice that each must be qualified with Example:: because the program does not provide any using directive or declarations indicating that it will use members of namespace Example. In addition, member integer1 must be qualified, because a global variable has the same name. Otherwise, the global variable's value is output. Notice that FISCAL3 is a member of nested namespace Inner, so it must be qualified with Example::Inner::. Function printValues (defined at lines 5056) is a member of Example, so it can access other members of the Example namespace directly without using a namespace qualifier. The output statement in lines 5255 outputs integer1, PI, E, doubleInUnnamed, global variable integer1 and FISCAL3. Notice that PI and E are not qualified with Example. Variable doubleInUnnamed is still accessible, because it is in the unnamed namespace and the variable name does not conflict with any other members of namespace Example. The global version of integer1 must be qualified with the unary scope resolution operator (::), because its name conflicts with a member of namespace Example. Also, FISCAL3 must be qualified with Inner::. When accessing members of a nested namespace, the members must be qualified with the namespace name (unless the member is being used inside the nested namespace).
https://www.programming-techniques.com/2011/10/c-tutorial-namespace-in-c.html
CC-MAIN-2018-43
en
refinedweb
Just resurrecting an oldish thread for a moment... I've got the JellyUnit stuff working now so that JUnit tests can be written (and dynamically generated) in Jelly script. So Jelly can be used to create TestSuite and TestCase objects, possibly dynamically using information from beans, XML, SOAP, SQL etc. Then Jelly can run the tests or they can be called from inside any existing JUnit TestRunner . From: "Vincent Massol" <vmassol@octo.com> > > -----Original Message----- > > From: Jeff Turner [mailto:jeff@socialchange.net.au] > > Sent: 01 July 2002 02:48 > > To: Jakarta Commons Developers List > > Subject: Re: [jelly] http and validation tag libraries > > > > [snip] > > > > Somewhat curious as to why everyone's so keen to reuse the JUnit API > 8-) > > I've found it to be so tightly engineered and 'pattern dense' that > it's > > hard to reuse outside it's intended scope. JUnit goes to a lot of > effort > > to isolate TestCases, and for functional testing we *want* to share > > information like session data. Once you've thrown away the testXxx() > > method introspection, startUp(), tearDown(), and all that, what's > left? > > > > - Mostly the tools and the front ends (TestRunner) : you can find JUnit > integration in any IDE. In addition, why reinvent a new testing > framework API when there is one already. I do agree with your remark of > TestCase isolation for functional test cases. However, it does not seem > to be such a problem to use JUnit for that (see my other email on the > same thread). That said, I need to verify that what I wrote is correct > ... > > Then you get the following additional benefits : > - people already know how to use your framework because the interface > (TestRunner) is standard (de facto) > - you get documentation/support/etc for free for your testing front end > - the JUnit name is a good seller ... :-) Agreed. Incidentally the trick to integrating JellyUnit test cases into an existing JUnit TestRunner framework is to write a single adapter class as follows, where a Jelly script 'suite.jelly' is assumed to be on the classpath in the same package as the TestFoo class... import junit.framework.TestSuite; import org.apache.commons.jelly.tags.junit.JellyTestSuite; /** * A helper class to run jelly test cases in a JUnit TestRunner */ public class TestFoo extends JellyTestSuite { public static TestSuite suite() throws Exception { return createTestSuite(TestFoo.class, "suite.jelly"); } }>
http://mail-archives.apache.org/mod_mbox/commons-dev/200207.mbox/%3C051801c23198$30dc9e30$9865fea9@spiritsoft.com%3E
CC-MAIN-2016-44
en
refinedweb
committed d On Tuesday 01 Oct 2002 9:53 pm, you wrote: > looks like the change I made to remove 'using namespace std' has broken > some naughty headers. fix is in progress > > Daniel > > On Tuesday 01 Oct 2002 9:06 pm, you wrote: > > On Mon, 30 Sep 2002 20:25:02 +0000 > > > > mark lybarger <mlybarge@insight.rr.com> wrote: > > > hi, > > > > > >: > > > > Hello, Everyone :) > > I just installed Red Hat 8.0 and I had the exact same problem. The > > error message looks SLIGHTLY different, but I declined to send it unless > > you thinks it's necessary. The version of gcc on my system is the same > > as Mark's. > > > > Thanks for your help :) > > Steven P. Ulrick
http://www.crosswire.org/pipermail/sword-devel/2002-October/016298.html
CC-MAIN-2016-44
en
refinedweb
One of the most common ways of terrain texturing is blending multiple tiled layers. Each layer has an opacity map which defines the extent of texture presence on the terrain. The method works by applying an opacity map to the higher levels, revealing the layers underneath where the opacity map is partially or completely transparent. Opacity map is measured in percentage. Of course on each point of a terrain the sum of opacities of all layers makes one-hundred percent as the terrain can't be transparent. Instead of tile textures, the opacity map stretches entirely on all terrain and therefore has quite a low level of detail. Now we will pass to the most interesting part — algorithms of blending of textures. For simplicity and obviousness our terrain will consist of sand and large cobble-stones. Simplest way of blending is to multiply texture color with opacity and then sum results. float3 blend(float4 texture1, float a1, float4 texture2, float a2) { return texture1.rgb * a1 + texture2.rgb * a2; } Such a technique is used in Unity3D in the standard terrain editor. As you can see, the transition is smooth but unnatural. Stones look evenly soiled by sand, but in the real world it doesn't happen like that. Sand doesn't stick to stones, instead it falls down and fills cracks between them, leaving the tops of stones pure. Let's try to simulate this behavior in Excel plots. As we want sand to be "fallen down" between cobble-stones, for each texture we need the depth map. In this example we consider the depth map is generated from grayscaled image and stored in the alpha channel of a texture. In Unity3D it can be done in the texture inspector by setting the flag "Alpha From Grayscale". First of all we will consider the simplified model of depth map of sand and stones. The blue line on the plot symbolizes the depth map of sand and red is cobble-stones. Notice that tops of stones lie higher than sand level. Considering this fact, we will try to draw pixels of that texture which is above. float3 blend(float4 texture1, float a1, float4 texture2, float a2) { return texture1.a > texture2.a ? texture1.rgb : texture2.rgb; } Excellent! Tops of cobble-stones remain pure whereas sand lies in cracks between them. But we didn't consider layer opacity yet. To use it we just sum depth map and opacity map. float3 blend(float4 texture1, float a1, float4 texture2, float a2) { return texture1.a + a1 > texture2.a + a2 ? texture1.rgb : texture2.rgb; } At the expense of summation less transparent texture will be higher than usual. So we have a more natural transition from sand to stones. As you can see, grains of sand start filling cracks between cobble-stones, gradually hiding them. But as calculations happens pixel-by-pixel, artifacts begin to appear on the border between textures. To get a smooth result we will take several pixels in depth instead of one and blend them. float3 blend(float4 texture1, float a1, float4 texture2, float a2) { float depth = 0.2; float ma = max(texture1.a + a1, texture2.a + a2) - depth; float b1 = max(texture1.a + a1 - ma, 0); float b2 = max(texture2.a + a2 - ma, 0); return (texture1.rgb * b1 + texture2.rgb * b2) / (b1 + b2); } In the code above we at first get part of a ground seen at a certain depth. And then we normalize it to get new opacities. As a result we found the algorithm of textures blending, which allows us to reach close to a natural terrain image. In summary I want to explain what this algorithm was developed for and how we use it. The shader was developed for turn-based strategic indie game Steam Squad. As engine and developing platform we use Unity3D. And as the Unity IDE is extremely flexible, we made our own level designer extension. In general the level designer is a simplified Unity3D terrain editor with some features of Titan Quest Editor. When you paint the texture on a terrain there is a recalculation of the opacity map corresponding to this texture. And as the sum of all opacities has to make 100%, the editor automatically normalizes opacity maps of other layers. Here is short YouTube video showing how it works. Shader which uses this algorithm in Unity3D Asset Store License GDOL (Gamedev.net Open License) That's a really cool technique! It adds quite a lot visually for only a little work. Thanks for sharing! This is one of those techniques that when seen, causes you to ask yourself: "Why hasn't anyone thought of this before?" The bottom picture looks natural. This is very impressive! I think many people have, the issue is the draw call and the load times; which leads me to my question. Doesnt the pixel shader run slower and cause considerable lag on a procedurally generated terrain setup? This setup would work on solid, never changing terrain, but I think it would cause serious issues with terrain that was to change on a constant or semi constant basis. Each modification of the land would require another draw call, would it not? Also, with our system we have been looking at doing this but we have 3 textures maps ( normal, specular, color ). Each one of these would need a new sample, this means 3 * 3 = 9 samples. We would have to blend this with another texture ( for the edges of the blocks/regions ) making a total of 18 samples.... is this correct? I have no clue why my post generated two down votes... as there was nothing negative about it. Oh well.... whatever! Seemed to me like you raised some valid points. O.o I like it as well... i just want to understand how it could be used in a modular world rather than a static one. Riuthamus, good questions! Shader behaves exactly like default one. Of course, it has more math operations, but delay is absolutely insignificant. In the my implementation of shader I can blend 9 textures: 4 color maps + 4 normal maps + noise map. And with some math magic I still fit in SM2.0 limitations. Also with some storage magic the changing of texture transparency isn't more difficult than moving point of a mesh. I can change it in realtime, but changing of set of textures is still expensive operation. Sorry but I can't show you all sources because the shader is part of commercial project. It would be helpful to people attempting to duplicate your results if the textures depicted above could be provided (or a modified version of them, such as with a text watermark). You. Great effect, thanks for sharing! This'd look nice with some sort of emboss-mapping like effect. Amazing! Keep up the good work! I implemented this technique in Unity3D. You can find shaders in Unity Asset Store and here is a demo. Thanks Andrey, this technique is beyond fantastic!
http://www.gamedev.net/page/resources/_/technical/graphics-programming-and-theory/advanced-terrain-texture-splatting-r3287?st=0
CC-MAIN-2016-44
en
refinedweb
Fix some Russian strings. Added Basque translation provied by Asier Iturralde Sarasola Ruby parser: don't create an extra scope after "for .. in .. do" When "do" appears as the separator after a "for", "while" or "until" construct, don't improperly make it start its own scope too. Check the VTE library we're loading actually have all symbols we need This prevents a crash if the VTE library we happen to load lacks a symbol we need, which can happen e.g. if the user passed an improper library to the --vte-lib command-line option or if the VTE library is loadable but broken. Don't access GtkColorSelectionDialog fields directly Also don't hack around and handle clicks on the dialog's buttons but rather simply handler the dialog's response. Don't use deprecated GtkObject Don't access GtkFontSelectionDialog fields directly Don't use gtk_widget_hide_all(), deprecated in 2.24 Don't use pre-GObject types and macros Don't access GtkSelectionData fields directly Don't access GtkWidget:parent directly Don't access GtkNotebook fields directly Don't use deprecated GtkNotebookPage Don't access GtkDialog fields directly Don't use long-deprecated gtk_widget_{ref,unref}() Don't use deprecated gtk_box_pack_start_defaults() Regenerate Python tag list Generated against a clean Python 2.7 installation. Strip more tags which start with a keyword Don't set the focus to the editor widget when clicking a symbol while holding Control When clicking a symbol in the Symbols sidebar and holding the Control modifier key, don't set the focus to the editor widget so further navigation in the Symbols sidebar with keys is possible. Use namespaces icon for Ruby modules It's not perfect but better than nothing since other tags have icons. Merge branch 'printing-with-scintilla' Closes #3475444, #2804000 and #2629121. Don't regenerate deps.mak files on 'make clean' (Windows makefile) Improve collapsing fold behaviour when start point is offscreen When collapsing a fold range whose starting line is offscreen, scroll the starting line to display at the top of the view. Otherwise it can be confusing when the document scrolls down to hide the folded lines. Update Scintilla to version 3.2.2 Save encoding in session as text Since reading locale and reading encodings from within files by regex can find encodings not on the Geany list, saving as text ensures that any encoding found can be saved in the session, otherwise a file can be opened but will not re-open because the encoding cannot be saved in the session. Since numeric encoding names exist prefix the text name by 'E' so they can be distinguished from saved numeric indexes..
https://sourceforge.net/p/geany/git/ci/d807eff73d61de95825d548471e0f00d50a6e6e9/log/
CC-MAIN-2016-44
en
refinedweb
Look no further. The Gadgeteer core library documentation is posted on the Gadgeteer community site at. This covers the namespaces: - Gadgeteer – including the Color, Mainboard, Picture, Program, Socket, StorageDevice and Timer classes. - Gadgeteer.Interfaces – including AnalogInput, AnalogOutput, DigitalInput, DigitalIO, DigitalOutput, I2CBus, InterruptInput, PWMOutput, Serial and SPI classes. - Gadgeteer.Modules – including Module, DaisyLinkModule, DisplayModule, DisplayModule.SimpleGraphicsInterface, and NetworkModule classes. - Gadgeteer.Networking Check it out, and if you have any questions, let us know in the Gadgeteer forums.
https://blogs.msdn.microsoft.com/net_gadgeteer/2011/12/20/looking-for-api-reference-docs-for-the-core-gadgeteer-libraries/
CC-MAIN-2016-44
en
refinedweb
namespace BusinessRules.Evolution_Four { /// <summary>Null Object Pattern</summary> /// <remarks> /// <list type="bullet"> /// <item><description>Provides an interface identical to IncomeTaxEngine Object's so that a null /// object can be substituted for a real object</description></item> /// <item><description>Implements its interface to do nothing. What exactly it means to do /// nothing depends on what sort of behaviour the client is expecting</description></item> /// <item><description>When there is more than one way to do nothing, more than one Null Object /// class may be required</description></item> /// </list> /// </remarks> internal class NullIncomeTaxEngine : IncomeTaxEngine { #region Methods /// <summary> /// Calculates the tax rate. /// </summary> /// <returns> /// Returns a double representing the tax liability for the investor. /// </returns> public override Calculation<Investor> CalculateTaxRate() { return delegate { return 0.0; }; } /// <summary> /// Calculates the tax liability. /// </summary> /// <returns> /// Returns a double representing the tax rate for the investor. /// </returns> public override Calculation<Investor> CalculateTaxLiability() { return delegate { return 0.0; }; } #endregion } }
http://www.codeproject.com/script/Articles/ViewDownloads.aspx?aid=16469&zep=BusinessRules%2F4+-+Evolution+Four%2FNullIncomeTaxEngine.cs&rzp=%2FKB%2Farchitecture%2Fdomainrules%2F%2Fdomainrules_src.zip
CC-MAIN-2016-44
en
refinedweb
For my actions that are going to interact with the User's account, I would like to create a "TheUser" object in addition to adding that object to "ViewData["TheUser"]" as soon as any action on my controller is called. If the User is logged in, it will grab the User's info from the database, if not, "TheUser" object will just be null. I tried accessing "User.Identity.Name" in the controller constructor, but it isn't created prior to any action being called. I was looking at custom authorization filters, but those wouldn't allow me to create the "TheUser" object and store it in the ViewData. This is a brief snippet of what I would like to accomplish: [Authorize] public class HomeController : Controller { User TheUser; public HomeController() { TheUser = User.Identity.IsAuthenticated ? UserRepository.GetUser(User.Identity.Name) : null; ViewData["TheUser"] = TheUser; } } I created a custom base Controller class and added a "CurrentUser" property to it. In the Initialize method, I placed the logic to get the user and then add it to the ViewData and the "CurrentUser" property of the controller. I had my controllers inherit the custom base Controller class and I was able to reference "CurrentUser" variable anywhere in the controller: public class CustomControllerClass : Controller { public User CurrentUser { get; set; } protected override void Initialize(RequestContext requestContext) { base.Initialize(requestContext); if (requestContext.HttpContext.User.Identity.IsAuthenticated) { string userName = requestContext.HttpContext.User.Identity.Name; CurrentUser = UserRepository.GetUser(userName); } ViewData["CurrentUser"] = CurrentUser; } }
https://codedump.io/share/D3sgPatLViRm/1/defining-a-user-with-useridentityname-in-controller-constructor
CC-MAIN-2016-44
en
refinedweb
Garrett Cooper <yanegomi at gmail.com> added the comment: My initial analysis was incorrect after talking with the bash(1) folks. test(1) is doing things wrong too: case FILEX: /* XXX work around eaccess(2) false positives for superuser */ if (eaccess(nm, X_OK) != 0) return 0; if (S_ISDIR(s.st_mode) || geteuid() != 0) return 1; return (s.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) != 0; So it looks like test(1) is broken as well (doesn't check for ACLs, or MAC info). Interesting why it's only implemented for X_OK though... Based on this analysis, I'd say that access(2) is broken on FreeBSD and needs to be fixed. ---------- _______________________________________ Python tracker <report at bugs.python.org> <> _______________________________________
https://mail.python.org/pipermail/docs/2010-July/000789.html
CC-MAIN-2016-44
en
refinedweb
In this code : class PersonCommand(sublime_plugin.TextCommand): def run(self, edit): self.name = None self.view.window().show_input_panel("Name", "", self.on_done, None, None) print "run: ", self.name def on_done(self, value): self.name = value print "on_done: ", self.name if we enter "Jack" we will get :run: Noneon_done: JackWhy there is such a problem and how to use the input panel as a prompt to read arguments ?! I understand that the on_done is not executed immediately , so how to create multiple inputs ?
https://forum.sublimetext.com/t/problem-self-object-and-on-done-function/7123/1
CC-MAIN-2016-44
en
refinedweb
PropertyItem Class Encapsulates a metadata property to be included in an image file. Not inheritable. Assembly: System.Drawing (in System.Drawing.dll) System.Drawing.Imaging.PropertyItem The data consists of: an identifier, the length (in bytes) of the property, the property type, and a pointer to the property value. A PropertyItem is not intended to be used as a stand-alone object. A PropertyItem object is intended to be used by classes that are derived from Image. A PropertyItem object is used to retrieve and to change the metadata of existing image files, not to create the metadata. Therefore, the PropertyItem class does not have a defined Public constructor, and you cannot create an instance of a PropertyItem object. To work around the absence of a Public constructor, use an existing PropertyItem object instead of creating a new instance of the PropertyItem class. For more information, see Image.GetPropertyItem. The following code example demonstrates how to read and display the metadata in an image file using the PropertyItem class and the Image.PropertyItems property. This example is designed to be used in a Windows Form that imports the System.Drawing.Imaging namespace. Paste the code into the form and change the path to fakePhoto.jpg to point to an image file on your system. Call the ExtractMetaData method when handling the form's Paint event, passing e as PaintEventArgs. Private Sub ExtractMetaData(ByVal e As PaintEventArgs) Try 'Create an Image object. Dim theImage As Image = New Bitmap("c:\fakePhoto.jpg") 'Get the PropertyItems property from image. Dim propItems As PropertyItem() = theImage.PropertyItems 'Set up the display. Dim font As New font("Arial", 10) Dim blackBrush As New SolidBrush(Color.Black) Dim X As Integer = 0 Dim Y As Integer = 0 'For each PropertyItem in the array, display the id, type, and length. Dim count As Integer = 0 Dim propItem As PropertyItem For Each propItem In propItems e.Graphics.DrawString("Property Item " + count.ToString(), _ font, blackBrush, X, Y) Y += font.Height e.Graphics.DrawString(" iD: 0x" & propItem.Id.ToString("x"), _ font, blackBrush, X, Y) Y += font.Height e.Graphics.DrawString(" type: " & propItem.Type.ToString(), _ font, blackBrush, X, Y) Y += font.Height e.Graphics.DrawString(" length: " & propItem.Len.ToString() & _ " bytes", font, blackBrush, X, Y) Y += font.Height count += 1 Next propItem font.Dispose() Catch ex As ArgumentException MessageBox.Show("There was an error. Make sure the path to the image file is valid.") End Try End Sub Available since 1.1 Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
https://msdn.microsoft.com/en-us/library/system.drawing.imaging.propertyitem(v=vs.110).aspx?cs-save-lang=1&cs-lang=vb
CC-MAIN-2016-44
en
refinedweb
CodePlexProject Hosting for Open Source Software I'm trying to enforce some code analysis rules against my Silverlight projects based on Prism. I'm running into errors with regard to the Bootstrapper. Specifically, I'm getthing the following errors when trying to test the bootstrapper, Method 'CreateShell' in type 'Test.MyBootstrapper' from assembly 'Test', Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' does not have an implementation. Is there an incompatability with FxCop that I'm not aware of? Thanks Rick Did you implement the method? Bootstrapper is derived from UnityBootstrapper, which is an abstract class, and the implementation of "CreateShell" is required. Here's the class that I'm using. public class MyBootstrapper : UnityBootstrapper { protected override DependencyObject CreateShell() { ShellView shell = Container.Resolve<IShellViewModel>().View as ShellView; Application.Current.RootVisual = shell; return shell; } protected override void ConfigureContainer() { base.ConfigureContainer(); Container.RegisterType<IAuthenticationContext, AuthenticationContext>(new ContainerControlledLifetimeManager()); Container.RegisterType<IAuthorizationContext, AuthorizationContext>(new ContainerControlledLifetimeManager()); Container.RegisterType<ISessionContext, SessionContext>(new ContainerControlledLifetimeManager()); Container.RegisterType<IShellModel, ShellModel>(new ContainerControlledLifetimeManager()); Container.RegisterType<IShellViewModel, ShellViewModel>(); Container.RegisterType<IShellView, ShellView>(); Container.Resolve<ISessionContext>(); } protected override IModuleCatalog GetModuleCatalog() { ModuleCatalog catalog = ModuleCatalog.CreateFromXaml( new Uri("ModuleCatalog.xaml", UriKind.Relative)); return catalog; } } Hi Rick, I have just talked with a colleague of mine who has been developing an application using Prism, Silverlight 3 and FxCop for a long time now. He says he had no issues while developing so far and FxCop works correctly. If blackjack’s suggestion was not accurate for your scenario, you could check if you are not missing any assembly references, or if anything of your environment is reproducing a bug Visual Studio might have (I am not aware of anything related to this, but surfing the Web might throw some answers). Please let me know if this helps. Damian Schenkelman Thanks for looking into this. The project builds just fine, so I'm going to reflect through FxCop and see where it's breaking and I'll see how it is trying to activeate the code. Seems that when our custom rules the problem is arising when we try to load the assemblies to compare types, Assembly asm = Assembly.LoadFrom(type.DeclaringModule.Location); This was causing the exception. I removed the depnedence on this and use the FrameworkType to evaluate the TypeNodes, if (type.IsAssignableTo(FrameworkTypes.Attribute)) Thanks again for looking into this. Are you sure you want to delete this post? You will not be able to recover it later. Are you sure you want to delete this thread? You will not be able to recover it later.
http://compositewpf.codeplex.com/discussions/65538
CC-MAIN-2016-44
en
refinedweb
jQuery Succinctly: Core jQuery Base Concept Behind jQuery While some conceptual variations exist (e.g. functions like $.ajax) in the jQuery API, the central concept behind jQuery is "find something, do something." More specifically, select DOM element(s) from an HTML document and then do something with them using jQuery methods. This is the big picture concept. To drive this concept home, reflect upon the code below. <!DOCTYPE html> <html lang="en"> <body> <!-- jQuery will change this --> <a href=""></a> <!-- to this <a href="">jQuery</a> --> <script src=""></script> <script> jQuery('a').text('jQuery').attr('href', ''); </script> </body> </html> Notice that in this HTML document we are using jQuery to select a DOM element ( <a>). With something selected, we then do something with the selection by invoking the jQuery methods text(), attr(), and appendTo(). The text method called on the wrapped <a> element and set the display text of the element to be "jQuery." The attr call sets the href attribute to the jQuery Web site. Grokking the "find something, do something" foundational concept is critical to advancing as a jQuery developer. The Concept, Behind the Concept, Behind jQuery While selecting something and doing something is the core concept behind jQuery, I would like to extend this concept to include creating something as well. Therefore, the concept behind jQuery could be extended to include first creating something new, selecting it, and then doing something with it. We could call this the concept, behind the concept, behind jQuery. What I am trying to make obvious is that you are not stuck with only selecting something that is already in the DOM. It is additionally important to grok that jQuery can be used to create new DOM elements and then do something with these elements. In the code example below, we create a new <a> element that is not in the DOM. Once created, it is selected and then manipulated. <!DOCTYPE html> <html lang="en"> <body> <script src=""></script> <script> jQuery('<a>jQuery</a>').attr('href', '').appendTo('body'); </script> </body> </html> The key concept to pick up here is that we are creating the <a> element on the fly and then operating on it as if it was already in the DOM. jQuery Requires HTML to Run in Standards Mode or Almost-Standards Mode There are known issues with jQuery methods not working correctly when a browser renders an HTML page in quirks mode. Make sure when you are using jQuery that the browser interprets the HTML in standards mode or almost standards mode by using a valid doctype. To ensure proper functionality, code examples in this book use the HTML 5 doctype. <!DOCTYPE html> Waiting on the DOM to Be Ready jQuery fires a custom event named ready when the DOM is loaded and available for manipulation. Code that manipulates the DOM can run in a handler for this event. This is a common pattern seen with jQuery usage. The following sample features three coded examples of this custom event in use. <!DOCTYPE html> <html lang="en"> <head> <script src=""></script> <script> // }); </script> </head> <body></body> </html> Keep in mind that you can attach as many ready() events to the document as you would like. You are not limited to only one. They are executed in the order they were added. Executing jQuery Code When the Browser Window Is Completely Loaded Typically, we do not want to wait for the window.onload event. That is the point of using a custom event like ready() that will execute code before the window loads, but after the DOM is ready to be traversed and manipulated. However, sometimes we actually do want to wait. While the custom ready() event is great for executing code once the DOM is available, we can also use jQuery to execute code once the entire Web page (including all assets) is completely loaded. This can be done by attaching a load event handler to the window object. jQuery provides the load() event method that can be used to invoke a function once the window is completely loaded. Below, I provide an example of the load() event method in use. <!DOCTYPE html> <html lang="en"> <head> <script src=""></script> <script> // Pass window to the jQuery function and attach // event handler using the load() method shortcut jQuery(window).load(function(){ alert('The page and all its assets are loaded!'); }); </script> </head> <body></body> </html> Include All CSS Files Before Including jQuery As of jQuery 1.3, the library no longer guarantees that all CSS files are loaded before it fires the custom ready() event. Because of this change in jQuery 1.3, you should always include all CSS files before any jQuery code. This will ensure that the browser has parsed the CSS before it moves on to the JavaScript included later in the HTML document. Of course, images that are referenced via CSS may or may not be downloaded as the browser parses the JavaScript. Using a Hosted Version of jQuery When embedding jQuery into a Web page, most people choose to download the source code and link to it from a personal domain/host. However, there are other options that involve someone else hosting the jQuery code for you. Google hosts several versions of the jQuery source code with the intent of it being used by anyone. This is actually very handy. In the code example below I am using a <script> element to include a minified version of jQuery that is hosted by Google. <script src=""></script> Google also hosts several previous versions of the jQuery source code, and for each version, minified and non-minified variants are provided. I recommend using the non-minified variant during development, as debugging errors is always easier when you are dealing with non-minified code. A benefit of using a Google hosted version of jQuery is that it is reliable, fast, and potentially cached. Executing jQuery Code When DOM Is Parsed Without Using Ready() The custom ready() event is not entirely needed. If your JavaScript code does not affect the DOM, you can include it anywhere in the HTML document. This means you can avoid the ready() event altogether if your JavaScript code is not dependent on the DOM being intact. Most JavaScript nowadays, especially jQuery code, will involve manipulating the DOM. This means the DOM has to be fully parsed by the browser in order for you to operate on it. This fact is why developers have been stuck on the window.onload roller coaster ride for a couple of years now. To avoid using the ready() event for code that operates on the DOM, you can simply place your code in an HTML document before the closing </body> element. Doing so ensures the DOM is completely loaded, simply because the browser will parse the document from top to bottom. If you place your JavaScript code in the document after the DOM elements it manipulates, there is no need to use the ready() event. In the example below, I have forgone the use of ready() by simply placing my script before the document body closes. This is the technique I use throughout this book and on the majority of sites I build. <!DOCTYPE html> <html lang="en"> <body> <p> Hi, I'm the DOM! Script away!</p> <script src=""></script> <script> alert(jQuery('p').text()); </script> </body> </html> If I were to place the <script> before the <p> element, it would execute before the browser had loaded the <p> element. This would cause jQuery to assume the document does not contain any <p> elements. However, if I were to use the jQuery custom ready() event, then jQuery would not execute the code until the DOM was ready. But why do this, when we have control over the location of the <script> element in the document? Placing jQuery code at the bottom of the page avoids having to using the ready() event. In fact, placing all JavaScript code at the bottom of a page is a proven performance strategy. Grokking jQuery Chaining Once you have selected something using the jQuery function and created a wrapper set, you can actually chain jQuery methods to the DOM elements contained inside the set. Conceptually, jQuery methods continue the chain by always returning the jQuery wrapper set, which can then be used by the next jQuery method in the chain. Note: Most jQuery methods are chainable, but not all. You should always attempt to reuse the wrapped set by leveraging chaining. In the code below, the text(), attr(), and addClass() methods are being chained. <!DOCTYPE html> <html lang="en"> <body> <a></a> <script src=""></script> <script> (function ($) { $('a').text('jQuery') // Sets text to jQuery and then returns $('a') .attr('href', '') // Sets the href attribute and then returns $('a') .addClass('jQuery'); // Sets class and then returns $('a') })(jQuery) </script> </body> </html> Breaking the Chain With Destructive Methods As mentioned before, not all jQuery methods maintain the chain. Methods like text() can be chained when used to set the text node of an element. However, text() actually breaks the chain when used to get the text node contained within an element. In the example below, text() is used to set and then get the text contained within the <p> element. <!DOCTYPE html> <html lang="en"> <body> <p></p> <script src=""></script> <script> (function ($) { var theText = $('p').text('jQuery').text(); // Returns the string "jQuery" alert(theText); // Cannot chain after text(). The chain is broken. // A string is returned, not the jQuery object. })(jQuery) </script> </body> </html> Getting the text contained within an element using text() is a prime example of a broken chain because the method will return a string containing the text node, but not the jQuery wrapper set. It should be no surprise that if a jQuery method does not return the jQuery wrapper set, the chain is thereby broken. This method is considered to be destructive. Using Destructive jQuery Methods and Exiting Destruction Using End() jQuery methods that alter the original jQuery wrapper set selected are considered to be destructive. The reason is that they do not maintain the original state of the wrapper set. Not to worry; nothing is really destroyed or removed. Rather, the former wrapper set is attached to a new set. However, fun with chaining does not have to stop once the original wrapped set is altered. Using the end() method, you can back out of any destructive changes made to the original wrapper set. Examine the usage of the end() method in the following example to understand how to operate in and out of DOM elements. <!DOCTYPE html> <html lang="en"> <body> <style> .last { background: #900; } </style> <ul id="list"> <li></li> <li> <ul> <li></li> <li></li> <li></li> </ul> </li> <li></li> <li></li> </ul> <script src=""></script> <script> (function ($) { $('#list') // Original wrapper set .find('> li') // Destructive method .filter(':last') // Destructive method .addClass('last') .end() // End .filter(':last') .find('ul') // Destructive method .css('background', '#ccc') .find('li:last') // Destructive method .addClass('last') .end() // End .find('li:last') .end() // End .find('ul') .end() // End .find('> li') .find('li') // Back to the orginal $('#list') .append('I am an &lt;li&gt;'); })(jQuery); </script> </body> </html> Aspects of the jQuery Function The jQuery function is multifaceted. We can pass it differing values and string formations that it can then use to perform unique functions. Here are several uses of the jQuery function: - Select elements from the DOM using CSS expressions and custom jQuery expressions, as well as selecting elements using DOM references: jQuery('p > a')or jQuery(':first')and jQuery(document.body) - Create HTML on the fly by passing HTML string structures or DOM methods that create DOM elements: jQuery('<div id="nav"></div>')or jQuery(document.createElement('div')) - A shortcut for the ready()event by passing a function to the jQuery function: jQuery(function($){/* Shortcut for ready() */}) Each of these usages is detailed in the code example below. <!DOCTYPE html> <html lang="en"> <body> <script src=""></script> <script> jQuery(function($){ // Pass jQuery a function // Pass jQuery a string of HTML $('<p></p>').appendTo('body'); // Pass jQuery an element reference $(document.createElement('a')).text('jQuery').appendTo('p'); // Pass jQuery a CSS expression $('a:first').attr('href', ''); // Pass jQuery a DOM reference $(document.anchors[0]).attr('jQuery'); }); </script> </body> </html> Grokking When the Keyword This Refers to DOM Elements When attaching events to DOM elements contained in a wrapper set, the keyword this can be used to refer to the current DOM element invoking the event. The following example contains jQuery code that will attach a custom mouseenter event to each <a> element in the page. The native JavaScript mouseover event fires when the cursor enters or exits a child element, whereas jQuery's mouseenter does not. <!DOCTYPE html> <html lang="en"> <body> <a id="link1">jQuery.com</a> <a id="link2">jQuery.com</a> <a id="link3">jQuery.com</a> <script src=""></script> <script> (function ($) { $('a').mouseenter( function () { alert(this.id); }); })(jQuery); </script> </body> </html> Inside the anonymous function that is passed to the mouseenter() method, we use the keyword this to refer to the current <a> element. Each time the mouse touches the "jQuery.com" text, the browser will alert which element has been moused-over by identifying its id attribute value. In the previous example, it is also possible to take the this reference and pass it to the jQuery function so that the DOM element is wrapped with jQuery functionality. So instead of this: // Access the ID attribute of the DOM element. alert(this.id); We could have done this: // Wrap the DOM element with a jQuery object, // and then use attr() to access ID value. alert($(this).attr('id')); This is possible because the jQuery function not only takes selector expressions, it will also take references to DOM elements. In the code, this is a reference to a DOM element. The reason you might want to wrap jQuery functionality around a DOM element should be obvious. Doing so gives you the ability to use jQuery chaining, should you have need for it. Iterating over a set of elements contained in the jQuery wrapper set is somewhat similar to the concept we just discussed. By using the jQuery each() method, we can iterate over each DOM element contained in a wrapper set. This allows access to each DOM element individually, via the usage of the this keyword. Building upon the markup in the previous example, we can select all <a> elements in the page and use the each() method to iterate over each <a> element in the wrapper set, accessing its id attribute. Here is an example. <!DOCTYPE html> <html lang="en"> <body><a id="link1">jQuery.com</a> <a id="link2">jQuery.com</a> <a id="link3">jQuery.com</a> <script src=""></script> <script> (function ($) { $('a').each(function(){ // Loop that alerts the id value for every <a> in the page alert($(this).attr('id')); // "this" refers to the current element in the loop }); })(jQuery); </script> </body> </html> If you were to load the HTML in a browser, the browser would alert for the id value of each <a> element in the page. Since there are three <a> elements in the page, you get three iterations via the each() method and three alert windows. Extracting Elements From a Wrapper Set, Using Them Directly Without jQuery Just because you wrap jQuery functionality around an HTML element does not mean you lose access to the actual DOM element itself. You can always extract an element from the wrapper set and operate on the element via native JavaScript. For example, in the code below I am setting the title attribute of the <a> element in the HTML page by manipulating the native title property of the <a> DOM element. <!DOCTYPE html> <html lang="en"> <body> <a>jQuery.com</a> <script src=""></script> <script> (function ($) { // Using DOM node properties to set the title attribute $('a').get(0).title = 'jQuery.com'; // Manipulation of DOM element using jQuery methods $('a').attr('href', ''); })(jQuery); </script> </body> </html> As demonstrated, jQuery provides the handy get() method for accessing DOM elements at a specific index in the wrapper set. But there is another option here. You can avoid using the get() method by simply using the square bracket array notation on the jQuery object itself. In the context of our prior code example: This code: $('a').get(0).title ='jQuery.com'; Could become this: $('a')[0].title ='jQuery.com'; Both allow access to the actual DOM element. Personally, I prefer square bracket notation. It is faster because it uses native JavaScript to retrieve the element from an array, instead of passing it to a method. However, the get() method provides a slick solution for placing all of the DOM elements into a native array. By simply calling the get() method without passing it an index parameter, the method will return all of the DOM elements in the wrapper set in a native JavaScript array. To demonstrate, let's take get() for a test drive. In the code below, I am placing all the <a> elements into an array. I then use the array to access the title property of the third <a> DOM object on the page. <!DOCTYPE html> <html lang="en"> <body> <a href="" title="anchor1">jQuery.com</a> <a href="" title="anchor2">jQuery.com</a> <a href="" title="anchor3">jQuery.com</a> <script src=""></script> <script> (function ($) { var arrayOfAnchors = $('a').get(); // Create native array from wrapper set alert(arrayOfAnchors[2].title); // Alerts the third link }) (jQuery); </script> </body> </html> Notes: Using get() will end jQuery's chaining. It will take the wrapper set and change it into a simple array of DOM elements that are no longer wrapped with jQuery functionality. Therefore, using the .end() method cannot restore chaining after .get(). Checking to See if the Wrapper Set Is Empty Before you begin to operate on a wrapper set, it is logical to check that you have, in fact, selected something. The simplest solution is to use an if statement to check if the wrapper set contains any DOM elements. <!DOCTYPE html> <html lang="en"> <body> <a>jQuery</a> <script src=""></script> <script> if (jQuery('a').get(0)) { // Is there an element in the set? jQuery('a').attr('href', ''); } if (jQuery('a').length) { // Check the length of the set. Can also use .size() jQuery('a').attr('title', 'jQuery'); } </script> </body> </html> The truth of the matter is the above if statements are not totally necessary, because jQuery will fail silently if no elements are found. However, each method chained to any empty wrapper set still gets invoked. So while we could actually forgo the use of the if statements, it is likely a good rule of thumb to use them. Invoking methods on an empty wrapper set could potentially cause unnecessary processing, as well as undesirable results if methods return values other than the wrapper set, and those values are acted upon. Creating an Alias by Renaming the jQuery Object Itself jQuery provides the noConflict() method which has several uses-namely, the ability to replace $ with another alias. This can be helpful in three ways: It can relinquish the use of the $ sign to another library, help avoid potential conflicts, and provide the ability to customize the namespace/alias for the jQuery object. For example, let's say that you are building a Web application for company XYZ. It might be nice to customize jQuery so that instead of having to use jQuery('div').show() or $('div').show() you could use XYZ('div').show() instead. <!DOCTYPE html> <html lang="en"> <body> <div>Syncfusion., Inc.</div> <script src=""></script> <script> var Syncfusion = jQuery.noConflict(); // Do something with jQuery methods alert(Syncfusion("div").text()); </script> </body> </html> Notes:By passing the noConflict() function a Boolean value of true, you can completely undo what jQuery has introduced into the Web page. This should only be used in extreme cases because it will, more than likely, cause issues with jQuery plugins. Using .each() When Implicit Iteration Is Not Enough Hopefully, it is obvious that if you have an HTML page (example below) with three empty <div> elements, the following jQuery statement will select all three elements on the page, iterate over the three elements (implicit iteration), and will insert the text "I am a div" in all three <div> elements. <!DOCTYPE html> <html lang="en"> <body> <div></div> <div></div> <div></div> <script src=""></script> <script> (function ($) { $('div').text('I am a div'); })(jQuery); </script> </body> </html> This is considered implicit iteration because jQuery code assumes you would like to manipulate all three elements, which requires iterating over the elements selected and setting the text node value of each <div> with the text "I am a div." When this is done by default, it is referred to as implicit iteration. This is pretty handy. For the most part, the majority of the jQuery methods will apply implicit iteration. However, other methods will only apply to the first element in the wrapper set. For example, the jQuery method attr() will only access the first element in the wrapper set when used to get an attribute value. Notes:When using the attr() method to set an attribute, jQuery will actually apply implicit iteration to set the attribute and its value to all the elements in the wrapper set. In the code below, the wrapper set contains all <div> elements in the page, but the attr() method only returns the id value of the first element contained in the wrapper set. <!DOCTYPE html> <html lang="en"> <body> <div id="div1">I am a div</div> <div id="div2">I am a div</div> <div id="div3">I am a div</div> <script src=""></script> <script> (function($){ // Alerts attribute value for first element in wrapper set alert($('div').attr('id')); // Alerts "div1" })(jQuery); </script> </body> </html> For the sake of demonstration, assume your goal is actually to get the id attribute value for each element on the page. You could write three separate jQuery statements accessing each <div> element's id attribute value. If we were to do that, it might look something like this: $('#div1').attr('id'); $('#div2').attr('id'); $('#div3').attr('id'); // or var $divs = $('div'); // Cached query $divs.eq(0).attr('id'); // Start with 0 instead of 1 $divs.eq(1).attr('id'); $divs.eq(2).attr('id'); That seems a bit verbose, no? Wouldn't it be nice if we could loop over the wrapper set and simply extract the id attribute value from each of the <div> elements? By using the $().each() method, we invoke another round of iteration when our wrapper set requires explicit iteration to handle multiple elements. In the code example below, I use the $().each() method to loop over the wrapper set, access each element in the set, and then extract its id attribute value. <!DOCTYPE html> <html lang="en"> <body> <div id="div1">div1</div> <div id="div2">div2</div> <div id="div3">div3</div> <script src=""></script> <script> (function($){ // 3 alerts, one for each div $('div').each(function(){ // "this" is each element in the wrapper set alert($(this).attr('id')); // Could also be written: alert(this.id); }); })(jQuery); </script> </body> </html> Imagine the possibilities ahead of you with the ability to enforce iteration anytime you please. Notes: jQuery also provides a $.each function, not to be confused with the $().each method, which is used specifically to iterate over a jQuery wrapper set. The $.each method can actually be used to iterate over any old JavaScript array or object. It is essentially a subsitute for native JavaScript loops. Elements in jQuery Wrapper Set Returned in Document Order The selector engine will return results in document order as opposed to the order in which the selectors were passed in. The wrapper set will be populated with the selected elements based on the order each element appears in the document, from top to bottom. <!DOCTYPE html> <html lang="en"> <body> <h1>h1</h1> <h2>h2</h2> <h3>h3</h3> <script src=""></script> <script> (function ($) { // We pass in h3 first, but h1 appears earlier in // the document, so it is first in the wrapper set. alert($('h3, h2, h1').get(0).nodeName); // Alerts "H1" })(jQuery); </script> </body> </html> Determining Context Used By the jQuery Function The default context used by the jQuery function when selecting DOM elements is the document element (e.g. $('a', document)). This means that if you do not provide the jQuery function (e.g. jQuery()) with a second parameter to be used as the context for the DOM query, the default context used is the document element, more commonly known as <body>. It is possible to determine the context in which the jQuery function is performing a DOM query by using the context property. Below I show two coded examples of retrieving the value of the context property. <!DOCTYPE html> <html lang="en"> <body> <div> <div> <div id="context"><a href="#">jQuery</a> </div> </div> </div> <script src=""></script> <script> (function ($) { // Alerts "object HTMLDocument" in Firefox // Same as $('a', document).context; alert($('a').context); // Alerts "object HTMLDivElement" in Firefox alert($('a', $('#context')[0]).context); })(jQuery); </script> </body> </html> Creating Entire DOM Structure, Including DOM Events, in a Single Chain By leveraging chaining and jQuery methods, you can create not only a single DOM element, but entire DOM structures. Below I create an unordered list of jQuery links that I then add to the DOM. <!DOCTYPE html> <html lang="en"> <body> <script src=""></script> <script> (function ($) { jQuery('<ul></ul>') .append('<li><a>jQuery.com</a></li><li><a>jQuery Documentation</a></li>') .find('a:first') .attr('href', '') .end() .find('a:eq(1)') .attr('href', '') .end() .find('a') .click(function () { return confirm('Leave this page?'); }) .end() .appendTo('body'); })(jQuery); </script> </body> </html> The concept you need to take away from the previous example is that jQuery can be used to craft and operate complex DOM structures. Using jQuery methods alone, you can whip up most any DOM structure you might need.
http://code.tutsplus.com/tutorials/core-jquery--net-33755
CC-MAIN-2014-35
en
refinedweb
You cannot redefine a static method by inheritance, but you will often want to provide a test implementation of static methods (which include the 'new' operator). A tool like PowerMock does allow for the redefinition of static methods, but if you don't get along with it, you can still work around the issue: if you're using dependency injection, you can write trivial classes to wrap static methods and substitute them with little intrusion into your code. If you're not using real DI (due to the start-up time, for instance), the following may help you start. If you decide to stick with this manual DI, you may find that certain methods (particularly Android ones) turn up regularly enough in different classes' tests to make it worth creating an external non-static utility class to inject. There'd be a temptation to let this grow into a grab-bag class containing all the statics you have ever needed (which probably isn't a problem beyond being a sprawling mess and potentially concealing that a class under test is doing too much), but you would want to guard against the temptation to sneak in things which aren't strictly statics "because it's a handy singleton in which to hide a bit of state" (which would be wrong). If you're a fan of 'single responsibility', you'll see that this StaticInjection should really be broken up into separate chunks - the beginnings of proper full-scale DI (albeit static DI, rather than the dynamic style of Guice etc.). Code under testEdit Adding an inner class allows you to provide default behaviour in a production environment, but special behaviour in tests. The example shows that it's not just Android that likes declaring methods static. /** * Activity that does something with a Facebook token. */ class MyActivity extends Activity { // Indirect static method calls, including 'new' for complex objects, to this class. static StaticInjection STATIC_INJECTION = new StaticInjection(); StaticInjection staticInjection; // Default constructor creates default StaticInjector public MyActivity() { this(STATIC_INJECTION); } // Non-default constructor for tests wishing to inject other implementations. // If your tests are package-scoped, don't make this public. MyActivity(StaticInjection staticInjection) { this.staticInjection = staticInjection; } // Your unit tests can invoke this; you will need Robolectric or similar to do that on the development machine. public void onCreate(Bundle bundle) { super.onCreate(bundle); String fbToken = staticInjection.sessionStoreGetAccessToken(this); Application app = staticInjection.getApplication(this); DooDad doodad = staticInjection.newDooDad(this, bundle); // use these in some way you can test } // Add any additional static stuff you need to stub out for your tests here. public static class StaticInjection { public String sessionStoreGetAccessToken(Context context) { return com.facebook.android.SessionStore.getAccessToken(context); } public Application getApplication(Activity activity) { return activity.getApplication(); } public DooDad newDooDad(Activity activity, Bundle bundle) { return new DooDad(activity, bundle); } } } If you find your StaticInjection class growing too much, you're probably doing too much in your Activity - try to follow the 'single responsibility' principle. TestEdit A test would either subclass and override bits of StaticInjection, or use mocking to constrain which bits of the StaticInjection were used: @RunWith(RobolectricTestRunner.class) public class MyActivityTest { @Rule public JUnitRuleMockery mockery = new ThreadSafeJUnitRuleMockery.WithImposteriser(); MyActivity activity; @Mock Bundle bundle; @Mock Application application; @Mock DooDad dooDad; @Test public void _onCreateAccessesFacebookToken() { MyActivity.StaticInjection injection = mockery.mock(MyActivity.StaticInjection.class); mockery.checking(new Expectations() {{ oneOf(injection).sessionStoreGetAccessToken(activity); will(returnValue("NotReallyAToken"); allowing(injection).getApplication(activity); will(returnValue(application)); oneOf(injection).newDooDad(activity, bundle); will(returnValue(dooDad)); }}); activity = new MyActivity(injection); activity.onCreate(bundle); // no asserts needed here: mockery will check that sessionStoreGetFacebookToken has been called once. } } MiscEdit The above example depends on these trivial classes: import org.jmock.integration.junit4.JUnitRuleMockery; import org.jmock.lib.concurrent.Synchroniser; import org.jmock.lib.legacy.ClassImposteriser; /** * Mock with extra magic stuff, use ThreadSafeJUnitRuleMockery.WithImposteriser, * or split the classes out and rename the inner one to something sensible. */ public class ThreadSafeJUnitRuleMockery extends JUnitRuleMockery { private ThreadSafeJUnitRuleMockery() { setThreadingPolicy(new Synchroniser()); } static public class WithImposteriser extends ThreadSafeJUnitRuleMockery { public WithImposteriser() { super(); setImposteriser(ClassImposteriser.INSTANCE); } } static public class WithoutImposteriser extends ThreadSafeJUnitRuleMockery { } }
http://en.m.wikibooks.org/wiki/Android/Testing/Unit_Testing/Injecting_Static_Methods
CC-MAIN-2014-35
en
refinedweb
Details of MSFT's Antitrust Lobbying 711 An anonymous sent in linkage to "A new ZDNet article detailing new evidence presented to the judge presiding over the Microsoft anti-trust case. It shows that Microsoft made political contributions during last year's (well, 2000's) elections on a scale never seen before... over $6 million. As comparison, this is four times the amount spent by Enron. It also reveals that Microsoft has been hiring every political lobbyist, and every law firm, with anti-trust expertise and putting them to work on unrelated projects- anything to make them unavailable to work for critics of Microsoft." And, we have no one to blame but ourselves. (Score:5, Interesting) We elected the politicans who made the laws in the first place which allowed campaign contributions to be illegal. Infact, during the last election, we didn't want the guy who was willing to do away with them. We wanted to play Bush vs. Gore instead. Before you run off pointing fingers at Microsoft for doing what they are within the scope of the law to do, ask yourself where the core of the corruption sits. Its not with them, or the politicians. Its us, and our lack of desire to make our elected officials accountable for their actions. Lobbying wouldn't exist if we as a people decide not to allow it. Anything beyond it would be bribery. Cheers, Re:And, we have no one to blame but ourselves. (Score:5, Insightful) If the Federal government were actually limited in scope (refer to Constitution here), then there would be a lot less to lobby for, to "contribute soft money" for, etc. I would like to not only limit the power of the government, but prevent lawyers from holding office. Re:And, we have no one to blame but ourselves. (Score:3, Insightful) This is dead on. I do not underastand those who say that the answer to bad ans stupid laws are is more of the same. People will bribe governments so long as governments have the power do something for them. Re:And, we have no one to blame but ourselves. (Score:2, Insightful) And when the government does not have any power anymore, we will have to bribe whatever entity governing instead of the government. I prefer to pay tax than "microsoft tax" or mob "protection" tax. Re:And, we have no one to blame but ourselves. (Score:3, Insightful) True but would you rather the bribes that polititican take be legal, as they are now, in the form of "Soft Money"? Or would you rather the that the dishonest people in government really act like crooks and be forced to solicit and accept illegal bribes? I would much rather see that we call it what it is (a bribe) and treat it that way, then wave our arms and declare that the real problem is elsewhere. Yes I understand that this is not to the point of the original argument, that government is to big and must be reduced, but change will most likely be incremental and not all at once. Let's take our victories where we can. Re:And, we have no one to blame but ourselves. (Score:3, Insightful) The Justice system is so bogged down that Congress can pass laws that they know will not be repealed by the Justice Department for years (when they can claim it was their predecessors who passed it in the first place). The President has become more of a figurehead than the Queen of England. What is even worse is that there is so much childish, partisanship in Congress that nothing ever gets done except when they have a common goal which is usually to benefit the corporate giants that line their pockets. Re:And, we have no one to blame but ourselves. (Score:3, Informative) I do agree about the childish partisanship, except that I get the feeling that it's all a ruse to distract us from noticing that common goal you mention. (lining their pockets w/ corporate money) Re:And, we have no one to blame but ourselves. (Score:2, Informative) No, the real - the only - remedy to this crisis of democracy is to curtail the financial power of the lobbies and private donators. Here in Quebec we had campaign financing reform thirty years ago, placing severe limits on how much politicians can receive from companies and individuals, and it has greatly enhanced the integrity of the political class. Sure, nothing's perfect, but it's still a lot better than it was before! Cutting out the source of evil, i.e. lobbies and companies "buying" influence (when that influence should come from the citizens alone if representative democracy is to be, well, democratic) by putting severe caps on campaign contribution is the simplest yet most efficient way to clean up Washington of its grimy layer of corruption. Well, the first layer, at least. If you don't think that's true, then ponder why most of the political class spends so much effort preventing this from happening... Re:And, we have no one to blame but ourselves. (Score:3, Insightful) So when you reduce the power of the federal government... where does it go? I seem to recall that the early power struggles in our countries infancy were primarily federal government vs. state governments. If more power were granted to the states, Microsoft and other corporations would merely switch their focus to brib^H^H^H^H contributing to state and local officials (Not that they're overlooking them now, mind). Re:And, we have no one to blame but ourselves. (Score:3, Informative) You act as if the government is some kind of third party in our lives like a referee in a football game. Ostensibly, the government is us . . . "We the People." So by advocating the reduction of the power of government you're advocating a reduction of the power of the people. I take that personally as I am one of those people. The people of the United States of America are already on their knees bowing to the power of the corporation. Why would you advocate reducing our only means of defending ourselves from exploitation? We the People! Re:And, we have no one to blame but ourselves. (Score:3, Informative) Your argument that Libertarians are in favor of reducing power is simply incorrect. I want my locally elected official to have the power that he/she should have as written in the Constitution. *I*, personally, want to power to decide certain things about my life, leaving the goverment out of those decisions. As a result, these powers need to be taken away fro the federal government. This is not a *reduction* in power, but a reallocation. The entire start of this thread was that if you reduce power to the federal government, you reduce power to corporations to bribe those same individuals. Your argument that we need a overly-protective federal government to protect us from those same corporations is exactly opposite to that thinking and the evidence pointed out in the original article. As for everyone arguing that moving power to the states will only mean that MS will resort to bribing them - remember who it is pushing for a weak settlement (Department of Justice and the White House) and who it is pushing for more extreme measures (the states and the states' Attorney Generals). This is direct evidence against that claim. Re:And, we have no one to blame but ourselves. (Score:3, Insightful) Re:And, we have no one to blame but ourselves. (Score:4, Interesting) I live in Switzerland which is a true democracy. In Switzerland every person has the right to vote yes or no to certain decisions. The government is only there for the details. Sure Swiss vote quite a bit, but the power is with the Swiss people and only the Swiss people. And in that case lobbying has absolutely no effect unless of course the lobbyists decide to give money to each Swiss. True democracy works and it should be used more often in other countries. Re:We have no one to blame but our dollars (Score:3, Insightful) Putting everything under the control of "one person, one vote" is simply mob rule. Democracy should have limits, as should every form of government. Having an all-powerful central government, but making it "democratic," does not change the fact that it's still an all-powerful central government. It just means there's more people to bribe. Re:And, we have no one to blame but ourselves. (Score:3, Insightful) When the government gets out of the tax-regulate-and-subsidize business, and sticks to preventing and punishing theft, injury, etc., then it will be performing its proper role. As long as a corporation can buy an advantage in the marketplace -- including shielding itself from liability -- then there will be a place for lobbying, bribes, etc. Would you prefer a corporation, with no obligation to listen to you, make important choices for you Absolutely not. I'm in favor of stripping corporations of their legal personhood, actually. I believe that campaign finance reform is in itself at least a start to solving many of these sorts of problems. Hmmm. Not really. It just stirs the pot a little. Strip corporations of their personhood, so they have no first amendment rights, and prohibit them from engaging in any political activity. I.e., make it the way things used to be. Re:And, we have no one to blame but ourselves. (Score:2) Excuse me? Have you seen what happens when capitalism is allowed to run unregulated? Enron? Microsoft? Standard Oil? Unregulated capitalism is far worse than regulated government - at least with the latter you know who's in charge. Re:And, we have no one to blame but ourselves. (Score:4, Insightful) Regulation is, like it or not, extending punishing of theft and injury laws to companies. Regulating companies stops them from harming their workers, their neigbours, their customers because they can. It also stops them from doing violence to other companies - which, let's be honest, is exactly what MS is currently on trial for, using its strength to force other companies out of the market or their products onto customers at nasty terms. You actually contradict yourself. To quote, "As long as a company can buy an advantage in the marketplace Subsidies are a harder argument, but here goes... Remove subsidies of all kinds (I'm including Social Security benefits here, they seem analagous) and you cause problems. You know all about needing money to make money? Well, how do you get that first step without money from _somewhere_? Anyway, you create people who simply can't earn a living (and where this isn't necessarily a permanent condition), so they either die or live from crime. Think what happens in a recession here - the very poorest either die or cause a crimewave. A crimewave causes clear problems for society as a whole, and ends up with a number of them locked up. So, what do you end up with? A larger prison population (expensive to maintain) and a smaller labour force, which pushes up wages and makes it harder to get ourt of recession. Eventually, you end up with smaller economic capacity this way because you simply don't have the workers you need. Whereas if you give them the money / resources they need to see out the recession, they remain economically active throughout the problems (so help maintain economic capacity) and are available to work afterwards, so keeping costs down due to a large labour force. Oh, you've also likely lost the majority of the crime which is good on its own but also reduces your expensive-to-maintain prison population. Or maybe health benefits. If the poorest can't get treatment then you have an increased potential for epidemic which can spread into the wider population. They're not likely to be particularly healthy to start with (worse diet & living conditions, can't afford better) so they're more susceptible, plus the poorer sections of society tend to live together, helping it spread quickly among them. Deny them medical treatment and ailments can run through them at ridiculous rates, then spread into the wider population. Also, deny them medical treatment and some will die, some will be disabled in some way and some will have to miss work. In each case you've removed someone from the available cheap labour pool, maybe others who now have to care for them too... What about subsidising companies? Well, statistically speaking, I understand that the major driver for economic growth is small companies, not large. Except that they can't exist without seed capital from somewhere... Remove government subsidies and some won't survive, so lower economic growth as a whole. Or another example, farm subsidies. The EU Common Agricultural Policy is a mess, I won't deny it. However... In the UK, we have many areas where sheep are farmed on open hillsides traditionally. These are only viable due to subsidies, because the animal densities are too low. Remove the subsidies and the sheep go. Remove the sheep, though, and the land quickly becomes covered in long grass and bracken. At which point it's considered less beautiful and is certainly less suitable for walking. You then have no farming income - and an area that only has tourism left, but can't any more attract people to look at the views and walk the hills because the environment has changed. You need the sheep as lawnmowers... The current system is a long way from being perfect. Heck, I'm a LibDem () so I'm working to change it in many ways. But, strangely enough, many of the current aspects of government have been set up because they look like a good idea and retained because they prove that they are a good idea! I'd LOVE to see corporations stripped of legal personhood, too, for example, and see no reason for them to make any political donations. Heck, while we're thinking about corporate political influence, it seems daft that sitting legislators can hold directorships in companies, or that individual companies can own large chunks of the news media. Or that foreign-owned companies can own any. Who says that an Australian run media isn't spinning the news to favour Australian interests over local? As you can see here, we have clear examples of corporate political speech needing legal controls to benefit the people... Posters in general and moderators in particular, _please_ think a little harder about this 'smaller government rules' (whoops, pun unintentional...) argument. It may sound good - and some of it may indeed be good - but look at the details and much of it is utter rubbish. Really. Re:And, we have no one to blame but ourselves. (Score:2, Interesting) Being a politician should be a volunteered public service, and no one should ever be allowed to make any money from doing such work. This would remove the "career politicians", cut down on cost (no salaries for them) and would force them to still be a working constituent as well as a politician. Making a career out of politics is simply sickening Re:And, we have no one to blame but ourselves. (Score:4, Insightful) That would create a class based government system (as if it isn't already). Because then only rich people could afford to serve the government, because the working class would have to work to eat. Re:And, we have no one to blame but ourselves. (Score:2) Re:And, we have no one to blame but ourselves. (Score:5, Informative) Have any of you American I couldn't blame MS for this. They are just playing the game, and playing it well. Re:And, we have no one to blame but ourselves. (Score:2, Insightful) The problem is with those who take the money, as you said. Anybody who believes that the current campaign finance reform crap (I have to call it what it is) is going to do ANYTHING, just think again. Whenever the recipients, namely the politicians have tried to 'clean it up, for the good of everyone', all that happens is the balance shifts around and loopholes are found. Heck, soft money didn't exist before the much touted Watergate reform! Can I fault Microsoft for doing stuff like this? Probably, this is For as long as Congress can make laws regulating what they cannot do, this problem will always exist in one form or another! That's life. Re:And, we have no one to blame but ourselves. (Score:5, Insightful) This is not directed to the poster per se but to all who carp along these lines, in increasing numbers today: Oh, whine whine whine. Of course people are going to find loopholes. Of course money will creep in again. Of course new dastardly means of influence peddling will be found. How absolutely fratzen stupid is it to throw up your hands and say, "Oh, well, the system can't be made perfect so we shouldn't even try to improve it." If new loopholes arise, plug them. Plain and simple. Yes, you'll actually have to keep figthing this battle. Yes, it will be honest-to-God actual work to be a member of a democracy. Horror of horrors. Stop bemoaning the lack of perfectibility. It doesn't get us anywhere and it actually impedes what progress can be made. Re:And, we have no one to blame but ourselves. (Score:2, Interesting) So they could say they were supporting one party over the other because they thought it's policies would benefit them. But in general companies (in the US and the UK) support both main parties. So either they are doing this without expecting anything in return (which is wasting shareholders money), or they are expecting to gain something for their money (which is bribery). So how is this legal?? Re:And, we have no one to blame but ourselves. (Score:2) Re:And, we have no one to blame but ourselves. (Score:2) Re:And, we have no one to blame but ourselves. (Score:2) Gore was one of the guys willing to do serious campaign reform. Re:And, we have no one to blame but ourselves. (Score:2) Besides...as has been pointed out elsewhere, bureaucrats work in CYA mode, and overwhelmingly prefer one kind of error (giving thumbs down to something that is worthwhile) to the other (approving something that later turns out to be bogus). How many people have died prematurely because of that? Enron? (Score:3, Insightful) So? What does Microsoft have to do with Enron? Oh, I get it..It's popular to bash Enron right now. More to the point, what did you expect MS to do? Suddenly start playing fair? Oh, you got me, here's where I hid the bodies, etc.? Please. Re:Enron? (Score:3, Informative) 1. It has recently become a very well known entity. 2. It was also large and had lots of money. 3. It spent quite a bit of money lobbying. 4. It puts people in the mindset the article is looking for. Re:Enron (Score:5, Insightful) Currently, Enron is the posterchild for the reason for campaign finance reform. If our politicians are swayed by the campaign contributions of Enron's scale, what corruption is seeded by a larger sum of money? If the advertising power of the campaigns is knocked askew by some soft money, isn't it knocked asunder by larger sums? For a few stories linking Enron to campaign finance, you can look at this topic list on Salon.com [salon.com]. The topic is campaign finance. The headlines mostly discuss Enron in recent weeks. Re:Enron (Score:2, Informative) Yet another reason... (Score:4, Funny) This news probably doesn't surprise too many people in this crowd, I think we all knew that MS was pretty generous with soft monies, but it's very nice to see an article like this. The best part of the entire article? The paragraph about the $25k given to buy off South Carolina's Attorney General. P.S. Anyone else amazed by the fact that there is a place called Chevy Chase, Maryland?! Re:Yet another reason... (Score:2) And that someone MS worked/lobbied there? their 2001 site says:: "he Village contains about 200 single-family residences and a few religious and professional establishments." Re:Yet another reason... (Score:3, Insightful) One way to build the party is to run "issue ads". For the uninitiated, "Bill Clinton blows goats. Al Gore says Clinton is the best President ever." is an issue ad. On the other hand, "Bill Clinton blows goats. Al Gore says Clinton is the best President ever. Vote Gore." is supporting a political candidate, and thus is subject to hard money limits. Now, on the one hand, the regulation of this spending means that there is no way that I could take out an ad saying "Vote for " on TV, because it's more costly than the rules allow. (This is blatantly unconstitutional.) On the other hand, I could take out an ad saying " is a total wad" and I'd be perfectly legal. Political parties can also take out such ads. So you want to ban "soft money". Sorry, you can't. The Supreme Court has already held that "money is expression" in that preventing someone from airing their views violates the first amendment. The Shays-Meehan (sp?) bill would instead ban unregulated contributions to political parties. There would be no prohibition on companies, unions or PACs running all the issue ads they want, or all the get out the vote campaigns they want, on behalf of a party, so long as the party does not direct their activities. Could somebody explain to me how preventing one body of private citizens (a political party) from doing something, while allowing another (say, a PAC) to do that thing, would be constitutional? It smacks of a bill of attainder, and certainly violates the first amendment in the event that what's being prevented is the expression of political views. It seems to me that the better way to handle election finance issues is to require all money used for political purposes to be disclosed, and to prosecute those guilty of influence peddling or accepting bribes. In most cases, it won't be clear cut, but it would certainly be possible to recall politicians who are abusing their office by acting on behalf of those who spent money for them. And realistically, what would probably happen is that candidates would get more money directly, and outside spending would decrease. -jeff Re:Yet another reason... (Score:2) Why? It was there first. In fact, Chevy Chase the comedian probably named himself after it; his birth name was Cornelius Crane Chase, you know. Chris Mattern Re:Yet another reason... (Score:3, Interesting) Not all of these groups want the government to line their pockets, they have issues that they want addressed and they to influence how they are addressed. That is what democracy is about, and since there is a first ammendment the government is not going to tell us that their views should or should not be listened to Comment 3 million! (Score:3, Interesting) A contrarian viewpoint. (Score:5, Interesting) The candidates take the money and use it to buy ads so they can reach the public. This is not a serious problem, it's what comes after that is a serious problem -- the quid pro quo that the donor expects. So the problem is not money, it is the influence of people who have money. Making money harder for candidates to raise doesn't mean the need for money goes away -- quite the contrary. The candidates have to work harder for every dollar. The marginal value of every additional dollar raised is higher to the candidate because of the general scarcity of funds. On the flip side, the cost of buying influence drops. Let me propose this law of political fundraising: As proof, let us suppose that Enron and Microsoft succeeded in buyin our federal government for a few paltry millions. This is unconscionable! It should cost billions to have this kind of influence; influence buying should require bribery on such a grand scale it either prices people out or requires a brazeness so affronting to the common votor that it becomes self defeating. We should also repeal the notion that corporations are persons with respect to campaign contributions -- it's a legal invitation to bribery. Re:A contrarian viewpoint. (Score:3, Insightful) It's especially disgusting when you realize the actual costs to us collectively. For a few millions, corporations buy their way into legal tax and accounting loopholes and exceptions worth TENS OF BILLIONS of dollars. It's estimated that there are at least $50bn in taxes uncollected due to shuttling profits to offshore holding companies. I think the "economic stimulus package" Bush proposed gave almost that much away to a few big companies like IBM. It is also quite common for companies like Pepsi(!) to use "restructuring" to avoid paying any income tax. It would be cheaper to pay all of our Sentators and Congresspeople a million dollars a year and give a million dollar government sponsored budget to every candidate with more than 25% poll numbers in every race for each seat than to keep the current system of influence peddling. Hell, if you paid people that much, you could even forbid them from working after they retire and avoid the corporate board/Presidential cabinet recycling loop that is an even bigger bribery scam than campaign contributions. I hope the mainstream press picks this up (Score:3, Informative) Hopefully this will get picked up by the AP or something. I mean this alone in most people should arouse serious feelings of mistrust for any company. Microsoft makes software. It shouldn't even be making *any* sorts of political contributions or anything. I seriously doubt that within three weeks the attorney general had suddenly decided MS wasn't violating any laws without persuasion If, at the very least, this and the enron scandal should be a wake up call for americans to consider political party financial reform. Re:I hope the mainstream press picks this up (Score:2, Interesting) What was Condon's track record before? If Condon expected (as I imagine) to be softer on monopolies, then of course Microsoft would support him and then he would act his conscience and support the comprimise. What about other people who received contributions? Did they behave differently than expected once they received the contribution? Most "buying" of politicians is buying of elections (not all, however). If the public would vote properly, I would argue, this would not be a problem. Unfortunately, advertising works, especially against news outlets. This just in....Microsoft spent MONEY!!! (Score:4, Interesting) Yeah, it's underhanded, maybe even a bit immoral, the problem is, *IT'S NOT ILLEGAL*!! Both sides are throwing money at this, unsurprisingly MS is throwing more. First off, it would be a violation of their fiduciary responsiblities if they didn't defend themselves as vigrorously as possible. Heck, they've already crossed the line of good taste/credibility in their PR and lobying campaigns in the past, why stop now? If we really want to do something about activities like this we need to correct the current political system. Now, I'll just remain in the legions who complain about it and don't have a good solution (the problem is WAY beyond my meager geek abilities to grok). The one item of interest I have heard is that the current proposed reforms may have allowed people to donate MORE money instead of less. We vote with our pocketbooks, Microsoft votes with its. They just happen to have a slightly bigger one. Finally, it's ironic that the concept of "free" speech is used to defend monetary contributions... Re:This just in....Microsoft spent MONEY!!! (Score:2) Re:This just in....Microsoft spent MONEY!!! (Score:4, Interesting) While it is not illegal, it is the reason for the Turney Act. If it can be shown they were using their money to influence the outcome of the penalty phase of the trial, the judge must consider it before accepting the agreement. In fact, it would be a reason to force the government to go back and renegotiate, or if the judge considered any outcome between the parties tainted, she could enforce her own. Based on past statements from her, I question if this formality has any influence at all. But, I want to give her the benefit of the doubt. It is not a perfect system, but it is a second check of the process. [IANAL--YMMV] Accountability (Score:2, Redundant) You think the US government would decline contributions from any and all companies who have had their questionable business behaviour legally challenged. Kinda makes sense, no? A lot like convicts being unable to cast a vote. Re:Accountability (Score:5, Informative) In this case, Microsoft had been challenged, but not yet convicted. Ever hear of a little concept known as "Innocent until PROVEN guilty"? Were this not the case, simply waging unfounded allegations against any person or company could (and likely would) impact that entity strongly for the worse. Um, no, in the antitrust suit, Microsoft has been found guilty and that ruling has been upheld on appeal already. It is just the forms of remedy, the corporate equivalent of sentencing the convicted criminal, that is of question now. Re:Accountability (Score:4, Interesting) I was not suggesting that Microsoft's campaign funding and lobbying to this date has been illegal; in fact, it's quite legal but increasingly repugnant to the citizenry who wants fair elections in the future. However, if a convict cannot vote, perhaps it is time to say that a convicted monopolist corporation cannot contribute money for some term. For whatever reason, a corporation is in all senses an individual in our law. The punishments for breaking corporate laws should be such that they restrict the otherwise granted rights. No free speech campaigning, no lobbying, no tax break incentives in new properties, no sealed oem contracts, pick an appropriate level of restrictions for the conviction. What did Enron's money get them? (Score:2) Some people would consider giving large amounts of money to people with the potential power to ameliorate your legal troubles bribery -- luckily for Microsoft no-one considers this to be the case here. A sad statement on the American political system, as far as I'm concerned. An experiment (Score:2) *Simply Shocked* (Score:4, Funny) right Of course you realise, this is the Microsoft philosophy applied to the legal field. Microsoft has had a history of buying up tecnologies and expertise, many of which have simply disappeared, never to see the light of day again. It is perhaps the only real innovation that I know of, to take their billions and buy up anything their legal opponents could use to convict them of their crimes. I am sure other big companies are taking notes. This convicts them even more in my mind. Like I have said before, every time I turn around there is something else that comes out and dirties their reputation in my eyes. Heck, if PR LapDogs like ZDNet are taking shots at MS, you know rats are starting to leave the ship. Re:*Simply Shocked* (Score:2) Legal DoS? (Score:2) "You have to watch the violence Lisa.. Else you'll never become desensitized to it" -- Bart Re:Legal DoS? (Score:2) 1. Sign the band to a long term, exclusive contract. 2. Take away all their rights to publish, record, and tour, without the label's explicit approval. 3. Find a new band to screw over. This is totally common. The industry refers to it as "building a stable of artists". I'm sure it happens in lots of other places, too. Legal context (Score:2) Say I have a legal issue with someone.. I 'retain' the best lawyer in town.. Now, my legal adversary can't use that lawyer because it would be a conflict of interest for the lawyer to take up that commission.. But I'm not actually using the lawyer.. I'm paying a lower fee, to 'retain' him, to have him available if I want.. It's really rather brilliant. Balls the size of Washington (Score:3) Now that's ballsy! Re:Balls the size of Washington (Score:2, Funny) Wasted money... (Score:3, Insightful) What a waste of resources. The United States Government (Score:5, Insightful) The real problem here is the idea of "corporate personhood" which extends all the civil rights meant for people (including buying congressmen, senators, presidents and supreme court justices) to corporations. individual people, and and not-for-profit groups can not compete with the cash generated by a large corporation. there is one easy solution to this (unfortunately, it's not easy:). make all elections 100% publicly funded (I believe that england does this and each candidate can only spend something like 10,000 pounds), ban any political advertizing by any non candidate which mentions, depicts or hints where a particlar candidate or party stands on an issue. Re:The United States Government (Score:2, Interesting) Behind every rich corporation is a bunch of rich people with a shared income source and each other's cell phone numbers. Making these people do things as coordinated individuals instead of a corporation will change nothing. make all elections 100% publicly funded (I believe that england does this and each candidate can only spend something like 10,000 pounds), ban any political advertizing by any non candidate which mentions, depicts or hints where a particlar candidate or party stands on an issue. So, force people to vote by how tall the politician is or how easy to remember his name is? Paid issue advertising is a good thing, it lets people know what a politician's history/position on an issue is, because the conventional media sure isn't any help there... -- Benjamin Coates Re:The United States Government, now with XP (Score:2) And you thought the posters at the post office were just advertisement. Re:The United States Government (Score:4, Insightful) Whoo-hoo! Vindication! Proof! If you read the article, it ends making my point: . " So the CORPORATION of M$ which is actually Gates, gives its money and holds positions counter to the vast majority of its own employees. A corporation cannot have rights, only INDIVIDUALS have rights. This corporation, like virtually all such monsters, does NOT hold legitimate points of view, it only presents the point of view of the CEO/President, or (some) board members while the majority of what makes up the corporation is ignored. Mantra: Only individuals have rights, not corporations. Corporations are NOT people. this is very common (Score:2) Re:this is very common (Score:3, Insightful) Corporations (Score:4, Insightful) The problem is that when a politician is elected due to large campaign contributions, he can't help but think that the contributions put him there rather than the votes of the citizens. He is elected, supposedly, to represent the needs of the citizens, but instead he ends up feeling like he is elected to represent the needs of his financiers (even an individual with good moral fiber will have this difficulty). A politician "should" be concerned first and foremost about how each decision will impact a private citizen. For example, how will DMCA impact the average consumer (loss of their fair use rights), how will extension of copyright laws affect the average individual (they will have access to no new public domain material in their lifetime), etc. It is getting to the point that the individuals need to hire lobbyists to plead their case with the politicians. Except that the politician was hired in the first place to be our lobbyist. Campain reform, not Campain finance reform... (Score:5, Interesting) Consider first why candidates need the huge amounts of money to be elected. They in effect need to run two entirely different campains - once for the primary, and once for the election. As a result, the cost more than doubles. Now, the thought is that once they've won the primary, their party will contribute to the main election. This is true but irrelevant to this discussion: the party must raise the money, and thus the need for money still is doubled. Now, I assert that anytime there is a demand, there will be a supply. Consider the origins of soft money - in the old days you could directly support your candidate with any amount of cash you wished. This was deemed a bad thing and so limits were placed on direct contributions. Bang - you now have created "soft money" that doesn't get covered under the hard money laws. Do you really expect that as long as candidates need money they won't find a way around soft money? And realize this: if you put up a piece on your personal web page about how you feel candidate X is [good|bad], that can be considered a "soft" contribution. Do you really want to give the government that power? Now, consider the 2000 elections. They were very close - so close that the actual vote difference between the candidates was lost in the noise floor. Was this really because the people were split 50/50 in liking Bush and Gore? Most people who voted for [Bush|Gore] did so because they disliked [Bush|Gore] marginally less than they disliked [Gore|Bush]. I assert that we need to make the following two changes to the system: 1) Allow anybody registered to vote to vote in any primary. 2) Require a binding "none of the above" entry on all elections. Let's examine the results these two changes would have had on the 2000 US presidential election: 1) By allowing anybody registered to vote in any primary, we would de-emphasize the importance of the primaries and pull the results of the primaries back from the extremes. I doubt that Bush would have won the Republican primary, and I doubt that Gore would have won the Democrat primary. Additionally, candidates such as McCain would have had a much better chance of getting support. 2) By having a binding "none of the above", even if the election had been Bush/Gore, the bulk of people could have voted None Of the Above. Had None Of the Above won, then NOBODY in that election could hold the office, and there would have to be a new election. Ask yourself this: no matter your political affiliation, if you could have had a chance to block both Bush and Gore in favor of a shot at a better candidate, would you? I assert that with these two changes, the following things would happen: 1) The third party candidates wouldn't run in the first race. Instead, they would encourage the voters to vote NOTA in the first race and knock the big boys out. 2) The big parties would no longer be able to take this "This is our guy, take it or leave it" attitude. Thus, they would tend to field more moderate candidates. 3) Because of 1 and 2, more people would feel their vote mattered, and we would get more turnout. 4) Because the primaries could no longer be used to limit our choices, they would become unimportant and would fad away. Remember - the primaries are entirely outside the election process as described in the Constitution. Now, I don't assert that these changes would prevent lobbying by corporations. However, if a party knew that they could no longer annoint a golden child in the primaries and force them down our throats, they might be more aware of how the PEOPLE feel about an issue, rather than MONEY. Discussion? Re:Campain reform, not Campain finance reform... (Score:2) Re:Campain reform, not Campain finance reform... (Score:2) Microsoft... a big disappointment (Score:2, Interesting) Instead of creating quality software that people would use because it is the most secure, efficient and capable software... they choose to write utter crap... and they hire marketers to tell us it's gold... hire political lobbiests to force policies and judicial decisions in their favor. When I started out in computing 26 years ago I never conceived that we would be as backwards as we are today. I never dreamed we would require a 1 gigahertz machine to run a windowing system poorly.... I never thought that instead of booting faster... that machines would boot slower and slower. Extremely disappointing that a marketing/political interest group has been allowed to pretty much destroy the computer industry. I guess we can hope and pray that MicroSoft goes the way of Enron... that it's dirty dealings are opened up to the world and that the world responds by simply refusing to have anything to do with the MicroSluts. Re:Microsoft... a big disappointment (Score:3, Interesting) 26 years in computing, you must be pretty old yet you don't seem to know that every big company gives huge contributions in order to avoid lawsuits. How did MS destroy the computer industry? They created it. Re:Microsoft... a big disappointment (Score:2) This is a common myth. MS has contributed almost nothing to the computing industry, certainly much less that the damage it has done by stiffling innovation and creativity by giving jobs to literally tens of thousands of shit programmers who would be unemployable in an industry where quality control existed. Flood the market with garbage and you end up with a garbage market. I don't know of a single thing MS has produced that didn't either suck (Windows, Outlook etc) or come from another company that they bought and released before making later versions suck (Flight Sim, Word etc.). I've been programming for 26 years and MS has done nothing except make life harder for people who want to produce quaility, working software that does its job by showing that such an attitude is unimportant in the face of marketing blitzes for crap products that don't work. The computing industry of 25 years ago was doing just fine without MS. Sure, IBM had a big grip on the business end of things but that was comming to an end as people like Lotus started up. IBM and Apple then helped MS by various insane business decisions and the rest is history. TWW Re:Microsoft... a big disappointment (Score:2) Stealing ideas? Are you still at school? every company does that, from television shows to cars. Besides, I thought that the GPL philosophy was all about not reinventing the wheel, using other peoples ideas and improving upon them. Look at Mandrake, they took a good Linux distribution and made it even better. Re:Microsoft... a big disappointment (Score:2) "Sure computers did exist, but Bill Gates brought them to the people." Really ? You think nobody would be using computers if Microsoft hadn't existed ? How do you figure that one out ? "Stealing ideas? Are you still at school? every company does that, from television shows to cars." Some companies *gasp* actually *invent new things*. Yes I know the concept is strange, but believe me, it does happen occasionally... "Besides, I thought that the GPL philosophy was all about not reinventing the wheel, using other peoples ideas and improving upon them. Look at Mandrake, they took a good Linux distribution and made it even better." Very true; however there is a difference between stealing something and using something which is given freely. If you don't believe me, just ask a judge. $6M vs $38,000M (Score:4, Interesting) Ralph Nader says this cash pile is distortion of capitalism. Traditionally companies pay out dividends once they have grown into profitibility. The stockholders are being screwed. Re:$6M vs $38,000M (Score:2) Re:$6M vs $38,000M (Score:2) Re:$6M vs $38,000M (Score:2) Despite the fact that Ralph Nader is a git, he has a point here. Unfortunately, companies now manage to stock value, rather than dividend payout. As a result, companies make decisions that can result in them losing money, but still returning value to their investors (by increasing stock price) until the bottom falls out, and the stock drops precipitously. Of course, they only do this because it's what the investors want. Investors want their stock to increase in value, so they can make money selling it, rather than for the stocks to return a cash dividend to them. Part of the reason is taxation laws which tax dividends more heavily than capital gains, and part of the reason is sheer shortsightedness on the part of the investors. Re:$6M vs $38,000M (Score:3, Informative) The reason that MS doesn't pay dividends is because Bill Gates is a major shareholder. If they payed dividends, then Bill will have to pay a HUGE tax bill. The real shocker.... (Score:4, Insightful) Are they afraid or just not that observant? This is definatly newsworthy. The ability to companies to donate money to politicians but shield which politician it is going to to is what is so evil about soft money. At least in the 20s the press could drag a politician through the mud based on his own specific donations. But what would the headline be now? at worst..."Republican party takes donations from Microsoft." Campain money IS NOT SPEECH. It's just the opposite. Re:The real shocker.... (Score:2) Large company lobbies government for favorable reform? This is news? No. Its not news. Its not newsworthy. Its just another day. Campaign money IS SPEECH. Jaded...nothing new really (Score:5, Insightful) As a Canadian, reading the reactions of various slashdotters, I find it very interesting. We as a tech community are so ready to shout that Microsoft is evil. You guys are forgetting that this is the American way (which applies to us up too...). Remember those Railroad Tycoons, the Oil Tycoons? The Rockafellers of the world are still around. Why do you think Texas has so many industries that could have been put elsewhere? (Count how many military bases that there are in Texas?)Prominent Texans ensured that Texas was given the goods, and in our present system of government they did not only what they could, but what was expected and did what benefited Texans and especially those prominant citizens. (Sorry Texans, but its the only example I know of as an ignorant canuck ;) Using money to influence government policy is how government has functioned for a long time. Remember in Ancient Rome, being in position of political power made you rich as businesses petitioned for your support. This is not going to change anytime soon unless we as a society decide that is unacceptable. America is the land of the free. Its the land of who has got more $$$. The more dough you have, the more freedom you have to do as you wish for good or ill. Don't piss on M$ because they are doing what is in their best interests and that they have the freedom to do so. Its disgusting that they did do it, but I am much more revolted that the so called democracy of the world is nothing more than auction and that THIS seems news to people . We have to as a society against this truly undemocratic behaviour. Hopefully this will serve as a case in point for seriously look at our Politicians and their Political Parties and how they govern us. Though I suppose it could be worse... at least we pretend to have democracy. Don't mind me though I am just a jaded youth.... If this is true, I'm worried. (Score:2) Campaign Finance Bill Vote Today Call these reps (Score:2) CAMPAIGN FINANCE REFORM: ACTION ALERT!!! A bandaged Sen. John McCain, R-Ariz., takes part in a Washington news conference to discuss campaign finance reform, Monday, Feb. 11, 2002. Last week, McCain had a cancerous lesion removed from the left side of his nose which was diagnosed as the earliest form of melanoma and was removed. (AP Photo/Stephen J. Boitano) One Last Push: Call Now! Thank you to all those who phoned and faxed Members of Congress over the past week and urged them to support the Shays-Meehan bill. We've heard many reports of offices flooded with calls on the issue, but the fight is not over. Recently, the republican party and its leadership stepped up the effort to fight meaningful reform. If you are a Republican, please make sure and mention that fact when you call or fax the following list of Members. Let them know that this issue is important to you and that the passage of Shays-Meehen is necessary in order to restore integrity to America. Speaker Hastert has declared the campaign finance reform fight "Armageddon" -- and true reform won't come easy. The vote is Wednesday--and we need to keep the pressure on. Below, we have included a list of Members of Congress that we are asking you to call or fax. Please let these members of Congress know that they must vote for Shays-Meehan. In addition, let them know to vote against the poison pill amendments and the sham Ney Bill. Please call or fax the following list of Representatives: Rep. Spencer Bachus (R-AL-6) (202) 225-4921 - (202) 225-2082 fax Rep. Elton Gallegy (R-CA-23) (202) 225-5811 - (202) 225-1100 fax Rep. Doug Ose (R- CA-3) (202) 225-5716 - (202) 226-1298 fax Rep. Michael Collins (R -GA-3) (202) 225-5901 - (202) 225-2515 fax Rep. Nathan Deal (R-GA-9) (202) 225-5211 - (202) 225-8272 fax Rep. John Shimkus (R-IL-20) (202) 225-5271 - (202) 225-5880 fax Rep. Kenny Hulshof (R -MO-9) (202) 225-2956 - (202) 226-0326 fax Rep. Nick Smith (R-MI-7) (202) 225-6276 - (202) 225-6281 fax Rep. Mark Kennedy (R-MN-2) (202) 225-2331 - (202) 225-6475 fax Rep. Frank LoBiondo (R-NJ-2) 202) 225-6572 - (202)225-3318 fax Rep. Rodney Frelinghuysen (R-NJ-11) (202) 225-5034 - (202) 225-3186 fax Rep. Jim Saxton (R-NJ-3) (202) 225-4765 - (202) 225-0778 fax Rep. Mike Ferguson (R-NJ-7) (202) 225-5361 - (202) 225-9460 fax Rep. John McHugh (R-NY-24) (202)225-4611 - (202)226-0621 fax Rep. Sue Kelly (R-NY-19) (202) 225-5441 - (202) 225-3289 fax Rep. Paul Gillmor (R-OH-5) (202) 225-6405 - (202)225-1985 fax Rep. Ralph Regula (R-OH-16) (202) 225-3876 - (202)225-3059 fax Rep. Steven LaTourette (R-OH-19) (202) 225-5731 - (202) 225-3307 fax Rep. Melissa Hart (R-PA-4) (202) 225-2565 - (202) 226-2274 fax Rep. Curt Weldon (R-PA-7) (202) 225-2011 - (202) 225-8137 fax Rep. John Duncan (R-TN-2) (202) 225-5435 - (202)225-6440 fax Rep. Shelly Moore Capito (R-WV-2) (202) 225-2711 - (202) 225-7856 fax Please also call your Representative at 1-800-660-8244, even if you did so last week. Urge them to support Shays-Meehan and oppose the sham Ney bill and poison pill amendments. The House of Representatives uses an e-mail system called "Write Your Rep". You can send e-mails only to your Representative by entering your zip code into the e-mail form - Will you also send this alert to a friend - or two or five - and ask them to do the same? Let's win true reform THIS WEEK. Thank you for your continued support. 1st amendment considerations (Score:2) Here's the deal. If I pay for an advert in support of electing Jimmy Schlessenbaum, that money is counted as a soft money donation to Mr Schlessenbaum. If I give him the money for the ad, and his campaign pays for it, that's a hard contribution and it gets handled under the existing rules and limitations. This is the problem. I have a right to express my opinion of who to vote for. If we start saying that there are limits on soft money contributions, then we're volunteering for legalized limits of individuals to express their opinions. For a better description of this, see This article [prospect.org]. I don't like the fact that corporations can buy elections. But I'd rather have an undamaged 1st amendment, than limits on soft contributions. new monopoly (Score:2) Re:fp (Score:4, Insightful) Parties should be limited as to how much they can spend during a campaign (as they are in Europe) and should maybe even be paid for through taxation- it would cost less thant 1% of the military budget and is a far bettter way of safeguarding democracy. Re:fp (Score:2) Cooperating politicians in a democracy win over the voters every time. And they've realized that. Re:fp (Score:2) We can complain all we want about bought politicians, but we cant change those rules, and the existing power structures appear unlikely to want to change it... And, of course, I do feel that they 'represent' me. I'm included in the demographically researched groups they target for advertising. Well, except, of course, the targetted advertising isnt exactly true, it's just what they say to get elected, so again they arent representing the voters. That, of course, means there isnt any real point to standing under the current system. You'll have to research the demographics yourself, and end up saying almost exactly the same things to get elected, after which you might as well just take cash, since you wont believe in the things you had to say to get elected anyway. Re:fp (Score:2) The MPAA/RIAA and the tobbaco industry has done this for years. They just fly in judges in first class jets to Hollywood with 5 star dinning experiences every night all in the name of educating the judge. The judge in Newy Ork who ruled agaisn't Jon Johnson did this. This kid went to prison, all paid for in the name of education via $$$. ITs sick but pefectly legal and impossible to make it illegal. Isn't this just like ... (Score:5, Insightful) ... charges that Microsoft buys (bought?) shelf space in stores to prevent competing products from even being visible? So, in other words, this is really nothing new. This is Microsoft being Microsoft; now, does anyone seriously doubt that this is an organization bent on doing whatever it takes, including things that are not just immoral, or violate common sense, but possibly things that are criminal, in order to ... what, make money? Has American society fallen so far into the pit of jade and cynicism that we shrug off the Enrons and Microsofts of the world as merely maladjusted money-seeking sycophants, instead of being so violently outraged that we take every chance to make them wish they'd never even started a business? What the hell are we doing? Every person who reads about Microsoft's behavior should be so sickened that they vomit. This is not normal. This is not acceptable. This is not "business as usual" in the United States. Just because it seems to happen a lot does not make it something we should tolerate, not even for a millisecond, and not for any reason. Re:Finally... (Score:3) It's not that few other companies can, it is that few other companies need to. How about somebody looks at what the tobacco industry spends on lobbying efforts? How about the RIAA and MPAA? Microsoft is NOT doing anything illegal when it spends money on political contributions. It is the politicians that are doing something illegal if they let that money sway their votes. Re:Finally... (Score:2) Illegal like what? The contributions and lobbying, while of dubious morality, are still legal. Any numbers available for Sun's lobbying and contributions? Re:Finally... (Score:2, Insightful) Was Sun contributing money while they were involved in legal action regarding their business practices? The Microsoft situation is less a matter of corporate political contributions than it is a matter of historic antitrust precedent. That M$'s behavior was not technically illegal brings to mind the Nuremburg legal defense that a war of genocidal agression was not illegal. Indeed, at the moment, it is not illegal to employ monopolistic activities on a scale without comparison in human history to turn the entire information industry into an oligarchy. As for myself, I find very little comfort in witholding my outrage based on this technicality. Re:Finally... (Score:3, Insightful) As a publicly traded company, they have a fiduciary responsibility to their shareholders. If they spend money away like this and don't expect a return, they are not living up to that responsibility. On the other hand, if they're spending the money and they DO expect something back, then these are bribes. Either way, I don't see how a publicly held corporation can spend any of its money on political activities. Re:Why isn't this mentioned on The Today Show? (Score:2, Interesting) MS-NBC [msnbc.com] -rp Re:Ban contributions? (Score:2) Uhhm, and how is it different from the current situations? Oh yeah, I get it! They are not technicaly bribes: they are called "contributions". Re:Could this be real? (Score:2) Absolutely not (Score:2) Microsoft has not debt to speak of and $38 billion in cash. You'd make a terrible investor or stock broker if you cant tell the difference. Re:SlashDot Users Paid By Microsoft? (Score:2) Oh wait.... we can tell just by counting the pro-microsoft comments in this thread!! Not necessarily! If I were a paid Microsoft Troll, why would I blindly spout pro-Microsoft rhetoric when I could be much more effective by quietly offering little tidbits of wisdom that cast doubt among the /. horde?.. This wisdom could be offered in the form of pro-BSD comments (MS likes BSD) or even as psuedo-reverse psychology type comments (i.e. "MS sucks, because they have huge security holes in tehir code like *this*".. Which prompts half a dozen folks to either mention that Linux has the same hole, or that MS fixed that problem 6 months ago).. The point is that if MS were hiring individuals to sway the /. crowd, you can bet your arse that they wouldn't be hiring script kiddies! Re:Malformed figures (Score:2) "...total donations to political donations from Microsoft and its employees to political parties, candidates and PACs in the 2000 election cycle amounted to more than $6.1 million. During this period, Microsoft and its executives accounted for $2.3 million in soft money contributions..." I'll agree that they don't fully explain how they arrive at the 6 million figure. None of the numbers provided add up, as the article lacks a thorough breakdown. Articles like this infuriate me because you never get the real story. Even after 300 words, all you have is an inflammatory headline (regardless of which "side" you're on), a bunch of numbers associated with a hot topic like money and politics, and not much else. As for the actual concept of buying political favours; I think we're all adult enough to realize this is nothing new. All this does is confirm to us that MS does it too, just as we suspected. and the Mass Misinformation Machine rolls on...
http://slashdot.org/story/02/02/13/140248/details-of-msfts-antitrust-lobbying
CC-MAIN-2014-35
en
refinedweb
Claims-aware applications Updated: August 22, 2005 Applies To: Windows Server 2003 R2 Claims are statements (for example, name, identity, key, group, privilege, or capability) made about users — and understood by both partners in an Active Directory Federation Services (ADFS) federation — that are used for authorization purposes in an application. A claims-aware application is a Microsoft ASP.NET application that has been written using the ADFS library. This type of application is fully capable of using ADFS Claims to make authorization decisions directly. A claims-aware application accepts claims that the Federation Service sends in ADFS security tokens. For more information about how the Federation Service uses security tokens and claims, see Federation Service. Claim mapping is the act of mapping, removing or filtering, or passing inbound claims into outbound claims. Claim mapping does not occur when claims are sent to an application. Instead, only the organization claims that are specified by the Federation Service administrator are sent to the application. (Organization claims are claims in intermediate or normalized form within an organization's namespace.) By default, no organization claims that are marked as auditable are sent. All nonauditable claims are sent. Therefore, the Federation Service administrator will opt in for auditable claims to be sent to the application and will opt out for nonauditable claims. The following list describes the organization claims that can be used by claims-aware applications: - Identity claims (UPN/e-mail/common name) When you configure the application, you specify which of these identity claims will be sent to the application. No mapping or filtering is performed. - Group claims When you configure the application, you specify the organization group claims that will be sent to the application. Organization group claims that are not designated to be sent to the application will be discarded. - Custom claims When you configure the application, you specify the organization custom claims that will be sent to the application. Organization custom claims that are not designated to be sent to the application will be discarded. Claims-aware authorization Claims-aware authorization consists of a Hypertext Transfer Protocol (HTTP) module and objects for querying the claims that are carried in the ADFS security token. Claims-aware authorization is supported only for Microsoft ASP.NET applications. The HTTP module processes ADFS protocol messages based on configuration settings in the Web application's Web.config file. The Web pages perform authentication and authorization tasks. The HTTP module also authenticates cookies and obtains claims from the cookies.
http://technet.microsoft.com/en-us/library/cc783377(d=printer,v=ws.10).aspx
CC-MAIN-2014-35
en
refinedweb
Originally posted by Przemek Malirz: After which line will the object passed to the method getObject() be eligible for garbage collection? public void getObject(Object a) { Object c, b = new Object(); //1 //do something with a c = b; //2 a = c;//3 b = a = null; //4 c = null; } Answers: //1, //2, //3, //4, None of these And this is a big difference. Enthuware question doesn't tell that outside getObject method exist reference variable to this Object, and that this variable is passed to this method. Enthuware explenation is incorrect: "...The point is that the objects passed to a method can never be garbage collected in that method. The reason is simple - such objects are created outside the method and so there are references pointing to these objects outside the method..." Wrong !!! There might be no reference at all !!! Originally posted by Przemek Malirz: Thanks for your answer. So why below code produce an output: 1 getObject.A Huge.finalize getObject.B 2 Originally posted by Przemek Malirz: And this is what I try to prove. "if we pass an Object reference to a method" an enthuware question is correct, and "if we pass an actual object" the question is incorrect. public class Main { public static void main(String[] args) { System.out.println("1"); getObject(new Huge()); System.out.println("2"); } public static void getObject(Object a){ a = null; System.out.println("getObject.A"); System.gc(); for(int i = 0;i < 20000;i++); System.out.println("getObject.B"); } } class Huge { protected void finalize() throws Throwable { System.out.println("Huge.finalize"); } }
http://www.coderanch.com/t/270115/java-programmer-SCJP/certification/GC-enthuware
CC-MAIN-2014-35
en
refinedweb
[DOM Level 2 Core] and the XPath 1.0 model , special extension functions or variables which are not defined in this specification. interface XPathEvaluator { XPathExpression createExpression(in DOMString expression, in XPathNSResolver resolver) raises(XPathException, DOMException);. createNSResolver lookupNamespacePrefixon Node.. typeof type unsigned short typeis specified, then the result will be coerced to return the specified type relying on XPath typePathExpression interface represents a parsed and resolved XPath expression. interface XPathExpression { XPathResult evaluate(in Node contextNode, in unsigned short type, in XPathResult. nullto be passed in invocation, allowing the implementation, if shared, to do anything it wants with a passed null. nullwhere required.. invalidIteratorState. Node.namespaceValueshould be identical to Node.namespaceURI and not null..
http://www.w3.org/TR/2002/WD-DOM-Level-3-XPath-20020328/xpath.html
CC-MAIN-2014-35
en
refinedweb
"I work for a software development house that creates business software, maintaining legacy MFC applications," Graf writes. "We recently received an issue where a filter-toggle wouldn't switch back and forth, never changing from its default value. It's was a small utility function, rarely used, so we were a bit surprised to see it come up. Taking a quick glance at the code revealed the following: #define ENABLE_FILTER void CReport::ToggleFilter() { #if defined(ENABLE_FILTER) #undef ENABLE_FILTER #else #define ENABLE_FILTER #endif } bool CReport::IsFilterEnabled() { #if defined(ENABLE_FILTER) return true; #else return false; #endif }
http://thedailywtf.com/Articles/The-Toggle-that-Wouldnt.aspx
CC-MAIN-2014-35
en
refinedweb
The mesh data is accessed in object mode and intended for compact storage, for more flexible mesh editing from python see bmesh. Blender stores 4 main arrays to define mesh geometry. Each polygon reference a slice in the loop array, this way, polygons do not store vertices or corner data such as UV’s directly, only a reference to loops that the polygon uses. Mesh.loops, Mesh.uv_layers Mesh.vertex_colors are all aligned so the same polygon loop indices can be used to find the UV’s and vertex colors as with as the vertices. To compare mesh API options see: NGons and Tessellation Faces This example script prints the vertices and UV’s for each polygon, assumes the active object is a mesh with UVs. import bpy me = bpy.context.object.data uv_layer = me.uv_layers.active.data for poly in me.polygons: print("Polygon index: %d, length: %d" % (poly.index, poly.loop_total)) # range is used here to show how the polygons reference loops, # for convenience 'poly.loop_indices' can be used instead. for loop_index in range(poly.loop_start, poly.loop_start + poly.loop_total): print(" Vertex: %d" % me.loops[loop_index].vertex_index) print(" UV: %r" % uv_layer[loop_index].uv) base classes — bpy_struct, ID
http://www.blender.org/documentation/blender_python_api_2_67_1/bpy.types.Mesh.html
CC-MAIN-2014-35
en
refinedweb
10 August 2009 04:51 [Source: ICIS news] SINGAPORE (ICIS news)--Fujian Refining and Petrochemical Co (FREP) has started shipping products from its new aromatics complex at Quanzhou in China’s southern Fujian province, sources close to the company said on Monday. “Some aromatics have been shipped to customers near us as well as to [nearby] ?xml:namespace> A company spokesman did not deny the commercial sales of the complex’s products but said: “The new plant is in the phase of start-up; the whole new project is expected to go into full operation in the second half of this year.” Other sources said that commercial production at the polyolefins unit had yet to start, but expected sales to begin at the end of the month. The 800,000 tonne/year steam cracker was also running at low rates currently but was expected to reach optimal operations by the latter half of the month, sources said. Besides the new cracker, the FREP is a joint venture of ExxonMobil (25%), Saudi Aramco (25%) and Fujian Petrochemical (50%). Fujian Petrochemical is a 50:50 joint venture between the Ong Sheau Ling, Judith Wang and Dolly Wu contributed to this article For more on aromatics &
http://www.icis.com/Articles/2009/08/10/9238418/chinas-frep-starts-shipping-aroms-to-customers.html
CC-MAIN-2014-35
en
refinedweb
So i found out my next program will need a lot of memory, but want to figure an estimate of how much. I first wanted to make an end_list[10000][100] array for the structure End, but since i only could get it working with [100][100] then i decided to make more structures and arrays but even that doesn't work. So why and how will I be able to solve this? Edit: Put system("pause") so I can check how much memory is taken, hopefully you have windows :PEdit: Put system("pause") so I can check how much memory is taken, hopefully you have windows :PCode: #include <stdio.h> #include <string.h> #include <time.h> #include <iostream> #include <stdlib.h> using namespace std; int main() { struct Start {char A[5]; char B[100];}; struct End1 {char A[5]; char B[100];}; // struct End2 {char A[5]; char B[100];}; // struct End3 {char A[5]; char B[100];}; // struct End4 {char A[5]; char B[100];}; Start start_list[100]; End1 end_list1[100][100]; // End2 end_list2[100][100]; // End3 end_list3[100][100]; // End4 end_list4[100][100]; system("pause"); }
http://cboard.cprogramming.com/cplusplus-programming/146663-limited-memory-allocation-printable-thread.html
CC-MAIN-2014-35
en
refinedweb
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
en
refinedweb
In this article, we discuss several use scenarios for inline assembly, also called inline asm. For beginners, we introduce basic syntax, operand referencing, constraints, and common pitfalls that new users need to be aware of. For intermediate users, we discuss the clobbers list, as well as branching topics that facilitate the use of branch instructions within inline asm stanzas in their C/C++ code. Lastly, we discuss memory clobbers and the volatile attribute for advanced users who use inline asm to optimize their code. We conclude with an example of multithreaded locking with inline asm. Basic inline asm In the asm block shown in code Listing 1, the addc instruction is used to add two variables, op1 and op2. In any asm block, assembly instructions appear first, followed by the inputs and outputs, which are separated by a colon. The assembly instructions can consist of one or more quoted strings. The first colon separates the output operands; the second colon separates the input operands. If there are clobbered registers, they are inserted after the third colon. If there are no clobbered inputs for the asm block, the third colon can be omitted, as Listing 2 shows. Listing 1. Opcodes, inputs, outputs, and clobbers int res=0; int op1=20; int op2=30; asm ( " addc. %0,%1,%2 \n" : "=r"(res) : "b"(op1), "r"(op2) : "r0" ); Listing 2. No clobbered inputs for the asm block, so third colon omitted asm ( " addc. %0,%1,%2 \n" : "=r"(res) : "b"(op1), "r"(op2) ); Note: The clobbers list is discussed later in this section. Each instruction "expects" inputs and outputs to be passed in a certain format. In the previous example, the addc. instruction expects its operands to be passed through registers, hence op1 and op2 are passed into the asm block with the "b" and "r" constraints. For a complete listing of all legal asm constraints for the IBM XL C and C++ compiler, see the compiler language reference. Register constraints on variable declarations In some programs, you will want to tie variables to certain hardware registers. This is done at the variable declaration. The following example ties the variable res to GPR0 throughout the life of the program: int register res asm("r0")=0; When the variable type is not matched with the type of target hardware register, you will receive a compilation error notice. After a variable is tied to a specific register, it is not possible to use another register to hold the same variable. For example, the following code will cause a compilation error, the variable res is associated at declaration time with GPR0, but in the asm block, the user attempts to use any register but GPR0 to pass in res . Listing 3. Compilation error when conflicting constraints are used on a variable int register res asm("r0")=0; asm ( " addc. %0,%1,%2 \n" : "=b"(res) : "b"(op1), "r"(op2) : "r0" ); In the example in Listing 4, there is no output operand for the stw instruction, hence the outputs section of the asm is empty. None of the registers is modified, so they are all input operands, and the target address is passed in with the input operands. However, something is modified: the addressed memory location. But that location is not explicitly mentioned in the instruction, so the output of the instruction is implicit rather than explicit. Listing 4. Instructions with no output operands int res [] = {0,0}; int a=45; int *pointer = &res[0]; asm ( " stw %0,%1(%2) \n" : : "r"(a), "i"(sizeof(int)),"r"(pointer)); Listing 5. Instructions with preserved operands int res [] = {0,0}; int a=45; asm ( " stw %0,%1(%2) \n" : "+r"(res[0]) : "r"(a), "i"(sizeof(int)),"r"(pointer)); In listing 5, if you want to preserve the initial value of a result variable that is not necessarily modified by the asm block, then you need to use the + (plus sign) constraint to preserve the initial value of that variable, as is shown with res[0]. Target memory addresses in inline asm If an instruction specifies two of its arguments in a form similar to D(RA), where D is a literal value and RA is a general register, then this is taken to mean that D+RA is an effective address. In this case, the appropriate constraints are "m" or "o". Both "m" and "o" refer to memory arguments. Constraint "o" is described as an offsettable memory location. But in the IBM® POWER® architecture, nearly all memory references require an offset, so "m" and "o" are equivalent. In this case, you can use a single constraint to refer to two operands in the instruction. Listing 6 is an example. Listing 6. A single constraint to refer to two operands in the instruction int res [] = {0,0}; int a=45; asm ( " stb %1,%0 \n" : "=m"(res[1]) : "r"(a)); The form of the instruction stb (from the assembly language reference) is: stb RS,D(RA). Although the stb instruction technically takes three operands (a source register, an address register, and an immediate displacement), the asm description of it uses only two constraints. The "=m" constraint is used to notify the compiler that the memory address of res is to be used for the result of the store instruction (The "sync" instruction is often used for this purpose, but there are others available, as described in the POWER ISA See Resources for a link.) The "=m" indicates that the operand is a modified memory location. You do not need to know the address of the target location beforehand, because that task is left to the compiler. This allows the compiler to choose the right register ( r1 for an automatic variable, for instance) and apply the right displacement automatically. This is necessary, because it would generally be impossible for an asm programmer to know what address register and what displacement to use. In other instances, you can also override this behavior by manually calculating the target address as in the following example. Listing 7. Manually calculating the target address int res [] = {0,0}; int a=45; asm ( " stb %0,%1(%2) \n" : : "r"(a), "i"(sizeof(int)),"r"(&res)); In this code, the specification %1(%2) represents a base address and an offset, where %2 represents the base address, and res[0] and %1 represent the offset, sizeof(int). As a result, the store is performed at the effective address, res. Note: For some instructions, GPR0 cannot be used as a base address. Specifying GPR0 tells the assembler not to use a base register at all. To ensure that the compiler does not choose r0 for an operand, you can use the constraint "b" rather than "r". Addressing modes for POWER and PowerPC instructions The IBM POWER architecture type is RISC. Instructions typically operate either with three register arguments (two registers for source arguments, one register to hold a result) or with two registers and an immediate value (one register and one immediate value for the source arguments, and one register to hold the result). There are exceptions to this pattern, but mostly it is true. Among the instructions that take two registers and an immediate value, there are two special subclasses: load instructions and store instructions. These instructions use the immediate value as an offset to the value in the source register to form an "effective address." The offset value is typically an offset onto the stack ( r1 is the stack pointer), or it is an offset to the TOC (Table of Contents -- r2 is the TOC pointer). The TOC is used to promote the construction of position-independent code, which enables efficient dynamic loading of shared libraries on these machines. When using inline asm, you do not have to use specific registers nor manually construct effective addresses. The argument constraints are used to direct the compiler to choose registers or construct effective addresses appropriate to the requirements of the instructions. Thus, if a general register is required by the instruction, you could use either the "r" or "b" constraint. The "b" constraint is of interest, because many instructions use the designation of 0 specially –- a designation of register 0 does not mean that r0 is used, but instead a literal value of 0. For these instructions, it is wise to use "b" to denote the input operands to prevent the compiler from choosing r0. If the compiler chooses r0, and the instruction takes that to mean a literal 0, the instruction would produce incorrect results. Listing 8. r0 and its special meaning in the stbx instruction char res[8]={'a','b','c','d','e','f','g','h'}; char a='y'; int index=7; asm (" stbx %0,%1,%2 \n" : : "r"(a), "r"(index), "r"(res) ); Here, the expected result string is abcdefgy, but if the compiler chose r0 for %1, then the result would incorrectly be ybcdefgh. To prevent this from happening, use "b" as in Listing 9 shows. Listing 9. Using "b" constraint to signify non-zero GPR char res[8]={'a','b','c','d','e','f','g','h'}; char a='y'; int index=7; asm (" stbx %0,%1,%2 \n" : : "r"(a), "b"(index), "r"(res) ); Another example is in the following ASM block. While it appears that the asm block below does res=res+4, that is not the actual functional behavior of the code. Listing 10. Meaning of r0 in the second operand with addi opcode int register res asm("r0")=5; int b=4; asm ( " addi %0,%0,%1 \n" : "+r"(res) : "i"(b) : "r0"); where: addi %0(result operand),%0(input operand res),%3(immediate operand b) Because res is tied to r0, the translation of the asm code in assembly looks becomes: addi 0, 0 ,4 The second operand does not translate to register zero. Instead, it translates to the immediate number zero. In effect, the following is the result of the addi operation: res=0+4 This case is special to the addi opcode. If, instead, res was tied to r1, then the original intended behavior would have been obtained: res=res+4 Clobbers list Basic clobbers list In cases when registers that are not directly tied to the inputs/outputs are used within the asm block, the user must specify such registers within the clobbers list. The clobbers list is used to notify the compiler that the registers contained within the list can potentially have their values altered. Hence, they should not be used to hold other data other than for the instructions that they are used for. In the example in Listing 11, registers 8 and 7 are added to the clobbers list because they are used in the instructions but are not explicitly tied to any of the input/output operands. Also, condition register field zero is added to the clobbers list for the same reason. Although it is not present in the input/output operands, the mfocrf instruction reads that bit from the condition register and moves the value in register 8. Listing 11. Clobbers list example asm (" addc. %0,%2,%3 \n" " mfocrf 8,0x1 \n" " andi. 7,8,0xF \n" " stw 7,%1 \n" : "=r"(res),"=m"(c_bit) : : "b"(a), "r"(b) : "r0","r7","r8","cr0" ); clobbers list If, instead, the mfocrf instruction read from condition register field 1 (cr1), then that field would need to be added to clobbers list instead. Also, the period [full stop] at the end of the addc. and andi. instructions means their results are compared to zero, and the result of the comparison is stored in condition register field 0. When clobbered registers are omitted from the clobbers list, the results from the asm operations might not be correct. This is because such clobbered registers might be reused to hold intermediate values for other operations. Unless the compiler detects that those registers are clobbered, the intermediate data can be used to perform the programmer's instructions, with inaccurate results. Also, the user's asm instructions may clobber values used by the compiler. Exceptions to the clobbers list Nearly all registers can be clobbered, except for those listed in Table 1. Table 1. Registers that cannot be clobbered Memory clobbers Memory clobber implies a fence, and it also impacts how the compiler treats potential data aliases. A memory clobber says that the asm block modifies memory that is not otherwise mentioned in the asm instructions. So, for example, a correct use of memory clobbers would be when using an instruction that clears a cache line. The compiler will assume that virtually any data may be aliased with the memory changed by that instruction. As a result, all required data used after the asm block will be reloaded from memory after the asm completes. This is much more expensive than the simple fence implied by the "volatile" attribute (discussed later). Remember, because the memory clobber says anything might be aliased, everything that is used needs to be reloaded after the asm, regardless of whether it had anything to do with the asm. A memory clobber can be added to the clobbers list by simply using the "memory" word instead of a register name. Branching Basic branching Branching can be tricky with inline asm, this is because you need to know the address of the instruction to which to branch before compile time. Although this is not possible, you can use labels. Using labels, the branch-to address can be designated with a unique identifier that can be used as a target branch address. Within a single source file, labels cannot be repeated within an inline asm block, nor within neighboring asm blocks within the same source. In a given program, each label is unique. There is an exception to this rule, however, and this is if you use relative branching (more on this later). With relative branching, more than one label with the same identifier can be found within the same program and within the same asm block. Note: Labels cannot be used in asm to define macros because of possible namespace clashes. In the example in Listing 12, the branch occurs when the LT bit, bit 0, of the condition register is set. If is it not set, then the branch is not taken. Listing 12. Example of branch taken when LT bit of CR0 is set (0x80000000) asm ( " addic. %0,%2,%4 \n" " bc 0xC,0,here \n" " there: add %1,%2,%3 \n" " here: mul %0,%2,%3 \n" : "=r"(res),"=r"(res2) : "r" (a),"r"(b),"r"(c) : "cr0" ); Likewise, a branch would occur if the GT bit (bit 1) of the condition register is set, as in the code in Listing 13. Listing 13. Example of branch taken when GT bit of CR0 is set (0x40000000) asm ( " addic. %0,%2,%4 \n" " bc 0xC,1,here \n" " there: add %1,%2,%3 \n" " here: mul %0,%2,%3 \n" : "=r"(res),"=r"(res2) : "r" (a),"r"(b),"r"(c) : "cr0" ); With inline asm, it is perfectly legal to branch within the same asm block; however, it is not possible to branch between different asm blocks, even if they are contained within the same source. Relative branching As discussed earlier, relative branching allows you to reuse the name of a label more than once within the same program. It is predominantly used, however, to dictate the position of the target address relative to the branch instruction. These are examples of the relative branch codes that can be used: - F -forward - B -backward Note: That they must be suffixed to numeric labels to be syntactically correct. In this example (Listing 14), notice that the target address is referenced as "Hereb". In this case, we use the label of the target address appended with a suffix that dictates where this label is located relative to the branch instruction itself. The label "Here" is located before the branch instruction, hence the use of the "b" suffix in "Hereb." Listing 14. Needs caption asm ( " 10: lwarx %0,0,%2 \n" " cmpwi %0,0 \n" " bne- 20f \n" " ori %0,%0,1 \n" " stwcx. %0,0,%2 \n" " bne- 10b \n" " sync \n" " ori %1,%1,1 \n" " 20: \n" :) The condition register The condition register is used to capture information on results of certain instructions. For non-floating point instructions with period (.) suffixes that set the CR, the result of the operation is compared to zero. - If the result is greater than zero, then bit 1 of the CR field is set (0x4). - If it is less than zero, then bit 0 is set (0x8). - If the result is equal to zero, then bit 2 is set (0x2). For all compare instructions, the two values are compared, and any CR field can be set (not just CR0). Table 2 lists the bits and their corresponding meanings (there are eight such sets of 4 bits in the condition register, called "cr0, cr1, cr2 … cr7"). Table 2. Bits of a CR field and the meanings of different settings Note: For floating point instructions with a period suffix, CR1 is set to the upper 4 bits of the FPSCR. Blocking the Volatile attribute Making an inline asm block "volatile" as in this example, ensures that, as it optimizes, the compiler does not move any instructions above or below the block of asm statements. asm volatile(" addic. %0,%1,%2\n" : "=r"(res): "=r"(a),"r"(a)) This can be particularly important in cases when the code is accessing shared memory. This will be illustrated in the next section on multithreaded locking.\ Multithreaded locking One of the most common uses of inline asm is in writing short segments of instructions to manage multithreaded locks. Because of the loose memory model on the POWER architecture, constructing such locks requires careful use of a pair of instructions: - One instruction that loads the lock word and creates a "reservation" - Another that updates the lock word if the reservation hasn't been lost in the interim Note: If the reservation has been lost, a loop can be used to retry repeatedly. Listing 15 shows a basic inline function that attempts to acquire a lock (there are several problems with this code, which we discuss after these examples). Listing 15. Example of Acquire lock function coded in asm; } Listing 16 is an example of how this inline function could be used. Listing 16. Example of how the acquireLock function can be used if (acquireLock(lockWord)){ //begin to use the shared region temp = x + 1; . . . } Because the function is inline, the resulting code won't have an actual call in it. Instead, it will precede the use of the shared region x with the instructions to acquire the lock. The first problem to notice with this code is the lack of a synchronization instruction. One of the key performance enhancements enabled by the loose memory model of the POWER architecture is the ability of the machine to reorder loads and stores to make more efficient use of internal pipelines. However, there are times when the programmer needs to curtail this reordering to some degree to properly access shared storage. In the case of a lock, you would not want a load of data from the shared region ("x" in the case above) to be reordered so that it occurs before the lock on the region is acquired. For this reason, a synchronization instruction should be inserted to tell the machine to limit reordering in this case. The sync instruction is often used for this purpose, but there are others available, as described in the POWER ISA (see Resources). In the code example in Listing 17, we inserted sync instruction to prevent reordering of loads of "x" (this is called an "import barrier"): Listing 17. Sync example " sync \n" //import barrier "; } In that asm block, the sync will prevent any subsequent loads from occurring until after it is known which way the preceding branch went. That way the variable x will not be loaded unless the branch was not taken and the acquireLock returns true. So, are we set now? Unfortunately not. We still have to worry what the compiler might do. Modern optimizing compilers can be very aggressive in moving code around -- and even removing it completely -- if it appears that the changes might make the program run faster without changing the semantics of the code. However, compilers typically aren't aware of the complexities involved with accessing shared memory. For example, a compiler might move the statement temp = x + 1; to a place higher in the program if it determines that the result would be scheduled more efficiently (and it assumes that the "if" is usually taken). Of course, that would be disastrous from the viewpoint of accessing shared data. To prevent the movement of any loads (or any instructions at all) from below the inline asm to a location above it, you can use the keyword "volatile" (also known as the volatile attribute) to modify the asm block, as Listing 18 shows. Listing 18. Volatile keyword example inline bool acquireLock(int *lock){ bool returnvalue = false; int lockval; asm volatile ( "0: lwarx %0,0,%2 \n" //load lock and reserve . . . "1: \n" //didn't get lock, return false : "+r" (lockval), "+r" (returnvalue) : "r"(lock) //parameter lock is an address : "cr0" ); //cmpwi, stwcx both clobber cr0 return returnvalue; } When you do this, an internal fence is placed before and after the asm block that prevents instructions from being moved past it. And remember that this asm block is inlined, so it will prevent the access to x from being moved above the asm-implemented lock. Memory clobbers in multithreaded locking The discussion of multithreaded locking would not be complete without a mention of memory clobbers. The keyword memory is often added to the clobber list in such situations, although it is not always clear why it would be needed. The use of memory in the clobbers list means that memory is altered unpredictably by the asm block. However, memory modifications in the locking example given are quite predictable. Although the variable lock is a pointer (that points to a lock location), that isn't any more unpredictable that the expression "*lock" in a C program. In that case, a well-behaved compiler would likely associate the expression "*lock" with all variables of the appropriate type, and so would correctly reload any affected variables after the pointer was used for modifying data. Nonetheless, the use of memory clobbers appears to be a pervasive practice, which is probably driven by an abundance of caution when dealing with shared regions. Programmers should be aware, though, of the performance penalties involved and of alternative approaches. When an inline asm includes "memory" in the clobbers list, it means that any variable in the program might have been modified by the asm, so it must be reloaded before it is used. This requirement can pretty much put a sledgehammer to optimization efforts by the compiler. A potentially lighter-weight approach would be to make the shared region volatile (in addition to the asm block itself). Making a variable volatile means its value must be reloaded before it is used in any given expression. If the shared region in question is a data structure, such as a list or queue, this will ensure that the updated structure is reloaded after the lock is acquired. However, all of the non-shared data accesses can enjoy the full complement of compiler optimizations. Tip: If the shared data structure is accessed by a pointer (say *p), be sure to declare the pointer so that you ndicate that it's the object pointed to that is volatile, not the pointer itself. For example, this declares that the list pointed to by p is volatile: volatile list *p Acknowledgments Thank you Ian McIntosh, Christopher Lapkowski, Jim McInnes, and Jae Broadhurst. You've each played an important role in publishing this article. Resources Learn - For alternatives to the sync instruction, see the IBM Power ISA (Instruction Set Architecture) PDF. - answers and get involved in the C/C++ community in Rational Cafés. - Join the Rational software forums to ask questions and participate in discussions. -.
http://www.ibm.com/developerworks/rational/library/inline-assembly-C-Cpp-guide/index.html
CC-MAIN-2014-35
en
refinedweb
- Fund Type: Unit Trust - Objective: North American Region - Asset Class: Equity - Geographic Focus: North American Region BT Investment Funds - BT American Share Fund+ Add to Watchlist BTSMAGI:AU2.70 AUD -0.00-0.10% As of 00:59:30 ET on 08/15/2014. Snapshot for BT Investment Funds - BT American Share Fund (BTSMAGI) Mutual Fund Chart for BTSMAGI - BTSMAGI:AU 2.73 … Previous Close - 1W - 1M - YTD - 1Y - 3Y - 5Y Open: High: Low:Volume: Recently Viewed Symbols Save as Watchlist Saving as watchlist... Fund Profile & Information for BTSMAGI BT Investment Funds - BT American Share Fund is an unit trust incorporated in Australia. The Fund aims to provide a return (before fees and taxes) that exceeds the return from the S&P 500 Total Return Index in AUD. The Fund invests primarily in North American shares. Fundamentals for BTSMAGI Dividends for BTSMAGI Fees & Expenses for BTSMAGI Top Fund Holdings for BTSMAGIFiling Date: 06/30/2014 Quotes delayed, except where indicated otherwise. Mutual fund NAVs include dividends. All prices in local currency. Time is ET. Sponsored Link Recommended Symbols: Advertisement Related News Advertisement Sponsored Links Advertisements
http://www.bloomberg.com/quote/BTSMAGI:AU
CC-MAIN-2014-35
en
refinedweb
Creating Simple Animations with Java ME This article explains how to create simple animations with Java ME. The code introduced in this article is compatible with most Java ME devices including Series 40 phones and Nokia Asha software platform 1.0. Nokia Asha Nokia Asha Platform 1.0 Series 40 Introduction The standard LCDUI framework has no support "out of the box" for animation. If you want to use animations with LCDUI you have no choice but to implement it yourself. This article studies implementing a basic, generic, UI independent animation framework that is both efficient and easy to use. The code has been tested in the Custom CategoryBar Demo, which implements the animations and applies them for transitions between the tabs (full source code is available here). - LWUIT does have animation support - Nokia UI API provides the FrameAnimator package, but that is not generic and has dependency to the user interface (UI) components. Implementation Architecture The architecture of the animation package is very basic. The main class, which you can consider to be the animation "engine" is IntAnimation. It is responsible for starting and stopping the animations, managing the animation state, threading etc. Together with the AnimationListener it provides the animation values when the animation is running. The class implementing AnimationListener is also notified when the state of an animation is changed. The three states currently implemented are running, stopped and finished. A concrete implementation of EasingCurve must be set before an animation can be run. The animation implementation hides the easing curves behind an enumeration; you as a developer don't have to mess with the easing curve class instances. Instead you set the easing curve as integer. Easing curves Easing curves play a vital part in defining the behaviour of an animation. The simplest easing curve, linear curve, moves the object you are animating from the source to the destination point with steady speed where-as in-out-quad easing curves makes the animation more vivid. Implementation-wise the approach here is to calculate the values for the animation beforehand. The easing curve implementation is responsible for calculating the values. The abstract base class EasingCurve implements everything but the calculate() method. The calculate() method of the linear easing curve is as follows: public class LinearEasingCurve extends EasingCurve { public boolean calculate(int from, int to, int duration) { _duration = duration; _steps = _duration / IntAnimation.UPDATE_INTERVAL; _values = new int[_steps]; _currentStepIndex = 0; final int stepLength = (to - from) / (_steps - 1); _values[0] = from; _values[_steps - 1] = to; for (int i = 1; i < _steps - 1; ++i) { _values[i] = from + stepLength * i; } return true; } } As you can see from the snippet above the animation is divided to n steps based on the duration. Then the values between the "from" and "to" point are evenly distributed making the animation linear. Currently, this light animation framework implements three easing curves: linear, in-out-quad and out-in-quad. Usage Using the animation package is easy. First have your class, that handles the animating, derive from AnimationListener. Create the IntAnimation instance where convenient - a straightforward place to do it is in the constructor. Remember to set the listener so that you can receive the animated values and changes in the animation states. public class MyCanvas extends Canvas implements AnimationListener { // Constants ... private static final int ANIMATION_DURATION = 500; private static final int EASING_CURVE = IntAnimation.EASING_CURVE_INOUTQUAD; ... private IntAnimation _animation = null; ... /** * Constructor. */ public MyCanvas() { super(); ... _animation = new IntAnimation(); _animation.setListener(this); ... Implement the methods required by the AnimationListener interface: /** * @see AnimationListener#onAnimatedValueChanged(int) */ public void onAnimatedValueChanged(int value) { // Handle the value ... repaint(); } /** * @see AnimationListener#onAnimationStateChanged(int) */ public void onAnimationStateChanged(int state) { switch (state) { case IntAnimation.STATE_RUNNING: ... break; case IntAnimation.STATE_STOPPED: ... break; case IntAnimation.STATE_FINISHED: ... break; default: break; } } Then just let it rip: boolean started = _animation.start(from, to, ANIMATION_DURATION, EASING_CURVE)) if (!started) { // Failed to start the animation! Handle this situation gracefully - maybe by just jumping to the "to" point. } Summary It's not hard to do animations with Java ME. However, it requires work and when you decide to implement the animations, make sure you do it in a way that you can re-use your stuff later in your other projects. The study, explained in this article, produced an animation package that is quite generic and you are free to use it and expand it with your own easing curves. Further improvements to this package would include implementing a dedicated thread for animations. The current implementation is basically based on just fire-and-forget principle.
http://developer.nokia.com/community/wiki/index.php?title=Creating_Simple_Animations_with_Java_ME&oldid=201386
CC-MAIN-2014-35
en
refinedweb
I'm trying to implement an anisotropic version of GGX in UDK. Here is what the shader looks like: float3 H = normalize(L + V); float NdotL = saturate(dot(N, L)); float NdotV = dot(N, V); float NdotH = dot(N, H); float LdotH = dot(L, H); float HdotX = dot(H, X); float HdotY = dot(H, Y); float NdotH_2 = NdotH * NdotH; float HdotX_2 = HdotX * HdotX; float HdotY_2 = HdotY * HdotY; float ax_2 = ax * ax; float ay_2 = ay * ay; float GGX = (ax * ay * pow(HdotX_2 / ax_2 + HdotY_2 / ay_2 + NdotH_2, 2.0)); float3 F = Ks + (1.0 - Ks) * exp(-6 * LdotH); float3 Rs = F / (4 * GGX * LdotH * LdotH); float3 Rd = Kd * (1 - Ks); return (Rs + Rd) * NdotL; The problem is I'm not sure what to use for vectors X and Y. Because this is UDK, vectors L and V are relative to the surface (tangent space), so would I simply use X = [1, 0, 0], Y = [0, 1, 0]? Edited by Chris_F, 12 February 2013 - 08:05 PM.
http://www.gamedev.net/topic/638701-anisotropic-specular/?forceDownload=1&_k=880ea6a14ea49e853634fbdc5015a024
CC-MAIN-2014-35
en
refinedweb
Interface class for identity linear operators. More... #include <Thyra_IdentityLinearOpBase.hpp> Interface class for identity linear operators. This interface represents a identity linear operator M of the form: M = I In other words, subclasses define apply() as: y = alpha*M*x + beta*y = alpha * x + beta * y Definition at line 68 of file Thyra_IdentityLinearOpBase.hpp.
http://trilinos.sandia.gov/packages/docs/r11.2/packages/thyra/doc/html/classThyra_1_1IdentityLinearOpBase.html
CC-MAIN-2014-35
en
refinedweb
:) >> What is even better yet is that you can port all of your Windows 8 applications into the phone in a few swift and easy steps. You obviously have never tried this, there is very little compatibility between the two platforms, unfortunately Hi ErikEJ, that's not true at all, let me explain to you. Windows 8 and Windows Phone 8 are sharing the same runtime, not all of it, but a significant subset of Windows Runtime is built natively into Windows Phone 8. This give you the ability to use the same APIs for common tasks like networking, sensors, location data, InApp purchase, proximity, Touch, Threading, etc. Using this common Windows Runtime API you increase the share code between WP8 and W8 Store Apps to save time and improve the maintainability. So it depends of the App, you can reuse up to 90% of your code, 50%, 30% depends of the app obviously. My recommendations: 1) Use a pattern MVVM, and use a Portable Class Library with W8 and WP8 compatibility and put all your models and viewmodels inside. 2) Be sure what APIs are 100% re-usable before use them in the app, Windows Phone 8 Runtime is a subset of the W8 Runtime, but still the same one, is not different. 3) XAML, design re-use. The set of controls used on Windows 8 is in the Windows.UI.Xaml.Controls, the Windows Phone 8 one is System.Windows.Controls although these are different namespaces and the types are different, there's a lot of similarity in the controls that are supported (names are the same). 4) SharedClasses: As you probably know Portable Class Library doesn't support Windows Runtime API so in this case you can create your portable code in a shared class and link this class from the W8 and WP8 projects. It's true that there is not much information about how to migrate apps from WP8 to W8 and from WP8 to W8 but it will come very soon, so please stay tuned!
http://blogs.msdn.com/b/msgulfcommunity/archive/2012/11/18/windows-phone-8-sdk-is-this-what-you-were-waiting-for.aspx?Redirected=true
CC-MAIN-2014-35
en
refinedweb
Excel worksheet protection The following example shows how you can protect a worksheet. Note that specifying advanced settings like sheet password is supported only in XLSX and XLS and allowing some objects to be editable is supported only for XLSX file format. using GemBox.Spreadsheet; class Program { static void Main() { // If using Professional version, put your serial key below. SpreadsheetInfo.SetLicense("FREE-LIMITED-KEY"); var workbook = new ExcelFile(); var worksheet = workbook.Worksheets.Add("Sheet Protection"); worksheet.Cells[0, 2].Value = "Only cells from A1 to A10 are editable."; for (int i = 0; i < 10; i++) { var cell = worksheet.Cells[i, 0]; cell.SetValue(i); cell.Style.Locked = false; } worksheet.Protected = true; var%"); } } Imports GemBox.Spreadsheet Module Program Sub Main() ' If using Professional version, put your serial key below. SpreadsheetInfo.SetLicense("FREE-LIMITED-KEY") Dim workbook = New ExcelFile Dim worksheet = workbook.Worksheets.Add("Sheet Protection") worksheet.Cells(0, 2).Value = "Only cells from A1 to A10 are editable." For i = 0 To 9 Step 1 Dim cell = worksheet.Cells(i, 0) cell.SetValue(i) cell.Style.Locked = False Next worksheet.Protected = True Dim%") End Sub End Module Want more? Like it? Published: December 13, 2018 | Modified: March 20, 2020 | Author: Damir Stipinovic
https://www.gemboxsoftware.com/spreadsheet/examples/excel-sheet-protection/704
CC-MAIN-2020-50
en
refinedweb
Introduction to Mule 4: Error Handlers. Now, each component declares the type of errors it can throw, so you can identify potential errors at design time. Mule Errors Execution failures are represented with Mule errors that have the following components: A description of the problem. A type that is used to characterize the problem. A cause, the underlying Java Throwablethat resulted in the failure. An optional error message, which is used to include a proper Mule Message regarding the problem. For example, when an HTTP request fails with a 401 status code, a Mule error provides the following information: Description: HTTP GET on resource ‘’ failed: unauthorized (401) Type: HTTP:UNAUTHORIZED Cause: a ResponseValidatorTypedException instance Error Message: { "message" : "Could not authorize the user." } Error Types In the example above, the error type is HTTP:UNAUTHORIZED, not simply UNAUTHORIZED. Error types consist of both a namespace and an identifier, allowing you to distinguish the types according to their domain (for example, HTTP:NOT_FOUND and FILE:NOT_FOUND). While connectors define their own namespace, core runtime errors have an implicit one: MULE:EXPRESSION and EXPRESSION are interpreted as one. Another important characteristic of error types is that they might the existing app’s behavior. When it comes to connectors, each connector defines its error type hierarchy considering the core runtime one, though CONNECTIVITY and RETRY_EXHAUSTED types are always present because they are common to all connectors. Error Handlers Mule 4 has redesigned error handling by introducing the error-handler component, which can contain any number of internal handlers and can route an error to the first one matching it. Such handlers are on-error-continue and on-error-propagate, which both support matching through an error type (or group of error types) or through an expression (for advanced use cases). These are quite similar to the Mule 3 choice ( choice-exception-strategy), catch ( catch-exception-strategy), and rollback ( rollback-exception-strategy) exceptions strategies However, they are much simpler and more consistent. If an error is raised in Mule 4, an error handler will be executed and the error will be routed to the first matching handler. At this point, the error is available for inspection, so the handlers can execute and act accordingly, relative to the component where they are used (a Flow or Try scope): An on-error-continuewill execute and use the result of the execution, as the result of its owner (as if the owner had actually completed the execution successfully). Any transactions at this point would be committed as well. An on-error-propagatewill roll back any transactions, execute, and use that result to re-throw the existing error, meaning its owner will be considered as “failing.” Consider the following application where an HTTP listener triggers a Flow reference to another flow that performs an HTTP request. If everything goes right when a message is received (1 below), the reference is triggered (2), and the request performed (3), which results in a successful response (4). If the HTTP request fails with a not found error (see 3 above) because of the error handler setup of inner-flow, then the error will be propagated (4), and the flow reference will fail (2). However, because primary-flow is handling that with an on-error-continue, this will execute (5), and a successful response will be returned (6). If the request fails with an unauthorized error instead (3), then-thrown. For example, if the request fails with a method not allowed error (3), then it will be propagated, causing the flow reference to fail (2), and that propagation will result in a failure response (4). The scenario above can with the HTTP namespace: Try Scope For the most part, Mule 3 only allows error handling at the flow level, forcing you to extract logic to a flow in order to address errors. In Mule 4, we’ve introduced a Try scope that you can use within a flow to do error handling of just inner components. The scope also supports transactions, which replaces the old Transactional scope. The error handler behaves as we have explained earlier. In the example above, any database connection errors are propagated, causing the try to fail and the flow’s error handler to execute. In this case, any other errors will be handled, and the Try scope will be considered successful which, in turn, means that the next processor in the flow, an HTTP request, will continue executing. Error Mapping Mule 4 now also allows for mapping default errors to custom ones. The Try scope is useful, but if you have several equal components and want to distinguish the errors of each one, using a Try on them can clutter your app. Instead, you can add error mappings to each component, meaning that all or certain kind of errors streaming from the component will be mapped to another error of your choosing. If, for example, you are aggregating results from 2 APIs using an HTTP request component for each, you might. The next example maps HTTP:INTERNAL_SERVER_ERROR so that different handling policies can be applied if the APIs go down (propagating the error in the first API and handling it in the second API).
https://docs.mulesoft.com/mule-runtime/4.1/intro-error-handlers
CC-MAIN-2020-50
en
refinedweb
useRealTime: a React hook for dealing with real-time applications In the last few months, I found myself building a few applications and features inside existing projects which relied on real-time. That means having stuff being updated in real-time on the screen as time passes. After iterating the code, I came up with a handy React hook that can be used like this: import React from "react" import useRealTime from "./hooks/useRealTime" const RealTimeComponent = () => { const now = useRealTime() return <div>The current time is {now.toISOString()}</div> } export default RealTimeComponent How it works Our function uses two existing hooks: 1. useState This will store the current value and provide an updater function for it. Every time there is an update it will trigger a re-render. 2. useEffect This will create an interval, which will repeatedly call our time updater function with an up to date value with a fixed time delay between each call. The interval is created just once when the component mounts — notice the empty array [] of dependencies at the end (you can also omit the [] if you want). The interval is also cleared when the component unmounts. Also notice that the main useRealTime function accepts an interval parameter, which is the amount of time in milliseconds between each update and is set to 100 as default. You could use it like this: const now = useRealTime(200) In the end, we just return the current now value. The hook import {useState, useEffect} from "react" const useRealTime = (interval = 100) => { // 💾 const [now, setNow] = useState(new Date()) // ⏱️ useEffect(() => { const realtimer = setInterval(() => { setNow(new Date()) }, interval) return () => { clearInterval(realtimer) } }, []) // 📨 return now } export default useRealTime
https://www.youfoundpiperguy.me/blog/a-React-hook-for-dealing-with-real-time-applications/
CC-MAIN-2020-50
en
refinedweb
ADC_InitSingle_TypeDef Struct Reference Single conversion initialization structure. #include <em_adc.h> Single conversion input.
https://docs.silabs.com/gecko-platform/3.0/emlib/api/efm32zg/struct-a-d-c-init-single-type-def
CC-MAIN-2020-50
en
refinedweb
Hi Simon, On Thu, 11 Mar 2004, Simon Waters wrote: > Care to name the platform? (I'm just curious). This was on NetBSD 1.6. > Better yet can we spot non-preemptive thread library at config time? I don't know (but it should be possible to create an ugly configure test...) The context in which I saw the problem is the NetBSD pkgsrc () that is a framework for packaging and building software. Pkgsrc is formally a NetBSD project, but it works on nearly all Unix-like operating systems. Pkgsrc sets up a unified environment when building packages. This environment includes the pthread library from the operating system, or the GNU PTH thread library for OS that do not have native threads. So testing for _POSIX_THREAD_IS_GNU_PTH solves my problem. (I don't think there are many other non-preemptive thread libraries out there...) > >. Hmm. I'm not sure which end conditions you mean, but the patch below is definitely more responsive... --- src/search.c.orig Tue Mar 16 00:04:30 2004 +++ src/search.c Tue Mar 16 00:07:48 2004 @@ -546,6 +546,10 @@ SET (flags, TIMEOUT); } } +#ifdef _POSIX_THREAD_IS_GNU_PTH + else if (NodeCnt & TIMECHECK) + sched_yield(); +#endif /* The following line should be explained as I occasionally forget too :) */ /* This code means that if at this ply, a mating move has been found, */ > We still have a known bug in the handling of games being reset whilst > the machine is thinking, does this cause a problem when you have no > pre-emptive threads? I have not seen that problem, but I have OTOH not tried it more than a couple of moves... :) /Krister
https://lists.gnu.org/archive/html/bug-gnu-chess/2004-03/msg00034.html
CC-MAIN-2020-50
en
refinedweb
Custom extensions have been an integral part of Fiori Elements Overview pages starting SAPUI5 version 1.48, with the SAP Web IDE version 180927 or higher the extensions can also be created using the Overview Page plugin. Let us take a look a the details. As a prerequisite import this project into your SAP Web IDE full stack. In this blog we will look into the details of adding a Custom Filter. Custom filters could be added in various scenarios Eg: where the filter value is not part of the GlobalFilterEntityType or its navigation entities, or the corresponding UI element used is not part of the supported list from Smart Filter Bar. - Step 1: Right click on the project and select New–>Extension - Select the Overview Page Extension and click Next - Select the Custom Filter and click Next. Notice the part highlighted in the yellow box in the screenshot below. It shows the files that are generated when you click finish on this wizard. - Click Finish on the Next Step - Notice the following section in the manifest where the new added fragment and controller files are added to the extensions object. - CustomFilter.fragment.xml and the custom.controller.js, created with the ext folder in webapp of the project are the files that we are interested in - Let us have a look at the files in detail. customFilter.fragment.xml has a sample code which we can make use of for this sample. Uncomment the section below <!– Example – Sales Order ID Filter –>, as we have SalesOrderID in the metadata used in this sample. With the property visibleInAdvancedArea set to true, you will already see it in the filter bar when you run the app with mockdata, as shown below <smartfilterbar:ControlConfiguration <smartfilterbar:customControl> <Input id="SalesOrderID" type="Text"/> </smartfilterbar:customControl> </smartfilterbar:ControlConfiguration> - Next we will look at the parts in the custom.controller.js that need to be adapted further for this new fitler to work. getCustomFilters() is the function that needs our attention.Define getCustomFilters() to return a filter object. Here too we have a sample code that needs further adjustment as follows: getCustomFilters: function () { var oValue2 = this.oView.byId("SalesOrderID").getValue(); var aFilters = [], oFilter2; if (oValue2) { oFilter2 = new Filter({ path: "SalesOrderID", operator: "EQ", value1: oValue2 }); aFilters.push(oFilter2); } if (aFilters && aFilters.length > 0) { return (new Filter(aFilters, true)); } } - With this our custom filter is ready to be used. You can enter the value “0500000001” in the Sales Order ID (Extension) field and see filtered data in the cards as follows: - But that’s not enough, since this is a custom filter the app developers need to take care of saving the app state while navigating away from the OVP and to restore on coming back.Define getCustomAppStateDataExtension(oCustomData) to store the application state. getCustomAppStateDataExtension: function (oCustomData) { var oCustomField2 = this.oView.byId("SalesOrderID"); if (oCustomField2) { oCustomData.SalesOrderID = oCustomField2.getValue(); } return oCustomData; } - Define restoreCustomAppStateDataExtension(oCustomData) to restore the application state. restoreCustomAppStateDataExtension: function (oCustomData) { var oCustomField2 = this.oView.byId("SalesOrderID"); oCustomField2.setValue(); if (oCustomData) { if (oCustomData.SalesOrderID) { oCustomField2.setValue(oCustomData.SalesOrderID); } } } With that you are all set to use the custom filter in your application. You will also notice that there are few other functions in the cusom.controller.js, let us now see what those are for? If you right click on the project and select New–>Extensions now you will see that only 2 options are allowed as shown below. The reason being any further filters that are to be added will be done via the same fragment and the getCustomFilters already generated. Also for other extensions like “Custom Navigation Parameters” “Custom Navigation Target”, “Modify startup extension”, the same custom.controller.js will be used. This will be discussed in detail in “Other Custom Extensions” blog. Thanks for nice Blog… Very Useful… Hi Prasita, I have followed the above block to add a custom filter in my app. but i’m not getting the smartFilters text boxes in the SmartFilter sections. Could please help to fix it. Are these the only filter fields you would expect to be added in the Smart filter bar? Do you also have other fields added to it using the UI.SelectionFields annotations? Yes. I’m expecting only the custom filter fields. i haven’t add any other filter fields using UI.SelectionFields Annotations. I have the same problem, the filters are blank. Hello Prasita, I have created OVP application using CDS , now I have added parameter to CDS , that parameter needs to be passed in WHERE clause. Is it possible to some how map this custom filter parameter with underlying CDS parameter ?? Also I tried replicating the things which are mentioned in below documentation ,but I am encountering some issues. Can you please once check below thread once, I have mentioned it in details.
https://blogs.sap.com/2018/11/02/fiori-elements-overview-pages-create-custom-filter-using-web-ide-plugin/
CC-MAIN-2020-50
en
refinedweb
. Errors - Session not created - Session does not exist. - No such window - The windowobject has been discarded, indicating that the tab or window has been closed. - Unexpected alert open - A user prompt, such as window.alert, blocks execution of command until it is dealt with. Examples Python: from selenium import webdriver session = webdriver.Firefox() session.get("") search_box = session.find_element_by_id("q") print(search_box.get_attribute("id")) Output: q Specifications.
https://developer.cdn.mozilla.net/en-US/docs/Web/WebDriver/Commands/GetElementAttribute
CC-MAIN-2020-50
en
refinedweb
How to translate Angular apps: @angular/localize and xlf How to translate your Angular application - a matter of choice Angular comes with a package called @angular/localize which is Angular's native way of translating your application. But there are also other packages - e.g. ngx-translate which has several advantages over @angular/localize. If you've already made your decision - this is the right tutorial for you. You might otherwise want to consider the following restrictions: Angular compiles your application with a specific locale. You have to build a separate application for each language. You can't change the locale at runtime Angular can only translate messaged found in your templates. You can't use translations in your source code (.ts files). If one of this is a restriction you can't live with checkout ngx-translate. This tutorial build a simple application with Angular 9 and adds translations to it. You can easily skip the first steps if you already have an application to work with. The example application is available as source code on github. Optional: Create a simple app to translate Now setup an application that you can use to experiment with some use-cases. You can skip this if want to work on an existing application. - Simple text - Text with a simple parameter - Text with a counter and a selection First, create a new, empty application: ng new angular-localization-demo Answer the questions like this: ? Would you like to add Angular routing? No ? Which stylesheet format would you like to use? SCSS Run ng serve and open your browser on Replace the content of the /app/app.component.html with the following code: <style> h1 {margin-bottom: 4rem} p {margin-bottom: 2rem} div {margin: 4rem; font-family: sans-serif; font-size: 14px;} </style> <div> <!-- static text --> <h1>Translation demo</h1> </div> Replace /app/app.component.ts with the following code: import { Component } from '@angular/core'; type Fruit = 'apple' | 'pear'; @Component({ selector: 'app-root', templateUrl: './app.component.html' }) export class AppComponent { name = "John Doe"; counter = 1; fruit:Fruits = 'apple'; public changeCounter(change:number) { this.counter = Math.max(0, this.counter+change); } public toggleFruit() { this.fruit = this.fruit === 'apple' ? 'pear' : 'apple'; } } Prepare your app for translation ng add @angular/localize Locale IDs Angular uses locale identifiers defined by BSP47. These identifiers consist of 2 parts: - language - country code Examples: en-US- English (en) spoken in the United States (US) en-GB- English (en) spoken in the Great Britain (GB) fr-FR- French (fr) spoken in France (FR) fr-CA- French (fr) spoken in Canada (CA) The country code has effects on the language (e.g. gray vs grey in en-US vs en-GB) but also effects how Angular formats numbers, dates, times, currencies and other values when you are using DatePipe, CurrencyPipe, DecimalPipe or PercentPipe. Angular's default locale is en-US. How to translate Angular template files The translation process for Angular applications consists of 5 steps: - Mark all text you want to translate in your templates. - Use the ng xi18ncommand line tool to extract the translations and create an XLIFF translation file - Translate the messages in the file (e.g. by using BabelEdit) - Edit the applications' configuration to recognize the new locale - Compile your application with the locales This tutorial takes you though all of these steps. We start with simple static text and go through the whole process. After that we'll cover pluralization and more complex stuff using the ICU syntax. Translating your first message The /app/app.component.html contains the following line: <h1>Translation demo</h1> To mark it as translatable text, you simply have to add an i18n attribute: <h1 i18n>Translation demo</h1> Simple. Now run ng xi18n --out-file src/locale/messages.en.xlf This generates a file called src/locale/messages.en.xlf - an XML based translation file in an industry standard format called XLIFF. This file contains all messages extracted from your source. Understanding translation IDs It now seems a bit low-level to take a deeper look at this file — but I am taking you here to help you understand and avoid problems in your project. In this file you see a so called trans-unit: <trans-unit <source>Translation demo</source> <context-group <context context-src/app/app.component.html</context> <context context-9</context> </context-group> </trans-unit> The trans-unit contains the source text in <source> and a file location. It also contains an attribute called id - that's an (ugly hexadecimal) identifier derived from the source text. Angular created this identifier for you because we did not specify any identifier manually. The problem with this identifier is that it changes each time you edit the source text! Add a simple ! after the text and run ng xi18n --out-file src/locale/messages.en.xlf <h1 i18n>Translation demo!</h1> See how the ID changed from fa498c44c35a9590523ab6de3c689aedcb33fb1d to 354127914de0aba23b09f129dcfbb0ba840bbecd. This is a problem because Angular uses the ID to reference the messages belonging together across multiple language files. If you've not created your translation in another file, the translation is now lost! Ouch! The better way is to specify translation IDs manually. The title has to start with @@. <h1 i18n="@@main.title">Title with manual ID</h1> You can use . in the title which allows you to structure your IDs. If you use BabelEdit you'll see the translations in a nice tree view which gives you even more control. Take a look at the messages.en.xlf: This is much better now: <trans-unit <source>Title with ID</source> ... </trans-unit> The translation process with BabelEdit I'll show you how to translate the file into German — simply because this is the language I know best :) Feel free to translate the file into a language of your choice. XLF is not meant to be edited by hand. Yes — you can do this. But: It's a real pain because you have to keep all your language files in sync. After adding a new message in one file you have to update all other language files. Do yourself a favor and download BabelEdit — for the sake of this tutorial. It comes with a free trial of 7 days, and it's quite inexpensive for a translation tool. Install and start the tool. Click on Angular and XLIFF to start a new translation project: Next drop your src/locale/message.en.xml onto the language configuration dialog. en-US as language. Click Add and New to add your first target language. Choose de-DE and change the file name to messages.de.xlf. In the last step select en-US as primary language. The primary language is the source language you use in your code. BabelEdit uses it for features like machine translations and suggestions. It also becomes read-only and can't be edited. The reason for this is that all changes you make to your source language would be over-written the next time you run ng xi18n. With these steps you should now see a screen similar to the following: . - The left side shows you the translation IDs available in your source code files. Note that the manually set translation ID main.titlehas a speech bubble icon. Translations with '.' automatically create a tree structure. Automatic IDs from Angular always craete a flat list. The hard-to-read IDs are replaced with parts of the source text. - The center view shows the selected translations from the left tree. Here is where you can see the full ID of the translation in the first line. - The text in the en-USedit fields is read only (primary language). - The text in the de-DErow is editable. - Click Enable if you want to send your source messages to Google Translate (TM) for suggestions and automatic translation of your files. BabelEdit now suggests translations for you: . Fill the German text fields and press Save. BabelEdit asks you to enter the name of a project file — this is used to save you the setup time. The file does not contain translation data — everything is stored in the xlf files directly. Adding the xlf translation file to your Angular app In your angular.json you have to specify the source language. For all target languages you set the file name from which the translated messages should be loaded: "angular-localization-demo": { "projectType": "application", "i18n": { "sourceLocale": "en", "locales": { "de": "src/locale/messages.de.xlf" } }, ... To build the app for all configured languages you have to add the following options to the project configuration in your angular.json: "architect": { "build": { "configurations": { "production": { "localize": true, "aot": true, "i18nMissingTranslation": "error" ... - the localizeoption tells Angular to build variants of your app for all languages. Instead of trueyou can pass a subset of your configured languages here, e.g. "localize": [ "en", "fr" ] - the aotoption enables ahead-of-time compilation. Angular does not support building localized apps in JIT (just-in-time) compilation mode. - the i18nMissingTranslationdefines what should happen if a translation is missing: by default a warning is displayed at compile-time and the app uses the source language text as fallback. If this option is set to error an error message is displayed and the build process is aborted. Note: If you enable save empty translations in the BabelEdit settings, missing translations will be saved as empty strings in the XLIFF file. Angular will no longer report these empty strings as "missing translation". ng serve can only serve one language. So you might want to define one build configuration per language, and refer to these build configurations in the serve configurations: "architect": { "build": { "configurations": { "de": { "localize": [ "de" ], "aot": true }, "en": { "localize": [ "en" ], "aot": true }, ... "serve": { "de": { "browserTarget": "angular-localization-demo:build:de" }, "en": { "browserTarget": "angular-localization-demo:build:en" }, ... With this configuration you can serve the localized app: ng serve --configuration=de You should now see the title in German. Providing more information to your translators With the manual IDs you can already give the translator some context. main.title says that this text is on the main screen, and it's the title - that's not perfect but at least better than nothing. You can give more context to the translator by altering the i18n attribute in the template: Add a more clear description before the @@: <h1 i18n="Long title on the main screen.@@main.title">Title with ID</h1> Run ng xi18n --out-file src/locale/messages.en.xlf and return to BabelEdit. The translation instruction from the file appears right after the translation ID. You can also add more detailed instructions by clicking on the little note-icon on the right. Messages with parameters (interpolation) Let's add a welcome message with the name as parameter to the template: <p i18n="Welcome message.@@main.hello">Hello {{name}}!</p> This simply places the value of the name variable in the text. In BabelEdit (after running ng xi18n) you'll see something like this: Hello <x id="INTERPOLATION" equiv-! For the translation simply copy the <x.../> to the target language. Don't change it. So the German translation is: Hallo <x id="INTERPOLATION" equiv-! Save in BabelEdit... and nothing happens in your Angular app. Yes. ng serve does not look for changes in .xlf files... you have to restart ng serve to see the changes. Number parameters and pluralization First run ng serve to switch back to the main language (English). Add a new message and 2 buttons (one for increment, one for decrement) to the project: <p i18n="@@icu.plural">There are {{counter}} apples in the basket.<p> <button (click)="changeCounter(-1)">+</button> <button (click)="changeCounter(1)">-</button> Ok... not exactly what you want? - There are 0 apples in the basket. - There are 1 apples in the basket. - There are 5 apples in the basket. Yes - we can do better! With ICU syntax and something that is called pluralization: <p i18n="@@icu.plural">There {counter, plural, =0 {are no apples} one {is one apple} other {are {{counter}} apples} } in the basket.<p> The syntax consists of the following: counter- the variable that is used for the choice - see app.component.ts plural- a keyword that triggers the pluralization <selector> {text}- the selector activates the following text in {}if the condition is met <selector> can be one of the following: =0, =1, =2, ... one two few- not available in all locales many- not available in all locales other The {text} can be any text — you can even create nested ICU messages. #as placeholder for the current value. Angular does not. If you want to write the counter value you have to use {{counter}}. Click on the + and - buttons to see the message change: - There are no apples in the basket. - There is one apples in the basket. - There are 5 apples in the basket. That's way better! ICU pluralization is not working!If only the first entry works (=0) the reason is usually that you added a comma ,after the first entry. Run ng xi18n --out-file src/locale/messages.en.xlf and open BabelEdit. Ok — now something unexpected happens: Instead of one you now get 2 new entries! I don't know why the Angular developers do this. There is practically no reference from the message you created to the sub-entry Angular creates. You might say: The text {counter, plural, =0 {...} one {...} other {...}} is the reference - that's right in this case. But the reference is exactly the same for each other entry that uses =0, one and other. Angular's manual states that the automatically generated entry is directly below the manual one. But this is also not always the case... I've opened a ticket in 2017: Translate select and plural looses references in xliff, xliff2 and xmb files... but nothing changed since. I am sorry to say so: We have to live with this for now... Another sad thing is that Angular automatically drops all formatting and newlines we added to the ICU messages for better readability. As I already mentioned: We have plans to add an ICU editor to BabelEdit to solve this. :) The manually generated message now is: en-US: There <x id="ICU" equiv- in the basket. de-DE: Es <x id="ICU" equiv- im Korb. and the automatically generated one is: en-US: {VAR_PLURAL, plural, =0 {are no apples} one {is one apple} other {are <x id="INTERPOLATION" equiv- apples} } de-DE: {VAR_PLURAL, plural, =0 {sind keine Äpfel} one {ist ein Apfel} other {sind <x id="INTERPOLATION" equiv- Äpfel} } Selections in ICU syntax Let's assume you also want to extend the application to not only support apples but also pears. We don't apply plurals later. Let's deal with one entry for the start. fruit is a variable of an enum type: enum Fruit { apple='apple', pear='pear' }; with this you could write: <!-- simple select --> <p i18n="@@icu.selection">There is one {{fruit}} in the basket.<p> <button (click)="toggleFruit()">Change fruit</button> Ok... so... this renders to There is one 0 in the basket.. Right. Enums are numbers. We can use an ICU select for this: <p i18n="@@icu.selection">There is {fruit,select, 0 {apple} 1 {pear} } in the basket.<p> There is unfortunately no way to use the enum values instead of the numbers in the template. The only way I know around this is to set a string value for each enum entry: enum Fruit { apple='apple', pear='pear' }; Now you can write the following in the template: <p i18n="@@icu.selection">There is one {fruit,select, apple {apple} pear {pear} } in the basket.<p> You can of course use defined strings instead: type Fruit = 'apple' | 'pear'; Run the extraction and open BabelEdit. In German and several other languages (e.g. French) you have to put the article or numerals ("one") inside the select. The reason is that these languages use different articles/numerals depending on the gender of the noun. en-US: There is one <x id="ICU" equiv- in the basket. de-DE: Es ist <x id="ICU" equiv- im Korb. en-US: {VAR_SELECT, select, apple {apple} pear {pear} } de-DE: {VAR_SELECT, select, apple {ein Apfel} pear {eine Birne} } Dealing with Angular's auto-generated IDs For the sake of consistency I'd recommend putting the "one" inside the selection - but you don't have too. ICU is clever enough to deal with both variations... anyways let's do it because I'd like to show you another pitfall with Angulars' translation module: Change the template to this: <p i18n="@@icu.selection">There is {fruit,select, apple {one apple} pear {one pear} } in the basket.<p> Extract the messages with ng xi18n --out-file src/locale/messages.en.xlf and open BabelEdit: What you see here is: - The ID that was removed by Angular - the source language is empty. - The new ID with no translation. BabelEdit keeps it open for you so that you can copy the texts to the new IDs. You can find these orphaned translations using BabelEdits filter function: Now copy the text from the deleted translation to the new id. After that use the menu item Edit / Delete unused translation... to get rid of them. Nesting ICU message Let's now combine both examples: We want to change the counter and the fruit type. The English sentence is simple - because the gender of the fruit does not influence the numeral: <p i18n="@@icu.combined"> There {counter, plural, =0 {are no {fruit, select, apple {apples} pear {pears}} } one {is one {fruit, select, apple {apple} pear {pear}} } other {are {{counter}} {fruit,select, apple {apples} pear {pears}} } } in the basket. <p> Ok - this works in English. Now run ng xi18n --out-file src/locale/messages.en.xlf and open BabelEdit: You now see a new entry icu.combined with this text: en-US: There <x id="ICU" equiv- in the basket. Add the German translation: de-DE: Es <x id="ICU" equiv- im Korb. Easy. The nested ICU part of the translation now became: en-US: {VAR_PLURAL, plural, =0 {are no {VAR_SELECT, select, apple {apples} pear {pears} } } one {is one {VAR_SELECT_1, select, apple {apple} pear {pear} } } other {are <x id="INTERPOLATION" equiv- {VAR_SELECT_2, select, apple {apples} pear {pears} } } } What you see here is that Angular for some strange reason does not create nested entries beyond the first level. So... let's translate this. As seen in our table from above we have to move the "is one" into the select: de-DE: {VAR_PLURAL, plural, =0 {sind keine {VAR_SELECT, select, apple {Äpfel} pear {Birnen} } } one {ist {VAR_SELECT_1, select, apple {ein Apfel} pear {eine Birne} } } other {es sind <x id="INTERPOLATION" equiv- {VAR_SELECT_2, select, apple {Äpfel} pear {Birnen} } } } Ok... it works! My opinion about @angular/localize If you've read through this text you might already sense that I am no fan of @angular/localize. When I am comparing it to ngx-translate, I don't see any advantage in using it. @angular/localize requires you to - Build separate apps for each language - Does not allow changing translations at runtime - Has several quirks when creating xlf files - Does not allow translating stuff in source code - only templates - Changing translations during development requires restarting ng serve If you think otherwise or have a great solution for these issues: Please contact me :) If you (or your boss) decides that you have to use it I can only recommend trying BabelEdit. It'll be a big help for you: It keeps your translation files consistent across all languages. Without it you'll end up copying new messages from one language file to another manually. It also takes the pain out of editing XLF files. Did you like the tutorial? Please share! Source code available for download The source code is available on GitHub. Clone it using git: git clone or download one of the archives: angular-localize-xlf-example.zip angular-localize-xlf-example.tar.gz
https://www.codeandweb.com/blog/2020/06/05/how-to-translate-your-angular9-app-with-xlf-files
CC-MAIN-2020-50
en
refinedweb
Interop Routing and Event System for UI5 This is a library for UI5 that allows many instances of UI5 applications to run simultaneously, integrated or independently of each other in sub-containers (side by side, or embedded) Container applications can register their container locations so that any app can navigate to a chosen container (eg: Left/Right/Header/Footer/Main/Master/Other) It also provides methods for communicating between those applications (simplified version of EventBus, for ease of use) What can you use it for? Use your imagination! but here’s a few examples, you can use this to compare two client records (instantiate the same fiori view twice, side by side, with different route params) Or even run completely different applications independently in the same window (for example, your Inbox in a side or top panel, so you can keep track of your job queue at all times) Why not just use ComponentContainers? Flexibility, Simplicity, and Routing. Even if you were to use ComponentContainers, how do you route them? how do you maintain two route url’s on the one page? these problems are solved in my Interop solution. And all apps that run this way, can be built in the usual UI5 way with standard routers. So all of your existing UI5 apps can be run in containers, and any new apps you build using Interop can still run as standalone applications when necessary. (aka: no dependency or tight coupling!) Why did I build this? I’ve seen a few attempts at building ‘frameworks’ that could dynamically call upon different UI5 applications, and I thought I could do better, so I gave it a shot. What bugged me most about these solutions I saw, was that any app or view used in them would follow a very custom pattern and was usually tightly-coupled. I wanted to do it in a reliable way, a standardised way, one that didn’t require re-training of staff to be able to use it, so any ui developer could write a standard app and it would work within it. I also thought it would be a very cool thing, to be able to run an Inbox application as a slide in panel, while also being able to compare two records side-by-side, and have process flows tracked in a header, etc etc. So… here we are. Limitations / Assumptions It it assumed that all applications using Interop use two word namespaces. eg: “product.app” if this isn’t the case you will run into trouble. This is the namespace convention I’m used to working with and have personally seen the most, which is why I’ve built it in this way. It could be made configurable, but you’d still need to at least be consistent (eg: 3 names is fine, but ALL apps would need to be 3 names) Download The Interop Library can be found on GitHub: Now, Let’s jump right in… Ok, so that’s the introduction / text-book stuff out of the way! I’ll show you what this little thing can do. I’ve created a sample container application, which is included in the Git repository. It is fully featured, I’ve not even utilised all the panels I’ve setup in it, so it should serve well as a starting point for most use cases. In my example I’ve created a split-app, and one other additional app, and am demonstrating how views from the split-app can be instantiated multiple times side by side for record comparisons. Here’s a few screenshots of me playing around with the panels. select a record expand the right hand panel click ‘move’ button on the right hand panel tick duplicate and apply (so that content on the main panel will be duplicated into the right side as a new instance) select a different record in the master list (which will update just our main content panel) click an action that performs a navigation, and see that only the relevant panel is affected I could go on and on, but I think this is enough to demonstrate what’s going on. Additionally to what i’ve done here, it should be noted that demoapp1 (this master/detail app) can be run in standalone mode, from its own index page. Even the inter-app routing has fallback routines to facilitate this. Try it for yourself. Live copy (HCP account required) How it works Merged URL Route Patterns You may not have noticed it at first, but the URL in this app has a querystring of “?nav=” This parameter is generated by Interop, and is a combined version of every panels current route pattern (for example, there’s two client records, so each instance of that view needs different parameters fed into its onRouteMatched event handler). You’ll also notice that it’s hard to read… that’s because I’ve implemented string compression, to keep it from getting too long. It also has the added advantage of discouraging users from messing with the url. However, if you would like it to be more readable, you can turn off Url Compression. These constructed URL’s allow the users session to be maintained, so if they hit F5 to refresh the page, it will remember what to load. Likewise they can copy&paste the URL into an e-mail and the correct configuration of views will be loaded when the recipient clicks it. While this could’ve been done automatically, I have designed this to be triggered by the container application, for reasons that will become obvious soon.. In the container app you’ll notice these little pieces of code for maintaining sessions //this allows the Interop system to manage browser history Interop.setRestoreOnBrowserBack(true); var sessionResult = Interop.restoreSession(); if(!sessionResult.restored) { //no existing route info, this is a blank run updateUrl: function() { if(this._loaded) { //save the session, and add additional session states (the state of expansion of the panels) //by doing this, we enable the page to be refreshed with f5 or the url to be copied & pasted into another browser, without losing track of what's in each panel Interop.saveSession({ me: window._masterOpen || false, re: this.oLayoutData.RightPanelOpen, rw: this.oLayoutData.RightPanelBig }); } }, You may have already gathered, that the container gets the opportunity to add its own custom session variables, these will be encoded into the ?nav= URL string along with the base information. (in this sample, it is used to remember the expanded state of the master and right hand panels) The container also controls what to do if a session isn’t present (in this case, my sample container looks for normal ui5 route parameters to see if an app has been specified, and load it, if not, it defaults to demoapp1) The setRestoreOnBrowserBack(true) is simply a necessity because browser events will be hooked when this is called. This allows the user to press the back button in their browser and have their session restored automatically by Interop Virtual Router Objects To allow legacy routing (apps running standalone OR within containers) without further development effort inside the app, virtual (or proxy) routers are created on the fly by Interop to simulate commonly used functionality of the standard SAP router classes. This means that when you call this.getRouter() you are getting a dummy object, that will simply translate your standard .navTo requests into Interop navigateContainer calls automatically. These virtual routers also handle onRouteMatch events, and will parse in all the same parameters you would usually expect, along with a few new ones (like “container”, telling you which container you’re in) To use virtual routers, simply inherit the dalrae.ui5.BaseController in all your view controllers. Or, copy its .getRouter function into your own base. onBeforeRendering: function() { //fallback routing support (allows apps to run standalone and still call .navigateContainer) -PhillS if(dalrae.ui5.routing.Interop.UseFallbackRouting) { dalrae.ui5.routing.Interop.mFallbackRouter = this.getRouter(); } }, // supports our Interop component containers method of routing -PhillS getRouter: function() { //UPDATED to work with manifest style apps -PhillS var router = sap.ui.core.UIComponent.getRouterFor(this); if(!router || dalrae.ui5.routing.Interop._cc ) { if(dalrae.ui5.routing.Interop._cc[dalrae.ui5.routing.Interop.StandardContainer.Main] || !router) { var router2 = dalrae.ui5.routing.Interop.getRouterFor(this); if(router2) { return router2; } } } if(dalrae.ui5.routing.Interop.UseFallbackRouting) { //fallback routing support (allows apps to run standalone and still call .navigateContainer) -PhillS dalrae.ui5.routing.Interop.mFallbackRouter = router; } return router; }, Essentially, the standard routers are totally overwritten by Interops own routing code, which is designed to emulate the sap router as closely as possible. Of course, some methods might be missing from my version of the router, and if this is an issue for your implementation you may need to extend the class yourself (or let me know). Globally Registered Containers Each area of the screen that is route-able, is registered as a container. This means that the container app, and the contained app, do not need to know each other. They simply need to know container id’s, such as “main” and “master” to interact, so neither are coupled or dependant upon each other to operate. The easiest way to do this is to just use the dalrae.ui5.routing.Container element in your XML view and assign it one of the standard id’s. However, you can use any UI element that has a <content> aggregation. To do so, you can call Interop.registerContainer() Interop.registerContainer( Interop.StandardContainer.Main , oPanel ); or <mvc:View xmlns: <routing:Container Container Navigation Inter-app navigation is highly simplified. rather than constructing deeplink urls, you can navigate a container to a completely different applications view by simply using the navTo parameters for that view. //demonstrating an Interop cross app navigation. Interop.navigateContainer( Interop.StandardContainer.Main , { app: "sample.demoapp2", nav: [ "main", { example: "an example parameter" } ] }); The only addition is the container ID, and the app namespace. Although it is also worth noting, that namespaces must be registered before being used. This is needed in Gateway/Launchpad systems, which use SemanticObjects. But in Hana you’ll still need to do it (until I come up with a clever way to autodetect Hana systems that is) //Registering a namespace in Hana Interop.registerNamespace("sample.demoapp1"); //Registering a namespace in Gateway Interop.registerNamespace("sample.demoapp1","ZDEMOAPP1"); The added perk of doing this, is that the master list can remain loaded as app1, while the main content panel can navigate off to app2, so the user doesn’t need to go back a screen in order to access another record from app1, which is far less disruptive to the user flow of the program. Global Event System As mentioned, a replacement to the EventBus system is provided. It works in basically the same way. My main motivation for doing this was to make the event signatures consistent with all other elements of UI5, which the event bus isn’t. To use it, you can register event handlers in any view of any app, and fire those events from anywhere as well. I haven’t really used much of these in my sample, but they are useful for when you’d like your applications to actually be able to talk to each other. There’s plenty of things you can achieve by having panels communicate. You could for example, have an event fired each time the main panel opens a client record, and have the header panel pop down with alerts or available actions for that client number, regardless of which app that client is being viewed in. Also, the Interop navigation fires off a few inbuilt events that you can take advantage of, and these, are in fact being used in my Sample so you can see them in action. OnNavigate: This event is fired when any container is navigated anywhere. So any program listening to this event will see the navigation of every other program. This is good for container applications which may want to show or hide certain panels. Parameters: app : app namespace (eg: “sample.demoapp1”) name : route name arguments : routing parameters container : ID of the container (eg: “main”) sessionRestore : true/false OnContainerCleared: This event is fired when any container has its content cleared via clearContainer, clearAllContainers, or a session restore. Parameters: container : ID of the container (eg: “main”) sessionRestore : true/false OnSessionRestored: This event is fired when a route pattern is successfully or unsuccessfully restored from a URL or custom source via the restoreSession() call Parameters: restored : true/false navs : internal data of the session extraStateInfo : custom values included in the session Flexible Layout Just to re-iterate… you can create any container application layout you like. Just be sure to use the standard container id’s (or if making your own, be consistent) and it will work just fine. You can even have multiple container apps if you like. The sample I have provided is precisely that, a sample, and I haven’t even used it to it’s full potential in this example. It actually has many active panels ready to go (diagram below) But as stated, just a sample, so go nuts, make your own, go crazy! Conclusion I don’t know how many of you will utilise this system, but I thought it was worth sharing, as it’s the kind of functionality I’d like to see available out-of-the-box. Being able to compare two client records, and giving users the choice to move content around, is something I’m eager to see, there’s many cool things I can think of that become possible. Additionally, the applications I’ve tried running in this way, have (in my opinion) run much smoother, since you never need to reload the entire screen. I’ve uploaded the code to GitHub with an MIT license, so you are free to use it yourself Download The Interop Library can be found on GitHub: Phillip, great blog. It’s exactly what I need. Just trying to understand how to implement interop. May need is a one container in which I can start serveral different applications depending on say for example which button I press in the container app. Is it possible to point me in the right direction. Regards Erik Hi Erik, I’m not sure exactly what scenario you’re talking about so I’m sorry if I miss the mark here. I assume you have an application already running in the main area (within a container) and when you perform an action (press button A), you want to open another application in another panel? There’s a few ways, the simplest way which seems adequate in your case is to just call the navigateContainer function, and have the container automatically open the target panel when it detects something navigated there (onNavigate) So for example: Then in the container app, you’ll see in the sample that there’s a handler of onNavigate, this will fire globally, when anything is navigated anywhere, so we use this to know that something has navigated that Right hand panel, and do something about it (expand it out so it’s visible, presumably) In more complex scenarios, you might want to setup custom events for your applications to fire, and let global logic in your controller completely handle what to do about those events. I hope that helps Phillip Thanks that worked.:) Iam now trying to start an app that is deployed on a abap stack. The question i have is it possible to navigate by using the semanticObject. As the app that i want to start is used on the FioriLaunchpad. Below you see how we now navigate from one app to the another one. var hash = oCrossAppNavigator.hrefForExternal({ target: { semanticObject: “PMApplication”, action: “CreateOrder” }, params: { “Guid”: oData.Guid } }); The downside is it opens in a new tab of the browser. We would like to open it within the current application as you do with the interop libs. Any ideas what we are doing wrong. Thanks Erik Hi Erik, Glad to hear it! I haven’t written up a navigate function to read semantic objects yet (it was something I thought I might do in future as an enhancement). Though it isn’t actually necessary for running on the abap stack. I have run this solution on a CRM system successfully, the navigation doesn’t change, all that changes is the registerNamespace call you make. What I mean is, when you want to navigate to your new app, you will still just use its namespace “your.app1” and not its semantic object. What you will have to setup beforehand though, is its BSP name. The reason for this, is Interop looks directly at the internal addresses of the BSP’s rather than the launchpad generated alias. so when your app starts (preferably in a common base class somewhere), you need to register all the applications you might possibly navigate to, doing so links their BSP and Namespace for Interop, like so Now when you ask Interop to load “your.app1” it knows how to construct a url to find it, because you’ve registered the BSP name So now you just do the navigateContainer the same as before. Now what this doesn’t solve for you, is your use of an action “CreateOrder”. Interop currently does not parse action/intent. Personally I avoid using them but obviously it’s what you’ve implemented so you’d need to either move that to a parameter of your route, or enhance Interop to facilitate parsing action through somehow. I no longer have easy access to an abap system so I can’t be of much more assistance I’m sorry. Hey Phillip, By implementing it as you said before(see code below) it works The navigation works and when debuggen I see that the second application “plannus” is loaded and Iam walking through the component of the app which then loads the appropriate view as stated in the manifest. I enter the controller of the view where the existing code doesn’t find the component any more. this statement errors as the ownerid is undefined this._oComponent = sap.ui.component(sap.ui.core.Component.getOwnerIdFor(this.getView())); How do i locate the correct component cheers Erik Thanks for you’re Help Hi Erik, Take a look at the BaseController I’ve setup, it has methods for getting the router and component (which will work inside Interop as well as Standalone), implementing these functions in your own base controller would be the fastest way to get up and running I believe, and use this.getComponent(). It is unfortunate that you will have to change that line of code in your application, since the idea is to not have to change any apps, but this is the exception to the rule. As long as everything is utilising a base controller you should be able to keep everything tidy and neutral Hope that helps Hi Phillip, Thanks for the reply. That worked for me. I agree it is a shame to change the app that is called but as you mentioned the change is minor. cheers Erik
https://blogs.sap.com/2018/06/14/interop-a-system-for-running-multiple-ui5-application-instances-simultaneously/
CC-MAIN-2020-50
en
refinedweb
Hi, how can we simplify a groovy code for several sql request which are not same. i'm querying different table for different data so i have at least 50 sql queries and for each query i set propertis with data retrieved from table. My problem is: i have 50 sql queries. Is there a way to simplify this code. I cannot use loop because all tables are differents. example of query: StringBuilder builder = new StringBuilder() def tableValues = sql.eachRow("select type from order where id = "abc123"") { row -> builder.append( "${row.type}" ) } //Set properties String myvalue = builder.toString() testRunner.testCase.setPropertyValue( "type", type) StringBuilder builder2 = new StringBuilder() def tableValues2 = sql.eachRow("select name from product where desc = "yzx"") { row -> builder.append( "${row.name}" ) } //Set properties String myvalue2 = builder2.toString() testRunner.testCase.setPropertyValue( "name", name) Solved! Go to Solution. I would probably just put the results into the test run context. context.type = sql.firstRow('select type from order where id = ?', ["abc123"]).typecontext.name = sql.firstRow('select name from product where desc = ?', ["yzx"]).name That form uses prepared statements, which you should be doing and is not much more difficult. To get the values in a request's body: ${type} ${name} To get the values in another groovy script: context.type context.name View solution in original post Thank you so much JHunt. in the case i have this sql request: select type from order where number = "789" and id = "abc123"; i tried this: context.type = sql.firstRow('select type from order where number ="789" and id = ?', ["abc123"]).type it returns error
https://community.smartbear.com/t5/SoapUI-Open-Source/How-to-simplify-groovy-code-for-several-sql-request-in-different/m-p/189838
CC-MAIN-2020-50
en
refinedweb
IOpipe v0.9.1 Released: An AWS Lambda Analytics and Tracing Agent for Python iopipe-python - Python agent for AWS Lambda tracing & analytics... (more…)Read more » asciimatics – A cross platform package to do curses-like operations, plus higher level APIs and widgets to create text UIs and ASCII art animations… Read more iopipe-python - Python agent for AWS Lambda tracing & analytics... (more…)Read more » python-for-android - Turn your Python application into an Android APK... (more…)Read more » This article was originally published at more » import operator f = lambda n: reduce(operator.mul, range(1,n+1))... (more…)Read more » clype - Python library for creating command line interfaces using type annotations... (more…)Read more »
https://fullstackfeed.com/asciimatics-cross-platform-curses-like-functionality-for-python/
CC-MAIN-2018-13
en
refinedweb
This is one of the 100 recipes of the IPython Cookbook, the definitive guide to high-performance scientific computing and data science in Python. Decisions trees are frequently used to represent workflows or algorithms. They also form a method for non-parametric supervised learning. A tree mapping observations to target values is learnt use this method to find the features the most influent on the price of Boston houses. We will use a classic dataset containing a range of diverse indicators about the houses' neighborhoud. import numpy as np import sklearn as sk import sklearn.datasets as skd import sklearn.ensemble as ske import matplotlib.pyplot as plt import matplotlib as mpl %matplotlib inline mpl.rcParams['figure.dpi'] = mpl.rcParams['savefig.dpi'] = 300 data = skd.load_boston() The details of this dataset can be found in data['DESCR']. Here is the description of all features: The target value is MEDV. RandomForestRegressormodel. reg = ske.RandomForestRegressor() X = data['data'] y = data['target'] reg.fit(X, y); reg.feature_importances_. We sort them by decreasing order of importance. fet_ind = np.argsort(reg.feature_importances_)[::-1] fet_imp = reg.feature_importances_[fet_ind] fig = plt.figure(figsize=(8,4)); ax = plt.subplot(111); plt.bar(np.arange(len(fet_imp)), fet_imp, width=1, lw=2); plt.grid(False); ax.set_xticks(np.arange(len(fet_imp))+.5); ax.set_xticklabels(data['feature_names'][fet_ind]); plt.xlim(0, len(fet_imp)); We find that LSTAT (proportion of lower status of the population) and RM (number of rooms per dwelling) are the most important features determining the price of a house. As an illustration, here is a scatter plot of the price as a function of LSTAT: plt.scatter(X[:,-1], y); plt.xlabel('LSTAT indicator'); plt.ylabel('Value of houses (k$)'); You'll find all the explanations, figures, references, and much more in the book (to be released later this summer). IPython Cookbook, by Cyrille Rossant, Packt Publishing, 2014 (500 pages).
http://nbviewer.jupyter.org/github/ipython-books/cookbook-code/blob/master/notebooks/chapter08_ml/06_random_forest.ipynb
CC-MAIN-2018-13
en
refinedweb
0 I'm going to have to include a lengthy bit of code, but its every necessary part for you to see what I need. import random availableCountries = range(20) # <--- Used at games start, player's countries taken from here firstTurnsCountries = [] # <--- Player one's country possesion secondTurnsCountries = [] # <--- Player two's country possesion pL0 = " " pL1 = " " pL2 = " " # Stores initial blank values for visual display of the continent pL3 = " " pL4 = " " pL5 = " " pL6 = " " pL7 = " " pL8 = " " pL9 = " " pL10 = " " pL11 = " " pL12 = " " pL13 = " " pL14 = " " pL15 = " " pL16 = " " pL17 = " " pL18 = " " pL19 = " " playerInitialList = [pL0, pL1, pL2, pL3, pL4, pL5, pL6, pL7, pL8, pL9, pL10, pL11, pL12, pL13, pL14, pL15, pL16, pL17, pL18, pL19] def continents(): #<--- Visual Display of the 3 continents print " __ ____" print " N.A. | \ / ." print " \__| \ 2 | ____" print " ____________ |" + str(pL2) + " / __ Eu / | |" print " / | 1 | \ \| /13\ ___/ | |" print "/ 0 |__" + str(pL1) + "__|_/ |\ ." + str(pL13) + "_// 14 / |" print "| " + str(pL0) + " | 3 | 4|__|5\ / " + str(pL14) + " / |" print " \/ \|__" + str(pL3) + "_|_" + str(pL4) + "__|_" + str(pL5) + "_\ __ |_/|_/| 19 /" print " / | 6 | 7 / /15\ __/ | " + str(pL19) + " /" print " |__" + str(pL6) + "__|_" + str(pL7) + "_/ ." + str(pL15) + "_/ | 16 | /" print " \ 8 | / _" + str(pL16) + " | |" print " \ " + str(pL8) + " \ /\ / \/\ |" print " \ \ /17|18/ ||" print " _\_ |" + str(pL17) + "_/ ." + str(pL18) + " \|" print " S.A._/ 9 \__" print " /___" + str(pL9) + "____|" print " | | /" print " \ 10|11/" print " |" + str(pL10) + " |" + str(pL11) + "/" print " |__|/" print " |12/" print " |" + str(pL12) + "/" print " |/" secondTurnsCountries.append(q) availableCountries.remove(q) firstTurnsCountries.sort() secondTurnsCountries.sort() player1 = raw_input("What is player 1's Name?") player2 = raw_input("What is player 2's Name?") countryDivider(len(availableCountries)) print "\n" + player1 + ", you have been given the following countries:",firstTurnsCountries print player2 + ", you have been given the following countries:",secondTurnsCountries playerInitialCounter = 0 # <--- This is the trouble making loop. while True: if playerInitialCounter in firstTurnsCountries: playerInitialList[playerInitialCounter] = player1[0] if playerInitialCounter in secondTurnsCountries: playerInitialList[playerInitialCounter] = player2[0] if playerInitialCounter == 19: break playerInitialCounter += 1 # if 0 in firstTurnsCountries: # pL0 = player1[0] # if 0 in secondTurnsCountries: # pL0 = player2[0] # if 1 in firstTurnsCountries: # pL1 = player1[0] # if 1 in secondTurnsCountries: # pL1 = player2[0] # if 2 in firstTurnsCountries: # pL2 = player1[0] # if 2 in secondTurnsCountries: # pL2 = player2[0] # if 3 in firstTurnsCountries: # pL3 = player1[0] # if 3 in secondTurnsCountries: # pL3 = player2[0] # if 4 in firstTurnsCountries: # pL4 = player1[0] # if 4 in secondTurnsCountries: # pL4 = player2[0] # if 5 in firstTurnsCountries: # pL5 = player1[0] # if 5 in secondTurnsCountries: # pL5 = player2[0] # if 6 in firstTurnsCountries: # pL6 = player1[0] # if 6 in secondTurnsCountries: # pL6 = player2[0] # if 7 in firstTurnsCountries: # pL7 = player1[0] # if 7 in secondTurnsCountries: # pL7 = player2[0] # if 8 in firstTurnsCountries: # pL8 = player1[0] # if 8 in secondTurnsCountries: # pL8 = player2[0] # if 9 in firstTurnsCountries: # pL9 = player1[0] # if 9 in secondTurnsCountries: # pL9 = player2[0] # if 10 in firstTurnsCountries: # pL10 = player1[0] # if 10 in secondTurnsCountries: # pL10 = player2[0] # if 11 in firstTurnsCountries: # pL11 = player1[0] # if 11 in secondTurnsCountries: # pL11 = player2[0] # if 12 in firstTurnsCountries: # pL12 = player1[0] # if 12 in secondTurnsCountries: # pL12 = player2[0] # if 13 in firstTurnsCountries: # pL13 = player1[0] # if 13 in secondTurnsCountries: # pL13 = player2[0] # if 14 in firstTurnsCountries: # pL14 = player1[0] # if 14 in secondTurnsCountries: # pL14 = player2[0] # if 15 in firstTurnsCountries: # pL15 = player1[0] # if 15 in secondTurnsCountries: # pL15 = player2[0] # if 16 in firstTurnsCountries: # pL16 = player1[0] # if 16 in secondTurnsCountries: # pL16 = player2[0] # if 17 in firstTurnsCountries: # pL17 = player1[0] # if 17 in secondTurnsCountries: # pL17 = player2[0] # if 18 in firstTurnsCountries: # pL18 = player1[0] # if 18 in secondTurnsCountries: # pL18 = player2[0] # if 19 in firstTurnsCountries: # pL19 = player1[0] # if 19 in secondTurnsCountries: # pL19 = player1[0] continents() If you uncomment all those lines of code near the bottom it will work flawlessly. But the problem is it's so much code. I tried to cut it down with the loop above it. But it won't work and I don't know why. It's supposed to change the variables one at a time to the correct first letter depending on who got which countries in their list. I have looked it over and over, but can't find why it won't work while the large section of code does. Any and all help would be greatly appreciated.
https://www.daniweb.com/programming/software-development/threads/66261/my-loop-won-t-work-but-i-m-positive-it-should
CC-MAIN-2018-13
en
refinedweb
Hello, I have a pololu maestro 18 channel servo controller . I have written a python code to control the maestro via pc using serial bluetooth HC 05 first of all I have made a library like this code / class Controller : self.PololuCmd = "0xaa" + "0xc" def setTarget(self, chan, target): lsb = target & 0x7f #7 bits for least significant byte msb = (target >> 7) & 0x7f #shift 7 and take next 7 bits for msb # Send Pololu intro, device number, command, channel, and target lsb/msb cmd = self.PololuCmd + "0x04" + hex(chan) + hex(lsb) + hex(msb) self.usb.write(cmd) / code it is not full code but a logic this seems to work when i use this library like this code / import maestro maestro = maestro.Controller() maestro.setTarget(0,9000) #moves to max angle / code but when i want to set targets at multiple channels like this code/ import maestro maestro = maestro.Controller() maestro.setTarget(0,9000) #moves to max angle maestro.setTarget(1,9000) /code this will successfully set servo 1 to max angle but servo 0 will not have any effect like it haven’t received any commands for servo 0 and this also happens vice versa maestro.setTarget(1,9000) #moves to max angle maestro.setTarget(0,9000) in this case servo 0 moves to max angle i think the problem is somewhere in sending some bytes i mean it only understands ending commands also there is a serial error of 0x0010 this lights up red led always i have used set multiple target command and it also works for both servo but set target method doesnt work for me any help would be appreciated
https://forum.pololu.com/t/controlling-two-servos-at-same-time-problem/12282
CC-MAIN-2018-13
en
refinedweb
Member 12 Points Participant 1740 Points Oct 19, 2012 01:48 AM|anil.india|LINK Have you taken reference of yor service in your project? Plz check Member 421 Points Oct 19, 2012 01:51 AM|narendrajarad|LINK Member 12 Points Participant 1740 Points Oct 21, 2012 01:38 AM|anil.india|LINK If references are available then you may missing to include that namespace into your code. using myNameSpaceGetsQualifyHere; If this is also there, then check accessibility of that Contributor 4926 Points Oct 21, 2012 11:28 PM|Steven Cheng - MSFT|LINK Hi sfiros2003, Are you using Web Application or web site project template for your we app? For Web site project, you need to save all items after you've added the webservice reference in your project. Also, I'd suggest you first creating a test Console project and add the webservice reference (either ServiceReference or WebReference) against the target service and make sure it works. Then, we can make sure the service is ok and further concentrate on the web application. #How to: Add, Update, or Remove a Service Reference #Add Web Reference in Visual Studio 2010 5 replies Last post Oct 21, 2012 11:28 PM by Steven Cheng - MSFT
https://forums.asp.net/t/1852481.aspx?Cannot+Use+Web+Service+in+code
CC-MAIN-2018-13
en
refinedweb
. Service class for interacting with the Google Base data API GBASE_ITEM_FEED_URI = '' Path to the customer items feeds on the Google Base server. GBASE_SNIPPET_FEED_URI = '' Path to the snippets feeds on the Google Base server. AUTH_SERVICE_NAME = 'gbase' Authentication service name for Google Base string $_defaultPostUri = 'self' The default URI for POST methods array $namespaces = 'array' Namespaces used for Zend_Gdata_Gbase __construct( Zend_Http_Client $client = null, string $applicationId = MyCompany-MyApp-1.0 ) : Create Zend_Gdata_Gbase object deleteGbaseItem( Zend_Gdata_Gbase_ItemEntry $entry, boolean $dryRun = false ) : Zend_Gdata_Gbase_ItemFeed Delete an entry getGbaseItemEntry( mixed $location = null ) : Zend_Gdata_Gbase_ItemEntry Retreive entry object getGbaseItemFeed( mixed $location = null ) : Zend_Gdata_Gbase_ItemFeed Retreive feed object getGbaseSnippetFeed( mixed $location = null ) : Zend_Gdata_Gbase_SnippetFeed Retrieve feed object insertGbaseItem( Zend_Gdata_Gbase_ItemEntry $entry, boolean $dryRun = false ) : Zend_Gdata_Gbase_ItemFeed Insert an entry updateGbaseItem( Zend_Gdata_Gbase_ItemEntry $entry, boolean $dryRun = false ) : Zend_Gdata_Gbase_ItemEntry Update an entry
https://framework.zend.com/apidoc/1.10/_Gdata_Gbase.html
CC-MAIN-2018-13
en
refinedweb
Python SDK for airbrake.io Project Description Airbrake integration for python that quickly and easily plugs into your existing code. import airbrake logger = airbrake.getLogger() try: 1/0 except Exception: logger.exception("Bad math.") airbrake-python is used most effectively through its logging handler, and uses the Airbrake V3 API for error reporting. install To install airbrake-python, run: $ pip install -U airbrake setup The easiest way to get set up is with a few environment variables: export AIRBRAKE_API_KEY=***** export AIRBRAKE_PROJECT_ID=12345 export AIRBRAKE_ENVIRONMENT=dev and you’re done! Otherwise, you can instantiate your AirbrakeHandler by passing these values as arguments to the getLogger() helper: import airbrake logger = airbrake.getLogger(api_key=*****, project_id=12345) try: 1/0 except Exception: logger.exception("Bad math.") setup for Airbrake On-Premise and other compatible back-ends (e.g. Errbit) Airbrake Enterprise and self-hosted alternatives, such as Errbit, provide a compatible API. You can configure a different endpoint than the default () by either: - Setting an environment variable: export AIRBRAKE_HOST= - Or passing a host argument to the getLogger() helper: import airbrake logger = airbrake.getLogger(api_key=*****, project_id=12345, host="") adding the AirbrakeHandler to your existing logger import logging import airbrake yourlogger = logging.getLogger(__name__) yourlogger.addHandler(airbrake.AirbrakeHandler()) by default, the ``AirbrakeHandler`` only handles logs level ERROR (40) and above Additional Options More options are available to configure this library. export AIRBRAKE_ENVIRONMENT=staging Or you can set it more explicitly when you instantiate the logger. import airbrake logger = airbrake.getLogger(api_key=*****, project_id=12345, environment='production') The available options are: - environment, defaults to env var AIRBRAKE_ENVIRONMENT - host, defaults to env var AIRBRAKE_HOST or - root_directory, defaults to None - timeout, defaults to 5. (Number of seconds before each request times out) - send_uncaught_exc, defaults to True (Whether or not to send uncaught exceptions) giving your exceptions more context import airbrake logger = airbrake.getLogger() def bake(**goods): try: temp = goods['temperature'] except KeyError as exc: logger.error("No temperature defined!", extra=goods) Setting severity notice = airbrake.build_notice(exception, severity="critical") airbrake.notify(notice) Using this library without a logger from airbrake.notifier import Airbrake ab = Airbrake(project_id=1234, api_key='fake') try: amazing_code() except ValueError as e: ab.notify(e) except: # capture all other errors ab.capture() Running Tests Manually Create your environment and install the test requirements virtualenv venv source venv/bin/activate pip install . python setup.py test To run via nose (unit/integration tests): source venv/bin/activate pip install -r ./test-requirements.txt source venv/bin/activate nosetests Run all tests, including multi-env syntax, and coverage tests. pip install tox tox -v --recreate [[what-is-severity]:] 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/airbrake/
CC-MAIN-2018-13
en
refinedweb
Flashcards Preview Burns The flashcards below were created by user Emilybillet on FreezingBlue Flashcards . Quiz iOS Android More What are the different mechanisms of burns? heat : flame, scalding water Chemicals : battery acid, cleaning fluids Electrical : equipment Radiation : sun, equipment Inhalation : smoke What population is highest risk for burns? Can most burn injuries be prevented? Elderly and children are most at risk; Yes, most can be prevented What is the skin composed of? Epidermis; dermis Subcutaneous fat tissue What functions does the integumentary system serve? Protects from infection (when skin is intact) prevents loss of body fluids thermoregulation production of vitamin D Excretion Sensation reception What factors determine the severity of injuries for a thermal burn? duration of contact temperature of agent amount of tissue exposed age of patient What are the methods of injury for a chemical burn? inhalation of fumes ingestion or injection In chemical burns what 2 broad effects can occur? how can you halt damage? What do you use for instructions when there is a chemical burn? they can be systemic or local effects The chemical must be completely removed or neutralized or damage continues The MSDS Material Safety Data Sheets have instructions for every chemical in a facility What determines the level of severity of chemical burns? What are the two types of chemical burns? Severity of injuries : type of agent, volume of agent, duration of contact, concentration of agent Types : Alkalis-base Acids What is the difference between high and low voltage electrical injuries? What is the energy level converted into? What is alternation current? What is direct current? High voltage : High is greater than 100 watts Low : less than 1000 watts Energy level is converted into heat Alternating current : flow of electrical charge periodically reverses direction. Higher probability of producing cardiac arrest Direct Current : unidirectional flow of electrical charge. Batteries, electric machines Who invented alternating current? Who invented direct current? Nikola tesla : AC Thomas Edison : DC What factors determine severity of injuries for electrical injuries? type and path of injury duration of contact environmental tissue resistance What is radiation injury? What determines the severity of injury Radioactive injury : exposure to large amount of radioactive material Severity : type of radiation, distance from source, duration of exposure, absorbed dose, depth of penetration What is an example of inhalation injury? How are they classified? Carbon monoxide poisoning; class : above or below the glottis What is the emergency management of burns? assess airway patency administer oxygen cover with blanket keep NPO elevate the extremities if no fracture is obvious vital signs initiate IV line for fluid replacement administer tetanus head-to-toe assessment What is the (specific to burn types) emergency management of burns? Flame burns : smother the flames, remove smoldering clothing and all metal objects Chemical : if dry chemical are present o the skin do not wet them, brush off any dry chemicals present on the skin or clothing, remove clothing, determine the chemical causing the burn, do not attempt to neutralize the chemical unless it has been positively identified and the appropriate neutralizing agent is available Electric burns : At the scene, separate patient from electrical current, smother any flames that are present, initiate cardiopulmonary resuscitation, obtain EKG Radiation : remove patient from radiation source, if the patient has been exposed to radiation from an unsealed source, remove the patient's clothing (using tongs or lead protective gloves, if the patient has radioactive particles on the skin send them to nearest designated radiation decontamination center, help the patient to bathe or shower What factors determine severity of burns? type of burn burn wound characteristics (depth, extent, body part burned) Any other injuries patient age preexisting health status What are the different depths of injury? superficial (first degree) : epidermis only; heals in 3-5 days without tx; erythema ( blanching on pressure, pain and mild swelling Not calculated for fluid resuscitation partial thickness (second degree) : epidermis and most of dermis full thickness : divided into 2 sub classifications- superficial partial thickness and deep partial thickness What is superficial partial thickness? Deep partial thickness? superficial : epidermis and limited portion of the dermis; heals in 10-21 days; moist pink or mottled red, very painful; blister formation Deep partial thickness : epidermis and most of the dermis; heals in 3-6 weeks; pale, mottled, pearly red/white; less painful What is full thickness? (third degree) Destruction of all layers down to or past fat, fascia, muscle or bone thick dry leathery appearance;dry, white, cherry-red, or brown-black insensate (no pain) does not heal; requires skin grafting How is the extent of injury expressed? What are the methods of measuring extent? expressed as total body surface area percent (%TBSA) methods : rule of nines, patient's palm method, (differences between adults and children) Lund-Browder chart describe the rule of nines Head : anterior 4.5; posterior 4.5 Chest : anterior 18; posterior 18 Right arm : anterior 4.5 posterior 4.5 left arm: anterior 4.5 posterior 4.5 pipi : 1 Right leg : anterior 9% posterior 9% Left leg: anterior 9% posterior 9% Burns of the face, neck, chest can lead to what what Nursing diagnosis? Burns to the hands, feet, joints can lead to what Nursing diagnosis? Ears/nose? Circumferential burns of the extremities can cause what? circulatory compromise; Face/neck/chest : R/F respiratory obstruction hands/feet/joints : R/F self care Ears/nose : R/F infection Circumferential burns can cause circulatory compromise (may develop compartment syndrome) What are risk factors make burns worse? older adults heal more slowly preexisting cardiovascular, respiratory, renal disease DM alcoholism drug abuse malnutrition concurrent fractures, head injuries or other trauma What are the local responses to burns? acute inflammation intravascular coagulation altered vascular permeability (fluid shifts) Describe fluid shifts fluid shifts to the extravascular space; burns greater than 20% total body surface areas; maximum edema 24-48 hours post burn burn shock (combination of distributive and hypovolemic shock What are the systemic responses to Burns (6) Cardiovascular : loss of intravascular volume; decreased cardiac output, tachycardia and vasoconstriction Host defense mechs : increased risk for infection Pulmonary : pulmonary HTN effect of direct injury Metabolic : hyper state, lasts up to 8 to 12 months after burn Gastrointestinal : ischemia due to redistribution of blood to brain and heart; paralytic ileus, curlings ulcers from stress Renal : sensitive to decreased cardiac output, initial decrease in urine output related to decreased GFR, followed by diuresis as fluid shifts What is prehospital care for burns? remove the person from the source of the burn and stop the burning process the caregiver must be protected from becoming part of the incident What is the emergent phase/care of burns? from burn onset to 5 or more days usually the fist 48 hours ABC's Fluid management to prevent shock Phase begins with fluid loss and edema formation and continues until fluid mobilization and diuresis begins Emergent phase is the period of time required to resolve the immediate problems resulting from the burn injury What is the pathophys of the emergent phase, what are the clinical manifestations? What are the complications? Fluid and electrolyte shifts; inflammation and healing; immunologic changes Manifestations : shock from pain and hypovolemia, blisters, adynamic ileus, shivering, altered Complications : cardiovascular system; respiratory system, urinary system What is the nursing and collaborative care of emergent phase? Airway management : intubation, oxygen-humidified/100%/O2; escharotomies Fluid therapy : Twp large bore IV (18 gauge); Parkland (baxter) formula for fluid replacement (2-4mL LR/kg/%TBSA=first 24 hours of fluid replacement half given in first 8 hours) colloidal therapy Describe wound care during the emergent phase delayed until patient has patent airway cleansing debridement immersion tank shower infection is the most serious threat to further tissue injury open method, multiple dressing changes, allograft or homograft skin other care measures facial care, ears-pressure free, peri-care, routine lab tests, early ROM exercises What drug therapy is used for the emergent phase? nutritional therapy? Drug : analgesics and sedatives, tetanus immunization, antimicrobial Nutritional : fluid replacement takes priority oral intake after bowel sounds return (usually at 48-72 hours) Hypermetabolic state (caloric needs- 500 kcal/day) What is the acute phase? the acute phase begins with the mobilization of extracellular fluid and subsequent diuresis The acute phase is concluded when the burned area is completely covered by skin grafts or when the wounds are healed What is the pathophys of the acute phase? Diuresis from fluid mobilization occurs bowel sounds return healing begins, necrotic tissue begins to slough formation of granular tissue Partial thickness : heal from the edges Full thickness : covered by skin grafts What are the clinical manifestations of the acute phase? Partial-thickness wounds from eschar eschar removed- epithealization begins expected to occur in 10-14 days Full thickness wounds require debridement What lab values will you see with acute phase? Sodium : hyponatremia Potassium : hyperkalemia/Hypokalemia What are the complications of acute phase? Infection cardiovascular and respiratory systems neurologic system musculoskeletal system gastrointestinal system endocrine system What wound care do nurses do during acute phase? Daily observations, assessment, cleansing, debridement excision and grafting : graft dressings, eschar removal, cultured epithelial autografts (CEA) Artificial skin What pain management is needed for acute phase? physical/occupational? Nutritional? Psychosocial? pain : pharmacologic, non pharm Physical/occupational : Exercise during/after hydrotherapy, passive or active ROM Nutritional therapy : High protein;high carb foods, diet supplements daily weights Psychosocial : social work, nursing staff, pastoral care What is the rehab phase? the rehabilitation phase is defined as beginning wen the patients burn wounds are covered with skin or healed and the patient is able to resume a level of self care activity What is the pathophys and clinical manifestations of the rehab phase? burn wound heals either by primary intention or by grafting Layers of epitheliazation begin rebuilding tissue structure Collagen fibers add strength to weakened areas 4-6 weeks- area becomes raised Mature healing : 6 months to 2 years Skin never completely regains its orginal color discoloration of scar fades with time; pressure can keep the scar flat (avoid Keloids) Newly healed areas : hyper/hypo-sensitive; protect from direct sunlight for 1 year What are the complications of rehab phase? Skin and joint contractures (most common complication) Hypertrophic scarring What is the nursing/collab care for the rehab phase? Patient and family actively learn to care for healing wounds emollient water-based cream should be used cosmetic surgery role of exercise cannot be overemphasized continuous encouragement/reassurance address spiritual cultural needs high calorie, high protein diet occupational therapy What things must be done before discharge? early patient assessment financial assessment evaluation of family resources weekly discharge planning meeting psychologic referral patient and family teaching (home care) designation of principal learners (specific family members of s/o who will help with care) development of a teaching plan training for wound care rehab referral home assessment/ environmental interventions medical equipment/ prosthetic rehab public health nursing referral evaluation of community resources visit to referral agency re-entry programs for school or work environment nursing home placement auditory testing/speech therapy What are the emotional needs of burn patients? Family members need to understand the importance of reestablishing the patient's independence Encourage family to participate as team member Early psychiatric intervention Assess psycho-emotional cues common emotional response : regress Issues of sexuality must be met with honesty Family and patient support groups What are the Expected outcomes for burn patients? Cardiac output restored or normal Pain alleviated or reduced No further skin integrity lost and skin integrity restored no infection adequate nutritional intake acceptable perception of body What issues with staffing do nurses experiencing? nurse cares for patients who at times may be unpleasant, hostile, apprehensive, and frustrated Nurses new to burn nursing often find it difficult to cope Author: Emilybillet ID: 299282 Card Set: Burns Updated: 2015-03-27 03:05:49 lccc cc Folders: Description: exam 3 cc Show Answers: Flashcards Preview
https://www.freezingblue.com/flashcards/print_preview.cgi?cardsetID=299282
CC-MAIN-2018-13
en
refinedweb
#include <Xm/SelectioB.h> Widget XmSelectionBoxGetChild( Widget widget, unsigned char child); XmSelectionBoxGetChild is used to access a component within a SelectionBox. The parameters given to the function are the SelectionBox widget and a value indicating which component to access. NOTE: This routine is obsolete and exists for compatibility with previous releases. Instead of calling XmSelectionBoxGetChild, you should call XtNameToWidget as described in the XmSelectionBox(3) reference page. For a complete definition of SelectionBox and its associated resources, see XmSelectionBox(3). Returns the widget ID of the specified SelectionBox component. An application should not assume that the returned widget will be of any particular class. XmSelectionBox(3).
http://www.makelinux.net/man/3/X/XmSelectionBoxGetChild
CC-MAIN-2015-32
en
refinedweb
Introduction One of the big differences between C# and VB.Net is the fact that VB.Net is case insensitive and C# isn’t. The case-insensitivity of VB.Net is sometimes weird and can lead to unwelcome side effects. Like you will see. Partial classes For example. the following is completely legal in VB.Net Module Module1 Sub Main() Dim t = New Test t.Test() t.partialtest() Dim t2 = New test t2.Test() t2.partialtest() Console.ReadLine() End Sub End Module Public Class test Public Sub Test() Console.WriteLine("test") End Sub End Class Partial Public Class Test Public Sub partialtest() Console.WriteLine("partialtest") End Sub End Class Watch the casing of the classes. See the instantiations? In C# we would use it like this. using System; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { var t = new ConsoleApplication2.test(); t.Test(); t.partialtest(); Console.ReadLine(); } } } In other words the name and casing of the class not the partial one. It won’t work with the partial one. So next time they try to convert your VB.Net code to C# they will have a problem with all the different casings and none of it will really work and if your code is big enough it will even hardly make sense. WHY????? The question begs of course, why would you do this?? You don’t!! But when you rename your class via Visual studio or just by deleting and retyping the characters than the partial class will not be renamed and in most cases you will not even notice because the partial class is in another file. Conclusion Be very careful with this kind of unwanted behavior you could upset someone.
http://blogs.lessthandot.com/index.php/DesktopDev/MSTech/how-a-vb-net-programmer/
CC-MAIN-2015-32
en
refinedweb
You can subscribe to this list here. Showing 1 results of 1 On 2/2/11 4:15 PM, Guenter Milde wrote: > On 2011-02-02, Paul Tremblay wrote: >> A simple question (I think). Can someone show me how to use the front >> end tools (or any other method) that allows me to convert an RST file to >> XML so that I get a string? I also need to use command line arguments. >> from docutils.core import publish_cmdline, default_description >> description = ('Generates Docutils-native XML from standalone ' >> 'reStructuredText sources. ' + default_description) >> publish_cmdline(writer_name='xml', description=description) >> Outputs to the terminal. I need to capture the output as a string (or as >> a path) and do further transformations. > >> status, output = commands.getstatusoutput('rst2xml.py --arsg >> file.rst') > >> Would work, but that is a bit of a hack, to say the least. > How about re-directing sys.stdout? > > Günter > > Thanks! Got it, finally: (PS What exactly does the 'import locale etc' do? ) # code starts here def publish_xml_cmdline (in_path = None, out_path = None, settings_overrides=None): try: import locale locale.setlocale(locale.LC_ALL, '') except: pass from docutils.core import default_description, default_usage import docutils.core description = ('Generates Docutils-native XML from standalone ' 'reStructuredText sources. ' + default_description) if out_path: sys.stdout = file(out_path, 'w') if in_path: sys.stdin = file(in_path) pub = docutils.core.Publisher(None, None, None, settings=None) pub.set_components('standalone', 'restructuredtext', 'xml') output = pub.publish( None, default_usage, description, None, settings_overrides, config_section=None, enable_exit_status=1) return output if __name__ == '__main__': custom = {'title':'Doc Title'} publish_xml_cmdline('test.rst', 'out.xml', custom)
http://sourceforge.net/p/docutils/mailman/docutils-develop/?viewmonth=201102&viewday=4
CC-MAIN-2015-32
en
refinedweb
Opened 4 years ago Closed 3 years ago #16418 closed Bug (fixed) Class based generic DetailView tries to access non-existant _meta field when get_object has been modified to return a ModelForm Description Summary I used DetailView and subclassed it, then modified get_object to return a ModelForm instance. When it executes an eeror message is generated due to the Meta class in ModelForm clashing with the expected Meta attributes in the usual object that is passed. This was initially posted to stackoverflow where the formatting is pleasant to read. This is my first bug report, so the formatting of the bug report may not be that good. Apologies in advance. Report Details I've been impressed how rapidly a functional website can go together with generic views in the tutorials. Also, the workflow for form processing is nice. I used the ModelForm helper class to create a form from a model I made and was delighted to see that so much functionality came together. When I used the generic list_detail.object_detail I was disappointed that all that I could display were fields individually. I knew the ModelForm class contained information for rendering, so I wanted to use the ModelForm with a generic view. I was asking around on stackoverflow to get some direction, and appreciate the answers and comments from several posters. I've figured out how to get this to work, but there is a bug in DetailView. The solution includes a workaround. To use a ModelView with the generic view and get all the fields to render automatically the following works: Create a project, and in it create application inpatients. If you have # inpatients/models.py class Inpatient(models.Model): last_name = models.CharField(max_length=30) first_name = models.CharField(max_length=30,blank=True) address = models.CharField(max_length=50,blank=True) city = models.CharField(max_length=60,blank=True) state = models.CharField(max_length=30,blank=True) DOB = models.DateField(blank=True,null=True) notes = models.TextField(blank=True) def __unicode__(self): return u'%s, %s %s' % (self.last_name, self.first_name, self.DOB) class InpatientForm(ModelForm): class Meta: model = Inpatient and # inpatients/views.py from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render_to_response from django.views.generic import DetailView from portal.inpatients.models import * def formtest(request): if request.method == 'POST': form = InpatientForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('/inpatients') else: form = InpatientForm() return render_to_response("formtest.html", {'form': form}) class FormDetailView(DetailView): model=Inpatient context_object_name='inpatient' # defines the name in the template template_name_field='inpatient_list_page.html' def get_object(self): inpatient=super(FormDetailView,self).get_object() form=InpatientForm(instance=inpatient) return form def get_template_names(self): return ['inpatient_list_page.html',] and #urls.py from django.conf.urls.defaults import patterns, include, url from django.views.generic import ListView from portal.inpatients.models import Inpatient, InpatientForm from portal.inpatients.views import FormDetailView urlpatterns = patterns('', (r'^formtest/$','portal.inpatients.views.formtest'), (r'^inpatients/$', ListView.as_view( model=Inpatient, {{ aninpatient }}, id={{ aninpatient.id }}</a></li> {% endfor %} </ul> {{ inpatient.as_p }} {% endblock %} # Yeah, kind of hokey. The template is for both the list view and detail view. # Note how the form is rendered with one line - {{ inpatient.as_p }} t works. The instructions for using class based generic views lives at Instructions there are pretty clear. The key to making things work is to redefine get_object. In the documentation under the section "Performing extra work" it nicely describes how to do this, the steps being to call the original version of get_object, and then to the extra work. The bit that I realized is that the return object can be a ModelForm object. The object that get_object returns goes straight into the template in a render. By taking the retrieved inpatient object and running it through InpatientForm it can be passed to a view as a form which then renders itself. As to the bug: The bug in DetailView is that the get_template_names function tries to make a template name from a structure that does not exist. In on lines 127 to 140 we have within SingleObjectTemplateResponseMixin.get_template_names: 127 # The least-specific option is the default <app>/<model>_detail.html; 128 # only use this if the object in question is a model. 129 if hasattr(self.object, '_meta'): 130 names.append("%s/%s%s.html" % ( 131 self.object._meta.app_label, 132 self.object._meta.object_name.lower(), 133 self.template_name_suffix 134 )) 135 elif hasattr(self, 'model') and hasattr(self.model, '_meta'): 136 names.append("%s/%s%s.html" % ( 137 self.model._meta.app_label, 138 self.model._meta.object_name.lower(), 139 self.template_name_suffix 140 )) The error is that the code on line 131 is executed and dies with error message <'ModelFormOptions' object has no attribute 'app_label'>. I conclude that the _meta object is defined. I suppose that the problem is that in a ModelForm the class Meta is defined. That Meta probably doesn't have the fields set that are expected. The workaround is just to rewrite get_template_names and return the correct template. I suppose a try statement could just go around where the assignments are done. The other issue is to decide what the best way is to define the template when a ModelForm is used. Some Feedback and Reply on StackOverflow I don't think this is a bug, and I do think get_object should always return model instance not ModelForm instance. Try using editing CBV. – rebus I think it is a bug for several reasons. The documentation does not say it is invalid. The test for valid data before the assignment tests for the existence of _meta rather than the actual fields. The routine that is looking for the template didn't find the template. Additionally, on the principal of Don't Repeat Yourself, the ModelForm should be able to be delivered to a template for rendering. – kd4ttc Another User Had Additional Insight You are right I believe. This is a bug which stems from the fact that both ModelForm and Models have a _meta attribute. This same bug would exhibit itself anytime an object is returned from get_object() that contains a _meta attribute. get_object does not have to return a Model instance. You can confirm this by looking at the source for DetailView and reading it's docstring: class DetailView(SingleObjectTemplateResponseMixin, BaseDetailView): """ Render a "detail" view of an object. By default this is a model instance looked up from `self.queryset`, but the view will support display of *any* object by overriding `self.get_object()`. """ Notice that the doc string explicitly says that any object is supported by overriding self.get_object(). Another piece of corroborating evidence is from the location where this bug itself occurs which is the get_template_names method of SingleObjectTemplateResponseMixin. # The least-specific option is the default <app>/<model>_detail.html; # only use this if the object in question is a model. if hasattr(self.object, '_meta'): names.append("%s/%s%s.html" % ( self.object._meta.app_label, self.object._meta.object_name.lower(), self.template_name_suffix )) elif hasattr(self, 'model') and hasattr(self.model, '_meta'): names.append("%s/%s%s.html" % ( self.model._meta.app_label, self.model._meta.object_name.lower(), self.template_name_suffix )) Again looking at this code, the comment itself say "If the object in question is a model". From this comment we can infer that the object doesn't always have to be a model. -- Donald Stufft Change History (10) comment:1 Changed 4 years ago by mattmcc - Needs documentation unset - Needs tests unset - Patch needs improvement unset comment:2 Changed 4 years ago by kd4ttc What I did was generate a list of entries with a generic view and then want to drill down to review the entries in all the fields. If it needs editing there are controls that will then go to a modification page. I will be trying out the generic edit views next. A similar bug might be there, too. comment:3 Changed 4 years ago by kd4ttc BTW I thought it was pretty well documented. What other documentation is needed? Should I propose a patch? What tests are needed?(this is my first bug report) comment:4 Changed 4 years ago by aaugustin - Triage Stage changed from Unreviewed to Accepted Based on the evidence provided in the original report, I'd say this attempt to check if self.object is a model is incorrect: if hasattr(self.object, '_meta'): It should be replaced by something along these lines: from django.db import models if isinstance(self.object, models.Model) comment:5 Changed 3 years ago by dstufft comment:6 Changed 3 years ago by aaugustin - Has patch set - Owner changed from kd4ttc to aaugustin comment:7 Changed 3 years ago by lrekucki I have to disagree. Doing this kind of explicit checks for types is not very pythonic, unless you plan to change models.Model into an ABC. Duck typing is usefull. Sure, there will be cases where attribute names overlap and lead to some confusion, but those are fairly rare. Lets not forget that the OP's problem, comes from misuse of the API (DetailView is designed to display instances of Model or objects behaving similar). @kd4ttc, if you need some extra objects (like a form) for rendering you can put the into context by overriding get_context_data(), no need to hack through the whole API. comment:8 Changed 3 years ago by dstufft - Cc donald.stufft@… added Doing the explicit checks for types here makes sense because all Django models must be derived from models.Model and the generic views are using the binary "is this a model y/n" question to kick in additional functionality. Essentially it's already doing a check for type, it's just doing so poorly because it assumes that only a Model would have a _meta attribute. And DetailView is _not_ designed only for model instances or objects behaving similarly, it is designed for an instance of an object regardless of how it behaves. This is evident through both the doc strings and the conditionals. While a model instance might be the most common use case, it is not the only valid use case as designed. Because this view not designed only for model instances, and because it wants to enable additional functionality when the object is a model the only sane choices, in my opinion, are to explicitly check for subclasses, or make the _meta api a public api so that people can make their objects conform to it. Without a public api you cannot expect people to even know that _meta exists. A quick grep of the docs show that _meta existing is only incidentally documented through it's use in example code of other features. comment:9 Changed 3 years ago by akaariai I agree that isinstance check is the correct one here. I don't see the value of duck typing in this case, it is not at all well defined what behavior the duck should have. It just having the _meta/model attribute is _not_ what we are interested in. So, isinstance is valid here. comment:10 Changed 3 years ago by Anssi Kääriäinen <akaariai@…> - Resolution set to fixed - Status changed from new to closed Ignoring whether or not this is a bug for the moment, if the primary object of your view is a form, wouldn't it work better to use CreateView, UpdateView, or your own view that pulls in ModelFormMixin?
https://code.djangoproject.com/ticket/16418?cversion=0&cnum_hist=7
CC-MAIN-2015-32
en
refinedweb
The. “Bit banging” is the most basic method of producing sound from an Arduino. Just connect a digital output pin to a small speaker and then rapidly and repeatedly flip the pin between high and low. This is how the Arduino’s tone() statement works. The output pins can even drive a small (4cm or less) 8-ohm speaker connected directly between the pin and ground without any amplification.. The Arduino’s analogWrite() function, which outputs a square wave at a fixed frequency of 490Hz, is handy to illustrate the concept. Connect your speaker to pin D9 and ground (Figure B) and run this sketch: void setup() { pinMode(9,OUTPUT); } void loop() { for (int i=0; i<255; i++) { analogWrite(9,i); delay(10); } } You should hear a tone of constant pitch, with a timbre slowly changing from thin and reedy (mostly space time) to round and fluty (equal mark and space time), and back to thin and reedy again (mostly mark time). A square wave with a variable duty cycle is properly called a pulse-width modulated (PWM) wave. Altering the duty cycle to change timbre may serve very basic sound functions, but to produce more complex output, you’ll need a more advanced approach. PWM waves are strictly digital, either high or low. For analog waves, we need to generate voltage levels that lie between these 2 extremes. This is the job of a digital-to-analog converter (DAC). There are several types of DAC. The simplest is probably the R-2R ladder (Figure C). In this example, we have 4 digital inputs, marked D0–D3. D0 is the least significant bit and D3 the most significant. If you set D0 high, its current has to pass through a large resistance of 2R + R + R + R = 5R to reach the output. Some of the current also leaks to ground through the relatively small resistance 2R. Thus a high voltage at D0 produces a much smaller output voltage than a high voltage at D3, which faces a small resistance of only 2R to reach the output, and a large resistance of 5R to leak to ground. Setting D0–D3 to binary values from 0000 to 1111 (0–15 decimal), and then back down to 000 in quick succession, ought to output the triangle wave shown in Figure D. To produce other waveforms, in theory, we must simply present the right sequence of binary numbers to D0–D3 at the right rate. Unfortunately, there are drawbacks to using an R-2R DAC, foremost probably that it requires very precise resistor values to prevent compound errors from adding up and distorting the waveform. The jagged “steps” must also be smoothed, using a low-pass filter, to prevent a discordant metallic sound. Finally, an R-2R DAC uses up more output pins than are strictly necessary. Though a bit harder to understand, the “1-bit” DAC produces very smooth, high-quality waveforms using just one output pin with a single resistor and capacitor as a filter. It also leaves the Arduino free to do other things while the sound is playing. If you replace the speaker from the bit-banging sketch with an LED, you’ll see it increase in brightness as the duty cycle increases from 0 to 100%. Between these 2 extremes, the LED is really flashing at around 490Hz, but we see these flashes as a continuous brightness. This “smoothing” phenomenon is called “persistence of vision,” and it can be thought of as a visual analogy to the low-pass filter circuit shown in Figure E. You can use this filter to smooth the output from a 1-bit DAC. The mark time of the incoming PWM wave determines the voltage at Vout from moment to moment. For example, a mark/space ratio of 50:50 outputs 50% of the high voltage of the incoming signal, a 75:25 ratio outputs 75% of that voltage, and so on. An Arduino’s digital pins produce a high of 5V, so a 50% duty cycle, for example, would give 2.5V at Vout. For best sound quality, the frequency of the PWM signal should be as high as possible. Luckily, the Arduino can produce fast PWM waves up to 62.5KHz. The hardware also provides a handy mechanism for updating the mark time from a lookup table at absolutely regular intervals, while leaving the Arduino free to do other things. The ATmega328 chip at the heart of the Arduino Nano 3 contains 3 hardware timers. Each timer includes a counter that increments at each clock tick, automatically overflowing back to 0 at the end of its range. The counters are named TCNTn, where n is the number of the timer in question. Timer0 and timer2 are 8-bit timers, so TCNT0 and TCNT2 repeatedly count from 0 to 255. Timer1 is a 16-bit timer, so TCNT1 repeatedly counts from 0 to 65535, and can also be made to work in 8-bit mode. In fact, each timer has a few different modes. The one we need is called “fast PWM,” which is only available on timer1. In this mode, whenever TCNT1 overflows to zero, the output goes high to mark the start of the next cycle. To set the mark time, timer1 contains a register called OCR1A. When TCNT1 has counted up to the value stored in OCR1A, the output goes low, ending the cycle’s mark time and beginning its space time. TCNT1 keeps on incrementing until it overflows, and the process begins again. This process is represented graphically in Figure F. The higher we set OCR1A, the longer the mark time of the PWM output, and the higher the voltage at Vout. By updating OCR1A at regular intervals from a pre-calculated lookup table, we can generate any waveform we like. Listing 1 (download Listings 1–6 as a .zip file) contains a sketch that uses a lookup table, fast PWM mode, and a 1-bit DAC to generate a sine wave. #include <avr/interrupt.h> // Use timer interrupt library /******** Sine wave parameters ********/ #define PI2 6.283185 // 2*PI saves calculation later #define AMP 127 // Scaling factor for sine wave #define OFFSET 128 // Offset shifts wave to all >0 values /******** Lookup table ********/ #define LENGTH 256 // Length of the wave lookup table byte wave[LENGTH]; // Storage for waveform void setup() { /* Populate the waveform table with a sine wave */ for (int i=0; i<LENGTH; i++) { // Step across wave table float v = (AMP*sin((PI2/LENGTH)*i)); // Compute value wave[i] = int(v+OFFSET); // Store value as integer } /****Set timer1 for 8-bit fast PWM output ****/ pinMode(9, OUTPUT); // Make timer’s PWM pin an output TCCR1B = (1 << CS10); // Set prescaler to full 16MHz TCCR1A |= (1 << COM1A1); // Pin low when TCNT1=OCR1A TCCR1A |= (1 << WGM10); // Use 8-bit fast PWM mode TCCR1B |= (1 << WGM12); /******** Set up timer2 to call ISR ********/ TCCR2A = 0; // No options in control register A TCCR2B = (1 << CS21); // Set prescaler to divide by 8 TIMSK2 = (1 << OCIE2A); // Call ISR when TCNT2 = OCRA2 OCR2A = 32; // Set frequency of generated wave sei(); // Enable interrupts to generate waveform! } void loop() { // Nothing to do! } /******** Called every time TCNT2 = OCR2A ********/ ISR(TIMER2_COMPA_vect) { // Called when TCNT2 == OCR2A static byte index=0; // Points to each table entry OCR1AL = wave[index++]; // Update the PWM output asm(“NOP;NOP”); // Fine tuning TCNT2 = 6; // Timing to compensate for ISR run time } First we calculate the waveform and store it in an array as a series of bytes. These will be loaded directly into OCR1A at the appropriate time. We then start timer1 generating a fast PWM wave. Because timer1 is 16-bit by default, we also have to set it to 8-bit mode. We use timer2 to regularly interrupt the CPU and call a special function to load OCR1A with the next value in the waveform. This function is called an interrupt service routine (ISR), and is called by timer2 whenever TCNT2 becomes equal to OCR2A. The ISR itself is written just like any other function, except that it has no return type. The Arduino Nano’s system clock runs at 16MHz, which will cause timer2 to call the ISR far too quickly. We must slow it down by engaging the “prescaler” hardware, which divides the frequency of system clock pulses before letting them increment TCNT2. We’ll set the prescaler to divide by 8, which makes TCNT2 update at 2MHz. To control the frequency of the generated waveform, we simply set OCR2A. To calculate the frequency of the resulting wave, divide the rate at which TCNT2 is updated (2MHz) by the value of OCR2A, and divide the result by the length of the lookup table. Setting OCR2A to 128, for example, gives a frequency of: which is roughly the B that’s 2 octaves below middle C. Here’s a table of values giving standard musical notes. The ISR takes some time to run, for which we compensate by setting TCNT2 to 6, rather than 0, just before returning. To further tighten the timing, I’ve added the instruction asm(“NOP;NOP”), executing 2 “no operation” instructions using one clock cycle each. Run the sketch and connect a resistor and capacitor (Figure G). You should see a smooth sine wave on connecting an oscilloscope to Vout. If you want to hear the output through a small speaker, add a transistor to boost the signal (Figure H, below). Once you know how to “play” a wave from a lookup table, creating any sound you want is as easy as storing the right values in the table beforehand. Your only limits are the Arduino’s relatively low speed and memory capacity. Listing 2 contains a waveform() function to prepopulate the table with simple waveforms: SQUARE, SINE, TRIANGLE, RAMP, and RANDOM. Play them to see how they sound (below). A SQUARE waveform can have a timbre ranging from round and fluty to thin and reedy, depending on its duty cycle. From our initial experiments with bit banging, we already know that a 50% duty cycle gives a flute-like sound. A SINE waveform consists of a smoothly oscillating curved signal representing the graph of the trigonometric function. It produces a clear, glassy tone that sounds very much like a tuning fork. A TRIANGLE waveform looks a little like a sine wave with sharp points and straight lines, or 2 ramp waveforms squashed back to back. It has a more interesting, rounded sound than a sine wave, a little like an oboe. A RAMP waveform consists of steadily increasing values, starting at zero. At the end of the waveform the value suddenly drops to zero again to begin the next cycle. The result is a sound that’s bright and brassy. A RANDOM waveform can sound like anything, in theory, but usually sounds like noisy static. The Arduino produces only pseudorandom numbers, so a particular randomSeed() value always gives the same “random” waveform. The RANDOM function just fills the table with pseudorandom integers based on a seed value. Changing the seed value using the randomSeed() function allows us to generate different pseudorandom sequences and see what they sound like. Some sound thin and weedy, others more organic. These random waveforms are interesting but noisy. We need a better way of shaping complex waves. In the 19th century, Joseph Fourier showed that we can reproduce, or synthesize, any waveform by combining enough sine waves of different amplitudes and frequencies. These sine waves are called partials or harmonics. The lowest-frequency harmonic is called the first harmonic or fundamental. The process of combining harmonics to create new waveforms is called additive synthesis. Given a complex wave, we can synthesize it roughly by combining a small number of harmonics. The more harmonics we include, the more accurate our synthesis. Professional additive synthesizers can combine over 100 harmonics this way, and adjust their amplitudes in real time to create dramatic timbre changes. This is beyond the power of Arduino, but we can still do enough to load our wave table with interesting sounds. Figure J—Adding the third harmonic creates a waveform that has a distinctly square look and sound, though still very rounded. Consider the loop in Listing 1 that calculates a sine wave. Call that the fundamental. To add, say, the third harmonic at 1/4 amplitude (Figure J), we add a new step: for (int i=0; i<LENGTH; i++) { // Step across table float v = (AMP*sin((PI2/LENGTH)*i)); // Fundamental v += (AMP/4*sin((PI2/LENGTH)*(i*3))); // New step wave[i]=int(v+OFFSET); // Store as integer } In this new step, we multiply the loop counter by 3 to generate the third harmonic, and divide by an “attenuation” factor of 4 to reduce its amplitude. Listing 3 (available at makezine.com/35) contains a general version of this function. It includes 2 arrays listing the harmonics we want to combine (including 1, the fundamental) and their attenuation factors. Figure K—Adding the first 8 odd harmonics gives a fairly good approximation of a square wave. Individual sine waves appear as little ripples. Combining more partials would reduce the size of these ripples. To change the timbre of the sound loaded into the lookup table, we just alter the values in the 2 arrays. A zero attenuation means the corresponding harmonic is ignored. The arrays in Listing 3, as written, produce a fairly good square wave (Figure K). Experiment with the arrays and see what sounds result. Professional synthesizers contain circuits or programs to “filter” sound for special effects. For instance, most have a low-pass filter (LPF) that gives a certain “waa” to the start and “yeow” to the end of sounds. Basically, an LPF gradually filters out the higher partials. Computationally, true filtering is too much for Arduino, but there are things we can do to the sound, while it’s playing, to give similar effects. Listing 4 includes a function that compares each value in the wave table to a corresponding value in a second “filter” table. When the values differ, the function nudges the wave value toward the filter value, slowly “morphing” the sound as it plays. Using a sine wave as the “filter” approximates true low-pass filtering. The harmonics are gradually removed, adding an “oww” to the end. If we morph the other way — by loading the wave table with a sine wave and the “filter” table with a more complex wave — we add a “waa” quality to the start. You can load the 2 tables with any waves you like. What if we want to make a sound fade away, like a real instrument that’s been plucked, strummed, or struck? Listing 5 contains a function that “decays” the sound to silence by steadily nudging the wave table values back toward a flat line. It steps across the wave table, checking each value — if it’s more than 127, it’s decremented, and if less, incremented. The rate of decay is governed by the delay() function, called at the end of each sweep across the table. Once the wave is “squashed,” running the ISR just ties up the CPU without making sound; the cli() function clears the interrupt flag set in setup by sei(), switching it off. The Arduino’s Atmel processor is based on the “Harvard” architecture, which separates program memory from variable memory, which in turn is split into volatile and nonvolatile areas. The Nano only has 2KB of variable space, but a (relatively) whopping 30KB, or so, of usable program space. It is possible to store wave data in this space, greatly expanding our repertoire of playable sounds. Data stored in program space is read only, but we can store a lot of it and load it into RAM to manipulate during playback. Listing 6 demonstrates this technique, loading a sine wave from an array stored in program space into the wave table. We must include the pgmspace.h library at the top of the sketch and use the keyword PROGMEM in our array declaration: prog_char ref[256] PROGMEM = {128,131,134,…}; Prog_char is defined in pgmspace.h and is the same as the familiar “byte” data type. If we try to access the ref[] array normally, the program will look in variable space. We must use the built-in function pgm_read_byte instead. It takes as an argument the address of the array you want to access, plus an offset pointing to individual array entries. If you want to store more than one waveform this way, you can access the array in pgm_read_byte like a normal two-dimensional array. If the array has, say, dimensions of [10][256], you’d use pgm_read_byte(&ref[4][i]) in the loop to access waveform 4. Don’t forget the & sign before the name of the array! To read wave table data from program memory, you have to hard-code it into your sketch and can’t generate it during runtime. So where does it come from? One method is to generate wave table data in a spreadsheet and paste it into your sketch. We’ve created a spreadsheet that will allow you to generate wave tables using additive synthesis, to see the shape of the resulting waves, and to copy out raw wave table data to insert into your sketch. Download it here. Audio feedback is an important way of indicating conditions inside a running program, such as errors, key presses, and sensor events. Sounds produced by your Arduino can be recorded into and manipulated by a software sampler package and used in music projects Morphing between stored waveforms, either in sequence, randomly, or under the influence of performance parameters, could be useful in interactive art installations. If we upgrade to the Arduino Due, things get really exciting. At 84MHz, the Due is more than 5 times faster than the Nano and can handle many more and higher-frequency partials in fast PWM mode. In theory, the Due could even calculate partials in real time, creating a true additive synthesis engine.
http://makezine.com/projects/make-35/advanced-arduino-sound-synthesis/
CC-MAIN-2015-32
en
refinedweb
Large-Scale Linux Configuration Management Before the introduction of LCFG, we were configuring machines using a typical range of techniques, including vendor installs and disk copying (cloning). These were followed by the application of a monolithic script which applied assorted “tweaks” for all the different configuration variations. This met with virtually none of the requirements listed above and was a nightmare to manage. The available alternatives ranged from large commercial systems (too expensive and probably too inflexible) to systems developed at individual sites for their own use (often not much of an improvement over our existing process). More recently, interesting tools such as COAS and the GNU cfengine (see Resources 5) have appeared, but we are still not aware of any comparable system which addresses quite the same set of requirements as LCFG. Given limited development resources, we attempted to design an initial system as a number of independent subsystems, intending to use temporary implementations for some of the ones where we could leverage existing technology: Resource Repository: design a standard syntax for representing resources (individual configuration parameters). These would be stored in a central place where they could be analysed and processed as well as distributed to individual machines. Resource Compiler: preprocess the resources so that we could create configurations by inheritance and avoid specifying large numbers of low-level resources explicitly. Distribution Mechanism: distribute the master copy of the resources to clients on demand in a robust way. Component Framework: provide a framework which allows components to be easily written for configuring new subsystems and services, using the resources from the repository. Core Components: implement a number of core components, including basic OS installation and the standard daemons. We wanted some of these to act as exemplars to make it as easy as possible for other people to create new components. Items of configuration data are represented as key,value pairs, in a way similar to X resources. The key consists of three parts: the hostname, the component and the attribute. For example, the nameserver (cul) for the host wyrgly is configured by the DNS component: wyrgly.dns.servers: cul.dcs.ed.ac.uk Notice that this specification is a rather abstract representation, not directly tied to the form in which the configuration is actually required by the machine, in this case, as a line in the resolv.conf file. This allows the same representation to be used for different platforms, and it permits high-level programs to analyse and generate the resources easily . The LCFG components on each machine are responsible for translating these resources into the appropriate form for the particular platform. COAS uses a similar representation for configuration parameters. The resources are currently stored in simple text files, with one file per host. This collection of files forms the repository. We intend to provide a special-purpose language for specifying these resources; it would support inheritance, default configurations, validation and some concept of higher-level specifications. However, we are currently using a “temporary” solution based on the C preprocessor, followed by a short Perl script to preprocess the resources. The C preprocessor provides file inclusion and macros, which can be used for primitive inheritance. The Perl script allows inherited resources to be modified with regular expressions. Wild cards are also supported to provide default values. In practice, most machines have very short resource files which simply inherit some standard templates. Machines can be cloned simply by copying these resource files. Often, a few resources are overridden to provide slight variations. For example: #include <generic_client.h> #include <linux.h> #include <portable.h> amd.localhome: paul auth.users: paul The name of the host is not necessary in the resource keys, because this is generated from the name of the resource file. Resources are currently distributed to clients using NIS (Sun's Network Information System). This is another “temporary” solution which is far from ideal; we hope to replace it in the near
http://www.linuxjournal.com/article/3467?page=0,1
CC-MAIN-2015-32
en
refinedweb
Accessing Primary KeysEdit When your primary key is not visible as a class property, the documented way to obtain the primary key values is with EOUtilities.primaryKeyForObject(). This works, but in the case where you have a single non-compound primary key, you need a few more lines of code to pull out this pk value. More troubling, the EOUtilities method, when called with a fault, will cause the fault to be resolved. The fault does not really need to be resolved to get the primary key, as the pk value is present even in the fault. Here's a method that works for EOs which have a single Integer primary key, to pull out that pk value, and without resolving a fault (possibly causing a trip to the db) when called on a fault value: public static Integer singleIntegerPrimaryKeyForObject(EOEnterpriseObject eo) { EOEditingContext ec = eo.editingContext(); if (ec == null) { //you don't have an EC! Bad EO. We can do nothing. return null; } EOGlobalID gid = ec.globalIDForObject(eo); if (gid.isTemporary()) { //no pk yet assigned return null; } EOKeyGlobalID kGid = (EOKeyGlobalID) gid; NSArray keyValues = kGid.keyValuesArray(); if (keyValues.count() != 1 || ! (keyValues.objectAtIndex(0) instanceof Integer)) return null; return (Integer) keyValues.objectAtIndex(0); } You can also use the EOUtilities method but please note that, at least as of WO5, there are two somewhat undesirable aspects of this EOUtilities code: - If the EO is a fault, calling the EOUtilities method will cause the fault to be resolved, possibly requiring a trip to the db, even though pk info is already present in the fault and the trip to the db is really unneccesary at this point. - If the EO has just been inserted and not yet committed, it does not have a pk yet, and the EOUtilities code will throw an exception. And it's not a logical exception corresponding to "no pk yet", but rather some uncaught exception thrown by some surprised Apple code. Assigning Primary KeysEdit Usually EOF doesn't get around to generating/inserting primary keys until you actually saveChanges() on an EOEditingContext containing newly created about-to-be saved EOEnterpriseObjects. But sometimes you want to assign a permanent pk as soon as you create the EOEnterpriseObject, not wait until it's actually committed to the db. Here's some code to do that, which, in a given situation, will generate the pk in the same way that EOF would have generated it later, but do it right away. [Thanks to Pierre Barnard] public void _insertObjectWithGlobalID(EOEnterpriseObject eo, EOGlobalID globalID) { EOEntity entity = EOUtilities.entityNamed(this, eo.entityName()); EODatabaseContext dbContext = EOUtilities.databaseContextForModelNamed(this, entity.model().name()); NSDictionary pkDict = primaryKeyDictionaryForDatabaseContextAndEntity(dbContext, entity); if (pkDict == null || pkDict.count() != 1) { NSLog.err.appendln("Failed to generate primary key for entity " + entity.name() + ", or pk is compound."); } else { Object pk = pkDict.allValues().lastObject(); globalID = EOKeyGlobalID.globalIDWithEntityName(entity.name(), new Object[] { pk }); } super._insertObjectWithGlobalID(eo, globalID); } public static NSDictionary primaryKeyDictionaryForDatabaseContextAndEntity(EODatabaseContext dbContext, EOEntity entity) { NSDictionary pk = null; try { dbContext.lock(); EOAdaptorChannel adaptorChannel = dbContext.availableChannel().adaptorChannel(); if (!adaptorChannel.isOpen()) { adaptorChannel.openChannel(); } pk = (NSDictionary) adaptorChannel.primaryKeysForNewRowsWithEntity(1, entity).lastObject(); } catch (Exception e) { NSLog.err.appendln("Can't get primary keys for entity " + entity.name() + " " + e); } finally { dbContext.unlock(); return pk; } } There are 2 insertObjectWithGlobalID methods in EOEditingContext. One has a name prefixed by an underscore. The regular one seems to call that one. For most uses overriding the regular one should be sufficient. With JavaClient however, the regular one is not called. On the server side only the one with the underscore is called. You'll have to override the method with the underscore in the server side context as the above will work only on the server. If you use nested ECs in a standard WO application you might have to override the same semi-private method should you want the parent EC to handle PK creation. BTW, I believe EOF does some optimization by retrieving PKs in batches rather than one by one. You lose that when using the above code.
https://en.m.wikibooks.org/wiki/WebObjects/EOF/Using_EOF/Primary_Keys
CC-MAIN-2015-32
en
refinedweb
Dat.20 (14 reviews) - 01 Jul 2015 20:35:06 GMT - Search in distribution - DateTime::Infinite - Infinite past and future DateTime objects - DateTime::Duration - Duration objects for date math - DateTime::LeapSecond - leap seconds table and utilities - 3 more results from DateTime » SPADKINS/App-Context-0.968 - 09 Jun 2010 21:33:19 GMT - Search in distribution - App - Backplane for core App services - App::quickstart - App::Context Developer's Quick-Start Guide - App::exceptions - Programming with Exceptions - 1 more result from App-Context » o...FGLOCK/DateTime-Set-0.3400 - 12 Feb 2014 10:25:31 GMT - Search in distribution - DateTime::Span - Datetime spans - DateTime::SpanSet - set of DateTime spans - Set::Infinite::_recurrence - Extends Set::Infinite with recurrence functions "SOAP::DateTime" converts dates into the format required by the "xsd:dateTime" type....MCMAHON/SOAP-DateTime-0.02 - 31 Aug 2005 23:48:37 This class introduces minimal interface to handle database table fields of type 'DATETIME'. This class is descendant of <ORM::Date> and behaves almost the same with few differences. To see interface of the class please refer to "ORM::Date". Members t...AKIMOV/ORM-0.85.1 - 14 Apr 2013 11:36:38 GMT - Search in distribution - lib/ORM/Datetime.pm - lib/ORM/Meta/ORM/Datetime.pm - ORM - Object relational mapper for Perl. - 2 more results from ORM » Types::DateTime is a type constraint library suitable for use with Moo/Moose attributes, Kavorka sub signatures, and so forth. Types This module provides some type constraints broadly compatible with those provided by MooseX::Types::DateTime, plus a ...TOBYINK/Types-DateTime-0.001 - 03 Apr 2014 21:45:44 GMT - Search in distribution TAKERU/Atompub-0.3.7 - 06 Apr 2012 01:07:31 GMT - Search in distribution - Search in distribution - BuzzSaw::DB - The BuzzSaw database interface - BuzzSaw::Report - A Moose class which is used for generating BuzzSaw reports - BuzzSaw::Parser - A Moose role which defines the BuzzSaw parser interface - 4 more results from BuzzSaw » This module enables you to generate DateTime objects that represent the current time with sub-second resolution....JHOBLITT/DateTime-HiRes-0.01 - 09 Sep 2003 07:37:14 GMT - Search in distribution"...ALEXMV/Jifty-1.50430 - 30 Apr 2015 20:48:27 GMT - Search in distribution - Jifty::Filter::DateTime - A Jifty::DBI filter to work with Jifty::DateTime objects - Jifty::Web::Form::Field::DateTime - Add date pickers to your forms - Jifty::Action - The ability to Do Things in the framework - 3 more results from Jifty » DateTime::Astro implements functions used in astronomical calendars, such as calculation of lunar longitudea and solar longitude. This module is best used in environments where a C compiler and the MPFR arbitrary precision math library is installed. ...DMAKI/DateTime-Astro-1.00 - 24 Aug 2012 09:51:23 GMT - Search in distribution - DateTime::Event::SolarTerm - Calculate Solar Terms - lib/DateTime/AstroXS.pm - lib/DateTime/AstroPP.pm AULUSOY/Banal-DateTime-0.10 - 20 Jul 2014 23:32:25 GMT - Search in distribution - Banal::DateTime::Duration - A trivial and shameless subclass of DateTime::Duration, aiming at encapsulating and adding "banal" functionality. DateTime::Locale is primarily a factory for the various locale subclasses. It also provides some functions for getting information on all the available locales. If you want to know what methods are available for locale objects, then please read the "...DROLSKY/DateTime-Locale-0.46 (1 review) - 21 May 2015 17:11:58 GMT - Search in distribution This Package will handle about everything you may need for displaying the date / time. If anything has been left out, please contact me at kmeltz@cris.com , tivoli.rhase@muc-net.de so it can be added. DETAILS d = dot, s = slash, m = minus ROUTINES De...RHASE/Tivoli_0.01 - 05 Aug 2001 23:08:53 GMT - Search in distribution This module simply exports all class methods of DateTime into the caller's namespace....AUDREYT/DateTime-Functions-0.10 - 08 Dec 2010 16:31:22 GMT - Search in distribution
https://metacpan.org/search?q=DateTime
CC-MAIN-2015-32
en
refinedweb
POE::Component::IRC::Plugin::Karma - A POE::Component::IRC plugin that keeps track of karma This plugin keeps track of karma ( perl++ or perl-- ) said on IRC and provides an interface to retrieve statistics. The bot will watch for karma in channel messages, privmsgs and ctcp actions. IRC USAGE * thing++ # comment Increases the karma for <th...APOCAL/POE-Component-IRC-Plugin-Karma-0.003 - 16 Apr 2011 01:35:42 GMT - Search in distribution Task::POE::All - All of POE on CPAN This task contains all distributions under the POE namespace....APOCAL/Task-POE-All-1.102 - 09 Nov 2014 11:07:41 GMT - Search in distribution Bot::Cobalt - IRC darkbot-alike plus plugin authoring sugar6 - 14 Apr 2015 00:58:42 GMT - Search in distribution
https://metacpan.org/search?q=POE-Component-IRC-Plugin-Karma
CC-MAIN-2015-32
en
refinedweb
frosted 1.2.1 A passive Python syntax checker Frosted is a fork of pyflakes that aims at more open contribution from the outside public, a smaller more maintainable code base, and a better Python checker for all. It currently cleanly supports Python 2.6 - 3.4 using pies () to achieve this without ugly hacks and/or py2to3. Installing Frosted Installing Frosted is as simple as: pip install frosted --upgrade or if you prefer easy_install frosted Using Frosted from the command line: frosted mypythonfile.py mypythonfile2.py or recursively: frosted -r . which is equivalent to frosted **/*.py or to read from stdin: frosted - from within Python: import frosted frosted.api.check_path("pythonfile.py") Discussing improvements and getting help Using any of the following methods will result in a quick resolution to any issue you may have with Frosted or a quick response to any implementation detail you wish to discuss. - Mailing List - best place to discuss large architectural changes or changes that effect that may effect Python code-quality projects beyond Frosted. - Github issues - best place to report bugs, ask for concretely defined features, and even ask for general help. - timothy.crosley@gmail.com - feel free to email me any questions or concerns you have that you don’t think would benefit from community wide involvement. What makes Frosted better then pyflakes? The following improvements have already been implemented into Frosted - Several improvements and fixes that have stayed open (and ignored) on mainline pyflakes have been integrated. - Lots of code has been re-factored and simplified, Frosted aims to be faster and leaner then pyflakes ever was. - Frosted adds the ability to configure which files you want to check, and which errors you don’t care about. Which, in my opinion, is a must have feature. - Frosted implements the .editorconfig standard for configuration. This means you only need one configuration file for isort, frosted, and all the code editors anybody working with your project may be using. - Frosted uses a more logical, self-documenting, and standard terminal interface. With pyflakes the default action without any arguments is to do nothing (waiting for stdin) with Frosted you get an error and help. - Frosted switched from Java style unittests to the more Pythonic py.test (I admit this is highly subjective). - The number one reason frosted is better is because of you! Or rather, the Python community at large. I will quickly respond to any pull requests, recommendations, or bug reports that come my way. - Frosting. Duh. And it will only get better from here on out! Configuring Frosted If you find the default frosted settings do not work well for your project, frosted provides several ways to adjust the behavior. To configure frosted for a single user create a ~/.frosted.cfg file: [settings] skip=file3.py,file4.py ignore_frosted_errors=E101,E205,E300 Additionally, you can specify project level configuration simply by placing a .frosted.cfg file at the root of your project. frosted will look up to 25 directories up, from the one it is ran, to find a project specific configuration. You can then override any of these settings by using command line arguments, or by passing in kwargs into any of the exposed api checking methods. Finally, frosted supports editorconfig files using the standard syntax defined here: Meaning You can place any standard frosted configuration parameters within a .editorconfig file under the *.py section and they will be honored. Frosted Error Codes Frosted recognizes the following errors when present within your code. You can use the ‘ignore_frosted_errors’ setting to specify any errors you want Frosted to ignore. If you specify the series error code (ex: E100) all errors in that series will be ignored. I100 Series - General Information - I101: Generic E100 Series - Import Errors - E101: UnusedImport - E102: ImportShadowedByLoopVar - E103: ImportStarUsed E200 Series - Function / Method Definition and Calling Errors - E201: MultipleValuesForArgument - E202: TooFewArguments - E203: TooManyArguments - E204: UnexpectedArgument - E205: NeedKwOnlyArgument - E206: DuplicateArgument - E207: LateFutureImport - E208: ReturnWithArgsInsideGenerator E300 Series - Variable / Definition Usage Errors - E301: RedefinedWhileUnused - E302: RedefinedInListComp - E303: UndefinedName - E304: UndefinedExport - E305: UndefinedLocal - E306: Redefined - E307: UnusedVariable E400 Series - Syntax Errors - E401: DoctestSyntaxError W100 Series - Exception Warning - W101: BareExcept Frosted Code API Frosted exposes a simple API for checking Python code from withing other Python applications or plugins. - frosted.api.check (codeString, filename, reporter=modReporter.Default, **setting_overrides) Check the Python source given by codeString for unfrosted flakes. - frosted.api.check_path (filename, reporter=modReporter.Default, **setting_overrides) Check the given path, printing out any warnings detected. - frosted.check_recursive (paths, reporter=modReporter.Default, **setting_overrides) Recursively check all source files defined in paths. Additionally, you can use the command line tool in an API fashion, by passing ‘-‘ in as the filename and then sending file content to stdin. Why did you fork pyflakes? Pyflakes was a great project, and introduced a great approach for quickly checking for Python coding errors. I am very grateful to the original creators. However, I feel over the last year it has become stagnate, without a clear vision and someone willing to take true ownership of the project. While I know it is in no way intentional, critical failures have stayed open, despite perfectly complete and valid pull-requests open, without so much as an acknowledgement from the maintainer. As I genuinely believe open source projects need constant improvement (releasing early and often), I decided to start this project and look for as much input as possible from the Python community. I’m hoping together we can build an even more awesome code checker! Note: the maintainer of pyflakes has been added as a contributer to frosted. Thanks and I hope you enjoy the new Frosted pyflakes! ~Timothy Crosley - Downloads (All Versions): - 152 downloads in the last day - 908 downloads in the last week - 2438 downloads in the last month - Author: Timothy Crosley - License: MIT - Requires pies - - Topic :: Utilities - Package Index Owner: timothycrosley - DOAP record: frosted-1.2.1.xml
https://pypi.python.org/pypi/frosted/1.2.1
CC-MAIN-2015-32
en
refinedweb
34 replies on 3 pages. Most recent reply: Jan 5, 2006 5:32 PM by Geek Alot. javax.management.StandardMBean: Because of the compatibility requirement, it's much easier to put things in than to take them out. So don't add anything to the API that you're not sure you need. There's an approach to API design which you see depressingly often. Think of everything a user could possibly want to do with the API and add a method for it. Toss in protected methods so users can subclass to tweak every aspect of your implementation. Why is this bad? The more stuff there is in the API, the harder it is to learn. Which classes and methods are the important ones? Which of the five different ways to do what I need is the best? The situation is exacerbated by the Javadoc tool, which dumps all the classes in a package, and all the methods in a class, in an undifferentiated lump. We can expect that JSR 260 will update the Javadoc tool to allow you to produce "views" of the API, and in that case fatter APIs will not be so overwhelming. The bigger the API, the more things can go wrong. The implementation isn't going to be perfect, but the same investment in coding and testing will yield better results for a smaller API. If your API has more methods than it needs, then it's taking up more space than it needs. The right approach is to base the API on example code. Think of problems a user might want to solve with the API. Add just enough classes and methods to solve those problems. Code the solutions. Remove anything from the API that your examples don't need. This allows you to check that the API is useful. As a happy side-effect, it gives you some basic tests. And you can (and should) share the examples with your users. There's a certain style of API design that's very popular in the Java world, where everything is expressed in terms of Java interfaces (as opposed to classes). Interfaces have their place, but it is basically never a good idea for an entire API to be expressed in terms of them. A type should only be an interface if you have a good reason for it to be. Here's why: Interfaces can be implemented by anybody. Suppose String were an interface. Then you could never be sure that a String you got from somewhere obeyed the semantics you expect: it is immutable; its hashCode() is computed in a certain way; its length is never negative; and so on. Code that used String, whether user code or code from the rest of the J2SE platform, would have to go to enormous lengths to ensure it was robust in the face of String implementations that were accidentally incorrect. And to even further lengths to ensure that its security could not be compromised by deliberately evil String implementations. String hashCode() In practice, implementations of APIs that are defined entirely in terms of interfaces often end up cheating and casting objects to the non-public implementation class. DOM typically does this for example. So you can't give your own implementation of the DocumentType interface as a parameter to DOMImplementation.createDocument and expect it to work. Then what's the point in having interfaces? DocumentType DOMImplementation.createDocument Integer, Integer.valueOf(n)). You would have to use IntegerFactory.newInteger(n) or whatever. This makes your API harder to understand and use. Integer int new Integer(n) Integer.valueOf(n) IntegerFactory.newInteger(n) Interfaces cannot evolve. Suppose you add a new method to an interface in version 2 of your API. Then user code that implemented the interface in version 1 will no longer compile because it doesn't implement the new method. You can still preserve binary compatibility by catching AbstractMethodError around calls to the new method but that is clunky. If you use an abstract class instead of an interface you don't have this problem. If you tell users not to implement the interface then you don't have this problem either, but then why is it an interface? AbstractMethodError Interfaces cannot be serialized. Java serialization has its problems, but you can't always get away from it. The JMX API relies heavily on serialization, for example. For better or worse, the way serialization works is that the name of the actual implementation class is serialized, and an instance of that exact same class is reconstructed at deserialization. If the implementation class is not a public class in your API, then you won't interoperate with other implementations of your API, and it will be very hard for you to ensure that you even interoperate between different versions of your own implementation. If the implementation class is a public class in your API, then do you really need the interface as well?. Runnable. Comparable Number.) java.lang.reflect.Proxy invoke The Java language has fairly limited ways of controlling the visibility of classes and methods. In particular, if a class or method is visible outside its package, then it is visible to all code in all packages. This means that if you define your API in several packages, you have to be careful to avoid being forced to make things public just so that code in other packages in the API can access them. The simplest solution to avoid this is to put your whole API in one package. For an API with fewer than about 30 public classes this is usually the best approach. If your API is too big for a single package to be appropriate, then you should plan to have private implementation packages.. sun.* com.sun.* A good convention for private packages is to put internal in the name. So the Banana API might have public packages com.example.banana and com.example.banana.peel plus private packages com.example.banana.internal and com.example.banana.internal.peel. internal com.example.banana com.example.banana.peel com.example.banana.internal. javax.management.JMX com.sun.jmx JMX javax.management. java.nio java.lang.ProcessBuilder T getThing() void setThing(T) T thing() ThisClass thing: clone() Banana. Use a checked exception "if the exceptional condition cannot be prevented by proper use of the API and the programmer using the API can take some useful action once confronted with the exception." In practice this usually means that a checked exception reflects a problem in interaction with the outside world, such as the network, filesystem, or windowing system. If the exception signals that parameters are incorrect or than an object is in the wrong state for the operation you're trying to do, then an unchecked exception (subclass of RuntimeException) is appropriate. RuntimeException Design for inheritance or don't allow it. Item 15 of Effective Java tells you all you might want to know about this. The summary is that every method should be final by default (perhaps by virtue of being in a final class). Only if you can clearly document what happens if you override the method should it be possible to do so. And you should only do that if you have coded useful examples that do override the method. interface String { signature { int size() { post { result >= 0; } } String concat(String s) { post { result.size() == size() + s.size(); } } ... } }
http://www.artima.com/forums/flat.jsp?forum=106&thread=142428&start=0&msRange=15
CC-MAIN-2015-32
en
refinedweb
This namespace holds a enum of various period types like era, year, month, etc.. More... This namespace holds a enum of various period types like era, year, month, etc.. the type that defines a flag that holds a period identifier Special invalid value, should not be used directly. Era i.e. AC, BC in Gregorian and Julian calendar, range [0,1]. Year, it is calendar specific, for example 2011 in Gregorian calendar. Extended year for Gregorian/Julian calendars, where 1 BC == 0, 2 BC == -1. The month of year, calendar specific, in Gregorian [0..11]. The day of month, calendar specific, in Gregorian [1..31]. The number of day in year, starting from 1, in Gregorian [1..366]. Day of week, Sunday=1, Monday=2,..., Saturday=7. Note that updating this value respects local day of week, so for example, If first day of week is Monday and the current day is Tuesday then setting the value to Sunday (1) would forward the date by 5 days forward and not backward by two days as it could be expected if the numbers were taken as is. Original number of the day of the week in month. For example 1st Sunday, 2nd Sunday, etc. in Gregorian [1..5] Local day of week, for example in France Monday is 1, in US Sunday is 1, [1..7]. 24 clock hour [0..23] 12 clock hour [0..11] am or pm marker [0..1] minute [0..59] second [0..59] The week number in the year. The week number within current month. First day of week, constant, for example Sunday in US = 1, Monday in France = 2.
http://www.boost.org/doc/libs/1_53_0/libs/locale/doc/html/namespaceboost_1_1locale_1_1period_1_1marks.html
CC-MAIN-2015-32
en
refinedweb
Your answer is better.Thank you Type: Posts; User: curious725 Your answer is better.Thank you Yes,I agree.but what if it is something complicated? like this package handler; import java.io.BufferedInputStream; import java.io.DataInputStream; import java.io.File; import... Maybe I do not understand something. So I've created the class in Java, which does some stuff.I need to create a main method or mainClass, that will start(run) my class. (I do not mean JUnit)....
http://www.javaprogrammingforums.com/search.php?s=110537594739c3f122948b9c14eeef88&searchid=1665239
CC-MAIN-2015-32
en
refinedweb
Details - Type: Bug - Status: Resolved - Priority: Minor - Resolution: Fixed - Affects Version/s: Lucene.Net 2.9.2 - Fix Version/s: Lucene.Net 2.9.4, Lucene.Net 2.9.4g - Component/s: Lucene.Net Core - Labels:None - Environment: Irrelevant Description. Activity - All - Work Log - History - Activity - Transitions Hello Digy, Thanks for your response. I don't want to sound overly pedantic (but please tell me if I do), but this changed implementation solves only part of the problem. Now, CharArraySet derives from Set<T>, which itself derives from List<T>. Items are now stored both in this base class, as in the private HashSet<string> _Set. However, because List<T> doesn't define its modifiers Add(T), Clear() and Remove(T) as virtual, the derived implementation defines them as "new". This violates a variant of the Liskov substitution principle: an operation on the derived type has not the same effect as the same operation on the base type. In this case, it means that the following code will cause the items in the List<T> base type and in the _Set to be desynchronized: CharArraySet set=... List<string> same=set; same.Add("whatever"); // at this point, same.Contains("whatever")==true but set.Contains("whatever")==false even though it's the same instance. You might rightfully retort that this never happens and I should mind my own business, but I know at least one poor soul who did just that: me . On a completely unrelated matter, the new implementation has 2 methods: public void Add(System.Collections.Generic.IList<T> items) public void Add(Support.Set<T> items) .. which can be collapsed into one, since the only thing used in both cases is the enumerator: public void Add(IEnumerable<T> items) I don't recall the design rule, but it's something like "to increase reuse, make your function parameters are general as possible, but their return value as specific as possible". I am unable to get 2.9.4g to investigate further, but if you are moving towards the Generic collections in Lucene, the following implementation should be a drop-in replacement, without suffering from the aforementioned quirks: [Serializable] public class Set<T> : ICollection<T> { private readonly System.Collections.Generic.HashSet<T> _Set = new System.Collections.Generic.HashSet<T>(); bool _ReadOnly = false; public Set() { } public Set(bool readOnly){ this._ReadOnly = readOnly; } public bool ReadOnly { set get{ return _ReadOnly; } } public virtual void Add(T item){ if (_ReadOnly) throw new NotSupportedException(); if (_Set.Contains(item)) return; _Set.Add(item); } public void Add(IEnumerable<T> items) { if (_ReadOnly) throw new NotSupportedException(); foreach (T item in items) } public void Clear(){ if (_ReadOnly) throw new NotSupportedException(); _Set.Clear(); } public bool Contains(T item){ return _Set.Contains(item); } public void CopyTo(T[] array, int arrayIndex){ _Set.CopyTo(array, arrayIndex); } public int Count { get } public bool IsReadOnly { get } public bool Remove(T item){ if (_ReadOnly) throw new NotSupportedException(); return _Set.Remove(item); } public IEnumerator<T> GetEnumerator(){ return _Set.GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return _Set.GetEnumerator(); } public void RemoveAll(System.Collections.Generic.IList<T> list){ if (_ReadOnly) throw new NotSupportedException(); } public void RetainAll(System.Collections.Generic.IList<T> list) { if (_ReadOnly) throw new NotSupportedException(); } public void RemoveAll(System.Collections.ArrayList list){ if (_ReadOnly) throw new NotSupportedException(); } public void RetainAll(System.Collections.ArrayList list) { if (_ReadOnly) throw new NotSupportedException(); } } I've copied RemoveAll/RetainAll verbatim, since I don't know what they are for. I also left them nonvirtual. Note that it implements ICollection<T> and not IList<T>: from what I can determine, IList<T> is not necessary. It's also weird to have an indexed access on a type that by definition cannot have one. My medicine won't work if non-generic collection interfaces are still lurking in other parts of the code, because List<T>, for historical reasons, also implements the non-generic IList and ICollection interfaces. Alas, this opens another can of worms (IList<T> doesn't implement IList, ICollection<T> doesn't implement ICollection, but IEnumerable<T> implements IEnumerable), but the margin of this e-mail is too small to write down the cure. I'll stop rambling now and will try my own medicine as soon as I'm able to get the 2.9.4g from the ASF SVN. In the meantime, have a nice week-end and thank you for being the cornerstone of .NET's premier search engine. Vincent I think the simplest solution for 2.9.4 will be adding // public virtual bool Add(object key, object value) { if (key is string) return Add((string)key); else if (key is char[]) return Add((char[])key); return false; } to CharArraySet DIGY Hi Vincent, I changed the CharArraySet implementation. Can you take a look at 2.9.4g branch? ( ) DIGY
https://issues.apache.org/jira/browse/LUCENENET-414?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=13033031
CC-MAIN-2015-32
en
refinedweb
Resets cookie configured for reset on user logout. The reset function passed in is called for each cookie configured for reset. If the function failed for any cookie, the last failed status is returned. #include "am_web.h" AM_WEB_EXPORT am_status_t am_web_log no values.
http://docs.oracle.com/cd/E19528-01/819-4676/gcrgi/index.html
CC-MAIN-2015-32
en
refinedweb
After setting up your Android development environment, and Developing an Android Application it’s time to set-up a automatic Android Test environment. The steps to achieve this are: - Choose a test technique. - Creating a test project. - Make the test. - Run the test. I will use the Android application which was developed inside my previous post. [Update 15-03-2011] Updated to Android 2.3.3. [Update 15-03-2011] Updated to Robotium 2.2. Choose a test technique There are different techniques you can use to test Android applications. The most commonly known is by way of JUnit. JUnit is used to test the technical quality of applications. But what about the testing the functional use of a application, like you would do it with Selenium for web application. For Android applications there is a similar tool for testing called Robotium. It is a UI testing tool which simulates touching, clicks, typing, and other users’ actions relevant for Android applications. In this example I will be using Robotium. Creating a test project - From within Eclipse select File menu, New and Other. - Choose Android Test Project inside the Android folder. - Provide the information about the Android Test project and click Next. - Press Finish. You should see the following directory structure Because I will be creating a Robotium test, I must provide the robotium-solo-2.2.jar as library. Make the test - From within Eclipse select File menu, New and JUnit Test Case. - Provide the information about the Junit Test Case and click Finish. - Change MainTest.java to the following import java.util.ArrayList; import com.jayway.android.robotium.solo.Solo; import android.app.Activity; import android.test.ActivityInstrumentationTestCase2; import android.widget.TextView; public class MainTest extends ActivityInstrumentationTestCase2 { private Solo solo; private Activity activity; public MainTest() { super("com.my", Main.class); } @Override protected void setUp() throws Exception { super.setUp(); this.activity = this.getActivity(); this.solo = new Solo(getInstrumentation(), this.activity); } @Override public void tearDown() throws Exception { try { this.solo.finalize(); } catch (Throwable e) { e.printStackTrace(); } this.activity.finish(); super.tearDown(); } /** * @throws Exception Exception */ public void testDisplay() throws Exception { String text = "Congratulations"; //Enter "Congratulations" inside the EditText field. this.solo.enterText((EditText) this.activity.findViewById(R.id.EditText01), text); //Click on the button named "Click". this.solo.clickOnButton("Click"); //Check to see if the given text is displayed. assertTrue(this.solo.searchText(text)); TextView outputField = (TextView) this.activity.findViewById(R.id.TextView01); ArrayList currentTextViews = this.solo.getCurrentTextViews(outputField); assertFalse(currentTextViews.isEmpty()); TextView output = currentTextViews.get(0); assertEquals(text, output.getText().toString()); } } Run the test Al that is left is running the test. - Right click MyAndroidAppTestProject. - Select Android Junit Test within the Run-As option. - Be patient, the emulator starts up very slow. You should get the following result Appendix Download source code Android.zip [16kB] and AndroidTest.zip [16kB] AndroidManifest.xmllook like?, this causes most of the problems associated with running android j-unit test. public TestTextView(String name)but public TestTextView()as constructor.
http://wiebe-elsinga.com/blog/automatic-testing-for-android-applications/
CC-MAIN-2015-32
en
refinedweb
W3C Web Services Policy 1.5 - Attachment W3C^? (MIT, ERCIM, Keio), All Rights Reserved. W3C liability, trademark and document use rules apply. ------------------------------------------------------------------------------- Abstract This specification, Web Services Policy 1.5 - Attachment, defines two general-purpose mechanisms for associating policies, as defined in Web Services Policy 1.5 - Framework, with the subjects to which they apply. This specification also defines how these general-purpose mechanisms may be used to associate policies with WSDL and UDDI descriptions. Web Services Policy 1.5 - Attachment specification. It has been produced by the Web Services Policy Working Group, released a test suite along with an implementation report. A diff-marked version against the previous version of this document is available.. Notations and Terminology 2.1 Notational Conventions 2.2 XML Namespaces 2.3 Terminology 2.4 Example 3. Policy Attachment 3.1 Effective Policy 3.2 Policy Attachment Mechanisms 3.3 XML Element Attachment 3.4 External Policy Attachment 3.4.1 URI Domain Expression 3.5 Use of IRIs in Policy Attachment 4. Attaching Policies Using WSDL 1.1 4.1 Calculating Effective Policy in WSDL 1.1 4.1.1 Service Policy Subject 4.1.2 Endpoint Policy Subject 4.1.3 Operation Policy Subject 4.1.4 Message Policy Subject 4.1.5 Example 5. WS-Policy Attachment for WSDL 2.0 5.1 Example 5.2 Attaching Policy Expressions 5.3 Extension to WSDL Component Model 5.4 Effective Policy 5.4.1 Service Policy Subject 5.4.2 Endpoint Policy Subject 5.4.3 Operation Policy Subject 5.4.4 Message Policy Subject (input message) 5.4.5 Message Policy Subject (output message) 5.4.6 Message Policy Subject (input fault message) 5.4.7 Message Policy Subject (output fault message) 6. Attaching Policies Using UDDI 6.1 Calculating Effective Policy and Element Policy in UDDI 6.1.1 Service Provider Policy Subject 6.1.2 Service Policy Subject 6.1.3 Endpoint Policy Subject 6.2 Referencing Remote Policy Expressions 6.3 Registering Reusable Policy Expressions 6.4 Registering Policies in UDDI Version 3 7. Security Considerations 8. Conformance 8.1 External Policy Attachment Conformance 8.2 WSDL 1.1 Attachment Conformance 8.3 WSDL 2.0 Attachment Conformance Appendices A. References A.1 Normative References A.2 Other References B. UDDI tModel Definitions B.1 Remote Policy Reference Category System B.1.1 Design Goals B.1.2 tModel Definition B.1.3 tModel Structure B.2 Web Services Policy Types Category System B.2.1 Design Goals B.2.2 tModel Definition B.2.3 tModel Structure B.3 Local Policy Reference Category System B.3.1 Design Goals B.3.2 tModel Definition B.3.3 tModel Structure C. Acknowledgements (Non-Normative) ------------------------------------------------------------------------------- 1. Introduction The Web Services Policy 1.5 - Framework [Web Services Policy Framework] specification defines an abstract model and an XML-based language for expressing policies of entities in a Web services-based system. This specification, Web Services Policy 1.5 - Attachment, defines two general-purpose mechanisms for associating policies with the subjects to which they apply; the policies may be defined as part of existing metadata about the subject or the policies may be defined independently and associated through an external binding to the subject. To enable Web Services Policy to be used with existing Web service technologies, this specification describes the use of these general-purpose mechanisms with WSDL [WSDL 1.1, WSDL 2.0 Core Language] definitions and UDDI [ UDDI API 2.0, UDDI Data Structure 2.0, UDDI 3.0]. 2. Notations and Terminology This section specifies the notations, namespaces, and terminology used in this specification. 2.1 Notational Conventions. namespace. Normative text within this specification takes precedence over normative outlines, which in turn take precedence over the XML Schema [XML Schema Structures] descriptions. 2.2 XML Namespaces This specification uses a number of namespace prefixes throughout; they are listed in Table 2-1. Note that the choice of any namespace prefix is arbitrary and not semantically significant (see [XML Namespaces]). Table 2-1. Prefixes and Namespaces used in this specification +-----------------------------------------------------------------------------+ |] | +-----------------------------------------------------------------------------+ All information items defined by this specification are identified by the XML namespace URI [XML Namespaces]. A normative XML Schema [XML Schema Structures, XML Schema Datatypes] document can be obtained indirectly by dereferencing the namespace document at the WS-Policy 1.5 namespace URI. In this document reference is made to the wsu:Id attribute in a utility schema ( oasis-200401-wss-wssecurity-utility-1.0.xsd). The wsu:Id attribute was added to the utility schema with the intent that other specifications requiring such an Id could reference it (as is done here).. 2.3 Terminology The keywords "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119 [IETF RFC 2119]. We introduce the following terms that are used throughout this document: collection The items in a collection in this specification are unordered and may contain duplicates. effective policy The effective policy, for a given policy subject, is the combination of relevant policies. The relevant policies are those attached to policy scopes that contain the policy subject. element policy The element policy is the policy attached to the policy subjects associated with the element information item that contains it. ignorable policy assertion An ignorable policy assertion is an assertion that may be ignored for purposes of determining the compatibility of alternatives in policy intersection in a lax mode (as defined in 4.5 Policy Intersection). merge A merge consists of serializing each policy as a policy expression, replacing their wsp:Policy element with a wsp:All element, and placing each as children of a wrapper wsp:Policy element. policy A policy is a potentially empty collection of policy alternatives. policy alternative A policy alternative is a potentially empty collection of policy assertions . policy assertion A policy assertion represents a requirement, a capability, or other property of a behavior. policy attachment A policy attachment is a mechanism for associating policy with one or more policy scopes. policy expression A policy expression is an XML Infoset representation of a policy, either in a normal form or in an equivalent compact form. policy scope A policy scope is a collection of policy subjects to which a policy may apply. policy subject A policy subject is an entity (e.g., an endpoint, message, resource, operation) with which a policy can be associated. 2.4 Example This specification defines several mechanisms for associating policies (Web Services Policy 1.5 - Framework, [Web Services Policy Framework]) with various XML Web service entities. For brevity, we define two sample policy expressions that the remainder of this document references. Example 2-1 indicates a policy for reliable messaging [WS-RM Policy]. Example 2-2 is a policy for securing messages using X509 certificates [ WS-SecurityPolicy]. Example 2-1. Example RM Policy Expression. (01) (05)
http://www.w3.org/TR/2007/REC-ws-policy-attach-20070904/ws-policy-attachment.txt
CC-MAIN-2015-32
en
refinedweb
You can subscribe to this list here. Showing 2 results of 2 David Bolen <db3l@...> writes: > Thomas Heller [mailto:theller@...] writes: > >> Can you please upload the example as zip-file somewhere the the bug >> tracker? Either Python (for modulefinder) or py2exe. I promise to look >> into it. > > Crud - while packaging for the bug report I found a bug in my > simplified version (misnamed module), so that my message as written > probably doesn't fail for anyone else. It still fails consistently > when using twisted, but I spent an hour or two trying to work my way > through the twisted base to again attempt a simpler example to no > effect yet. (twisted's imports remind me of Adventure's "a maze of > twisty little passages, all alike"). I'm guessing it's related to > recursive imports somewhere along the line, since a lot of that > happens in the Twisted core due to inter-dependencies between > sub-packages. > > I don't suppose you have a copy of twisted (either 1.3.0 or 2.x seem > the same) on any system do you? If so, then replacing the "from a.c > import resource" with "from twisted.web import resource" in a's > __init__ should show the problem. If not, I'll keep digging to see > if I can create a simplified use case of some sort. David, I have tried to build the a.c package as you described, and installed twisted 1.3.0 for Python 2.4.1. Still, the main.exe file builds fine. Here are the last lines of the py2exe output: The following modules appear to be missing ['Crypto.Cipher', 'FCNTL', 'OpenSSL', 'jarray', 'java.io.IOException', 'java.io.InterruptedIOException', 'java.net', 'resource'] The missing 'resource' module may be related to the error that YOU get, but basically it is correct. It refers to these lines in twisted\internet\process.py file, near line 409: try: import resource maxfds = resource.getrlimit(resource.RLIMIT_NOFILE)[1] + 1 # OS-X reports 9223372036854775808. That's a lot of fds to close if maxfds > 1024: maxfds = 1024 > Also, for what it's worth, py2app under OS X doesn't exhibit the same > problem. I know it uses a modified version of modulefinder > (modulegraph) so it would seem like some of those modifications > resolved whatever is happening under the covers here. Not sure if > you've ever considered trying modulegraph in a subsequent release of > py2exe or not? The resource module that is imported here is the top-level stdlib resource module, which is only available in Unix (and OSX, I assume). So it may be that Unix and OSX doen't have this problem because the builtin resource module is found, or it may be that py2app's modulegraph works better than modulefinder. Still, I would really like you to post a reproducible testcase for Windows, because I HAVE seen cases where to many careless imports fail in the py2exe'd app. I'm willing to install even other packages, if it is required ;-) Thomas I'm working on a tool to make many different builds with py2exe(including and excluding different things). I have been able to make a function to build using py2exe(I change sys.argv then do the setup(... and then set the sys.argv to what it was originally) I was wondering if there was an easy way to tell if it py2exe was successful or not. I have already looked at what setup() returns and I could not find anything useful in the result. I would prefer not to have to check the existence of files. --=20 -Echo
http://sourceforge.net/p/py2exe/mailman/py2exe-users/?viewmonth=200508&viewday=4
CC-MAIN-2015-32
en
refinedweb
Scout/HowTo/3.7/Add an icon Contents Add the icon file to the project In the client Plug-In (e.g. tutorialMiniCrm.client.tutorialMiniCrm) add the icon file to the resources/icons folder. Scout supports many different picture formats. You can use a PNG file that has a size of 16*16 pixels. Link your file to your application Open the Icons class in the shared (e.g. tutorialMiniCrm.shared.tutorialMiniCrm.Icons) and add a new line like this: public static final String UserHome ="home_red"; - Name of the constant is the name that you will use in your application. (e.g. UserHome) - Value is the name of your file without the extension. (e.g. home_red.png) Use your icon When you need to provide an Icon you can now use the Icons class. For example: @Override protected String getConfiguredIconId(){ return Icons.UserHome; } With the appropriate import: import tutorialMiniCrm.shared.tutorialMiniCrm.Icons; Of course the new icon is listed in the icon editor in the Scout SDK (Explorer View: Project > Shared > Icons, Object Properties View: Open icons editor). It is also available in the icon chooser field in order to configure quickly your GUI..
http://wiki.eclipse.org/Scout/HowTo/3.7/Add_an_icon
CC-MAIN-2015-32
en
refinedweb
A while ago I proposed DaST as a new architectural pattern for building highly dynamic Web 2.0 apps. In short, a web page is rendered as a set of randomly nested rectangles where each rectangle is controlled individually and every combination of rectangles can be partially updated via AJAX. The concept is currently implemented for ASP.NET as the open-source ASP.NET DaST framework, Just recently I published the first stable version of the framework and completed the documentation. This article is a DaST Tutorial that sums up the work done since the project started. DaST technology is a big shift to web development paradigm. It was designed specifically to turn creating of highly dynamic Web 2.0 apps into a trivial task. ASP.NET DaST proves that tiny open-source toolset can accomplish the job of highest complexity, outperforming monsters like standard WebForms and MVC in simplicity, architecture, flexibility, performance, presentation separation, and many other important web development aspects. I know how this sounds, but I can promise that further in this article DaST approach will completely change your idea about web application design and development. First impression is important. I'm putting this 1-minute overview here, before the main article, in order to highlight some DaST features, so you can get a feeling of what this technology is and what you can achieve using it in your web applications. Framework ASP.NET DaST is contained in a single .dll file. This framework is not an add-on, but a complete alternative to the standard WebForms and MVC frameworks. In the same time, ASP.NET DaST does not deny any standard features and can be smoothly integrated into existing ASP.NET applications page by page. .dll Assume we have some user-order-item data that we want to output in tree-like form. The DaST template for this could the the following: <div dast: <b>Customer:</b> {CustomerName} <div dast: <div><b>Order:</b> {OrderID}</div> <div dast: <div><b>Item:</b> {ItemName}</div> </div> </div> </div> Normally, to output user-order-item data we would need 3 nested repeaters. DaST template has 3 nested scopes instead. Plus, this is clear and pure HTML, without any special markup or control-flow statements! The controller tells the system how to render the template. Here is a part of the controller for our previous template: public class NonsenseExample1aController : ScopeController { private void DataBind_CustomerRepeater() { var customers = DataLayer.GetCustomers(); // get customers CurrPath().RepeatStart(); // zeroize repeater foreach (var c in customers) // loop through customers { CurrPath().Repeat(); // repeat scope for current customer CurrPath().Replace("{CustomerName}", c.GetValue("Name")); // render name CurrPath("OrderRepeater").Params.Set("CUST", c); // pass to next scope } } private void DataBind_OrderRepeater() { ... } private void DataBind_ItemRepeater() { ... } } The DataBind_CustomerRepeater() handler controls CustomerRepeater scope in the template. It simply retrieves customer objects and repeats the scope for each of them replacing {CustomerName} placeholder with its real value on each iteration. Two other handlers, for OrderRepeater and ItemRepeater scopes would be analogical. DataBind_CustomerRepeater() CustomerRepeater {CustomerName} OrderRepeater ItemRepeater Actions mechanism is DaST substitution for events. Action is raised on the client-side using JavaScript DaST.Scopes.Action(..) function: DaST.Scopes.Action(..) <a href="javascript:DaST.Scopes.Action('...', 'SubmitInput', ['abc', 123])"> </a> This code raises SubmitInput action that will be processed by action handler implemented inside the controller class. Last parameter is some generic data passed along with the action: SubmitInput private void Action_SubmitInput(object arg) { string p1 = (string)((object[])arg)[0]; // "abc" int p2 = (int)((object[])arg)[1]; // 123 // processing goes here ... } One of the coolest DaST features is that you can raise actions in the opposite direction, from server to client, and handle them in your JavaScript! This mechanism is called Duplex Messaging and here is a sample: private void Action_SubmitInput(object arg) { // processing goes here ... CurrPath().MessageClient("InputSubmitted", new object[] {"abc", 123}); } This sends InputSubmitted message to the client along with the generic argument. On the page we use JavaScript to handle this message: InputSubmitted <script language="javascript" type="text/javascript"> DaST.Scopes.AddMessageHandler('...', 'InputSubmitted', function(data) { var p1 = data[0]; // "abc" var p2 = data[1]; // 123 // processing goes here }); </script> DaST has the simplest and most powerful area-based native AJAX support where we literally can update any page area we point at without extra code or markup. private void Action_SubmitInput(object arg) { // processing goes here ... CtrlPath("CustomerRepeater", 2, "OrderRepeater").Refresh(); } So, we simply point at some scope and call Refresh() on it - that's all! This causes the system to re-invoke necessary binding handler(s), generate partial output, and update the corresponding container on the client-side. Refresh() In general case, the DaST page consists of multiple controllers (and multiple nested templates) that can communicate between each other. This is where Controller Actions mechanism is used. Here is a sample how to raise actions to talk to child or parent controller: private void Action_SomeActionName(object arg) { // some processing can go here CurrPath().RaiseAction("HelloFromChild", new object[] { "abc", 123 }); CurrPath("SomeChildScope").InvokeAction("HelloFromParent", new object[] { "abc", 123 }); // other processing can go here } Same as for client actions, we can pass generic parameters along with controller actions. Then HelloFromChild and HelloFromParent actions can be handled inside parent and child controllers respectively: HelloFromChild HelloFromParent private void Action_HelloFromChild(object arg) // or Action_HelloFromParent for child controller { string p1 = (string)((object[])arg)[0]; // "abc" int p2 = (int)((object[])arg)[1]; // 123 // processing goes here } The syntax here is totally uniform with client action handlers. Surpassing WebForms in all respects, DaST also has important advantages over the most recent MVC frameworks. Just divide your page into nested rectangles and manipulate them to reach the desired output! That's what the web development should be. No need for tons of server controls, weird page lifecycle, bulky binding expressions, or anything like this. Pure HTML templates can be stored anywhere providing native CMS capabilities. Plus you get the simplest and most powerful area-based native AJAX support where you literally can update any page area you point at without extra code or markup. This concept is very fresh and unique and it’s just as simple as it sounds. And for those, who feel lazy about learning new framework, there's really NOT MUCH to learn about DaST. It will take you about 2 hours – just time of going through this tutorial – to learn absolutely all aspects of DaST development. It’s a simple concept, some theory, a dozen of API functions, and truly intuitive programming on the top – that’s all. Here is the list of helpful links that you may need: Now it's time to turn to the actual tutorial. It gives you all needed concept theory followed by coding walk-through with samples of real applications that you can download and run on your local machine. I hope you enjoy it! To demonstrate DaST technology in action, I created a LittleNonsense DEMO web application. As its name implies, this app does not make much sense in a real world; however, it perfectly demonstrates power of DaST pattern and all features of the framework. I suggest you download the source code and run this app on your local machine. Overall functionality of this demo app is fairly simple. It reads customer orders data from XML file and outputs it to the web page in a user-friendly form. Listing below shows a part of this source XML data file located in /App_Data folder: /App_Data Listing 0.1: Part of ../App_Data/Data/LittleNonsense.xml data source XML file 01: <?xml version="1.0" encoding="utf-8"?> 02: <LittleNonsense> 03: <Customer id="C01" name="John"> 04: <Order id="O01" date="2012-01-01"> 05: <Item id="I01" name="IPod Touch 16GB" /> 06: <Item id="I02" name="HDMI Cable" /> 07: </Order> 08: </Customer> 09: <Customer id="C02" name="Roman"> 10: <Order id="O02" date="2012-04-05"> 11: <Item id="I03" name="ASUS/Google Nexus 7 Tablet" /> 12: <Item id="I04" name="Nexus 7 Protective Case" /> 13: </Order> 14: <Order id="O03" date="2012-04-22"> 15: <Item id="I05" name="ASUS EEEPC Netbook" /> 16: <Item id="I06" name="8 Cell Battery" /> 17: </Order> 18: </Customer> 19: ............... 20: </LittleNonsense> As you can see, structure of XML data file is trivial. We have a set of customers. Each customer can have multiple orders. And each order consists of multiple order items. Each element has a unique id attribute and a second attribute carrying some meaningful data: customer name, order date, or item name. id I divided the LittleNonsense application into 2 separate parts: Example 1 and Example 2 implemented on NonsenseExample1.aspx and NonsenseExample2.aspx pages respectively. Example 1 is trivial and is used for concept explanation and Coding Basics part of this tutorial. Example 2 has much more stuff in it and demonstrates Web 2.0 and all advanced features of DaST framework. Example 2 is used for the Advanced Coding part of this tutorial and we'll come to it later. Now, let's introduce Example 1. NonsenseExample1.aspx NonsenseExample2.aspx This example was designed to give you a feeling of DaST Rendering mechanism and show you what is so different about DaST concept. Specifically, Example 1 covers the following topics: All this application does is reading some hierarchical data from XML file and outputting it using 3 nested repeaters. Below is a screenshot of Example 1 output: Fig. EX1: Screenshot of NonsenseExample1.aspx page output So, we just repeat customers, orders for each customer, and items for each order, displaying the result in the form of user-friendly hierarchical tree. The id attribute of each element from XML file is displayed in square brackets before actual text data. In further sections I’ll do a complete Example 1 source code walkthrough with all details and explanations. Right now I’d like start with some theoretical knowledge and explanation of DaST Concept. First of all, DaST is much more than a framework – it’s a whole new web development pattern and a unique application design concept. The ASP.NET DaST project is a .NET implementation of this pattern. But the pattern can be implemented for any other platform such as PHP (upcoming project), JSP, etc. The concept started from a very simple thought that every web page is nothing, but a bunch of data produced by server-side logic and presented to the user in the client browser. The entire page rendering process can be separated in two steps: To accomplish these steps, DaST uses a combination of template and controller. Controller is a back-end class that generates the values. Template is a W3C compliant and valid HTML file where the values get inserted. And it’s just as simple as it sounds: Besides obvious simplicity and flexibility of this approach, HTML templates give us theoretical maximum of presentation separation! The central question here is what happens in between the controller and the template during rendering and how the values are delivered to the specific spots within the HTML template... And this is exactly what DaST engine is for! DaST stands for data scope tree. You’ll see why in a second, but before going into more details, let me illustrate DaST rendering approach by a simple picture that you will use for your reference: Fig. 1.1: Top-level design of DaST rendering process This picture visualizes the whole point of DaST pattern and illustrates the use of template/controller combination to get page output. Now, I’ll explain Fig 1.1 and give the formal definition of the concept: DIV SPAN dast:scope {SomeValue} This is the top-level concept definition. Next we will take a closer look at the scope tree. Scope tree is essentially a mechanism that gives the developer full control over the page output. In the beginning of page rendering process, DaST builds the scope tree by parsing the HTML template. This tree structure is exposed to the developer via Scope Tree API, so developer task inside action and binding handlers of the controller class reduces to pointing at the specific scopes in the tree and manipulating them: bringing real values to placeholders, repeating scope content, and others. Scope tree structure is not constant. Once the tree is initially parsed from the HTML template, it may change during further rendering process. For example, when some scope gets repeated, the tree gets an additional branch coming from this scope. We will distinguish 2 primary states of the scope tree: initial scope tree and rendered scope tree. Initial scope tree is the one that is parsed from the HTML template in the beginning of rendering process. In other words, initial tree is a structural skeleton of the HTML template. Template defines the initial tree, and vice versa, having initial scope tree, we can build valid and fully functional HTML template consisting of only scope container elements. For better understanding I will depict all scope trees that I talk about. I’ll use the following notation: Let’s now create the initial scope tree for our Example 1. To achieve the UI shown on Fig EX1 in Example 1 Intro section, it’s obvious that we need 3 nested repeaters. In DaST terms this a tree of 3 nested scopes repeating their content. Fig 1.2 shows the initial scope tree that I came up with: Fig. 1.2: Initial scope tree for Example 1 part of LittleNonsense demo A couple of important things to note: NULL Now let’s talk about the rendered scope tree. Rendered scope tree is the one that initial tree turns into in the end of rendering process. In other words, rendered tree represents the resulting web page. It’s always bigger than initial tree, because of new branches appeared due to the repeated scopes. Recalling graph theory we can make a couple of observations: Back to our Example 1. Looking at the UI on Fig EX1 in Example 1 Intro section and the initial tree on Fig. 1.2, let’s now depict the rendered scope tree: Fig. 1.3: Rendered scope tree for Example 1 part of LittleNonsense demo The initial tree which is a sub-tree of the rendered scope tree is depicted in black color. Grey part is whatever is added after all needed scopes are repeated to get the desired output. Blue comments help you to understand how scopes in the rendered tree correspond to the resulting output of Example 1 page. There are 3 customers in the XML data file, so CustomerRepeater content is repeated 3 times for customers "John", "Roman", and "James". Customer "Roman" has 2 orders, so OrderRepeater content is repeated 2 times for "[O02]" and "[O03]" order IDs. And so on. As I mentioned earlier, the developer controls page output by manipulating the scopes via Scope Tree API. Before manipulating the specific scope, it must be selected using scope path. The scope path is simply a way of addressing scope in the tree. Every data scope is uniquely identified by its scope path. When web page is rendered, string versions of scope paths are used in id attributes of the corresponding scope container elements. Uniqueness of scope path guaranties uniqueness of scope container element id attribute. Scope path consists of segments. Segment is a combination of the 0-based repeating axis and the scope name. Repeating axis indicates the repeating iteration of the container scope. If parent container scope does not repeat its content, then repeating axis stays 0. In the source HTML of Example 1 resulting page, scope container elements look like the following: <div id="SCOPE$0-CustomerRepeater$1-OrderRepeater$0-ItemRepeater"> The id attribute contains the string representation of the path for this scope. The actual path follows after “SCOPE” prefix and segments are delimited by “$” sign. NULL scope is always the same, so we don’t include it in the scope paths. Looking at the id attribute above, we can immediately tell which scope this DIV corresponds to on Fig 1.3. Just follow the path: take 1st (axis 0) CustomerRepeater, then take 2nd (axis 1) branch to OrderRepeater, then 1st branch to ItemRepeater. So, this path points to the ItemRepeater scope with "[O02] 2012-04-05" text on it (see Fig 1.3). DIV CustomerRepeater OrderRepeater ItemRepeater Note that scope container id attributes always use absolute paths, but inside the controller callbacks, we can also use relative scope paths. Relative paths start from the current scope i.e. the one that current action or binding handler is executing for. Controller is a back-end class that tells the system how to render the scope tree. The scope tree is defined by the template associated with the controller. You can think of DaST controller and template combinations as a conceptual replacement for standard ASP.NET server controls or MVC views/controllers. Every controller can consist of other nested controllers, each of them responsible for its own part of the scope tree. To control the desired part of the tree, the controller needs to be attached to the specific scope in the initial scope tree. When controller is attached to the scope, it becomes responsible for rendering of the partial scope tree (or sub-tree) starting from this scope. The sub-tree is rendered by the rendering traversal procedure that visits scopes one after another, calls corresponding binding handlers, and generates output (more details in Page Rendering section). Attaching controllers to their scopes is a part of tree model building which happens in the very beginning of the rendering process, so we’re only talking about the initial scope tree here. This is done before any of action or binding handlers are invoked, so the scope tree still has its initial structure parsed from the template. By default, DaST page is driven by one top-level controller called root controller associated with the root template. Root controller is always attached to the NULL scope of the tree defined by this template. If there are no other controllers, root controller becomes responsible for rendering the entire scope tree. For example, in Example 1 app for simplicity I used a single top-level root controller responsible for the entire scope tree. But if I attached some child controller to the OrderRepeater scope on Fig 1.2 and rendering traversal went beyond the OrderRepeater, then the responsible controller would be the one attached to OrderRepeater rather then the root controller attached to the NULL scope. And this controller would be used to execute action and binding handlers. All corresponding coding techniques are explained in depth in Controller Class section. Scope Tree API is the interface for talking to the scope tree from inside action and binding handlers in the controller class. In order to get the desired page output, our task reduces to manipulating specific scopes in the tree. After scope is pointed using scope path (see Scope Paths), we can perform certain manipulations on it such as: For more details go to Scope Tree API Reference. DaST page rendering process is the period from client request hitting the page until the response is sent back to the client. In standard ASP.NET we used to call it a “page lifecycle”, but I intentionally do not use this term here to emphasize the difference. There is no weird sequence of page and child control events where execution goes back and forth, no questions which event to use to do the certain task, no ambiguity at all. DaST rendering process is defined with mathematical precision and it is the most beautiful part of DaST pattern. Let’s start from looking at the top-level picture of client-server interaction and request processing flow. Below is the diagram showing this flow step-by-step: Fig. 1.4: Top-level request processing flow So, page loads initially, then reloads multiple times in response to some events on the client side. Overall workflow looks pretty standard except for having DaST page instead of the regular page. Below is the more detailed descriptions of steps marked with red circles on Fig 1.4: There is a couple of important things to note here. First, there is no such thing as full page postback in DaST. Every client action in DaST results in partial refresh of the specific scopes on the page. Whatever you wish to update, needs to be wrapped into the data scope. Second, in terms of code-behind design, DaST partial update has huge advantage over the standard AJAX based on UpdatePanel control. The standard async postback re-executes all your code unless surrounded by ugly IsAsyncPostBack conditionals. DaST re-executes binding handlers for the refreshed scopes only! All details are in the next section. UpdatePanel IsAsyncPostBack Now let’s delve into the page rendering process and see what happens behind the scenes. Like everything else in DaST, rendering process is based on the scope tree defined by the template. Note that rendering process illustrated on Fig 1.1 is a bit simplified, because there is only a single root controller responsible for the entire scope tree. In real apps, one page is usually rendered by multiple nested controllers, each of them responsible for its own part of the scope tree i.e. scope sub-tree (see Controller section). So, let’s formalize the rendering process now. On the top-level, it can be divided into 3 steps: Now let’s elaborate what system actually does during these steps. This has to be done separately for initial and subsequent page loads (see Workflow section), because there are some differences in how steps are executed in these two states. So, first, assume we’re on the initial page load. Rendering steps for this case are below: Now, assume we’re on the subsequent page load. Then rendering steps look like the following: And this is it! Sounds unbelievable, but this simple, clear, and transparent approach renders any page no matter how complex it is! Just look how clean, uniform, and well-defined DaST rendering process is in comparison with standard ASP.NET rendering, weird page lifecycle, event precedence, tons of server controls with nested data binding delegates, and so on! Even MVC, being is a huge step ahead of the WebForms, and being very well organized on the server-side, uses control flow and code generation constructs in views and partial views that immediately kills every hope for proper presentation separation. DaST pattern does not have any of these problems. It just dumps all this complexity at once! Since the developer deals only with the controller class, we also want to look at rendering process from the controller point of view. Inside the controller class, execution can be divided into 3 separate stages: Based on these simple stages, we always know the exact order of execution for all functions inside the controller. You’ll see how this works in coding walkthrough sections that follow. For now, we’re done with concept theory! At this point we know enough to start going through the real coding examples and talk about DaST development techniques. There is a bit more theory left, but we will learn the rest as we go through the code samples in this tutorial. To learn basics of DaST programming, we will walk through the code of Example 1 part of LittleNonsense demo application. For deeper understanding I suggest you download the source code and have it in front of you for all explanations. Also, all functions in this tutorial belonging to Scope Tree API are followed by "[*]" link that take you directly to API Reference for this function. So, let’s get started with coding now. Before doing anything we need to reference DaST framework. ASP.NET DaST is contained in a single AspNetDaST.dll and you have to drop this DLL into the /Bin folder of your web application. All classes from Scope Tree API are located in the AspNetDaST.Web namespace. AspNetDaST.dll /Bin AspNetDaST.Web The request URL in DaST leads to a physical .aspx page, which is similar to WebForms and different from MVC’s pattern based request routing. The content of .aspx file is ignored – this page is needed only as a request entry point. After hitting the page, the request processing workflow goes to DaST rendering engine. In other words, DaST framework overrides the entire rendering of the standard ASP.NET page. .aspx Look at Example 1 now. The request hits NonsenseExample1.aspx page and the purpose of the corresponding code-behind is to transfer the flow to the specific DaST controller. The source code of the code-behind is below: NonsenseExample1.aspx Listing 2.1: NonsenseExample1.aspx.cs file 1: public partial class NonsenseExample1 : AspNetDaST.Web.DaSTPage 2: { 3: protected override AspNetDaST.Web.ScopeController ProvideRootController() 4: { 5: return new NonsenseExample1Controller(); 6: } 7: } So, to turn regular.aspx page to DaST page you do the following: AspNetDaST.Web.DaSTPage System.Web.UI.Page ProvideRootController() This is it! Now you have a DaST page driven by the specified root controller. The question you might have at this point is why not to use URL pattern-based request routing directly to the controller, just like the way it is done in MVC and what is the purpose of having that intermediate.aspx page that does nothing? Ok, the main reason and a huge benefit of this design is that DaST pages can coexist with standard ASP.NET pages in one application without any extra settings! This allows the developers to smoothly transition existing ASP.NET apps to DaST-based apps page by page. I tried to smoothly integrate DaST into the existing ASP.NET infrastructure, so we can still use all standard features like HTTP context, session handling, cache management, etc. without changes. Template is passed to the controller as plain text, so the physical location of the template can be anywhere: files, database, remote server, etc. For LittleNonsense app all templates are stored as .htm files under /App_Data/Templates/ folder. Let’s now build the template for Example 1. .htm /App_Data/Templates/ In ASP.NET and MVC we built pages and views by reverse-engineering the desired page look into the set of server controls. Same thing in DaST – we take the desired UI and reverse-engineer it into the data scope tree. In Scope Tree section we’ve already found that Example 1 UI on Fig EX1 can be achieved with 3 nested data scopes. The initial scope tree is on Fig 1.2 and the corresponding template is on the listing below: Listing 2.2: ../App_Data/Templates/NonsenseExample1.htm 01: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ""> 02: <html xmlns=""> 03: <head> 04: <title>ASP.NET DaST - Little Nonsense | {TodayDate}</title> 05: .................... 06: </head> 07: <body class="some-class-{TodayDate}"> 08: .................... 09: <div dast: 10: <b>CUSTOMER:</b> [{CustomerID}] {CustomerName} 11: <div dast: 12: <div><b>ORDER:</b> [{OrderID}] {OrderDate}</div> 13: <div dast: 14: <div><b>ITEM:</b> [{ItemID}] {ItemName}</div> 15: </div> 16: </div> 17: </div> 18: </body> 19: </html> You can see our 3 scopes represented by nested DIV containers with dast:scope attributes and placeholders. On the rendering output stage (see Rendering section), the scopes are repeated and placeholders are replaced by the corresponding values giving us the desired output. dast:scope You might notice the {TodayDate} placeholder in the BODY tag class and in the TITLE. It’s there just to demonstrate that values can be inserted anywhere in the template including HEAD section. However, we cannot put scopes into this section, because container elements like DIV are not permitted in the HEAD tag. Whatever markup this tag has, it is considered as a part of NULL scope content. {TodayDate} BODY TITLE HEAD Designing the HTML template is a creative process. Templates can get more complex depending on the kind of UI your are trying to achieve. In the same time, it is always a way less complex than MVC views or, moreover, stardard .aspx markup pages, because template always stays just the valid HTML with scope containers, no matter how sophisticated your UI is. Since the entire DaST processing revolves around the data scope tree, it is important that the initial scope tree is properly parsed from the template (see rendering step 3.1.2 in Rendering Process section) . Due to this, DaST engine is very sensitive to bad-formed HTML in your templates. It is the responsibility of the developer to make sure that HTML template is well-formed (all tags are properly closed, attributes have name/value format, etc). If DaST is not able to parse your template, the engine will throw the exception with more detailed explanation of the problem. Currently I use a grammar-based HTML parser to extract data scope tree from the template. Later on this might be changed to the regex-based parser, so DaST will be more forgiving to syntax errors in the templates. After template from Listing 2.2 is completely rendered, we have the desired Example 1 page shown on Fig EX1. From this moment the control flow returns back to .aspx page that completes the output. In other words, DaST does not just output the resulted page as is, but does this via standard Web.UI.Page facilities. Behind the scenes the following happens to the resulted page: Web.UI.Page body There are some good reasons for mimicking the standard .aspx page. First, we need the seamless DaST integration into the standard ASP.NET. Second, in order to save implementation time and make my life easier, it was decided to use standard MS AJAX library with DaST add-on instead of creating my own AJAX layer, because it already has all those postback client scripts and everything else. Creating the dedicated light-weight DaST AJAX layer is on the development list. In the beginning, I wanted to prove the concept ASAP, obviously, and did not bother with my own AJAX. Now, when fully functional library is released, it’s time to clean, polish, and add more features. It is possible that PHP DaST framework gets the jQuery based AJAX library from the beginning and then I will port it for ASP.NET DaST. Controller is where the serious programming starts. From the DaST Concept section you should already have a good top-level picture of what controller class is and what it is for. In LittleNonsense demo all controllers are stored in .cs files under /App_Code/Controllers/ folder. From Listing 2.1 we see that NonsenseExample1.aspx page uses root controller class called NonsenseExample1Controller for processing all client requests. Let me give full source code for this class first, and then in the rest of the section I will explain this code line by line: .cs /App_Code/Controllers/ NonsenseExample1Controller Listing 2.3: ../App_Code/Controllers/NonsenseExample1Controller.cs 01: public class NonsenseExample1Controller : ScopeController 02: { 03: public override string ProvideTemplate() 04: { 05: return Utils.LoadTemplate("NonsenseExample1.htm"); // load temlate content from anywhere 06: } 07: 08: public override void InitializeModel(ControllerModelBuilder model) 09: { 10: // use one binding handler to bind all nested scopes (except for root scope) 11: model.SetDataBind(new DataBindHandler(DataBind_ROOT)); 12: model.Select("CustomerRepeater").SetDataBind(new DataBindHandler(DataBind_CustomerRepeater)); 13: model.Select("CustomerRepeater", "OrderRepeater").SetDataBind(new DataBindHandler(DataBind_OrderRepeater)); 14: model.Select("CustomerRepeater", "OrderRepeater", "ItemRepeater").SetDataBind(new DataBindHandler(DataBind_ItemRepeater)); 15: } 16: 17: // 18: private void DataBind_ROOT() 19: { 20: CurrPath().Replace("{TodayDate}", DateTime.Now.ToString("yyyy-MM-dd")); // output some example values 21: } 22: 23: private void DataBind_CustomerRepeater() 24: { 25: var customers = DataLayer.GetCustomers(); // get all customers 26: 27: CurrPath().RepeatStart(); // zeroize repeater 28: foreach (var c in customers) // loop through customers 29: { 30: CurrPath().Repeat(); // repeat scope for current customer 31: CurrPath().Replace("{CustomerID}", c.GetValue("ID")); // bind customer id 32: CurrPath().Replace("{CustomerName}", c.GetValue("Name")); // bind customer name 33: CurrPath("OrderRepeater").Params.Set("CUST", c); // pass customer to next scope 34: } 35: } 36: 37: private void DataBind_OrderRepeater() 38: { 39: var c = CurrPath().Params.Get<object>("CUST"); // customer passed in params 40: var orders = DataLayer.GetOrders((string)c.GetValue("ID")); // customer orders 41: 42: CurrPath().RepeatStart(); // zeroize repeater 43: foreach (var o in orders) // loop through orders 44: { 45: CurrPath().Repeat(); // repeat scope for current order 46: CurrPath().Replace("{OrderID}", o.GetValue("ID")); // bind order id 47: CurrPath().Replace("{OrderDate}", o.GetValue("Date")); // bind order date 48: CurrPath("ItemRepeater").Params.Set("Order", o); // pass order to next scope 49: } 50: } 51: 52: private void DataBind_ItemRepeater() 53: { 54: var o = CurrPath().Params.Get<object>("Order"); // order passed in params 55: var items = DataLayer.GetOrderItems((string)o.GetValue("ID")); // order items 56: 57: CurrPath().RepeatStart(); // zeroize repeater 58: foreach (var i in items) // loop through items 59: { 60: CurrPath().Repeat(); // repeat scope for current item 61: CurrPath().Replace("{ItemID}", i.GetValue("ID")); // bind item id 62: CurrPath().Replace("{ItemName}", i.GetValue("Name")); // bind item name 63: } 64: } 65: } As I already mentioned, Example 1 is driven by a single root controller whose code is on listing above. This controller is responsible for the entire scope tree starting from the NULL scope. Before delving into actual code, I want to talk about controller implementation structure. Let’s look at the structure of the controller on Listing 2.3. On the top-level, functions inside the controller class can be split into 3 categories that strictly correspond to 3 rendering stages (see Controller Rendering section): ProvideTemplate() InitializeModel() Action_SubmitInput() DataBind_ROOT() DataBind_OrderRepeater() DataBind_ItemRepeater() Next, before taking closer look, let's learn some basic APIs that we use to control scope tree. Before we delve into the controller source code, let’s learn some basic APIs. I already mentioned that the entire Scope Tree API consists of just a couple of classes with a dozen of functions in total. Knowing these, you’ll be able to create apps of any complexity level. In this section I’m going to highlight the most important APIs that we need to understand the code on Listing 2.3. First, ControllerModelBuilder [*] class is used for working with initial scope tree and to setup tree model on Stage 1. Instance of this class is passed to InitializeModel() [*] callback in model parameter. Following is usage example: ControllerModelBuilder model model.Select("CustomerRepeater", "OrderRepeater").SetDataBind(new DataBindHandler(SomeHandler)); This call consists of 2 steps: 1) pointing the scope with Select() [*] function, and 2) calling one of model setup functions. Function Select() [*] takes scope path specification as parameter and moves the scope pointer accordingly. Path consist of scope names only, because we work with the initial scope tree. Path specified is relative to the controller root scope. Then SetDataBind() [*] function associates handler function with the pointed scope. You can also call HandleAction() [*] to bind action handler or SetController() [*] to attach the child controller to the selected scope. I chose to force chained function call syntax everywhere because it looks very compact and readable. And this is all we need to setup tree model on Stage 1. SetDataBind() HandleAction() SetController() Second, ScopeFacade [*] class is used for working with the rendered scope tree and manipulate the scopes from inside your action and binding handlers on Stage 2 and Stage 3. It has a few functions and properties and throughout this tutorial all these members will be explained in greater details. ScopeFacade Same as for initial tree, before calling any member of ScopeFacade [*], the specific scope has to be selected. This is done by CurrPath() [*] and CtrlPath() [*] functions that take scope path (see Scope Paths) specification as optional parameter and return an instance of ScopeFacade [*] pointing at the selected scope. The difference between these 2 functions is that CurrPath() [*] starts from the current scope i.e. the scope for which current binding handler is executed, and CtrlPath() [*] starts from the controller root scope. So they are just like a Select() [*] function for model setup stage, but work in the rendered scope tree. Following is usage example: ScopeFacade CurrPath() CtrlPath() CurrPath() CurrPath("CustomerRepeater", 2, "OrderRepeater").Replace("{SomeValue}", "Hello World!"); Again, chained syntax is used. First call is to point the specific scope, and next call is one of ScopeFacade [*] members. In our case it’s a Replace() [*] function that takes placeholder name and a replacement value. Replace() [*] function has several overloads allowing different combinations of parameters. Note that this time I specified path with repeating axis for OrderRepeater scope. If axis is not specified, it’s considered 0. Replace() Finally, frequently used APIs are Params [*] and StoredParams [*] properties of ScopeFacade [*] class. These two allow us to associate some generic parameters with scopes. Essentially Params [*] is a way of passing data between the scopes during the rendering process. StoredParams [*], as it follows from its name, allows us to persist parameters between subsequent postbacks. Read the API description for these properties for more info. It is important to understand that DaST uses same controller instance to process the entire sub-tree that it’s responsible for and we should not create any instance members inside the controller to store any data. All data must be stored outside and if there is a need for passing objects between scopes, Params [*] property should be used. Params [*] property is of ParamsFacade [*] type that has a set of overloaded functions to get and set scope parameters. Params StoredParams Params StoredParams ParamsFacade Ok, now we know enough to start digging into the code. The order in which controller functions are executed is strictly defined by the rendering process and traversal flow (see Rendering Process). As the system goes through this process and traverses the scope tree, the callback functions inside responsible controllers get invoked one after another until page output is complete. In this section I’ll explain all controller functions in the order of their execution. Before reading further, you need to recall Rendering Process and Controller Rendering sections, because I’ll frequently reference them. Below I’ll follow the controller rendering stages, list callbacks in execution order, and describe what they do and how they work. It all starts with client request hitting the NonsenseExample1.aspx page. Example 1 does not use actions, so we only talk about initial page load here. Code-behind logic on Listing 2.1 transfers all further processing to NonsenseExample1Controller class given on Listing 2.3. NonsenseExample1Controller Execution begins from Stage 1: Controller model preparation. As I mentioned on step 3.1 of rendering process, controller preparation is executed ONCE per controller whenever traversal procedure hits the scope whose responsible controller model is not setup yet. So, for our controller whose model is not setup yet, DaST needs to call 2 setup functions: The purpose of overriding this function is to return the specific template as plain text. On line 5 I use utility function to read template by name from directory on the site and return it. Such simple approach is cool, because we can store our templates anywhere and build flexible CMS engines. Once template is returned, system proceeds with the next function call: This function has the important task to associate scope tree with the controller. In the previous sub-section I explained how ControllerModelBuilder [*] class is used for setting up the tree model. So, on line 11 we associate DataBind_ROOT() with the controller root scope which is the same as NULL scope in our case. Notice that I omitted Select() [*] call, so pointer stays at the controller root. Next, on line 12 we associate DataBind_CustomerRepeater() handler with CustomerRepeater scope. To point at the CustomerRepeater scope, we use Select() [*] function passing relative path to it. On lines 13-14 we do the same for OrderRepeater and ItemRepeater scopes. This time paths consist of multiple segments. ControllerModelBuilder At this point, model setup is complete and the system turns to Stage 2: Action processing. In Example 1 we don’t have any actions, so this stage is simply skipped. No callbacks get invoked here. Actions is more advanced topic and you’ll see how it works in second part of this tutorial. Finally, system comes to Stage 3: Scope tree rendering output. This is the stage where actual rendering happens and our scope tree turns into the rendered scope tree on Fig 1.3. During this stage the traversal visits scopes one by one, invokes binding handlers, and outputs the result. So, traversal starts from visiting the NULL scope of the tree: DataBind_ROOT() SCOPE For better understanding, I will always specify the current scope path i.e. the one that CurrPath() [*] points to if called without parameters. This time current path is SCOPE meaning that CurrPath() [*] points to the NULL scope. The DataBind_ROOT() handler has only a single line of code. In the previous sub-section I explained how ScopeFacade [*] class is used to manipulate scopes from inside action and binding handlers. So, on line 20 we use CurrPath() [*] without parameter to point at the current scope which is the root scope. And then we call Replace() [*] on it to output formatted date into the {TodayDate} placeholder. Recall that this placeholder is used in our template on Listing 2.2 inside TITLE and BODY tags that belong to the NULL scope. And we’re done here. Next traversed scope is CustomerRepeater: SCOPE TITLE SCOPE$0-CustomerRepeater The content of CustomerRepeater scope needs to be repeated for every customer. The {CustomerID} and {CustomerName} placeholders need to be replaced on every iteration with appropriate customer data. So, on line 25 we retrieve the list of customers. We do it using data layer utility that returns entities from XML. Then we call RepeatStart() [*] on the current scope to reset repeating axis counter to 0. This function must be always called before repeating scope content, because by default there is always 1 axis for every scope. On lines 28-34 we loop through all customer objects, repeat the scope, and replace the placeholder. The loop iterates 3 times for customers “John”, “Roman”, and “James”. On line 30 the Repeat() [*] function is called instructing the system to repeat content of the pointed scope once. This function has to be called before anything else on the current iteration. On line 31-32 we use already familiar syntax to paste values into {CustomerID} and{CustomerName} placeholders in the current scope. On line 32 we point to the OrderRepeater scope and use Params [*] property to pass customer object to this scope as parameter. In the previous sub-section I explained how Params [*] property works. The customer saved on this step will be retrieved when execution comes to OrderRepeater binding handler, and we will know whose orders to display. So, our next scope visited by traversal is OrderRepeater: {CustomerID} RepeatStart() Repeat() SCOPE$0-CustomerRepeater$0-OrderRepeater Here we need to do pretty much the same as before, but for customer orders. On line 39 we start from retrieving the customer object passed from the previous traversal step. Current customer object is for “John”. After we get the customer, we use data layer to get the list of his orders. Then, on line 42 we prepare the scope for repeating again by calling RepeatStart() [*]. Finally, on lines 43-49 we do the loop analogical to previous binding handler, but this time for customer orders, replacing placeholders with specific order ID and date values. In the end of iteration, we, again, use Params [*] to save order object for ItemRepeater scope. We’re done here and traversal continues to ItemRepeater scope: SCOPE$0-CustomerRepeater$0-OrderRepeater$0-ItemRepeater Everything is the same here as before, but now for ItemRepeater. First, we retrieve order object from scope parameters. Then get order items from XML. Then loop through them, repeat the scope, and replace the placeholders with item values. This time we don’t need to save anything in Params [*], because there are no more scopes. Now look at the scope tree on Fig 1.3. At this point we have completely traversed the first branch, and the traversal would stop here if we had only one customer. But since we have multiple repeated customers, the traversal has to travel all branches. So, our next visited scope is OrderRepeater again, but on the next repeated branch: DataBind_OrderRepeater() SCOPE$0-CustomerRepeater$1-OrderRepeater Notice the repeating axis of OrderRepeater scope in the current path – it is 1, not 0, because we’re on the second branch now! The customer object retrieved on line 39 is now for “Roman” i.e. the one saved on the 2nd repeating iteration of the previous CustomerRepeater scope. Everything else is the same – get the list of orders for current customer and repeat the scope to display them. Continuing traversal on the same branch, next visited scope is ItemRepeater: SCOPE$0-CustomerRepeater$1-OrderRepeater$0-ItemRepeater As before, first, we retrieve the saved order object for “O02”. Then get its items with “I03” and “I04” IDs. Then repeat the scope for every item and replace placeholders. Next visited scope is ItemRepeater again: SCOPE$0-CustomerRepeater$1-OrderRepeater$1-ItemRepeater It’s the same scope again, but with the different scope path. We are here, because customer “Roman” has 2 orders and we need to output items for order “O03” now. So, order object saved at the current path corresponds to “O03” and we repeat it 2 items. This branch is complete and traversal goes back to OrderRepeater: DataBind_OrderRepeater SCOPE$0-CustomerRepeater$2-OrderRepeater The repeating axis for current scope is 2, because we are now on the 3rd branch for customer “James”. Everything else is the same as before and next scope is ItemRepeater: DataBind_ItemRepeater() SCOPE$0-CustomerRepeater$2-OrderRepeater$0-ItemRepeater Again, except for different path, functionality is analogical to previously visited ItemRepeater scopes. And finally, traversal visits ItemRepeater again, because "James" has one more order: SCOPE$0-CustomerRepeater$2-OrderRepeater$1-ItemRepeater And we’re DONE! Our tree is completely rendered and output is ready. In our simplified Example 1 of LittleNonsense where the page is driven by a single top-level controller, you might get a feeling that traversal cannot go anywhere until it finishes work in the current controller. It’s not true. In case of multiple controllers, the traversal can go beyond the current controller at any time. The traversal simply travels the rendered scope tree and for every visited scope system executes functions inside the currently responsible controller. For example, look at the scope tree on Fig 1.3 and imagine that there is a nested controller attached to ItemRepeater scope. If this were a case, then instead of executing DataBind_ItemRepeater() inside the root controller, the system would execute this handler inside the controller, attached to ItemRepeater. Moreover, the system would have to run the model preparation stage for this nested controller before calling any binding handlers. After it’s done, the traversal would return back to calling DataBind_OrderRepeater() on root controller for the repeated axis. So, execution can go beyond the bounds of the current controller and then come back again. LittleNonsense Look how clear and intuitive your controller code is! No matter how big your scope tree grows – the rendering part of the controller always consists of a plain list of binding handlers. This means that structural complexity of your code does not grow even for sophisticated Web 2.0 designs! This, in its turn, results in simple and readable source code as well as slim application architecture. At this point the first part of this tutorial is completed. We’ve learned basics of DaST design and development and it’s time to delve into true Web 2.0 programming world and see the full power of DaST in action. In this part of the tutorial we will learn the rest of DaST features needed for building highly complex and dynamic Web 2.0 sites. To demonstrate all these new features, I designed Example 2 part of LittleNonsense demo. Further in this section I’ll walk through the source code of this app with all necessary explanations. I’ll start from giving the complete source code for all templates and controllers that participate in Example 2 implementation. This section will be used as code reference for all explanations throughout the rest of this tutorial. At the moment you can skip through it quickly. First of all, this time the request entry point is NonsenseExample2.aspx page. In NonsenseExample2.aspx.cs file everything is simple and analogical to what we’ve seen already in the previous example (see DaST Page section). The system is told to use NonsenseExample2Controller for processing all requests coming to this page. NonsenseExample2.aspx.cs NonsenseExample2Controller Now, as before, I'll give all code listings of Example 2 and will explain everything line by line throughout the rest of this article. Let's start from NonsenseExample2.htm file containing template for the root controller: NonsenseExample2.htm Listing 3.1: ../App_Data/Templates/NonsenseExample2.htm 01: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ""> 02: 03: <html xmlns=""> 04: <head> 05: <title>ASP.NET DaST - Little Nonsense | {TodayDate}</title> 06: <link href="res/CSS/common.css" type="text/css" rel="stylesheet" /> 07: <script type="text/javascript" src="res/jQuery/jquery-1.7.1.min.js"></script> 08: </head> 09: <body class="some-class-{TodayDate}"> 10: 11: <div style="font-size: x-large; background-color: Gray; color: White; padding: 10px;">Little Nonsense | ASP.NET DaST Application DEMO</div> 12: <div style="margin: 0 10px;"><a href="NonsenseExample1.aspx">Example 1</a> | <a href="NonsenseExample2.aspx">Example 2</a></div> 13: <div style="margin: 20px; font-size: x-large; font-weight: bold;">Example 2: Partial Update, Actions, and Messages</div> 14: 15: <div dast: 16: <div dast:</div> 17: <div dast: 18: <div dast:</div> 19: <div class="txt"><b>CUSTOMER:</b> [{CustomerID}] {CustomerName}</div> 20: <div dast: 21: <div dast:</div> 22: <div dast: 23: <div dast:</div> 24: <div class="txt"><b>ORDER:</b> [{OrderID}] {OrderDate}</div> 25: <div dast: 26: <div dast:</div> 27: <div dast: 28: <div dast:</div> 29: <div class="txt"><b>ITEM:</b> [{ItemID}] {ItemName}</div> 30: </div> 31: </div> 32: </div> 33: </div> 34: </div> 35: </div> 36: 37: <script language="javascript" type="text/javascript"> 38: 39: function markScopeUpdated(scopeID) 40: { 41: $("div[id='" + scopeID + "'].gizmo").addClass("updated bold") 42: .find(".gizmo").addClass("updated"); 43: } 44: 45: function hideRepeaterHeaders() 46: { 47: // leave only first gizmo header in case of repeater gizmos 48: $(".gizmo").each(function () { $(this).find("> .headerScope:not(:nth-child(1))").hide(); }); 49: } 50: 51: // add server message handler 52: DaST.Scopes.AddMessageHandler("{ScopeID}", "RefreshedFromServer", function (data) 53: { 54: markScopeUpdated(data.ScopeID); 55: hideRepeaterHeaders(); 56: }); 57: 58: // some initial load UI setup 59: $(document).ready(function () 60: { 61: $("form").attr("autocomplete", "off"); 62: hideRepeaterHeaders(); 63: }); 64: 65: </script> 66: </body> 67: </html> Next listing is for child controller template used to display the header section of all scopes: 01: <div class="hdr"> 02: <span class="high-on-update"><b>Updated:</b> Next listing is root controller class itself: Listing 3.3: ../App_Code/Controllers/NonsenseExample2Controller.cs 001: public class NonsenseExample2Controller : ScopeController 002: { 003: public override string ProvideTemplate() 004: { 005: return Utils.LoadTemplate("NonsenseExample2.htm"); // load temlate content from anywhere 006: } 007: 008: public override void InitializeModel(ControllerModelBuilder model) 009: { 010: // scope binding handlers 011: model.SetDataBind(new DataBindHandler(DataBind_ROOT)); 012: model.Select("CustomerRepeater").SetDataBind(new DataBindHandler(DataBind_CustomerRepeater)); 013: model.Select("CustomerRepeater", "Customer").SetDataBind(new DataBindHandler(DataBind_Customer)); 014: model.Select("CustomerRepeater", "Customer", "OrderRepeater").SetDataBind(new DataBindHandler(DataBind_OrderRepeater)); 015: model.Select("CustomerRepeater", "Customer", "OrderRepeater", "Order").SetDataBind(new DataBindHandler(DataBind_Order)); 016: model.Select("CustomerRepeater", "Customer", "OrderRepeater", "Order", "ItemRepeater").SetDataBind(new DataBindHandler(DataBind_ItemRepeater)); 017: model.Select("CustomerRepeater", "Customer", "OrderRepeater", "Order", "ItemRepeater", "Item").SetDataBind(new DataBindHandler(DataBind_Item)); 018: 019: // set child controllers 020: model.Select("CustomerRepeater", "Header").SetController(new ScopeHeaderController()); 021: model.Select("CustomerRepeater", "Customer", "Header").SetController(new ScopeHeaderController()); 022: model.Select("CustomerRepeater", "Customer", "OrderRepeater", "Header").SetController(new ScopeHeaderController()); 023: model.Select("CustomerRepeater", "Customer", "OrderRepeater", "Order", "Header").SetController(new ScopeHeaderController()); 024: model.Select("CustomerRepeater", "Customer", "OrderRepeater", "Order", "ItemRepeater", "Header").SetController(new ScopeHeaderController()); 025: model.Select("CustomerRepeater", "Customer", "OrderRepeater", "Order", "ItemRepeater", "Item", "Header").SetController(new ScopeHeaderController()); 026: 027: // handle client actions 028: model.Select("CustomerRepeater", "Header").HandleAction("RaisedFromChild", new ActionHandler(Action_RaisedFromChild)); 029: model.Select("CustomerRepeater", "Customer", "Header").HandleAction("RaisedFromChild", new ActionHandler(Action_RaisedFromChild)); 030: model.Select("CustomerRepeater", "Customer", "OrderRepeater", "Header").HandleAction("RaisedFromChild", new ActionHandler(Action_RaisedFromChild)); 031: model.Select("CustomerRepeater", "Customer", "OrderRepeater", "Order", "Header").HandleAction("RaisedFromChild", new ActionHandler(Action_RaisedFromChild)); 032: model.Select("CustomerRepeater", "Customer", "OrderRepeater", "Order", "ItemRepeater", "Header").HandleAction("RaisedFromChild", new ActionHandler(Action_RaisedFromChild)); 033: model.Select("CustomerRepeater", "Customer", "OrderRepeater", "Order", "ItemRepeater", "Item", "Header").HandleAction("RaisedFromChild", new ActionHandler(Action_RaisedFromChild)); 034: } 035: 036: // 037: #region Action Handlers 038: 039: private void Action_RaisedFromChild(object arg) 040: { 041: if ((string)arg == "parent") 042: { 043: CurrPath(-1).Refresh(); // refresh parent scope of the root scope of header controller 044: CtrlPath().MessageClient("RefreshedFromServer", new { ScopeID = CurrPath(-1).ClientID }); // notify client of refreshed scope 045: } 046: else if ((string)arg == "child") 047: { 048: // find name of the next scope depending on current scope 049: string nextScope = null; 050: string currScope = CurrPath(-1).ClientID.Split('-').Last(); 051: switch (currScope) 052: { 053: case "CustomerRepeater": nextScope = "Customer"; break; 054: case "Customer": nextScope = "OrderRepeater"; break; 055: case "OrderRepeater": nextScope = "Order"; break; 056: case "Order": nextScope = "ItemRepeater"; break; 057: case "ItemRepeater": nextScope = "Item"; break; 058: } 059: // invoke action on Header scope of the first child scope 060: if (nextScope != null) 061: { 062: CurrPath(-1, nextScope, "Header").InvokeAction("InvokedFromParent", null); 063: } 064: } 065: } 066: 067: #endregion 068: 069: // 070: #region Binding Handlers 071: 072: private void DataBind_ROOT() 073: { 074: CurrPath().Replace("{TodayDate}", DateTime.Now.ToString("yyyy-MM-dd")); // output some example values 075: CurrPath().Replace("{ScopeID}", CurrPath().ClientID); // bind scope client id 076: } 077: 078: private void DataBind_CustomerRepeater() 079: { 080: var customers = DataLayer.GetCustomers(); // get all customers 081: CurrPath().RepeatStart(); 082: foreach (var customer in customers) // repeat scope for each customer 083: { 084: CurrPath().Repeat(); 085: CurrPath("Customer").StoredParams.Set("CustomerID", customer.GetValue("ID")); // pass customer ID to each child Customer scope 086: } 087: } 088: 089: private void DataBind_Customer() 090: { 091: var customerID = CurrPath().StoredParams.Get<string>("CustomerID"); // get customer ID set in previous binding handler 092: var customer = DataLayer.GetCustomer(customerID); // get customer object by ID 093: CurrPath().Replace("{CustomerID}", customer.GetValue("ID")); 094: CurrPath().Replace("{CustomerName}", customer.GetValue("Name")); 095: } 096: 097: private void DataBind_OrderRepeater() 098: { 099: var customerID = CurrPath(-1).StoredParams.Get<string>("CustomerID"); // get customer ID from parent Customer scope 100: var orders = DataLayer.GetOrders(customerID); // get orders by customer ID 101: CurrPath().RepeatStart(); 102: foreach (var order in orders) // repeat scope for each order 103: { 104: CurrPath().Repeat(); 105: CurrPath("Order").StoredParams.Set("OrderID", order.GetValue("ID")); // pass order ID to each child Order scope 106: } 107: } 108: 109: private void DataBind_Order() 110: { 111: var orderID = CurrPath().StoredParams.Get<string>("OrderID"); // get order ID set in previous binding handler 112: var order = DataLayer.GetOrder(orderID); // get order object by ID 113: CurrPath().Replace("{OrderID}", order.GetValue("ID")); 114: CurrPath().Replace("{OrderDate}", order.GetValue("Date")); 115: } 116: 117: private void DataBind_ItemRepeater() 118: { 119: var orderID = CurrPath(-1).StoredParams.Get<string>("OrderID"); // get order ID from parent Order scope 120: var items = DataLayer.GetOrderItems(orderID); // get order items by order ID 121: CurrPath().RepeatStart(); 122: foreach (var item in items) // repeat scope for each item 123: { 124: CurrPath().Repeat(); 125: CurrPath("Item").StoredParams.Set("ItemID", item.GetValue("ID")); // pass item ID to each child Item scope 126: } 127: } 128: 129: private void DataBind_Item() 130: { 131: var itemID = CurrPath().StoredParams.Get<string>("ItemID"); // get item ID set in previous binding handler 132: var item = DataLayer.GetOrderItem(itemID); // get item object by ID 133: CurrPath().Replace("{ItemID}", item.GetValue("ID")); 134: CurrPath().Replace("{ItemName}", item.GetValue("Name")); 135: } 136: 137: #endregion 138: } And final listing is for the child controller used for all scope headers: 01: public class ScopeHeaderController : ScopeController 02: { 03: public override string ProvideTemplate() 04: { 05: return Utils.LoadTemplate("ScopeHeader.htm"); // load template content from anywhere 06: } 07: 08: public override void InitializeModel(ControllerModelBuilder model) 09: { 10: // scope binding handlers 11: model.SetDataBind(new DataBindHandler(DataBind_ROOT)); 12: 13: // handle client actions 14: model.HandleAction("RefreshFromClient", new ActionHandler(Action_RefreshFromClient)); 15: model.HandleAction("InvokedFromParent", new ActionHandler(Action_InvokedFromParent)); 16: } 17: 18: // 19: #region Action Handlers 20: 21: private void Action_RefreshFromClient(object arg) 22: { 23: // client call was DaST.Scopes.Action(scopeID, 'RefreshFromClient', [input, target]); 24: string input = (string)((object[])arg)[0]; // 1st elem of passed JSON array 25: string target = (string)((object[])arg)[1]; // 2nd elem of passed JSON array 26: 27: switch (target) 28: { 29: case "self": break; 30: // notify parent scope by rasing action passing string target as parameter 31: case "parent": CtrlPath().RaiseAction("RaisedFromChild", "parent"); break; 32: case "child": CtrlPath().RaiseAction("RaisedFromChild", "child"); break; 33: default: throw new Exception("Unknown target"); 34: } 35: 36: CtrlPath().Params.Set("PostedData", input); // set posted data parameter 37: 38: CtrlPath().Refresh(); // refresh control root scope 39: CtrlPath().MessageClient("RefreshedFromServer", null); // notify client of refreshed scope 40: } 41: 42: private void Action_InvokedFromParent(object arg) 43: { 44: CtrlPath().Refresh(); // refresh control root scope 45: CtrlPath().MessageClient("RefreshedFromServer", null); // notify client of refreshed scope 46: } 47: 48: #endregion 49: 50: // 51: #region Binding Handlers 52: 53: private void DataBind_ROOT() 54: { 55: CurrPath().Replace("{Updated}", DateTime.Now.ToString("HH:mm:ss")); // bind update time 56: CurrPath().Replace("{ScopeID}", CurrPath().ClientID); // bind scope client id 57: if (CurrPath().Params.Has("PostedData")) // if PostedData param is set for the scope ... 58: { 59: var data = CurrPath().Params.Get<string>("PostedData"); // retrive posted data containing user input 60: 61: CurrPath().Replace("{PostedData}", data); // bind input value to output it 62: CurrPath().AreaConditional("data-posted", true); // display data-posted conditional area 63: } 64: else 65: { 66: CurrPath().AreaConditional("data-posted", false); // hide data-posted conditional area 67: } 68: } 69: 70: #endregion 71: } As you can see, there is lots of interesting stuff in the code. Below I’ll do the quick introduction into the Example 2 demo, then I’ll talk about nested controllers and new features in binding handler, and finally, I’ll turn to the most exciting part which is actions, AJAX partial updates, and duplex messaging. I designed Example 2 application to demonstrate all DaST programming techniques that you might possibly need for creating complex Web 2.0 designs: AJAX partial updates, multiple nested controllers, event handling, duplex messaging, and others. In the same time this demo is quite simple and straightforward. As you might have already guessed, DaST partial update mechanism is based on the scope tree just like everything else in DaST world. Putting it simple, every scope in the tree can be refreshed independently. Main idea in Example 2 is to visualize physical scope containers of the rendered scope tree on the resulting page and allow partial updates of random scopes, so that you can actually see how scope tree works, how scopes get updated, how data is passed, how controllers communicate, feel the workflow, and feel the real power of DaST pattern. In Example 1 our initial scope tree consisted of 3 repeater scopes (see Scope Tree section). Such structure allows us to update the entire repeaters, but not individual repeated items. In Example 2 we wrap repeated items into separate scopes so that partial updates can be also applied to these individual items. As a result, in addition to CustomerRepeater, OrderRepeater, and ItemRepeater scopes, our tree gets Customer, Order, and Item scopes. Next, for better scope visualization I want to output a special info header for each scope in the tree. This header will be displayed on the top of every scope container and will show scope client ID, last updated timestamp, and link buttons to raise actions and do partial update. I want to enclose header into a separate Header scope that will be a first child scope of every other scope in our tree. The resulted initial scope tree for Example 2 is shown below: Customer Order Item Fig. 3.1: Initial scope tree for NonsenseExample2.aspx page of LittleNonsense demo Having this structure of the scope tree, I get the control over every possible part of the page. I can apply partial updates or pass data anywhere I want in any scope combination. Now let’s see the UI output of this demo. A part UI output of this demo is shown below on Fig EX2: Fig. EX2: Part of Example 2 output As you can see, it is essentially the same hierarchical structure as in Example 1 based on the same XML data file of customer orders, but with more functionality and more sophisticated UI. Main thing I do to visualize the scopes is a dotted border around every scope container. Now we can actually see the scopes and ensure that their nesting configuration strictly corresponds to the initial scope tree on Fig 3.1. Also, the border around the scopes that were partially updated due to the last postback will have a red color. Scopes updated directly will have a bold red border, and scopes updated as result of parent scope update will have a regular red border. Shortly you’ll see how this looks. Second, all output of the actual data values from XML input file, is marked with blue background. This is done just to visually distinguish it from other markup on the page not related to values in XML file. And finally, every scope has a header highlighted with yellow background. The header section, as I said before, is wrapped into its own Header scope, so you can see the dotted border around header as well. Let’s take a closer look at the header now. Header Info header not only has its own scope, but also its own controller! Using this example I demonstrate working with multiple controllers, all related techniques, and APIs. If we tried to implement scope tree from Fig 3.1 using single controller with single template (as we did before in Example 1), we would end up duplicating header section code in both template and back-end controller. It is very intuitive to factor header section out into the separate controller with partial template and reuse it every time a scope needs header section. SCOPE$0-CustomerRepeater$0-Header The most interesting part of the scope header is the input box and 3 link buttons. These are needed to demonstrate data input and all Web 2.0 related mechanisms. The idea is that you enter random text in the input field and click one of the links on the left. This raises client action which passes your input data to the server, processes it, applies partial update to the specific scopes, and initiates duplex reply message, handled on the client side. The whole process will be explained in details through the rest of tutorial. Right now I’ll just describe the functionality of these 3 link buttons. So, let’s pick the scope header and enter “Hello World!!!” in it. Now click 1st “HeaderOnly” link. The result will be the following: Here you see the bold red border around the header meaning that scope was directly updated. When we clicked the link button, the action was raised and our input text was passed to the server side along with the action. On the server side we tell the system to display this text within the scope and apply partial update to this scope to reflect the changes. This is a typical interaction workflow for all Web 2.0 apps. As a result, you see your input text output in the “Passed” field on the right and the scope is highlighted. So “Header Only” link means pass the text and update only the header. Now input “Hello World 2!!!” in the same field and click the 2nd link “Parent Scope”. There result is below: This time the header and the parent scope were updated directly. Directly means that we will explicitly ask the system to update these scopes. All child scopes are also updated as result parent scope update, so they have a regular red border. The meaning of updating the parent scope is to show you how nested controllers communicate using controller actions. Since header has its own controller and ItemRepeater is in responsibility of the root controller, in order to update ItemRepeater we will have to notify the root controller. I will explain this interesting process in depth in the further sections. Finally, input “Hello World 3!!!” and click the 3rd link “First Child Scope”. You’ll see the following: Now we see that header of the current scope is updated as well as the header of the first child scope. This is even more sophisticated controller communication, we need to notify the root controller first, and the root controller needs to access current scope’s first child and notify its header. So it’s two steps: from child controller to parent, and from parent to another child controller. Now it’s time to delve into the code and see how this all actually works. And we will start from going through rendering and binding handlers part of the controllers which is already familiar to us from the previous example. Before reading further, please recall all theory from Controller section. In the current section we will walk through the source code of Example 2 controller binding handlers as well as controllers setup. From the Controller Class section in the previous example we already know how binding handlers work and what they are for. But this time the example application has much richer functionality and there are some new features to highlight in connection with rendering process. And, of course, the main difference is that now we have multiple nested controllers with multiple templates, so we want to see how everything works in this case. In Example 2 we use two different controllers and separate templates for each of them. The root controller is NonsenseExample2Controller on Listing 3.3 and its template is in NonsenseExample2.htm on Listing 3.1. The other controller is ScopeHeaderController on Listing 3.4 and its template is in ScopeHeader.htm on Listing 3.2. This controller is needed to display header section for every scope on the page. ScopeHeaderController ScopeHeader.htm Now look at the scope tree on Fig 3.1. We will need to attach child ScopeHeaderController to every Header scope in the tree to make it responsible for outputting the header. Attaching child controllers is a part of the model preparation rendering stage (recall Controller Rendering section). From HTML template point of view, the container element for the scope, to which you’re going to attach the controller, must be empty i.e. contain no markup. This is natural, because every child controller has its own template whose rendered result gets populated into that empty container during rendering traversal. Rendering traversal is not impacted by presence of child controllers anyhow. It still goes through the scope tree in the same traversal order executing binding handlers inside appropriate controllers. So, for currently traversed data scope, system finds the responsible controller and attempts to execute the corresponding binding handler inside it. Recall Traversal Between Controllers section above where I mentioned how execution can go back and forth between parent and child controllers. Now it’s time to touch some source code starting from HTML templates. Our root template is on Listing 3.1. It is responsible for the entire UI except header section. Root templates always look like a complete web page with <HTML> and <BODY> tags, while child templates only contain partial HTML fragments. <HTML> <BODY> All scope containers defining the data scope tree are on lines 15-35. Nesting structure is similar to our previous example, but we have more scopes this time. The multiple Header scopes (lines 16, 18, 21, 23, 26, and 28) are the ones to which ScopeHeaderController will be attached. In the template these scopes look like the following: 16: <div dast:</div> So, as I already said, if we want to attach the controller to the scope, its container must be empty; otherwise, the error is thrown. Child controller has its own template populated into this empty container after rendering. There is also a JavaScript block on lines 37-65. Most of this JavaScript is needed just for fancier output except for lines 52-56 where I use one of the coolest DaST features to handle message sent from the server side. In combination with client actions, this mechanism is called duplex messaging and I’ll talk about all this in depth in our next sections. Now look at the child template on Listing 3.2. On lines 1-11 it has some markup to output the header section UI. Note that there are no nested scopes here, so the scope sub-tree that child ScopeHeaderController is responsible for a single Header scope which is also a root scope of this controller in the same time. The markup is trivial. There are some placeholders to display updated timestamp and scope ID and link buttons to raise actions on lines 5-7. Actions will be explained in depth in Actions section. On lines 8-10 we use another DaST feature called conditional area. I’ll explain this feature in one of the next sections. Child template also includes a JavaScript block on lines 13-56. I use typical jQuery syntax to create a $.ScopeHeader plugin to prepare data and raise actions. This all will be explained in Actions section. Notice the if condition on line 17 – it is needed to avoid plugin class redefinition, because there are multiple Header scopes on the resulted page so this script will be pasted multiple times. I could simply place it in the parent template and the problem would disappear, but I just wanted to show how to write fully independent templates containing mix of markup and scripts. $.ScopeHeader if Now let’s turn to the source code of our controllers. Look at the new scope tree on Fig 3.1. First thing we need to do in the root controller is to attach the child ScopeHeaderController to all Header scopes to make it responsible for rendering the header section. Child controller should be attached in the InitializeModel() [*] override of the parent controller using SetController() [*] API where the instance of the desired child controller is passed. So, on lines 20-25 of our top-level controller on Listing 3.3 we attach ScopeHeaderController to every Header scope in the scope tree. Every call in InitializeModel() [*] follows the same idea all the time – the target scope is selected using Select() [*] and the desired setup API is called on it. So, the typical call to attach the child controller looks like the following: 20: model.Select("CustomerRepeater", "Header").SetController(new ScopeHeaderController()); The SetController() [*] expects an instance of the controller class to be passed as parameter. We can pass the same instance everywhere or use the new one every time like I did – it does not matter, because by design inside the controller we do not rely on instance anyway and use context-dependent facilities like Params [*] collection and others. Now, after controllers are attached, our scope tree is ready for traversal. Leaving all actions related stuff for the future sections, let’s just do a quick overview of binding handlers inside both controllers. From the Controller Class section we already know how binding handlers work and what they are for. So, let’s start from the root controller on Listing 3.3. On lines 11-17 of Listing 3.3 we do some boilerplate code to associate binding handlers with the scopes in the tree using SetDataBind() [*]. Here we have more scope binding expressions than our previous controller in Example 1, simply because there are more scopes this time. We bind all scopes that we have in the scope tree on Fig 3.1 except for Header scope, because this scope has an attached child controller that becomes responsible for rendering this scope. Binding handler implementations are on lines 72-135. In the previous example we only had handlers for 3 nested repeaters. Now we have to add more handlers for Customer, Order, and Item scopes wrapping individual items inside the corresponding repeaters. Other than that, the idea is pretty much the same: retrieve items, repeat scope in a loop, save current item in params, etc. Let’s go through some of the binding handlers really quick. Item First binding handler is DataBind_ROOT() on line 72 for the controller root scope which is also a NULL scope. Nothing special about it. Just replace some placeholders in the root scope. DataBind_ROOT() Next one is DataBind_CustomerRepeater() on line 78. This is already familiar to us: we get the list of customer objects, loop through them, and repeat the current scope. Unlike previous example, we don’t have to replace any placeholders here, because for each item in this repeater we have a dedicated Customer scope whose binding handler should do all replacements. The only thing we need is to pass the customer object to the next traversed scope using scope parameters. Customer And here is the interesting moment. On line 85, to pass customer to the next scope I use StoredParams [*] collection instead of Params [*]: 85: CurrPath("Customer").StoredParams.Set("CustomerID", customer.GetValue("ID")); This time instead of the complete customer object, I pass the ID that can be used to retrieve this customer directly. Why I cannot use Params [*] to do this? Params [*] work only when we need to pass data between the handlers executed on the same traversal run. But since in Example 2 every scope can be randomly refreshed, causing the traversal to re-execute binding handlers starting from this scope, I cannot rely on Params [*] anymore – the customer ID simply will not be there unless DataBind_CustomerRepeater() is executed on the current traversal run. Using StoredParams [*] instead solves the problem easily, because values saved in StoredParams [*] persist during consequent actions and postbacks. I would advice against heavy use of StoredParams [*], because its idea is similar to the standard ASP.NET VIEWSTATE which adds some overhead between Ajax requests. All you can do with StoredParams [*], you can also do without it by just passing parameters along with actions. For our example I just want to demonstrate how to use StoredParams [*] if you really need to. VIEWSTATE Next handler is DataBind_Customer() on line 89. Its implementation is trivial. On line 91 we retrieve previously saved customer ID. Even if traversal starts from current binding handler (partial update), the StoredParams [*] will still contain the needed customer ID value saved there on the initial page load when traversal went through the entire tree. On line 92 we get the customer object using customer ID. And on lines 93-94 we replace the placeholders. DataBind_Customer() Next one is DataBind_OrderRepeater() on line 99. And here we see one more interesting thing – negative number in the scope path: 99: var customerID = CurrPath(-1).StoredParams.Get<string>("CustomerID"); Read the CurrPath [*] API description and refer to the Example 2 scope tree on Fig 3.1. Current scope is OrderRepeater and negative -1 tells the system to go 1 scope backwards i.e. point at the previous Customer scope. Since customer ID was saved with the Customer scope, we can always retrieve this ID by pointing at this customer scope. CurrPath -1 Everything else in this handler is the same as for previous repeater. We retrieve a list of orders by customer ID, repeat scope in a loop, and pass current order ID to Order scope on each iteration. Order And so on. Other binding handlers in NonsenseExample2Controller are analogical. Now let’s see what’s going on in the child ScopeHeaderController on Listing 3.4. The Header scope that this controller is attached to, becomes the root scope of this controller. Except the root scope, there are no more scopes in this controller. So we only need one binding handler for the root scope. The handler is set on line 11 and the callback function DataBind_ROOT() is on line 53. This binding handler will render the entire header UI. First of all, on lines 55 and 56 we replace {Updated} and {ScopeID} placeholders with current timestamp and ClientID [*] of the current scope respectively. Take a look at the template on Listing 3.2 where all these values are inserted. Next, on line 57, we use Params.Has() [*] to check if parameter named "PostedData" is set. If yes, then this data is output to the {PostedData} placeholder; otherwise, we hide the entire output area. On the initial load, "PostedData" parameter is not set. On the subsequent loads, it is set for the current scope by the action handler in response to user input in the text box within the scope header. This will be explained in depth in our next Actions section. For now, last thing in binding handlers that needs explanation is usage of AreaConditional() [*] API on lines 62 and 66. {Updated} {ScopeID} ClientID Params.Has() "PostedData" {PostedData} "PostedData" AreaConditional() Take a quick look at the AreaConditional() [*] API. This is simply a way to hide or show a fragment of your HTML code depending on some condition. This fragment has to be wrapped into a special comment tag with the special syntax. In our child controller template on Listing 3.2 we have such conditional on lines 8-10: AreaConditional() 08: <!--showfrom:data-posted--> 09: <b>Passed:</b> <span class="passedData">{PostedData}</span> 10: <!--showstop:data-posted--> This area is controlled from the binding handler using AreaConditional() [*] API. On line 66 of Listing 3.4 we have the following statement: 66: CurrPath().AreaConditional("data-posted", false); This tells the system to remove specified area from the resulting page. On line 62 we pass TRUE for the second parameter meaning that area needs to be added to the resulted page. Same thing we could achieve by wrapping conditional area in the scope and hiding it when necessary, but we don’t want to flood our scope tree with unnecessary scopes. Conditionals are the light-weight approach to toggling different UI areas on the page. TRUE Area conditionals can be nested to achieve logical AND or put beside each other for logical OR. You can combine conditions in many different configuration to achieve your UI requirements. One thing to remember about conditionals is that they should not contain nested scopes. It will not break anything, but from the design point of view, it does not make sense to hide scopes using parent conditional area. In such case a parent scope should be used to maintain a clear scope tree. Actions and duplex messaging mechanism in combination with partial updates is another outstanding feature that makes DaST different from other frameworks. Main asset of DaST concept is that simplicity and flexibility of the core features design are both at the maximum level in the same time, while other modern server-page engines usually have to sacrifice one for the sake of the other. Actions mechanism is a DaST replacement for event handling. The typical action workflow is the following: In our Example 2, action is raised when user inputs some text into the textbox located in the header area of every scope and clicks one of the link buttons on the right. In Intro section I’ve already described the differences of those 3 link buttons and the resulting action top-level workflow. Let’s go though this process from the very beginning and explain everything in details. Action is raised in the client browser using DaST.Scopes.Action() [*] API. The scopePath passed to this function is the ID of the scope whose responsible controller should be used to handle the event. The actionName parameter identifies the action within the controller. Finally, actionArgs is a generic data parameter passed along with an action. The DaST.Scopes.Action() [*] function can be called from anywhere within your web page. You can put it in the onclick attribute of HTML element or call it from your JavaScript – there are no limitations. Now back to our example on Listing 3.2. Assume we input “Hello World!!!” and clicked “Header Only” link button as described in Example 2 Intro section. The result of this action is also described in Example 2 Intro section. Now let’s follow the code and see what happens and how exactly it works. The “Header Only” link button is on line 5 of Listing 3.2 and it looks like the following: DaST.Scopes.Action() scopePath actionName actionArgs onclick 5: <a href="javascript:$.ScopeHeader('submit', '{ScopeID}', 'self')">Header Only</a> All 3 buttons call the same submit method of $.ScopeHeader plugin (I use jQuery plugin syntax just because I like it) passing different parameter to it depending on which button is clicked. The method is implemented on lines 23-36. Even though it’s not directly related to actions, I’ll give a bit of explanation here. The purpose of submit method is to get input text from the corresponding text box, prepare some values, and raise action passing the text and the prepared values as parameters. Since “Header Only” is clicked, the target parameter equals “self”. On line 26 I clear all bolded and red borders bringing them to the initial state before Ajax call. On line 29 I use passed scopeID value to find the current scope container where button is clicked. Note that jQuery will not accept DaST id specification with “$” delimiters, so I have to use attribute selector. I’ll change the delimiters in the future to solve the problem. Next, on line 30 I get the currently input text. Next, we have an if clause on line 31 and warning message display on line 35 in case of the invalid input. Finally, if input is valid, we come to line 33 where all interesting stuff happens: submit target scopeID 33: DaST.Scopes.Action(scopeID, 'RefreshFromClient', [input, target]); This is our long waited call to DaST.Scopes.Action() [*] API to raise a client action. The scopeID param is reused here to point at the scope whose responsible controller should handle an action. Recall that we’re currently in the template for one of the Header scopes, so scopeID will point to one of Header scopes depending on where we clicked the button. And the controller attached to this scope is ScopeHeaderController, so the system will use its instance to handle current action, which is the desired behavior. Second parameter is action name and I chose "RefreshFromClient". It’s self-explanatory telling that “this is a refresh request coming from client”. Note that action name has to be unique for the entire controller, not for the target scope. Last parameter is the generic data value that will be passed to the action handler on the server side. This value has to be a JSON-serializable object. In our case we pass the JSON array where we put input text and a target (whose value is "self" in our case). Now action is raised. Let’s see how to handle this action on the server side. ScopeHeaderController "RefreshFromClient" "self" In the controller class, actions are bound to their handlers inside the InitializeModel() [*] method using HandleAction() [*] API. There is no need to point at the specific scope using Select() [*], because client actions are bound on per-controller basis. The action handler function must have a generic object argument that equals the data value passed to DaST.Scopes.Action() [*] on the client side. Inside action handler, CurrPath() [*] always points to the scope specified by scopePath parameter in DaST.Scopes.Action() [*] call. Back to our example. As we know from previous section, the system chooses ScopeHeaderController attached to Header scope to process our "RefreshFromClient" action. The code for this controller is on Listing 3.4. First thing we have to do is to bind the action to its handler and this is done on line 14 as following: CurrPath() "RefreshFromClient" 14: model.HandleAction("RefreshFromClient", new ActionHandler(Action_RefreshFromClient)); So, you pass action name and the handler function. Implementation of Action_RefreshFromClient() handler is on lines 21-40. Let’s go through the source code of this handler and explain what it does. The purpose of this handler is to take the text input by the user, save it in the "PostedData" param for the scope that submitted this data, and then refresh certain scopes to make them re-render. Since we used “Header Only” button, we only need to refresh the current Handler scope (target is equal to "self"). From section Child Control Binding section we already know how DataBind_ROOT() binding handler on lines 53-68 works. On re-render, this handler is called again. This time "PostedData" value is set and the conditional area reveals the HTML snippet with actual input data, so you see your “Hello World!!!” output in red rectangle (see Header Action Links section). Action_RefreshFromClient() Handler "self" "PostedData " First of all, handler function has a generic arg parameter which is set to the JSON value passed to DaST.Scopes.Action() [*] from the client side. JSON objects are represented in .NET as combination of arrays and name-value dictionaries so it’s quite simple to work with them. Recall that I passed array of two values: input text and target. On lines 24 and 25 I retrieve these values into local variables. Next, on line 27, we switch on target value which does nothing in our case, because target equals "self". All other cases will also be explained in further tutorial sections. CurrPath() [*] points to the controller root i.e. the Header scope. On line 36 we save our “Hello World!!!” text under "PostedData" name to the current Header scope, so that it will be picked up inside the DataBind_ROOT() on re-rendering. Finally, we notice two more interesting expressions in the end of the action handler. On line 38 we see the DaST partial update used to refresh the current Header scope. And line 39 demonstrates DaST duplex messaging mechanism used to notify the client side of the event and pass data to it. Both these cool features are explained in depth on the next two sections. arg In DaST partial update can be applied to any scope or multiple scopes inside the tree. If scope is refreshed, its child scopes are refreshed as well. DaST does not refresh any scopes on a postback unless it is explicitly instructed to do so. There are no things like UpdatePanel triggers or similar stuff from standard ASP.NET. To refresh the scope in DaST, you need to point it using CtrlPath() [*] or CurrPath() [*] and call Refresh() [*] function. If you do this on multiple scopes, all of them are refreshed. It’s just that simple. When Refresh() [*] is called on the pointed scope, this scope is placed into the refresh queue. After completion of Stage 2: Action processing, the Stage 3: Rendering output starts (see Controller Rendering section). This time, instead of traversing the scope tree from the NULL scope, the tree is traversed partially starting from the scopes in the refresh queue. The resulting output for each sub-tree is sent back to the client and is applied to the corresponding scopes on the web page. It’s important to understand that during partial update, DaST executes binding handlers for the refreshed scopes ONLY! This is a mathematically correct approach to partial update, when partial UI refreshing results it partial code execution on the back-end. Compare to ugly UpdatePanel based updates in standard ASP.NET, where every partial update executed the entire page lifecycle. Now back to our sample code on Listing 3.4. The refresh is done on line 38 by the following instruction: CtrlPath() 38: CtrlPath().Refresh(); The “Header Only” link refreshes only one scope which is a Header scope corresponding to the header where the link button is clicked. Due to this instruction, the DataBind_ROOT() on line 53 will be re-executed during rendering traversal and the newly generated output will be applied to the corresponding scope on the web page. The resulting UI from clicking “Header Only” link was shown in Header Action Links section. To highlight the specific scope with red borders I need to be able to detect on the client side whether this scope was refreshed. For this purpose I can use one of my favorite DaST features – duplex messaging. Putting it simple, client messaging mechanism is like actions, but in the opposite direction. While action is raised on the client side and handled on the server side, the message is raised on the server side and is handled by JavaScript in the client browser! Actions and client messages complement each other allowing true both-ways duplex communication between the client and the server. This mechanism is something that DaST can be really proud of, because with all its simplicity, it brings unmatched Web 2.0 capabilities to your apps. The syntax is uniform like everything else in DaST: to send message to the client browser you need to point at the scope and call MessageClient() [*] function on it passing message ID and JSON data object. In the client script we use DaST.Scopes.AddMessageHandler() [*] JavaScript API to add handler for the specific scope and message ID combination. Back to our code on Listing 3.4. On the last line 39 of our action handler we see the following instruction: MessageClient() DaST.Scopes.AddMessageHandler() 39: CtrlPath().MessageClient("RefreshedFromServer", null); Here I send the "RefreshedFromServer" message to the client side, so that client code can handle this message and update the desired scope borders accordingly. The second parameter to MessageClient() [*] is some generic data value that have to be JSON-serializable object as before. This object is passed to the client and is given to the JavaScript message handler as argument. In our case we don’t need to pass any data, so just pass null. Let’s now see how the message is handled on the client side. In Listing 3.2 on lines 51-54 we see the following: "RefreshedFromServer" null 51: DaST.Scopes.AddMessageHandler("{ScopeID}", "RefreshedFromServer", function (data) 52: { 53: markScopeUpdated("{ScopeID}"); 54: }); And this is a JavaScript handler for our message! The {ScopeID} is replaced by the actual value pointing at the current Header scope. Recall that inside our action handler, the "RefreshedFromServer" message was also sent for the Header scope. Third parameter of DaST.Scopes.AddMessageHandler() [*] is a callback function with data param that gets the JSON representation of the value, passed to MessageClient() [*]. I love JSON, because it’s consistent everywhere. Note that this code is not a part of if(!$.ScopeHeader) condition starting from line 17. This condition need to avoid $.ScopeHeader plugin redefinition, because it’s always the same for all Header scopes. But code on lines 51-54 is always different due to different values of {ScopeID} and in our case message handler needs to be added for every Header scope on the page. Next, inside the callback function on line 53 I call a helper markScopeUpdated() function to give our scope the updated look and feel. This helper function is implemented inside the root template on Listing 3.1 on lines 39-43. You can see that I simply select the updated scope container and assign CSS classes to it so it becomes red and bold. Also I make all child containers red, but not bold, so that only the directly updated scope becomes bold. This achieves the UI we could see in Example 2 UI section. And this is it! Our scope gets updated, message is handled, UI is adjusted. Now it's time to see what other two link buttons do. data if(!$.ScopeHeader) $.ScopeHeader markScopeUpdated() Last topic that we need to learn is controller-to-controller communication. In DaST controllers talk to each other using controller actions. One of the biggest DaST assets is that syntax of controller actions is absolutely uniform with actions raised on the client. Assume we entered “Hello World 2!!!” into the header of ItemRepeater as shown in Header Action Links section. We already know how “Header Only” button works, but the other two buttons require a bit more programming. Main difference is that for “Header Only” button both action handling and scope refreshing were done in one ScopeHeaderController, because we only needed to refresh the Header scope. For “Parent Scope” and “First Child Scope” buttons we also need to refresh the parent ItemRepeater scope that root NonsenseExample2Controller is responsible for. So, what we need to do here is to refresh the Header scope and then tell the parent controller to refresh the ItemRepeater. To communicate between controllers DaST provides controller actions mechanism. The child controller can raise action that can be handler in the parent controller. Actions are raised using RaiseAction() [*] function where we pass action name and generic argument. This action can be handled on a parent controller using HandleAction() [*] API with syntax uniform with client actions handling. The only difference is that data item does not have to be JSON-serializable this time, because object is passed on the server side. Also, when handling client action, there is no need to point the scope before calling HandleAction() [*], but in case of controller action, we must point at the scope to which the desired child controller is attached. Back to our example. Assume we input “Hello World 2!!!” as shown in Header Action Links section and clicked “Parent Scope” button. The action is raised again by line 33 on Listing 3.2, but this time target equals "parent". Our action handler on line 21 of Listing 3.4 is executed again and this time switch clause on line 27 chooses case for "parent": RaiseAction() "parent" 31: case "parent": CtrlPath().RaiseAction("RaisedFromChild", "parent"); break; This is where we raise our "RaisedFromChild" action to be handled in a parent controller. I pass “parent” as generic data parameter because I’ll need to use this value later. After this line is executed, the action is raised and becomes visible to the parent controller which is in our case a root NonsenseExample2Controller on Listing 3.3. First thing we need to handle this action is to associate the action handlers. This is done on lines 28-33 of Listing 3.3 where I point all Header scopes (to which ScopeHeaderController is attached) one by one and associate the Action_RaisedFromChild() action handler with "RaisedFromChild" action. So, Action_RaisedFromChild() on line 39 gets called in response to the "RaisedFromChild" action with arg equal to "parent". The if clause on line 41 gets satisfied and lines 43 and 44 are executed. CurrPath() [*] still points and the Header scope, so, to refresh the ItemRepeater, we must go 1 step back in the scope tree first and then refresh. This is done on line 43. On line 44 we send a duplex "RefreshedFromServer" message to the client passing scope ID as parameter to notify our UI about the scope refresh. In the root template on Listing 3.1 this message is handled using the following code on line 52: "RaisedFromChild" Action_RaisedFromChild() 52: DaST.Scopes.AddMessageHandler("{ScopeID}", "RefreshedFromServer", function (data) 53: { 54: markScopeUpdated(data.ScopeID); 55: hideRepeaterHeaders(); 56: }); And this calls markScopeUpdated() helper function already familiar to us from the previous section. This function takes the ID of the refreshed scope as a parameter and I use the data.ScopeID that I passed to the previous MessageClient() [*] call. Could it be simpler? Ok, cool, but this is not it. After Action_RaisedFromChild() handler completes, the execution returns to Action_RefreshFromClient() handler on Listing 3.4 to line 36. The statements on lines 36, 38, and 39 get executed and I've already explained them in the previous section. So, as a result, the Refresh() [*] is called on both ItemRepeater and Header scopes. Since this Header is a child of ItemRepeater, it does not really matter if we call Refresh() [*] on the Header scope, because it is updated anyway as a child of the refreshed scope. Next thing to note is that we send two duplex messages to the client during current action handling procedure: on line 44 of Listing 3.3 and on line 39 of Listing 3.4. This, in its turn, means that both message handlers will be invoked on the client side: one on line 52 of Listing 3.1 and the other on line 51 of Listing 3.2. As a result, both Header and ItemRepeater scopes get the bold red borders. markScopeUpdated() data.ScopeID Action_RefreshFromClient() Now the other way around – parent controller can also raise action handled in its child controller. Or it’s more precise to say invoke action on a child controller. Actions are invoked using InvokeAction() [*] function where you pass action name and generic data item. Before calling this API, you have to point at the scope to which the desired controller is attached. Everything else is very similar to raised controller actions in the previous section. Action is handled using uniform syntax and HandleAction() [*] API (no need to point at the scope, because action is invoked per controller). Now let’s see how the last button works. Assume we enter some “Hello World 3!!!” into the header of ItemRepeater and click “First Child Scope” link as shown in Header Action Links section. This one is the most complex case. Here, instead of updating the parent ItemRepeater scope, we want to update Header scope of the first direct child of the ItemRepeater. There is no real meaning in this operation – I just want to demonstrate various updating and controller communication techniques here. So, in this case, the child ScopeHeaderController still notifies the parent NonsenseExample2Controller, and instead of updating ItemRepeater scope, the controller pushes notification further to the header of its first child scope i.e. to another child ScopeHeaderController. Let’s see how this looks in the code. The action is raised same way by line 33 on Listing 3.2, but this time target equals "child". Our action handler on line 21 of Listing 3.4 is executed again and this time switch clause on line 27 chooses case for "child": InvokeAction() NonsenseExample2Controller "child" 32: case "child": CtrlPath().RaiseAction("RaisedFromChild", "child"); break; So, we raise "RaisedFromChild" controller action again similar way we did for the previous button, but now passing "child" as data. Action_RaisedFromChild() callback on line 39 on Listing 3.3 is executed and this time flow goes to the second if branch on lines 46-64. Now look at the scope tree on Fig 3.1. For all explanations here I assumed we used buttons from header of ItemRepeater. So, action is raised from the controller attached to the Header scope whose parent is ItemRepeater. Our purpose is to access header of the first child Item scope of ItemRepeater passing appropriate path to CurrPath() [*] and notify it of the event. So the task reduces to finding the right path. Knowing that CurrPath() [*] points to the original Header scope and looking at the tree on Fig 3.1 it’s not hard to see that relative path will be -1$0-Item$0-Header i.e. one step back to ItemRepeater and then to first Item and its Header. The problem is that in general case we don’t know which Header raised the action and we have to build the desired path based on the current path. This is what I do on lines 49-58. Basically, I take the last segment on the scope ID and depending on the scope name, I take the proper next scope. That switch is a bit ugly, but this is just a quick and dirty solution. As a result, we have our path and use it to invoke action on the child controller on line 62: Action_RaisedFromChild() -1$0-Item$0-Header Header 62: CurrPath(-1, nextScope, "Header").InvokeAction("InvokedFromParent", null); I point at the desired Header scope that ScopeHeaderController is attached to and call InvokeAction() [*] API passing "InvokedFromParent" for action name and null for generic data item. In ScopeHeaderController on line 15 this action is bound to the Action_InvokedFromParent() handler defined on line 42. The code of this handler is trivial – first, we refresh current scope (which is a Header scope pointed for previous InvokeAction() [*] call) and send another "RefreshedFromServer" message to the client. So, this time we also updated 2 scopes and sent 2 corresponding duplex messages: one for original Header and the other for the Header of the first child scope. The UI result of this operation is on the last picture in Header Action Links section. Only 2 Header scopes are updated and not anything else. "InvokedFromParent" null Action_InvokedFromParent() "RefreshedFromServer" Congratulations! This tutorial is complete and now you're DaST expert! I know it's unusual that such limited set of tools can replace standard frameworks like WebForms or MVC, but it really can. Design your web page UI, divide it in scopes, and use DaST to control you markup areas individually – this is all. That's how web development should look like – simple and intuitive. No need to learn tons of server controls, weird page lifecycle events, grid/repeater/whatever binding expressions, etc. And a huge benefit of DaST is fully separated presentation – the HTML design group can work on real templates while developers work with skeleton templates. Also, whenever existing app needs UI changes, the HTML designer can do it without interrupting programmers. Of course, the ASP.NET DaST framework is still on the early stage. At the moment, we have a well defined pattern, proven concept, and working rendering core that already allow us to do a lot. But there are still some features that will be added in the near future. Within the next couple of months I want to accomplish the following: FORM If you wish to join the project (or PHP DaST) - do it right now! If you have any bright ideas/suggestions, please share with me. Watch for updates and follow @rgubarenko on Twitter. I'm open to any type of questions and will be glad to hear your feedback. Please drop me few lines what you think about all this. All useful links are below..
http://www.codeproject.com/Articles/560364/ASP-NET-DaST-to-wrestle-with-MVC-and-WebForms?fid=1829182&df=90&mpp=50&noise=3&prof=False&sort=Position&view=Normal&spc=Relaxed
CC-MAIN-2015-32
en
refinedweb
Introduction Essentially, the Business Object Model (BOM) is the representation of the domain model in scope for efficient rule processing. It is this representation of the model against which rules are written. BOM elements are the classes, attributes and methods grouped into packages. Natural-language verbalization is attached to the BOM elements to make rule authoring user friendly. Verbalizations on all the BOM elements form the vocabulary that business policy managers use to define rules using JRules. The BOM is not the model used during runtime – that would be the Execution Object Model (XOM). Loosely speaking, the XOM is related to the BOM as database table is related to a database view or an implementation model is related to the logical model. The XOM is defined either as Java™ classes or XML schema definitions. At runtime, it is the methods on instances of the XOM that are executed as rule conditions and actions. The BOM-to-XOM mapping (B2X) defined in the BOM is used to translate the BOM into the corresponding XOM element. Since the BOM is the foundation on which rules are written, creating a good BOM is a crucial part of the rule development process. On the face of it, creating a BOM seems like a straightforward process, especially since a XOM can be directly used in a Rule Studio wizard to generate the BOM. However, experience has shown that there are several pitfalls in creating a BOM that can get in the way of rule projects delivering on their promise of easy maintenance. Down the line, these pitfalls can lead to expensive refactoring or even failure. This article examines these missteps and pitfalls and suggests ways to avoid them. Note: The screen captures and examples in this article use JRules, but the techniques described are also applicable to the new version of JRules, WebSphere Operational Decision Management. Prerequisites This article is written for the intermediate JRules developer. It is assumed that the reader has a basic understanding of WebSphere ILOG JRules (or WebSphere Operational Decision Management) from a developer's perspective. Refer to the Resources section for relevant links to help you acquire the prerequisite knowledge for completing this article. The product version used in this article is WebSphere ILOG Rules Studio V7.1.x. Pitfall: Neglecting business in the BOM As should be evident from its name, the essence of a BOM is that it is the business users' view of their domain. However, this basic tenet is sometimes overlooked, leading to detrimental effects. This usually happens when the decision service uses an enterprise model or industry standard information model as the XOM. These models tend to be complex and large in their breadth and depth because they need to cater to all of the data requirements across all of the enterprise applications. Enterprise models deal with classes that do not necessarily correspond with the concepts used by policy managers and subject matter experts (SMEs). The class names and attribute names tend to be IT-centric and are usually not business friendly. The least cost path of then directly using this XOM in a Rule Studio wizard to generate the BOM leads to a BOM that is unsuitable for writing rules. Some of this can be mitigated through appropriate BOM verbalizations. However, more troublesome is when rule authors need to understand and navigate through a complex class hierarchy, one that is very different from their conceptual model. This discrepancy leads to cognitive dissonance, which is a feeling of discomfort and confusion that results from simultaneously holding two models at variance. As an example, consider an insurance company that has decided to use ACORD (See Resources for additional information on ACORD) as its standard. This in itself is a fine enterprise-level architectural decision as it promotes interoperability among applications within the company and potentially even across partners in the industry. Data is passed between applications using ACORD data types. The insurance company uses a JRules rule application to provide online insurance policy quotes for new customers for which the ACORD format is used in the service contract design. Therefore, this decision service receives data in ACORD format. Figures 1 and 2 show a slightly modified view of a portion of the ACORD model. The input to the decision service is an ACORD object. As depicted in Figure 1, navigation to the policy quote request itself requires jumping across two links on the class diagram starting from the root ACORD request. Figure 1. Navigating to the Policy Quote request (See a larger version of Figure 1.) From the policy quote, we need to jump through four more links to navigate to the birth date of the driver in a rule that references the age of the driver, as shown in Figure 2. Figure 2. Navigating to the birth date of the driver (See a larger version of Figure 2.) In other words, a simple conceptual attribute, such as "age of the driver" requires the rule author to navigate through six classes! Consider a simple business policy: "Refuse policy if any drivers are under 21 years of age in CA and NV." The following code listing shows a business rule implementation of this policy using the above BOM. definitions set 'State' to the controlling state prov cd of the pers policy of the pers auto policy quote inq rq of the insurance svc rq of 'request Acord'; set 'persAutoLineBusiness' to a pers auto line business from the pers auto line business of the pers auto policy quote inq rq of the insurance svc rq of 'request Acord'; set 'persDriver' to a pers driver in the pers drivers of persAutoLineBusiness; set 'Driver Info' to a driver info from the driver info of persDriver; set 'Personal Info' to a person info from the person info of 'Driver Info'; set 'CurrentAge' to the calculated age using the birth dt of 'Personal Info'; if all of the following conditions are true : - State is one of { CA, NV } - CurrentAge is less than 21 then … Clearly, the above rule is unnecessarily complex, hard to read and hard to maintain. Moreover, as it does not match the policy manager's conceptual model, it feels obscure and burdensome to maintain for the business user. The conceptual model in the policy manager's mind is radically simpler than the enterprise model. For example, they may conceive the policy quote request (or a portion of it) as a simple model, as shown in Figure 3. Figure 3. Conceptual policy model The BOM should mimic this conceptual model. With the BOM aligned with the conceptual model, the same rule can be expressed in a much simpler and straightforward manner, as shown in the following listing, thereby eliminating the cognitive dissonance. definitions set 'driver' to a driver in the drivers of 'policy request'; set 'currentAge' to the calculated age using the birth date of 'driver'; if all of the following conditions are true : - the controlling state of 'policy request' is one of { CA, NV } - currentAge is less than 21 then … Although this example highlights the problems inherent in directly using the ACORD structure as the BOM, this applies to most other industry standards as well, such as the MISMO model for mortgage loans and the Primavera model for insurance. As is evident, the BOM should present a very specific viewpoint of the domain that is suitable for the policy manager to conceptualize and author business rules. Anything that upsets this viewpoint, be it new concepts, new terminology or discrepancy in relationships, introduces cognitive dissonance. Another situation where this may occur is when the modeler decides to model the "real world" instead of just the specific business viewpoint. With this intent, the modeler zestfully introduces many new concepts and associations that are at best superfluous to the business viewpoint and at worst actually discordant with it. This real world BOM may start to look like an enterprise model, with all its negative consequences. Traditional object-oriented analysis (OOA) makes the distinction between analysis models and design models. The chasm between the BOM and the decision service model runs even deeper than this distinction in the aforementioned examples because the BOM should represent the rule analysis model while the external model should represent the object-oriented design model. Techniques for avoiding the "neglecting the business in the BOM" pitfall As illustrated in the above example, the BOM should match the conceptual model of a policy manager. However, the input data into the decision service is the enterprise information model. So how do we reconcile these two seemingly conflicting requirements? There are two ways: - Use a Transformer in the decision service. - Build a BOM adapter layer using a BOM to XOM layer (B2X). Both of these approaches essentially utilize a data adapter layer to build a façade. Using a Transformer In this approach, we build an XOM that is aligned with the simple conceptual model, essentially ignoring the enterprise model until later. Therefore, the BOM derived from this XOM is also simple and easy to use for rule authoring. However, the service contract is based on the enterprise model. During rule invocation, a Transformer is used in the decision service to convert the request sent by a rule client from the complex enterprise model into the simple XOM. The Transformer may just be some simple Java classes or may employ XSLT. Alternatively, if using service-oriented architecture (SOA), it may be a transformation service provided by service-oriented integration (SOI) middleware or an enterprise service bus (ESB). The transformed XOM objects are then sent to the rule engines for rule execution using the Rule Session API. The rule response also is transformed from the XOM objects to the enterprise objects before returning to the rule client, as shown in Figure 4. Figure 4. Using a transformer to convert the enterprise model into a simple XOM This approach leads to a loosely coupled system and has the advantage that the rule developer can practically ignore the complexities of the enterprise model. Only the decision service developer, who is responsible for providing the integration layer needs to even be aware of the enterprise model. Additionally, unit testing of rules is easier using the simple model. The disadvantage is that a new component, namely the Transformer, has to be built as a data adapter. Moreover, as the ruleset evolves, if a rule makes use of an existing enterprise model element that has thus far not been included in the BOM, a new BOM element will need to be added. This requires modifications to the Transformer and redeployment of the Rule Decision Service. Using a BOM Adapter layer This approach uses the complex enterprise model as the XOM. However, the BOM is not directly derived from this XOM, but is created as an empty BOM entry in the Rule Studio. The rule developer then builds all the BOM classes as virtual classes by cherry-picking from the enterprise model and applying verbalizations and BOM to XOM mappings, thereby providing a view of the enterprise model that matches the conceptual model. The B2X mapping is used to flatten the enterprise model vertically (class hierarchies) and horizontally (multiple navigations), which eliminates the need for complex navigations when authoring rules. Figure 5 shows the rule execution environment and rule authoring environment with the B2X adapter layer. Figure 5. Using B2X to map to a simple BOM Implementation of the BOM adapter layer for a portion of the BOM outlined in Figure 3 is described below. As illustrated in Figure 6, a virtual PolicyQuoteRequest class is defined, which has the ACORD class as its superclass as well as its execution name (in its BOM to XOM mapping). Figure 6. The virtual PolicyQuoteRequest BOM class Attributes are defined on this virtual class to match the conceptual model. For example, as illustrated in Figure 7, the controllingState attribute is defined with a suitable verbalization and an appropriate data type (in this case, StateType, which is an enumerated list defined in the enterprise model). Figure 7. Defining the controllingState member on the virtual class Since this is a synthetic attribute, the BOM to XOM mapping is used to actually map to the execution model. The BOM to XOM mapping for the controllingState, shown below, navigates through a series of objects of the enterprise model to retrieve the controlling state code. return (com.ibm.schemas.ibm.acordtypes.StateType) this.InsuranceSvcRq.PersAutoPolicyQuoteInqRq.PersPolicy.ControllingStateProvCd; Only these virtual classes are verbalized and therefore rules are only offered the business view of the domain in the BOM. The ugly complexities are hidden in the BOM to XOM mappings. The main advantage to this approach is that the entire enterprise model is available for potential use in the future. Adding a new BOM element that references an existing enterprise model element can be handled through suitable B2X edits in the BOM editor and is deployed as part of the ruleset, with no changes to the Rule Decision Server. Therefore, it can be "hot-deployed." The biggest drawback is that it requires a lot more development effort to build out the B2X. Also, unit testing is much harder, especially using the Decision Validation Services (DVS) module, since the data is much more nested and complex. Moreover, it is not straightforward to test the rules, since building a test case requires knowledge of how the enterprise data is mapped to the BOM elements. Another drawback is that the performance is slightly compromised because the B2X code is not as efficient as Java code. Considering these drawbacks, unless hot deployment of new BOM elements is critical, it is better to use the Transformer approach. Since the BOM is detached from the enterprise model, a side benefit of either approach is that the rule project is insulated from changes to the external model. This is tremendously valuable when the enterprise model is in a state of flux. Both these approaches prevent cognitive dissonance by minimizing new concepts in the BOM. In addition, the structure and cardinality of relationships that the policy manager uses in his or her view of the domain is carefully preserved. However, there are cases where we may need to introduce a new element to the BOM to facilitate rule processing; for example, we may use a "processing status" to keep track of whether the claim has already been denied, thus avoiding further processing. In such cases, it is very important to educate the business users on the purpose and usage of these elements. The policy managers should be fully cognizant of and comfortable with each and every verbalized element in the BOM. Pitfall: The abstract BOM Philosophically, abstraction is the thought process where ideas are distanced from objects. This thought process, applied to modeling, leads to higher order concepts, taxonomies and ontologies. These are very useful in certain areas, but can be detrimental when applied to a BOM. As the adage goes: the road to hell is paved with good intentions. This is precisely because abstraction introduces new concepts which lead to cognitive dissonance, as discussed in the previous section. This is best illustrated through an example. Consider a claim processing rule application that is responsible for automating the decision of whether to deny or permit a claim. There are several checks that would need to be made on the claim. One such simple rule that a policy manager may verbalize is: "If the effective date of the policy is after the date of service on any of the service lines, then deny the claim." Using a BOM in which a claim and the associated policy are input parameters, this can be implemented using the following simple rule: definitions set ‘the service line' to a service line in the service lines of 'the claim'; if the effective date of the policy is after the date of service of the service line then deny the claim This rule utilizes a simple BOM that matches the business viewpoint of the model, a portion of which is shown in Figure 8. It has concrete classes such as Claim, ServiceLine and InsurancePolicy. Figure 8. Simple claim model However, with the goal of flexibility in mind, one may model the claim as a form with several form fields in it. Additionally, one may identify a policy as a just a relationship between the insurance company and the payer and note that these are all entities that have several attributes associated with them. These can then be used to create an abstract model, or an "adaptive object model," as shown in Figure 9, containing concepts that may be understandable, but not commonly used by a policy manager. Figure 9. An abstracted claim model This model is highly flexible because new forms and form fields can be added without making any changes whatsoever to the XOM. New relationships and attributes can be dynamically added, too. But at what price? Following is the sample rule implemented with this model as the BOM: definitions set ‘the service line' to a service line in the service lines of 'the claim'; set 'dos field' to a form field in the form fields of 'the service line' where the name of this form field contains “Date of Service”; set 'the event date' to the value of 'dos field'; set 'payer' to a relationship in the relationships of 'the claim' where the name of this relationship is “Payer”; set 'the policy effective date attribute' to an attribute in the attributes of 'payer' where the attribute name is “dateOfService”; set 'the policy effective date' to the attribute value of 'the policy effective date attribute'; if 'the policy effective date' converted to date is after 'the event date' converted to date then From a business user's standpoint, this rule is simply horrific! As can easily be imagined, the policy manager does not find this easy to read, easy to author, or easy to maintain. There is a large gap between how the policy manager conceptualizes it and how it is verbalized. This frequently leads to a technical developer having to handle rule maintenance and impact analysis, thereby defeating one of the key potential benefits of a business rule management system. Moreover, using this XOM one cannot answer even simple static structural questions about the model, such as what the attributes of a Claim are. This makes it hard for the invoking application to correctly pass the data, and errors are detected only at runtime, not at compile time. Even if flexibility requirements demand such a flexible XOM, the policy manager should be shielded from this through techniques described in the earlier section titled Techniques for avoiding the "neglecting the business in the BOM" pitfall. Pitfall: The loose BOM With the intent of keeping the model flexible, a modeler may sometimes choose not to use strong typing of the data. For example, consider an input Account class, as shown in Figure 10, where all of the attributes are defined to be of type String. Since the account type is defined as just a string, there is no restriction on what account types may be passed in. So as new account types are added, there is absolutely no change required to this model. Additionally, the establishDate attribute can accept dates in different formats. Figure 10. Loose data types on Account However, when writing a business rule with this as the BOM, several problems arise: - During rule authoring, no hints are provided about the possible list of values of any of these attributes. The rule author is required to know this list; for example, that the account type value may only be Consumeror Business. - Mistakes made in the string constant, such as incorrect letter case or invalid use of spaces in the string, are not detected during rule authoring. They are detected only during runtime when a rule does not fire as expected. Even unit tests may not catch this mistake since the unit test data may use the same string constant used in the rules. - The rule client that has to populate the rule request data does not have any restrictions or hints on the values for any of these attributes. For example the model does not tell the rule client if the dormant indicator should be entered as NOT DORMANT, NOT_DORMANTor False. - Rule conditions have to convert from string to the required data type for usage in methods. For example, in the following listing, the establish date needs to be converted into a date object before comparing it with the current date. - The biggest chunk of time spent by JRules execution is in XOM method execution. Using Strings, and thus equals operators, through the Rete networks operations eventually proves costlier than using ==. if the type of the account is “Consumer” and the dormant indicator of the account is “NOT DORMANT” and the establish date of the account converted to date is after today then … When using a strongly typed BOM, as shown in Figure 11, some flexibility is sacrificed, but the aforementioned problems are overcome and the rule authoring and testing process is greatly facilitated. In this model, a Java enumeration called AccountType restricts the values that can be passed in from the rule client for this attribute. Since this is a Java enum, there is no possibility for entering illegal data in the rule client. All of the other attributes are strongly typed, too. Figure 11. Account class with strongly typed attributes With this strong typing, the JRules Intellirule Editor prompts the rule author with the appropriate set of values, as shown in Figure 12, so there is no need for the author to guess the exact string representations and the possibility for errors is eliminated. Figure 12. Intellirule prompts for auto completion Also, no intermediate functions are necessary for rules to use the attributes, as seen in the establish date usage in the following rule definition. if the type of the account is CONSUMER and it is not true that the account is dormant and the establish date of the account is after today then … As already noted, the strong data typing approach comes at a price – that of flexibility. This is particularly true in the case of enumerations. For instance, consider a scenario in the future where an account type is added. This requires a change to the XOM thereby necessitating a change to the rule client, redeployment of the decision service and possibly even changes to the decision service WSDL. So what about those situations where the model needs to be dynamic and redeployment is not an option? Well, there is a solution: the XOM is not strongly typed for those dynamic attributes and restrictions are implemented in the BOM layer. For instance, the account type is defined not as a Java enum, but as a string in the XOM. In the BOM, there are two approaches to restrict this string value to a list of values. - Using literal domains - Using a virtual enumeration type Using literal domains A simple way to restrict a string attribute in the BOM is to use a list of literal values as a literal domain. For example, as shown in Figure 13, the account type is defined as a string with a domain type consisting of the literals CONSUMER and BUSINESS. Figure 13. Literal domain Although this approach is simple, the drawback is that these literals may need to be redefined in multiple places. For instance, if the account type is used as an argument in other methods, these literal domains will have to be redefined for each usage of account type as an argument. In such cases, it is better to define a virtual enumeration type. Using a virtual enumeration type In this approach, a virtual enumeration type is defined as a BOM class. For instance, AccountType is defined as a BOM class, as illustrated in Figure 14. The execution class in its B2X is specified as java.lang.String and so is its superclass. Figure 14. Virtual AccountType BOM class Now each of the possible values is defined as members of this virtual enumeration class, with the type of that virtual class. For example, BUSINESS is defined as a read-only static final member with a data type of AccountType and a B2X mapping of BUSINESS, as shown in Figure 15. Figure 15. Member definition of virtual AccountType This virtual enumeration type is used as the data type for the attribute in the Account BOM class, as shown in Figure 16. Figure 16. Usage of virtual enumeration class in Account The main advantage of using this approach is that this virtual enumeration class can be reused to restrict other attributes and methods that utilize accountType. However, this approach requires more development effort, and when dealing with a large list of values, this approach can get very tedious. In those cases, it would be preferable to use dynamic domains, which is beyond the scope of this article, but you can refer to the Resources section for a tutorial on the subject. Pitfall: Ignoring the rule author The BOM should be well verbalized because it forms the vocabulary that is used by rule authors when defining rules. Superfluous or poor verbalization leads to rules that are hard to read and maintain, and becomes an impediment to the rule author. Poor verbalization Frequently, blind usage of the Rule Studio wizard to generate the BOM from an XOM leads to a BOM with less than ideal verbalizations, especially when it comes to methods with multiple arguments. For example, consider a Java XOM method on an Util class that adds a notification given an account, the notification message, an error ID, the name of the rule producing this notification and the current timestamp, as follows: public static void addNotification(Account account, String message, String id, String rulename, Date timestamp) { … This creates a default verbalization of: util.addNotification({0}, {1}, {2}, {3}, {4} A rule action using this method looks like this: then util.addNotification ( the account , "Account not yet established must be dormant", "W2101", the name of this rule , today ) ; There are several issues with this approach: - The rule author is prompted to enter a string for the second, third and fourth arguments, but there is no contextual information on what these strings are. The author has to know that the message is to be entered first and then the ID, and so on. - The verbalization is Java-like and not business friendly. - For each occurrence, the rule author has to include the rule name and date, even though these are the current values. To alleviate these problems, it is better to not verbalize the Util.addNotification method, but instead create a new virtual static method on the same Util class that only takes the necessary arguments (that is, without rule name and timestamp). Following is a business friendly verbalization that provides contextual information: add a notification using {0, account}, {1, message}, {2, id} When the rule author uses this method, there is an indicator of what the argument represents, as shown in Figure 17. Figure 17. Context-specific argument information (See a larger version of Figure 17.) Since this is a virtual method, it needs a B2X mapping. Notice that the rule name and timestamp are not passed in as method arguments, but are added in the mapping, as follows: String name = ilog.rules.brl.IlrNameUtil.getBusinessIdentifier(instance.ruleName); java.util.Date now = new java.util.Date(); Util.addNotification(account, message, id, name, now); Pitfall: Superfluous verbalization In a rush to generate the BOM from the XOM, the Rule Studio wizard for BOM creation may be used indiscriminately, without paying attention to which of the attributes and methods should actually be verbalized. This often results in many superfluous verbalizations, especially among setter methods of attributes, thereby needlessly cluttering the drop-down lists provided during rule authoring. This impedes ease of use from a rule author perspective. To avoid this, carefully select only those attributes and methods that do need verbalization. Another scenario in which BOM elements may be redundantly added is when different rule projects refer to some common XOM elements. For instance, consider a rule project that has to determine the credit rating of a mortgage customer and another that determines the price to charge for the mortgage. Typically, the common business entities such as Account and Customer would be in a CommonXOM Java project, while credit specific classes such as CreditBureau would be in CreditXOM while classes such as PricingSheet would be in PricingXOM. Now, the PricingRules rule project depends on both the common XOM and the pricing XOM, so it could have a BOM with two entries mapping to it, the same as with the CreditRatingRules project, as shown in Figure 18. Figure 18. Common BOM elements duplicated in Pricing BOM and Credit BOM However, that would be a mistake because the common classes are now duplicated in the BOM entries or PricingRules and in CreditRatingRules. Any change to the common BOM would need to be propagated to both these entries, creating to maintenance issues. The technique to avoid this issue is to create a separate BOM rule project that contains only the common BOM and that is reused by the two rule projects, as shown in Figure 19. Thus, PricingRules references the common BOM that is defined as a separate rule project and the BOM entry in PricingRules contains only the BOM classes that are specific to pricing. Figure 19. Common BOM is externalized and shared In addition, if some classes and members of the common BOM apply only to the Pricing or Credit rules, that can be handled by creating two categories called pricing and credit, assigning appropriate categories to those BOM elements, and filtering them during rule authoring using rule category filters. Conclusion A poorly designed BOM can greatly impede the productivity of rule authors and the maintainability of rule projects. The most important consideration is to prevent cognitive dissonance by absolutely minimizing new concepts and terminology in the BOM and by preserving the business viewpoint. There may be a big chasm between the BOM and the XOM because the BOM is a product of rule analysis, while the XOM is the design model that is produced through object-oriented analysis. The BOM is the business view of the domain from the viewpoint of a policy manager. The XOM is designed with flexibility and performance in mind. This article has described techniques for bridging this chasm. When introducing new concepts or terminology, it is very important to educate the business users on their purpose and usage. The policy managers should be fully cognizant of and comfortable with each and every element in the BOM. The Rule Studio wizard for importing the XOM to create a BOM is an extremely useful tool, but should not be used blindly. Not only is this true to maintain the necessary separation in viewpoints of the BOM and XOM, but also to judiciously control the verbalization of the BOM elements. Additionally, when BOM elements are to be reused across different projects, one should enable reuse by creating a separate rule project just to house the common BOM. Resources Learn - WebSphere ILOG JRules Information Center - WebSphere Operational Decision Management Information Center - WebSphere ILOG JRules product information: - WebSphere Operational Decision Management product information - ACORD: ACORD (Association for Cooperative Operations Research and Development) is a global, nonprofit standards development organization serving the insurance industry and related financial services industries. - Abstraction: Definition in wikipedia - The Adaptive Object-Model Architectural Style: This paper describes the Adaptive Object-Model architecture style along with its strengths and weaknesses. It illustrates the Adaptive Object- Model architectural style by outlining examples of production systems. (PDF) - Customizing WebSphere ILOG JRules for rule authoring, Part 1: Exploring dynamic domains: This series of articles explores various techniques for customizing the authoring environment of the WebSphere ILOG Rule Team Server. (Nasser & White, developerWorks, 2010) - Agile Business Rule Development: Process, Architecture, and JRules Examples: The authors' presentation covers all four aspects required for a successful application of the business rules approach: foundations, methodology, architecture and implementation. (Boyer & Mili, Springer, 2011. - Proven practices for enhancing performance: A Q&A for IBM WebSphere ILOG JRules 7.0.x.: This IBM Redpaper provides information on the performance aspects of WebSphere ILOG BRMS 7.0. A question and answer format is used in order to cover as many dimensions as possible. Furthermore, performance is considered from various perspectives, with an emphasis on production environments and execution.(Paumelle, IBM Redbooks,. Get products and technologies - WebSphere ILOG JRules V7.1.x: Trial.
http://www.ibm.com/developerworks/websphere/bpmjournal/1202_col_rao/1202_rao.html?ca=drs-
CC-MAIN-2015-32
en
refinedweb
Recently, I have been experimenting with different approaches for building vanilla JavaScript apps. And I got the idea to recreate basic React functionality in order to get a similar workflow as in React. This would enable me to keep the benefits of vanilla JavaScript while having the structure of React apps. It would also make it easy to migrate code into React if the app grows. By the end of this post, I will show you how to make a counter component with code that looks almost identical to React code, without using any React. As can be seen here:; You can find the repository here. Setup The first thing that I did was that I installed webpack and typescript. The main reason why I'm using typescript is because it makes it easy to use jsx, otherwise it's not mandatory. The same could likely be done with babel as well. After a standard webpack and typescript installation, I installed typed-html npm install --save typed-html. This is a package that lets us use jsx inside of typescript tsx files. After it was installed, I added the following lines into the typescript config file. { "compilerOptions": { "jsx": "react", "jsxFactory": "elements.createElement", } } This factory comes with some limitations. <foo></foo>; // => Error: Property 'foo' does not exist on type 'JSX.IntrinsicElements'. <a foo="bar"></a>; // => Error: Property 'foo' does not exist on type 'HtmlAnchorTag' We can't use props and components like we usually would in React, instead, a component will be a function call and the function arguments will be props. Now, what does the jsx factory even do? It transpiles the jsx into a string. That works for me, because I wanted to do the rending with a simple .innerHTML. But if you want to get some other kind of output, you could use some other factory or even make your own. You could also avoid using jsx and just use template literals instead. Before I started coding I also had to create an index.html file. /public/index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="theme-color" content="#000000" /> <title>App</title> </head> <body> <noscript>You need to enable JavaScript to run this app.</noscript> <div id="root"></div> <script src="bundle.js"></script> </body> </html> Rendering Now that everything was set up, it was time to dive into JavaScript. First I made a file called notReact.ts and put it inside of the /src folder. This file is where all of the rendering and state logic was located in. First I made a function closure and put two functions inside of it. One for initialization and one for rendering. export const notReact = (function() { let _root: Element; let _templateCallback: ITemplateCallback; function init(rootElement: Element, templateCallback: ITemplateCallback) { _root = rootElement; _templateCallback = templateCallback; render(); } function render() { _root.innerHTML = _templateCallback(); } return {init, render}; })(); type ITemplateCallback = { (): string; } init() has two arguments, a root element that will be used as a template container and a callback function that returns a string, containing all of the html. The render() function calls the template callback and assigns it to the .innerHTML of the root element. Next, I made the index.ts and the App.tsx file and put both of them inside of the /src folder. Then I initialized the rendering and called the App component inside of the index.ts file. import App from "./App"; import { notReact } from "./notReact"; const render = () => { const root = document.getElementById('root'); notReact.init(root, App); } window.addEventListener("DOMContentLoaded", () => render()); Inside of the App component I wrote a simple "Hello world". import * as elements from 'typed-html'; const App = () => { return ( <h1> Hello world; </h1> ); } export default App; State and event listeners Now that the rendering was done, it was time to write the useState hook, while also creating a basic counter application to test it out. First I created another component called Counter.tsx and put it inside of the components folder. I wrote it the same way it would be written in regular React, with the exception of the onClick event that I omitted for now. import * as elements from 'typed-html'; import { notReact } from '../notReact'; const Counter = () => { const [count, setCount] = notReact.useState(0); const increaseCounter = () => { setCount(count+1); } return ( <div> <h1>Counter: {count}</h1> <button>Increase count</button> </div> ); } export default Counter; After that, I had to change the App component: import * as elements from 'typed-html'; import Counter from './components/Counter'; const App = () => { return ( <div> {Counter()} </div> ); } export default App; With everything being ready, it was time to write the useState hook. export const notReact = (function() { let hooks: Array<any> = []; let idx: number = 0; function useState(initValue: any) { let state; state = hooks[idx] !== undefined ? hooks[idx] : initValue; const _idx = idx; const setState = (newValue: any) => { hooks[_idx] = newValue; render(); } idx++; return [state, setState]; } function render() { idx=0; //resets on rerender ... } return {useState, init, render}; })(); There are two local variables. An array variable called hooks that contains all of the state values. And the idx variable which is the index used to iterate over the hooks array. Inside of the useState() function, a state value together with a setter function get returned for each useState() call. Now we have a working useState hook, but we can't test it out yet. We need to add an onclick event listener to the button first. The problem here is that if we add it directly into the jsx, the function will be undefined because of the way the html is being rendered here. To fix this, I had to update the notReact.ts file again. export const notReact = (function() { const _eventArray: IEventArray = []; function render() { _eventArray.length = 0; //the array gets emptied on rerender ... document.addEventListener('click', (e) => handleEventListeners(e)); function handleEventListeners(e: any) { _eventArray.forEach((target: any) => { if (e.target.id === target.id) { e.preventDefault(); target.callback(); } }); } function addOnClick(id: string, callback: any) { _eventArray.push({id, callback}); } return {useState, useEffect, init, render, addOnClick}; })(); type IEventArray = [{id: string, callback: any}] | Array<any>; I made a local variable named eventArray. It's an array of objects, containing all elements that have an onclick event, together with a callback function for each of those events. The document has an onclick event listener. On each click it checks if the target element is equal to one of the event array elements. If it is, it fires it's callback function. Now let's update the Counter component so that the button has an onclick event: const Counter = () => { ... notReact.addOnClick("increaseCount", increaseCounter); ... return ( <div> <h1>Counter: {count}</h1> <button id="increaseCount">Increase count</button> </div> ); } Here is the result so far: Side effects The last thing that I added was the useEffect hook. Here is the code: export const notReact = (function() { let hooks: Array<any> = []; let idx: number = 0; function useEffect(callback: any, dependancyArray: Array<any>) { const oldDependancies = hooks[idx]; let hasChanged = true; if (oldDependancies) { hasChanged = dependancyArray.some((dep, i) => !Object.is(dep, oldDependancies[i])); } hooks[idx] = dependancyArray; idx++; if (hasChanged) callback(); } return {useState, useEffect, init, render, addOnClick}; })(); It saves dependancies from the last render and checks if they changed. If they did change the callback function gets called. Lets try it in action! I added a message bellow the button that changes if the counter gets higher than 5. Here is the final counter Component code:; Conclusion This is it! The component is looking a lot like actual React now. Changing it for React would be trivial, the only thing that would need to be changed is the onclick event and the imports. If you enjoy working in React, an approach like this might be worth trying out. Just keep in mind that this code is proof of concept, it isn't very tested and there are definitely a lot of bugs, especially when there are a lot of different states. The code has a lot of room for improvement and expansion. It's not a lot of code though, so it would be easy to change it based on your project requirements. For a more serious application, you would most likely have to implement some sort of event loop that would synchronize the state changes. I didn't go very in depth about my implementation of the useState and useEffect hooks. But if you want more details, you can check out this talk, it's what inspired my implementation. Again, all of the code can be found in this repository. Thank you for reading! 😁 Discussion (0)
https://dev.to/maturc/recreating-the-react-workflow-in-vanilla-javascript-449c
CC-MAIN-2022-21
en
refinedweb
Hello everyone, I am writing a custom python script to write up a stone map for me. Currently I iterate over all the block instances in the scene and assign them bounding boxes. The only problem is the orientation of the gym interferes with the bounding box measurements. If the gem is rotated 90+ degrees it will measure its depth as width. I have been looking for a way to measure the gems. Any help would be much appreciated. Here is a sample of the code: def measureGems(gems): gemDict = {} for gem in range(0, len(gems)): box = rs.BoundingBox(gems[gem]) if box: for i in range(0,len(box)): width = round(rs.Distance(box[0], box[1]),1) length = round(rs.Distance(box[0], box[3]),1) height = round(rs.Distance(box[0], box[4]),1) gemDict[ gems[gem] ] = (length, width) return gemDict
https://discourse.mcneel.com/t/rhino-python-custom-stonemap-tool-measure-block-instances-gemstones/38348
CC-MAIN-2022-21
en
refinedweb
¶ -.1 Changelog - Next: 0.9 Changelog - Up: Home - On this page: - 1.0 Changel 1.0 Changelog¶ 1.0.19. 1.0.18¶Released: July 24, 2017. tests¶ Fixed issue in testing fixtures which was incompatible with a change made as of Python 3.6.2 involving context managers. 1.0.17¶Released: January 17, 2017 orm¶ misc¶ Fixed Python 3.6 DeprecationWarnings related to escaped strings without the ‘r’ modifier, and added test coverage for Python 3.6. 1.0.16¶Released: November 15, 2016 orm¶ Fixed bug in Session.bulk_update_mappings()where an alternate-named primary key attribute would not track properly into the UPDATE statement. Fixed bug where joined eager loading would fail for a polymorphically- loaded mapper, where the polymorphic_on was set to an un-mapped expression such as a CASE expression. Fixed bug where the ArgumentError raised for an invalid bind sent to a Session via Session.bind_mapper(), Session.bind_table(), or the constructor would fail to be correctly raised. Fixed bug in Session.bulk_save()where an UPDATE would not function correctly in conjunction with a mapping that implements a version id counter. Fixed bug where the Mapper.attrs, Mapper.all_orm_descriptorsand other derived attributes would fail to refresh when mapper properties or other ORM constructs were added to the mapper/class after these accessors were first called.. Updated the server version info scheme for pyodbc to use SQL Server SERVERPROPERTY(), rather than relying upon pyodbc.SQL_DBMS_VER, which continues to be unreliable particularly with FreeTDS. Added error code 20017 “unexpected EOF from the server” to the list of disconnect exceptions that result in a connection pool reset. Pull request courtesy Ken Robbins.. misc¶ Fixed bug where setting up a single-table inh subclass of a joined-table subclass which included an extra column would corrupt the foreign keys collection of the mapped table, thereby interfering with the initialization of relationships. 1.0.15¶Released: September 1, 2016 orm¶ Fixed bug in subquery eager loading where a subqueryload of an “of_type()” object linked to a second subqueryload of a plain mapped class, or a longer chain of several “of_type()” attributes, would fail to link the joins correctly. sql¶ mysql¶ Added support for parsing MySQL/Connector boolean and integer arguments within the URL query string: connection_timeout, connect_timeout, pool_size, get_warnings, raise_on_warnings, raw, consume_results, ssl_verify_cert, force_ipv6, pool_reset_session, compress, allow_local_infile, use_pure. misc¶ Fixed bug in sqlalchemy.ext.bakedwhere the unbaking of a subquery eager loader query would fail due to a variable scoping issue, when multiple subquery loaders were involved. Pull request courtesy Mark Hahnenberg. 1.0.14¶Released: July 6, 2016 examples¶ Fixed a regression that occurred in the examples/vertical/dictlike-polymorphic.py example which prevented it from running. engine¶ Fixed bug in cross-schema foreign key reflection in conjunction with the MetaData.schemaargument, where a referenced table that is present in the “default” schema would fail since there would be no way to indicate a Tablethat has “blank” for a schema. The special symbol sqlalchemy.schema.BLANK_SCHEMAhas been added as an available value for Table.schemaand Sequence.schema, indicating that the schema name should be forced to be Noneeven if MetaData.schemais specified. sql¶ Fixed issue in SQL math negation operator where the type of the expression would no longer be the numeric type of the original. This would cause issues where the type determined result set behaviors. Fixed bug whereby the __getstate__/ __setstate__methods for sqlalchemy.util.Properties were non-working due to the transition in the 1.0 series to __slots__. The issue potentially impacted some third-party applications. Pull request courtesy Pieter Mulder. FromClause.count()is pending deprecation for 1.1. This function makes use of an arbitrary column in the table and is not reliable; for Core use, func.count()should be preferred.(). Fixed bug whereby Table.tometadata()would make a duplicate UniqueConstraintfor each Columnobject that featured the unique=Trueparameter. postgresql¶ Fixed bug whereby TypeDecoratorand Varianttypes were not deeply inspected enough by the PostgreSQL dialect to determine if SMALLSERIAL or BIGSERIAL needed to be rendered rather than SERIAL.. 1.0.13¶Released: May 16, 2016 orm¶ Fixed bug in “evaluate” strategy of Query.update()and Query.delete()which would fail to accommodate a bound parameter with a “callable” value, as which occurs when filtering by a many-to-one equality expression along a relationship. Fixed bug whereby the event listeners used for backrefs could be inadvertently applied multiple times, when using a deep class inheritance hierarchy in conjunction with multiple mapper configuration steps. Fixed bug whereby passing a text()construct to the Query.group_by()method would raise an error, instead of interpreting the object as a SQL fragment.. Fixed regression appearing in the 1.0 series in ORM loading where the exception raised for an expected column missing would incorrectly be a NoneTypeerror, rather than the expected NoSuchColumnError. examples¶ Changed the “directed graph” example to no longer consider integer identifiers of nodes as significant; the “higher” / “lower” references now allow mutual edges in both directions. sql¶ Fixed bug where when using case_sensitive=Falsewith an Engine, the result set would fail to correctly accommodate for duplicate column names in the result set, causing an error when the statement is executed in 1.0, and preventing the “ambiguous column” exception from functioning in 1.1. Fixed bug where the negation of an EXISTS expression would not be properly typed as boolean in the result, and also would fail to be anonymously aliased in a SELECT list as is the case with a non-negated EXISTS construct. Fixed bug where “unconsumed column names” exception would fail to be raised in the case where Insert.values()were called with a list of parameter mappings, instead of a single mapping of parameters. Pull request courtesy Athena Yao. postgresql¶ Added disconnect detection support for the error string “SSL error: decryption failed or bad record mac”. Pull request courtesy Iuri de Silvio. mssql¶ Fixed bug where by ROW_NUMBER OVER clause applied for OFFSET selects in SQL Server would inappropriately substitute a plain column from the local statement that overlaps with a label name used by the ORDER BY criteria of the statement.. oracle¶. misc¶ Fixed bug in “to_list” conversion where a single bytes object would be turned into a list of individual characters. This would impact among other things using the Query.get()method on a primary key that’s a bytes object. 1.0.12¶Released: February 15, 2016 orm¶. Fixed regression since 0.9 where the 0.9 style loader options system failed to accommodate for multiple undefer_group()loader options in a single query. Multiple undefer_group()options will now be taken into account even against the same entity. engine¶ Sessionand Connection, and taking place for operations such as a failure on “RELEASE SAVEPOINT”. Previously, the fix was only in place for a specific path within the ORM flush/commit process; it now takes place for all transactional context managers as well. sql¶ Fixed issue where the “literal_binds” flag was not propagated for insert(), update()or delete()constructs when compiled to string SQL. Pull request courtesy Tim Tate.. postgresql¶ mssql¶ Fixed the syntax of the extract()function when used on MSSQL against a datetime value; the quotes around the keyword are removed. Pull request courtesy Guillaume Doumenc.. oracle¶ Fixed a small issue in the Jython Oracle compiler involving the rendering of “RETURNING” which allows this currently unsupported/untested dialect to work rudimentarily with the 1.0 series. Pull request courtesy Carlos Rivas. misc¶ Fixed bug where some exception re-raise scenarios would attach the exception to itself as the “cause”; while the Python 3 interpreter is OK with this, it could cause endless loops in iPython. 1.0.11¶Released: December 22, 2015 orm¶ Fixed regression caused in 1.0.10 by the fix for #3593 where the check added for a polymorphic joinedload from a poly_subclass->class->poly_baseclass connection would fail for the scenario of class->poly_subclass->class.. Major fixes to the Mapper.eager_defaultsflag, this flag would not be honored correctly in the case that multiple UPDATE statements were to be emitted, either as part of a flush or a bulk update operation. Additionally, RETURNING would be emitted unnecessarily within update statements. Fixed bug where use of the Query.select_from()method would cause a subsequent call to the Query.with_parent()method to fail. sql¶ Fixed bug in Update.return_defaults()which would cause all insert-default holding columns not otherwise included in the SET clause (such as primary key cols) to get rendered into the RETURNING even though this is an UPDATE. mysql¶ An adjustment to the regular expression used to parse MySQL views, such that we no longer assume the “ALGORITHM” keyword is present in the reflected view source, as some users have reported this not being present in some Amazon RDS environments. Added new reserved words for MySQL 5.7 to the MySQL dialect, including ‘generated’, ‘optimizer_costs’, ‘stored’, ‘virtual’. Pull request courtesy Hanno Schlichting. misc¶ Further fixes to #3605, pop method on MutableDict, where the “default” argument was not included.. 1.0.10¶Released: December 11, 2015 orm¶ Fixed issue where post_update on a many-to-one relationship would fail to emit an UPDATE in the case where the attribute were set to None and not previously loaded.. orm declarative¶ Fixed bug where in Py2K a unicode literal would not be accepted as the string name of a class or other argument within declarative using backref()on relationship(). Pull request courtesy Nils Philippsen. sql¶ Added support for parameter-ordered SET clauses in an UPDATE statement. This feature is available by passing the update. Fixed bug where CREATE TABLE with a no-column table, but a constraint such as a CHECK constraint would render an erroneous comma in the definition; this scenario can occur such as with a PostgreSQL INHERITS table that has no columns of its own. postgresql¶ Fixed issue where the “FOR UPDATE OF” PostgreSQL-specific SELECT modifier would fail if the referred table had a schema qualifier; PG needs the schema name to be omitted. Pull request courtesy Diana Clarke. Fixed bug where some varieties of SQL expression passed to the “where” clause of ExcludeConstraintwould fail to be accepted correctly. Pull request courtesy aisch. Fixed the .python_typeattribute of INTERVALto return datetime.timedeltain the same way as that of python_type, rather than raising NotImplementedError. mysql¶ mssql¶ Added the error “20006: Write to the server failed” to the list of disconnect errors for the pymssql driver, as this has been observed to render a connection unusable. A descriptive ValueError is now raised in the event that SQL server returns an invalid date or time format from a DATE or TIME column, rather than failing with a NoneType error. Pull request courtesy Ed Avis. Fixed issue where DDL generated for the MSSQL types DATETIME2, TIME and DATETIMEOFFSET with a precision of “zero” would not generate the precision field. Pull request courtesy Jacobo de Vera. tests¶ The ORM and Core tutorials, which have always been in doctest format, are now exercised within the normal unit test suite in both Python 2 and Python 3. misc¶ Added support for the dict.pop()and dict.popitem()methods to the MutableDictclass.. 1.0.9¶Released: October 20, 2015 orm¶ Added new method Query.one_or_none(); same as Query.one()but returns None if no row found. Pull request courtesy esiegerman.. Fixed rare TypeError which could occur when stringifying certain kinds of internal column loader options within internal logging. Fixed bug in Session.bulk_save_objects()where a mapped column that had some kind of “fetch on update” value and was not locally present in the given object would cause an AttributeError within the operation. Fixed 1.0 regression where the “noload” loader strategy would fail to function for a many-to-one relationship. The loader used an API to place “None” into the dictionary which no longer actually writes a value; this is a side effect of #3061. examples¶ Fixed two issues in the “history_meta” example where history tracking could encounter empty history, and where a column keyed to an alternate attribute name would fail to track properly. Fixes courtesy Alex Fraser. sql¶ postgresql¶. oracle¶. This change is also backported to: 0.7.0b1. misc¶ Added the AssociationProxy.infoparameter to the AssociationProxyconstructor, to suit the AssociationProxy.infoaccessor that was added in #2971. This is possible because AssociationProxyis constructed explicitly, unlike a hybrid which is constructed implicitly via the decorator syntax.. 1.0.8¶Released: July 22, 2015 engine¶. This change is also backported to: 0.7.0b1 sqlite¶ Fixed bug in SQLite dialect where reflection of UNIQUE constraints that included non-alphabetic characters in the names, like dots or spaces, would not be reflected with their name. This change is also backported to: 0.9.10 misc¶. 1.0.7¶Released: July 20, 2015 orm¶. orm declarative¶. engine¶. Fixed regression where ResultProxy.keys()would return un-adjusted internal symbol names for “anonymous” labels, which are the “foo_1” types of labels we see generated for SQL functions without labels and similar. This was a side effect of the performance enhancements implemented as part of #918. sql¶ Added a ColumnElement.cast()method which performs the same purpose as the standalone cast()function. Pull request courtesy Sebastian Bank. Fixed bug where coercion of literal Trueor Falseconstant in conjunction with and_()or or_()would fail with an AttributeError. Fixed potential issue where a custom subclass of FunctionElementor other column element that incorrectly states ‘None’ or any other invalid object as the .typeattribute will report this exception instead of recursion overflow. Fixed bug where the modulus SQL operator wouldn’t work in reverse due to a missing __rmod__method. Pull request courtesy dan-gittik. schema¶ Added support for the MINVALUE, MAXVALUE, NO MINVALUE, NO MAXVALUE, and CYCLE arguments for CREATE SEQUENCE as supported by PostgreSQL and Oracle. Pull request courtesy jakeogh. 1.0.6¶Released: June 25, 2015 orm¶. Fixed 1.0 regression where the enhanced behavior of single-inheritance joins of #3222 takes place inappropriately for a JOIN along explicit join criteria with a single-inheritance subclass that does not make use of any discriminator, resulting in an additional “AND NULL” clause. Fixed bug in new Session.bulk_update_mappings()feature where the primary key columns used in the WHERE clause to locate the row would also be included in the SET clause, setting their value to themselves unnecessarily. Pull request courtesy Patrick Hayes.. sql¶. postgresql¶. Repaired the ExcludeConstraintconstruct to support common features that other objects like Indexnow do, that the column expression may be specified as an arbitrary SQL expression such as castor text. mssql¶. misc¶ Fixed an internal “memoization” routine for method types such that a Python descriptor is no longer used; repairs inspectability of these methods including support for Sphinx documentation. 1.0.5¶Released: June 7, 2015 orm¶. The “lightweight named tuple” used when a Queryreturns rows failed to implement __slots__correctly such that it still had a __dict__. This is resolved, but in the extremely unlikely case someone was assigning values to the returned tuples, that will no longer work. engine¶ Added new engine event ConnectionEvents.engine_disposed(). Called after the Engine.dispose()method is called. Adjustments to the engine plugin hook, such that the URL.get_dialect()method will continue to return the ultimate Dialectobject when a dialect plugin is used, without the need for the caller to be aware of the Dialect.get_dialect_cls()method. Fixed bug where known boolean values used by engine_from_config()were not being parsed correctly; these included pool_threadlocaland the psycopg2 argument use_native_unicode.. mssql¶ Added support for *argsto be passed to the baked query initial callable, in the same way that *argsare supported for the BakedQuery.add_criteria()and BakedQuery.with_criteria()methods. Initial PR courtesy Naoki INADA.. 1.0.4¶Released: May 7, 2015 orm¶. schema¶ tests¶ Fixed an import that prevented “pypy setup.py test” from working correctly. This change is also backported to: 0.9.10 misc¶ Fixed bug where when using extended attribute instrumentation system, the correct exception would not be raised when class_mapper()were called with an invalid input that also happened to not be weak referencable, such as an integer. This change is also backported to: 0.9.10 1.0.3¶Released: April 30, 2015 orm¶ Fixed regression from 0.9.10 prior to release due to #3349 where the check for query state on Query.update()or Query.delete()compared the empty tuple to itself using is, which fails on PyPy to produce Truein this case; this would erroneously emit a warning in 0.9 and raise an exception in 1.0. Fixed regression from 0.9.10 prior to release where the new addition of entityto the Query.column_descriptionsaccessor would fail if the target entity was produced from a core selectable such as a Tableor CTEobject. Fixed regression within the flush process when an attribute were set to a SQL expression for an UPDATE, and the SQL expression when compared to the previous value of the attribute would produce a SQL comparison other than. Fixed issue in new QueryEvents.before_compile()event where changes made to the Queryobject’s collection of entities to load within the event would render in the SQL, but would not be reflected during the loading process. engine¶()is added to complement it. Also added new flag ExceptionContext.invalidate_pool_on_disconnect. Allows an error handler within ConnectionEvents.handle_error()to maintain a “disconnect” condition, but to handle calling invalidate on individual connections in a specific manner within the event. Added new event do_connect, which allows interception / replacement of when the Dialect.connect()hook is called to create a DBAPI connection. Also added dialect plugin hooks Dialect.get_dialect_cls()and Dialect.engine_created()which allow external plugins to add events to existing dialects using entry points. sql¶ Added a placeholder method TypeEngine.compare_against_backend()which is now consumed by Alembic migrations as of 0.7.6. User-defined types can implement this method to assist in the comparison of a type against one reflected from the database.. misc¶ Fixed bug in association proxy where an any()/has() on an relationship->scalar non-object attribute comparison would fail, e.g. filter(Parent.some_collection_to_attribute.any(Child.attr == 'foo')) 1.0.2¶Released: April 24, 2015 orm declarative¶ Fixed unexpected use regression regarding the declarative __declare_first__and __declare_last__accessors where these would no longer be called on the superclass of the declarative base. sql¶ Labelconstruct that is also present in the columns clause. Additionally, no backend will emit GROUP BY against the simple label name only when passed a Labelconstruct. 1.0.1¶Released: April 23, 2015 orm¶ Fixed unexpected use regression cause by #3061 where the NEVER_SET symbol could leak into relationship-oriented queries, including. engine¶ Added the string value "none"to those accepted by the Pool.reset_on_returnparameter as a synonym for None, so that string values can be used for all settings, allowing utilities like engine_from_config()to be usable without issue. This change is also backported to: 0.9.10 sql¶()). sqlite¶ Fixed a regression due to #3034 where limit/offset clauses were not properly interpreted by the Firebird dialect. Pull request courtesy effem-git. Fixed support for “literal_binds” mode when using limit/offset with Firebird, so that the values are again rendered inline when this is selected. Related to #3034. 1.0.0¶Released: April 16, 2015 orm¶ Added new argument Query.update.update_argswhich allows kw arguments such as mysql_limitto be passed to the underlying Updateconstruct. Pull request courtesy Amir Sadoughi.. sql¶ The topological sorting used to sort. Fixed issue where a MetaDataobject that used a naming convention would not properly work with pickle. The attribute was skipped leading to inconsistencies and failures if the unpickled MetaDataobject were used to base additional tables from. This change is also backported to: 0.9.10 postgresql¶ Fixed a long-standing bug where the Enumtype as used with the psycopg2 dialect in conjunction with non-ascii values and native_enum=Falsewould fail to decode return results properly. This stemmed from when the PG ENUMtype used to be a standalone type without a “non native” option. This change is also backported to: 0.9.10 mssql¶. Using the Binaryconstructor now present in pymssql rather than patching one in. Pull request courtesy Ramiro Morales. tests¶. 1.0.0b5¶Released: April 3, 2015 orm¶. This change is also backported to: 0.9.10. Added a list() call around a weak dictionary used within the commit phase of the session, which without it could cause a “dictionary changed size during iter” error if garbage collection interacted within the process. Change was introduced by #3139.. sql¶. postgresql¶ 1.0.0b4¶Released: March 29, 2015 sql¶ Fixed bug in new “label resolution” feature of #2992 where a label that was anonymous, then labeled again with a name, would fail to be locatable via a textual label. This situation occurs naturally when a mapped column_property()is given an explicit label in a query. Fixed bug in new “label resolution” feature of #2992 where the string label placed in the order_by() or group_by() of a statement would place higher priority on the name as found inside the FROM clause instead of a more locally available name inside the columns clause. schema¶ mysql¶ Repaired the commit for issue #2771 which was inadvertently commented out. 1.0.0b2¶Released: March 20, 2015 orm¶ Fixed unexpected use regression from pullreq github:137 where Py2K unicode literals (e.g. u"") would not be accepted by the relationship.cascadeoption. Pull request courtesy Julien Castets. orm declarative¶. engine¶ The “auto close” for ResultProxyis now a “soft” close. That is, after exhausting Fixed the BITtype on Py3K which was not using the ord()function correctly. Pull request courtesy David Marin. This change is also backported to: 0.9.10 Structural memory use has been improved via much more significant use of _. The __module__attribute is now set for all those SQL and ORM functions that are derived as “public factory” symbols, which should assist with documentation tools being able to report on the target module.. The subquery wrapping which occurs when joined eager loading is used with a one-to-many query that also features LIMIT, OFFSET, or DISTINCT has been disabled in the case of a one-to-one relationship, that is a one-to-many with relationship.uselistset to False. This will produce more efficient queries in these cases.. A new series of Sessionmethods Added a parameter Query.join.isouterwhich is synonymous with calling Query.outerjoin(); this flag is to provide a more consistent interface compared to Core FromClause.join(). Pull request courtesy Jonathan Vanasco. Added new event handlers AttributeEvents.init_collection()and AttributeEvents.dispose_collection(), which track when a collection is first associated with an instance and when it is replaced. These handlers supersede the collection.linker()annotation. The old hook remains supported through an event adapter. The(). A new implementation for KeyedTupleused by the Queryobject offers dramatic speed improvements when fetching large numbers of column-oriented rows. The behavior of joinedload.innerjoinas well as relationship.innerjoinis now to use “nested” inner joins, that is, right-nested, as the default behavior when an inner join joined eager load is chained to an outer join eager load.. The infoparameter has been added to the constructor for SynonymPropertyand ComparableProperty. The InspectionAttr.infocollection is now moved down to InspectionAttr, where in addition to being available on all MapperPropertyobjects, it is also now available on hybrid properties, association proxies, when accessed via Mapper.all_orm_descriptors.. The proc()callable passed to the create_row_processor()method of custom Bundleclasses now accepts only a single “row” argument. Deprecated event hooks removed: populate_instance, create_instance, translate_row, append_result See also Deprecated ORM Event Hooks Removed.9.5,.9.5, 0.8.7. This change is also backported to: 0.9.9 Fixed bug where internal assertion would fail in the case where an after_rollback()handler for a Sessionincorrectly adds state to that Sessionwithin the handler, and the task to warn and remove this state (established by #2389) attempts to proceed. This change is also backported to: 0.9.9 Fixed bug where TypeError raised when Query.join()called with unknown kw arguments would raise its own TypeError due to broken formatting. Pull request courtesy Malthe Borch. Fixed bug regarding expression mutations which could express itself as a “Could not locate column” error when using Queryto select from multiple, anonymous column entities when querying against SQLite, as a side effect of the “join rewriting” feature used by the SQLite dialect. This change is also backported to: 0.9.9 Fixed bug where the ON clause for Query.join(), and Query.outerjoin()to a single-inheritance subclass using of_type()would not render the “single table criteria” in the ON clause if the from_joinpoint=Trueflag were set. This change is also backported to: 0.9.9. This change is also backported to: 0.9.8. This change is also backported to: 0.9.8 Fixed warning that would emit when a complex self-referential primaryjoin contained functions, while at the same time remote_side was specified; the warning would suggest setting “remote side”. It now only emits if remote_side isn’t present. This change is also backported to: 0.9.8. This change is also backported to: 0.9.7. This change is also backported to: 0.9.7 Fixed bug where items that were persisted, deleted, or had a primary key change within a savepoint block would not participate in being restored to their former state (not in session, in session, previous PK) after the outer transaction were rolled back. This change is also backported to: 0.9.7 Fixed bug in subquery eager loading in conjunction with with_polymorphic(), the targeting of entities and columns in the subquery load has been made more accurate with respect to this type of entity and others. This change is also backported to: 0. This change is also backported to: 0.9.5. This change is also backported to: 0.9.5. This change is also backported to: 0.9.5. This change is also backported to: 0.9.5 Fixed bug in SQLite join rewriting where anonymized column names due to repeats would not correctly be rewritten in subqueries. This would affect SELECT queries with any kind of subquery + join. This change is also backported to: 0.9.5. This change is also backported to: 0.9.5 Fixed bug where the session attachment error “object is already attached to session X” would fail to prevent the object from also being attached to the new session, in the case that execution continued after the error raise occurred. The primary. Repaired support of the copy.deepcopy()call when used by the CascadeOptionsargument, which occurs if copy.deepcopy()is being used with relationship()(not an officially supported use case). Pull request courtesy duesenfranz. Fixed bug where Session.expunge()would not fully detach the given object if the object had been subject to a delete operation that was flushed, but not committed. This would also affect related operations like make_transient(). The. Improvements to the mechanism used by Sessionto locate “binds” (e.g. engines to use), such engines can be associated with mixin classes, concrete subclasses, as well as a wider variety of table metadata such as joined inheritance tables.. The ON clause rendered when using Query.join(), Query.outerjoin(), or the standalone join()/. A major rework to the behavior of expression labels, most specifically when used with ColumnProperty constructs with custom SQL expressions and in conjunction with the “order by labels” logic first introduced in 0.9. Fixes include that an. Changed the approach by which the “single inheritance criterion” is applied, when using. The “resurrect” ORM event has been removed. This event hook had no purpose since the old “mutable attribute” system was removed in 0.8.. The IdentityMapexposed from Session.identity_mapnow returns lists for items()and values()in Py3K. Early porting to Py3K here had these returning iterators, when they technically should be “iterable views”..for now, lists are OK. The. Fixed “‘NoneType’ object has no attribute ‘concrete’” error when using AbstractConcreteBasein conjunction with a subclass that declares __abstract__. This change is also backported to: 0.9.8 Fixed bug where using an __abstract__mixin in the middle of a declarative inheritance hierarchy would prevent attributes and configuration being correctly propagated from the base class to the inheriting class. A relationship set up with declared_attron a AbstractConcreteBasebase class will now be configured on the abstract base mapping automatically, in addition to being set up on descendant concrete classes as usual. examples¶ Added a new example illustrating materialized paths, using the latest relationship features. Example courtesy Jack Zhou. This change is also backported to: 0.9.5. This change is also backported to: 0.9.9 Fixed a bug in the examples/generic_associations/discriminator_on_association.py example, where the subclasses of AddressAssociation were not being mapped as “single table inheritance”, leading to problems when trying to use the mappings further. This change is also backported to: 0.9.9 engine¶ Added new user-space accessors for viewing transaction isolation levels; Connection.get_isolation_level(), Connection.default_isolation_level. This change is also backported to: 0.9.9 Added new event ConnectionEvents.handle_error(), a more fully featured and comprehensive replacement for ConnectionEvents.dbapi_error(). This change is also backported to: 0.9.7 The engine-level error handling and wrapping routines will now take effect in all engine connection use cases, including when user-custom connect routines are used via the create_engine.creatorparameter, as well as when the Connectionencounters a connection error on revalidation. Removing (or adding) an event listener at the same time that the event is being run itself, either from inside the listener or from a concurrent thread, now raises a RuntimeError, as the collection used is now an instance of collections.deque()and does not support changes while being iterated. Previously, a plain Python list was used where removal from inside the event itself would produce silent failures.(). This change is also backported to: 0.9.5. This change is also backported to: 0.9.5. Literal values within a DefaultClause, which is invoked when using the Column.server_defaultparameter, will now be rendered using the “inline” compiler, so that they are rendered as-is, rather than as bound parameters. The type of expression is reported when an object passed to a SQL expression unit can’t be interpreted as a SQL fragment; pull request courtesy Ryan P. Kelly.. Insert.from_select()now includes Python and SQL-expression defaults if otherwise unspecified; the limitation where non- server column defaults aren’t included in an INSERT FROM SELECT is now lifted and these expressions are rendered as constants into the SELECT statement.. Added new method Select.with_statement_hint()and ORM method Query.with_statement_hint()to support statement-level hints that are not specific to a table. The infoparameter has been added as a constructor argument to all schema constructs including MetaData, Index, ForeignKey, ForeignKeyConstraint, UniqueConstraint, PrimaryKeyConstraint, CheckConstraint. The Table.autoload_withflag now implies that Table.autoloadshould be True. Pull request courtesy Malik Diarra., The column()and table()constructs are now importable from the “from sqlalchemy” namespace, just like every other Core construct. The implicit conversion of strings to text()constructs when passed to most builder methods of select()as well as. Fixed bug in Enumand other SchemaTypesubclasses where direct association of the type with a MetaDatawould lead to a hang when events (like create events) were emitted on the MetaData. This change is also backported to: 0.9.7, 0.8.7 Fixed a bug within the custom operator plus TypeEngine.with_variant()system, whereby using a TypeDecoratorin conjunction with variant would fail with an MRO error when a comparison operator was used. This change is also backported to: 0.9.7, 0.8.7 Fixed bug in INSERT..FROM SELECT construct where selecting from a UNION would wrap the union in an anonymous (e.g. unlabeled) subquery. This change is also backported to: 0.9.5, 0.8.7 Fixed bug where Table.update()and Table.delete()would produce an empty WHERE clause when an empty and_()or or_()or other blank expression were applied. This is now consistent with that of This change is also backported to: 0.9.5, 0.8.7 Added the native_enumflag to the __repr__()output of Enum, which is mostly important when using it with Alembic autogenerate. Pull request courtesy Dimitris Theodorou. This change is also backported to: 0.9.9. This change is also backported to: 0.9.9. This change is also backported to: 0.9.9 Fixed bug where a fair number of SQL elements within the sql package would fail to __repr__()successfully, due to a missing descriptionattribute that would then invoke a recursion overflow when an internal AttributeError would then re-invoke __repr__(). This change is also backported to: 0.9.8 An adjustment to table/index reflection such that if an index reports a column that isn’t found to be present in the table, a warning is emitted and the column is skipped. This can occur for some special system column situations as has been observed with Oracle. This change is also backported to: 0.9.8 Fixed bug in CTE where literal_bindscompiler argument would not be always be correctly propagated when one CTE referred to another aliased CTE in a statement. This change is also backported to: 0.9.8 Fixed 0.9.7 regression caused by #3067 in conjunction with a mis-named unit test such that so-called “schema” types like Booleanand Enumcould no longer be pickled. This change is also backported to: 0.9.8. This change is also backported to: 0.9.7 Fixed bug in common table expressions whereby positional bound parameters could be expressed in the wrong final order when CTEs were nested in certain ways. This change is also backported to: 0.9.7 Fixed bug where multi-valued Insertconstruct would fail to check subsequent values entries beyond the first one given for literal SQL expressions. This change is also backported to: 0.9.7 Added a “str()” step to the dialect_kwargs iteration for Python version < 2.6.5, working around the “no unicode keyword arg” bug as these args are passed along as keyword args within some reflection processes. This change is also backported to: 0.9.7 The TypeEngine.with_variant()method will now accept a type class as an argument which is internally converted to an instance, using the same convention long established by other constructs such as Column. This change is also backported to: 0. This change is also backported to: 0.9.5 Fixed bug where the Operators.__and__(), Operators.__or__()and Operators.__invert__()operator overload methods could not be overridden within a custom Comparatorimplementation. This change is also backported to: 0.9.5 Fixed bug in new DialectKWArgs.argument_for()method where adding an argument for a construct not previously included for any special arguments would fail. This change is also backported to: 0.9.5 Fixed regression introduced in 0.9 where new “ORDER BY <labelname>” feature from #1068 would not apply quoting rules to the label name as rendered in the ORDER BY. This change is also backported to: 0.9.5 Restored the import for Functionto the sqlalchemy.sql.expressionimport namespace, which was removed at the beginning of 0.9. This change is also backported to: 0.9.5 The multi-values version of. Fixed bug in Table.tometadata()method where the CheckConstraintassociated with a Booleanor Enumtype object would be doubled in the target table. The copy process now tracks the production of this constraint object as local to a type object. The behavioral contract of the ForeignKeyConstraint.columnscollection has been made consistent; this attribute is now a ColumnCollectionlike that of all other constraints and is initialized at the point when the constraint is associated with a Table.. Fixed the name of the PoolEvents.reset.dbapi_connectionparameter as passed to this event; in particular this affects usage of the “named” argument style for this event. Pull request courtesy Jason Goldberger. Reversing a change that was made in 0.9, the “singleton” nature of the “constants” null(), true(), and false()has been reverted. These functions returning a “singleton” object had the effect that different instances would be treated as the same regardless of lexical use, which in particular would impact the rendering of the columns clause of a SELECT statement.. Using Insert.from_select()now implies inline=Trueaccessor does not apply. Previously, there was a documentation note that one may prefer inline=Truew.. schema¶ The DDL generation system of. Added a new accessor Table.foreign_key_constraintsto complement the Table.foreign_keyscollection, as well as ForeignKeyConstraint.referred_table. The Added support for the CONCURRENTLYkeyword with PostgreSQL indexes, established using postgresql_concurrently. Pull request courtesy Iuri de Silvio. See also Indexes with CONCURRENTLY This change is also backported to: 0.9.9 Support is added for “sane multi row count” with the pg8000 driver, which applies mostly to when using versioning with the ORM. The feature is version-detected based on pg8000 1.9.14 or greater in use. Pull request courtesy Tony Locke. This change is also backported to: 0.9.8 Added kw argument postgresql_regconfigto the ColumnOperators.match()operator, allows the “reg config” argument to be specified to the to_tsquery()function emitted. Pull request courtesy Jonathan Vanasco. This change is also backported to: 0.9.7 Added support for PostgreSQL JSONB via JSONB. Pull request courtesy Damian Dimmich. This change is also backported to: 0.9.7 Added support for AUTOCOMMIT isolation level when using the pg8000 DBAPI. Pull request courtesy Tony Locke. This change is also backported to: 0.9.5. This change is also backported to: 0.9.5 The PG8000 dialect now supports the create_engine.encodingparameter, by setting up the client encoding on the connection which is then intercepted by pg8000. Pull request courtesy Tony Locke. Added support for PG8000’s native JSONB feature. Pull request courtesy Tony Locke. Added support for the psycopg2cffi DBAPI on pypy. Pull request courtesy shauns. Added support for the FILTER keyword as applied to aggregate functions, supported by PostgreSQL 9.4. Pull request courtesy Ilja Everilä. See also PostgreSQL FILTER keyword Support has been added for reflection of materialized views and foreign tables, as well as support for materialized views within Inspector.get_view_names(), and a new method PGInspector.get_foreign_table_names()available on the PostgreSQL version of Inspector. Pull request courtesy Rodrigo Menezes. Added support for PG table options TABLESPACE, ON COMMIT, WITH(OUT) OIDS, and INHERITS, when rendering DDL via the Tableconstruct. Pull request courtesy malikdiarra. See also Added new method PGInspector.get_enums(), when using the inspector for PostgreSQL will provide a list of ENUM types. Pull request courtesy Ilya Pekelny..9.5, 0.8.7 Added a new “disconnect” message “connection has been closed unexpectedly”. This appears to be related to newer versions of SSL. Pull request courtesy Antti Haapala. Fixed bug in arrayobject where comparison to a plain Python list would fail to use the correct array constructor. Pull request courtesy Andrew. This change is also backported to: 0.9.8. This change is also backported to: 0.9.8 Fixed bug introduced in 0.9.5 by new pg8000 isolation level feature where engine-level isolation level parameter would raise an error on connect. This change is also backported to: 0. This change is also backported to: 0.9.5 The. The The MySQL dialect now renders TIMESTAMP with NULL / NOT NULL in all cases, so that MySQL 5.6.6 with the explicit_defaults_for_timestampflag enabled will will allow TIMESTAMP to continue to work as expected when nullable=False. Existing applications are unaffected as SQLAlchemy has always emitted NULL for a TIMESTAMP column that is nullable=True.. The gaerdbmsdialect is no longer necessary, and emits a deprecation warning. Google now recommends using the MySQLdb dialect directly. This change is also backported to: 0.9.9.9.7, 0.8.7.9.5, 0.8.7 Added support for reflecting tables where an index includes KEY_BLOCK_SIZE using an equal sign. Pull request courtesy Sean McGivern. This change is also backported to: 0.9.5, 0.8.7 Added a version check to the MySQLdb dialect surrounding the check for ‘utf8_bin’ collation, as this fails on MySQL server < 5.0. This change is also backported to: 0.9.9 This change is also backported to: 0.9.8 Unicode SQL is now passed for MySQLconnector version 2.0 and above; for Py2k and MySQL < 2.0, strings are encoded. This change is also backported to: 0.9.8 The MySQL dialect now supports CAST on types that are constructed as TypeDecoratorobjects.. The SETthat actually wants to include the blank value SET.retrieve_as_bitwiseflag, which will persist and retrieve values unambiguously using their bitflag positioning. Storage and retrieval of unicode values for driver configurations that aren’t converting unicode natively is also repaired. true()and false()symbols again produce the keywords “true” and “false”, so that an expression like column.is_(true())again works on MySQL. The MySQL dialect will now disable ConnectionEvents.handle_error()events from firing for those statements which it uses internally to detect if a table exists or not. This is achieved using an execution option skip_user_error_eventsthat” to False for MySQLconnector. This was set at True for some reason. The “buffered” flag unfortunately must stay at True as MySQLconnector does not allow a cursor to be closed unless all results are fully fetched. sqlite¶ Added support for partial indexes (e.g. with a WHERE clause) on SQLite. Pull request courtesy Kai Groner. See also This change is also backported to: 0.9.9 UNIQUE and FOREIGN KEY constraints are now fully reflected on SQLite both with and without names. Previously, foreign key names were ignored and unnamed unique constraints were skipped. Thanks to Jon Nelson for assistance with this. The SQLite dialect, when using the DATE, TIME, or. Added Enabled “multivalues insert” for SQL Server 2008. Pull request courtesy Albert Cervin. Also expanded the checks for “IDENTITY INSERT” mode to include when the identity key is present in the VALUEs clause of the statement. This change is also backported to: 0.9.7 Fixed the version string detection in the pymssql dialect to work with Microsoft SQL Azure, which changes the word “SQL Server” to “SQL Azure”. This change is also backported to: 0.9.8 Revised the query used to determine the current default schema name to use the database_principal_id()function in conjunction with the sys.database_principalsview so that we can determine the default schema independently of the type of login in progress (e.g., SQL Server, Windows, etc). This change is also backported to: 0.9.5 oracle¶ Added support for cx_oracle connections to a specific service name, as opposed to a tns name, by passing ?service_name=<name>to the URL. Pull request courtesy Sławomir Ehlert. New Oracle DDL features for tables, indexes: COMPRESS, BITMAP. Patch courtesy Gabor Gombas. Added support for the Oracle table option ON COMMIT. Fixed long-standing bug in Oracle dialect where bound parameter names that started with numbers would not be quoted, as Oracle doesn’t like numerics in bound parameter names. This change is also backported to: 0.9.8 Fixed bug in oracle dialect test suite where in one test, ‘username’ was assumed to be in the database URL, even though this might not be the case. This change is also backported to: 0.9.7 An alias name will be properly quoted when referred to using the %(name)stoken inside the Select.with_hint()method. Previously, the Oracle backend hadn’t implemented this quoting. tests¶ Fixed bug where “python setup.py test” wasn’t calling into distutils appropriately, and errors would be emitted at the end of the test suite. This change is also backported to: 0.9.7 Corrected for some deprecation warnings involving the impmodule and Python 3.3 or greater, when running tests. Pull request courtesy Matt Chisholm. This change is also backported to: 0.9.5 misc¶ Added a new extension suite sqlalchemy.ext.baked. This simple but unusual system allows for a dramatic savings in Python overhead for the construction and processing of orm Queryobjects, from query construction up through rendering of a string SQL statement. See also The sqlalchemy.ext.automapextension will now set cascade="all, delete-orphan"automatically on a one-to-many relationship/backref where the foreign key is detected as containing one or more non-nullable columns. This argument is present in the keywords passed..9.5, 0.8.7 Fixed bug in mutable extension where MutableDictdid not report change events for the setdefault()dictionary operation. This change is also backported to: 0.9.5, 0.8.7 Fixed bug where MutableDict.setdefault()didn’t return the existing or new value (this bug was not released in any 0.8 version). Pull request courtesy Thomas Hervé. This change is also backported to: 0.9.5, 0.8.7 Fixed bug where the association proxy list class would not interpret slices correctly under Py3K. Pull request courtesy Gilles Dartiguelongue. This change is also backported to: 0.9.9. This change is also backported to: 0.9.8 Fixed bug in ordering list where the order of items would be thrown off during a collection replace event, if the reorder_on_append flag were set to True. The fix ensures that the ordering list only impacts the list that is explicitly associated with the object. This change is also backported to: 0.9.8 Fixed bug where MutableDictfailed to implement the update()dictionary method, thus not catching changes. Pull request courtesy Matt Chisholm. This change is also backported to: 0.9.8 Fixed bug where a custom subclass of MutableDictwould not show up in a “coerce” operation, and would instead return a plain MutableDict. Pull request courtesy Matt Chisholm. This change is also backported to: 0.9.8. This change is also backported to: 0.9.8 Fixed bug when the declarative __abstract__flag was not being distinguished for when it was actually the value False. The __abstract__flag needs to actually evaluate to a True value at the level being tested. This change is also backported to: 0.9.7 In public test suite, changed to use of String(40)from less-supported Textin StringTest.test_literal_backslashes. Pullreq courtesy Jan. This change is also backported to: 0.9.5 The Drizzle dialect has been removed from the Core; it is now available as sqlalchemy-drizzle, an independent, third party dialect. The dialect is still based almost entirely off of the MySQL dialect present in SQLAlchemy. flambé! the dragon and The Alchemist image designs created and generously donated by Rotem Yaari.Created using Sphinx 4.5.0.
https://docs.sqlalchemy.org/en/14/changelog/changelog_10.html
CC-MAIN-2022-21
en
refinedweb
OVERVIEW In this blog, I will show you, - How to Create the project on the firebase. - how to write/update the data to the real-time database on the firebase. Now, let’s get started and understand how to do it. Firstly let’s create the project on firebase. Creating a project on Firebase Firstly, go to and sign in to get started. After that click on “Go to console” as shown here, After that, you will see all the project if you have already created before but if you are creating it for the first time then it will redirect you to create a project but if it doesn’t redirect you automatically the click on “Add project” as shown below, Then, it will ask you to enter the project name which should be unique. Also, it will suggest the names if the name provided by you is not available. Then, on the next page it will ask you to enable for “Google Analytics for your Firebase project”, enable it and press on “continue”. After that, it will ask you to select the account. Select the account you are using and then click on “Create project”. Then, it will create a project for you with in a minute. So, the project is ready and now you can create your real-time database to read/update/write the data to the database. Now click on “Database”, which will open a new webpage for you and on to that webpage click on “Create database”. It will open a pop up window for you and in that window select “Start in test mode” and then click on “Next”. Then on the next page click on “Done” and your real-time database is ready for use. Now select “Real-time Database”, Now you can write the code for NodeMCU in Arduino IDE for reading/writing/updating the database. You can also check this for more clarification, Now, we have setup the real-time database on firebase. So, it’s time to write the code for the integration of Firebase with NodeMCU. Writing/Updating the data to Firebase Once you are ready with the project on firebase with a real-time database. Now we can go ahead and write the code that needs to be uploaded to the Nodemcu to write/update the data to the real-time database on firebase. Before that one more thing you have to set up, that is, to interface any input device/component with the NodeMCU whose value you are going to upload to the Real-Time database. In our case, we will be using the IR(Infrared) sensor to read the signal and to further update it. So let’s first interface the NodeMCU with the IR sensor. Interfacing IR sensor to NodeMCU Now you have to interface NodeMCU with IR sensor as shown below in the circuit diagram. Circuit Connections: Once you are done with the circuit interface. We can move ahead to write the program as per the circuit interfaced. Firstly, open Arduino IDE and follow the path Sketch > Include Library > Manage Libraries… and search for “Arduino JSON” and install it as shown here. After, the installation check out this link to download FirebaseArduino Download Firebase-Arduino library Now, add the downloaded zip file to Arduino by following this path Sketch > Include Library > Add .ZIP Library… this will add the FirebaseArduino library to the Arduino path. Now write the code given below: #include <ESP8266WiFi.h> #include <FirebaseArduino.h> #define FIREBASE_HOST "******************.firebaseio.com" #define FIREBASE_AUTH "***********************************" #define WIFI_SSID "***********" #define WIFI_PASSWORD "**************" int sensor=D1; void setup() { Serial.begin(115200); pinMode(sensor,INPUT); WiFi.begin(WIFI_SSID, WIFI_PASSWORD); Serial.print("Connecting to "); Serial.print(WIFI_SSID); while (WiFi.status() != WL_CONNECTED) { Serial.print("."); delay(500); } Serial.println(); Serial.print("Connected"); Serial.print("IP Address: "); Serial.println(WiFi.localIP()); //prints local IP address Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH); // connect to the firebase } void loop() { int h = digitalRead(sensor); if (isnan(h)) // Checking sensor working { Serial.println(F("Failed to read from sensor!")); return; } if (h==0){ Firebase.pushString("Light", “OFF”); //setup path to send light readings } else{ Firebase.pushString("Light", “ON”); } if (Firebase.failed()) { Serial.print("pushing /logs failed:"); Serial.println(Firebase.error()); return; } delay(2000); } In here you have to enter the FIREBASE_HOST and FIREBASE_AUTH that you will get from the firebase. Check this to know more: Once you are done with this code. Connect the NodeMCU to the system and then upload the code. This is how you can easily connect the firebase to the NodeMCU and apply Internet of things to your devices. You can also check this for more clarification, Time to wrap up now. Hope you liked our content on How to send real-time sensor data to google firebase. “Easily Send Real-Time Sensor Data to Google Firebase with ESP8266” Code does not compile. In file included from C:\Users\cagan\Documents\Arduino\libraries\firebase-arduino-master\src/Firebase.h:30:0, ^ ^ from C:\Users\cagan\Documents\Arduino\libraries\firebase-arduino-master\src/FirebaseArduino.h:22, from C:\Users\cagan\Desktop\sketch_apr11c\sketch_apr11c.ino:2: C:\Users\cagan\Documents\Arduino\libraries\firebase-arduino-master\src/FirebaseObject.h:109:11: error: StaticJsonBuffer is a class from ArduinoJson 5. Please see arduinojson.org/upgrade to learn how to upgrade your program to ArduinoJson version 6 std::shared_ptr<StaticJsonBuffer> buffer_; In file included from C:\Users\cagan\Documents\Arduino\libraries\firebase-arduino-master\src/FirebaseArduino.h:22:0, from C:\Users\cagan\Desktop\sketch_apr11c\sketch_apr11c.ino:2: C:\Users\cagan\Documents\Arduino\libraries\firebase-arduino-master\src/Firebase.h:86:11: error: StaticJsonBuffer is a class from ArduinoJson 5. Please see arduinojson.org/upgrade to learn how to upgrade your program to ArduinoJson version 6 std::shared_ptr<StaticJsonBuffer> buffer_; exit status 1 Error compiling for board NodeMCU 1.0 (ESP-12E Module).
https://innovationyourself.com/send-real-time-data-to-firebase/
CC-MAIN-2022-21
en
refinedweb
I am trying to use mp-api and MPR.query(formula=‘Fe2O3’, fields=[…]) to query Fe2O3-related information from the Materials Project. May I ask how to retrieve the icsd_ids and corresponding BibTex Citation? They are displayed in the web app as follows but I didn’t find a relevant keyword to put in ‘fields’. Thanks! Hi, I think the screenshot that you have shared is from the legacy site (legacy.materialsproject.org), while the mp-api is primarily designed to interact with the new Materials Project site (next-gen.materialsproject.org). Most of the information will likely be the same, but the new site is constantly being updated while the legacy site is now frozen. Link to documentation for the API: Materials Project API - Swagger UI For using the mp-api: If you know the material project id (MP ID) for the Fe2O3 material of interest (for example, mp-19770), then you can query the provenance doc directly. The two key fields are “database_IDs” which will retrieve the ICSD IDs and the “references” field will retrieve the BibTex citations. # Import from mp_api import MPRester with MPRester(API_KEY) as mpr: doc = mpr.provenance.get_data_by_id("mp-19770", field = ["database_IDs", "references"] ) # To get the ICSD ids doc.database_IDs # To get the BibTex citations doc.references In the case that you don’t know the MP ID of the Fe2O3 material of interest, you can also use the mp-api to get all the MP IDs associated with Fe2O3 as shown below: from mp_api import MPRester with MPRester(API_KEY) as mpr: # Query the summary doc to get the MP IDs of all Fe2O3 materials in the MP # You could filter by additional field arguments to reduce the amount entries returned # Fe2O3_docs is a list of SummaryDoc objects Fe2O3_docs = mpr.summary.search(formula="Fe2O3", fields = ["material_id"]) # Create a list of the ids mp_ids = [i.material_id for i in Fe2O3_docs] # To then get the icsd_ids and references, we would loop over the list of MP IDs, and get the provenance doc for each material # provenance_docs will be a list of ProvenanceDoc objects. with MPRester(API_KEY) as mpr: provenance_docs =[mpr.provenance.get_data_by_id(mp_id, fields =["material_id", "database_IDs", "references"]) for mp_id in mp_ids] # We could then look at one example from our query and print the MP ID, database IDs (if any) and references # Let's print out the first results from provenance_docs print(provenance_docs[0].material_id) print(provenance_docs[0].database_IDs) print(provenance_docs[0].references) Hope my responses have helped! Thank you very much! It is very clear!
https://matsci.org/t/how-to-get-icsd-ids-via-mp-api/41970
CC-MAIN-2022-21
en
refinedweb
Hi PierPaolo, This function is in libMathCore that is not part of the default library set. You should link with: g++ -g -O -o mycode mycode.o `root-config --libs` -lMathCore Rene Brun Pierpaolo Righini wrote: > Hi Rene, > I tried but unsuccesfully to follow your suggestion for compiling the > Math libraries, for example to use > "gaussian_quant" here are a very simple code: > > > #include "TROOT.h" > #include "Math/ProbFuncMathCore.h" > using namespace ROOT::Math; > int main(int argc, char **argv){ > TROOT root("Call center","analysis"); > double f=gaussian_quant(0.1,1.); > return(0); > } > > that I try to compile with: > g++ -g -I$ROOTSYS/include -c mycode.cpp > g++ -g -O -o mycode mycode.o `root-config --libs` > > but I get the following error when trying to link it: > > undefined reference to `ROOT::Math::gaussian_quant(double, double, > double)' > > Could you tell me where is the mistake? > > Many thanks > > Pierpaolo > Received on Mon Sep 04 2006 - 19:03:18 MEST This archive was generated by hypermail 2.2.0 : Mon Jan 01 2007 - 16:32:00 MET
https://root.cern.ch/root/roottalk/roottalk06/1163.html
CC-MAIN-2022-21
en
refinedweb
GitHub Copilot is the newest tool developed by GitHub to autocomplete code with the help of OpenAI. Copilot generates smart code suggestions with context, such as docstrings, code comments, function names, or even file names. It then uses all this information to suggest code snippets that developers can easily accept by pressing the Tab key on a keyboard. It understands Python, JavaScript, TypeScript, Ruby, and Go, as well as dozens of other languages because it’s “trained on billions of lines of public code,” per the Copilot website. And while it’s currently still in its limited technical preview, those interested can sign up to join a waitlist to try it out. In this article, we’ll explore Copilot’s main functionalities, how to build a simple application using only Copilot, and its pros and cons. Copilot’s main features Copilot’s main feature is its autocomplete function. When typing a function description, for example, Copilot completes the whole function before a user finishes. While this autocomplete is similar to other general autocomplete functionalities, Copilot goes a step beyond. When continuing to write code and adding more comments, Copilot begins to understand the whole context of the code through its AI capabilities. With the context, it autocompletes comments mid-sentence. For example, by adding a function, it generates a whole comment and a function; in this case, it figured out the last function should be a multiply function, as seen below. Another cool feature of Copilot is the ability to see 10 full-page suggestions, instead of a single one-liner suggestion, and choosing which suits the code best. To do that, press ^ + Return on a Mac keyboard or Ctrl + Enter on Windows to open a list of suggestions, as shown below. Can you build an application with only GitHub Copilot? With Copilot’s capabilities, I wanted to challenge myself to build a small application using only Copilot. For this challenge, I wanted to create a simple random quote application that also displays the sentiment of the quote. To do this, I had a few rules to follow to see how much benefit I could receive from Copilot. First, I could not search the internet if I encountered a problem, including using Stack Overflow or documentation. This let me see whether it was possible to solely rely on Copilot’s suggestions to create working code. The second rule was that I could not write any new code myself. I could, however, write comments, variables, names, and function names to trigger Copilot’s suggestions. Similarly, I could also make small edits to the suggested code. And finally, I could trigger the list of Copilot suggestions and accept one, since this is a built-in feature. Setting up the project I chose Next.js and React to build this project since they are the tools I am most familiar with to help me better evaluate Copilot’s performance. Since React makes it fairly painless for developers to build applications, and I wanted to see how Copilot would manage React components. For Next.js, it provides a good starting point where I didn’t need to spend a lot of time setting everything up, and it has built-in back-end functions, making it useful to call different API endpoints without triggering CORS errors. While Next.js might seem too powerful for this small project, there’s no need to install other dependencies beforehand and its integrated, easy-to-use API functions make it a good choice for this challenge. Developing the API endpoints Starting with developing API endpoints, I wanted a quote generator that returns a random quote on a GET request and a sentiment analysis endpoint. The sentiment analysis endpoint needed to receive a string as a query parameter and return a sentiment. Since I didn’t know what format the return value would be, I let Copilot write it and see what it could return. /api/get_quote GET request endpoint To create two endpoints using Next.js, I created two files in the api folder: get_quote.js and get_sentiment.js. Next.js could then create these endpoints based on the file names. All that was left is to define was the handler functions inside those files, and I let Copilot do that for me. For the get_quote endpoint, I wrote a comment and chose a good suggestion: // get random quote from random API Clicking the comment, Copilot responds with a list of different options to pick from. The suggestion I selected was the following: const getQuote = async () => { const response = await fetch(' const quote = await response.json() return quote.contents.quotes[0].quote } This suggestion worked. Almost all of the other suggestions that I checked were either broken or required an API key that I didn’t have. This could be because Copilot was trained on open source GitHub code, and some endpoints might be outdated already, which can be frustrating. Also, this endpoint returns the quote of the day, which means for every call, I receive the same quote for the current day, which was not what I was expecting. Instead, for every endpoint call, I wanted to receive a different random quote. For the second part of this endpoint, I needed to create a handler for the endpoint that calls the function Copilot already generated. The handler is the function that Next.js calls when the client requests the endpoint. To do this, I declared the function with its name to see whether Copilot would suggest the correct implementation or not. And Copilot surprised me again. Everything seemed correct. First, it called the getQuote function and returned the quote received from the web service. Then, it saved the quote to the constant and returned JSON to the client with the retrieved quote. The only thing I had to add was .status(200) to send the 200 status code to the client. /api/get_sentiment GET request endpoint For the get_sentiment function, I chose Copilot’s suggestion and didn’t have to change anything. I input the following: // determine if the text is positive or negative Then, Copilot suggested the following code, which I used: async function getSentiment(text) { const response = await fetch(` { method: "POST", body: `text=${text}`, headers: { "Content-Type": "application/x-www-form-urlencoded", }, }) const json = await response.json() return json.label } However, for the endpoint part, I had to add .status(200), similar to the get_quote endpoint. Here is what I provided to Copilot: export default async function handler(req And then, Copilot suggested the following, which I selected: export default async function handler(req, res) { const sentiment = await getSentiment(req.query.text) res.json({ sentiment }) } Copilot managed to provide us with a working solution again, suggesting the right handler and calculating what the get_sentiment handle function needed to return. This suggestion looks similar to the one we had previously. Let’s see how Copilot handled React component generation next. React components For the frontend, I needed a couple of specified React components and a React controller component with a button. The two specified components needed to display text: one for quote text and another for sentiment text. Let’s see how Copilot handled creating these React components. QuoteTextBox I began with the QuoteTextBox component that would showcase a simple quote; I added the following comment to see what Copilot would suggest: // React component to show a quote inside a div const Copilot suggested a simple function component, which I did not have to change at all. const QuoteTextBox = (props) => { const { quote } = props return ( <div className="quote-text-box"> <p>{quote}</p> </div> ) } export default QuoteTextBox SentimentTextBox To build the sentiment text box, I added the following comment: // React component to show sentiment text inside a div const For this text box, it was a bit trickier to find the right suggestions, and I had to scroll through most of them until I found one that would work with my code: const SentimentTextBox = (props) => { // Get sentiment text from props const sentimentText = props.sentimentText // Return component return ( <div className="sentiment-text-box"> {sentimentText} </div> ) } // Export component export default SentimentTextBox It’s important to clearly understand what to expect from Copilot because it is only a tool, and developers can’t just rely on the first suggestion it gives. I still needed to come back to this component to map what the API returns to readable text. For example, if the web service returns neg, I needed to map it to Negative. Controller component with button I also needed a controller component to manage all the logic. The first two React components I created just received data and rendered it on-screen, but the controller component needed to manage the API calls. I started by inputting the following: // React component that uses QuiteTextBox and SentimentTextBox and APIs to show quotes and sentiment with a button to generate new quotes. const Then, Copilot brought this suggestion: const QuoteGenerator = ({quote, sentiment, onClick}) => { return ( <div> <QuoteTextBox quote={quote} sentiment={sentiment} /> <button onClick={onClick}>Generate New Quote</button> <SentimentTextBox sentiment={sentiment} /> </div> ) } export default QuoteGenerator The controller component suggested by Copilot appeared to be pretty basic; it lacked the API calls and didn’t use correct props for SentimentTextBox. However, Copilot did provide the correct structure, it just needed some tweaks to finish it. Then, I just needed to add functions to the controller component. Instead of passing quote, sentiment, and onClick, I asked Copilot to generate them. I also needed some Hooks to store the sentiment and quote data received from calling the APIs. For Hooks, Copilot figured out right away what I needed. To trigger the suggestion for the first Hook, I began typing a comment and Copilot suggested the correct Hook. However, for the second Hook, I didn’t even need to type a comment. I accepted the first Hook suggestion, moved to the next line, and Copilot suggested the second Hook immediately. While the endpoints were correct, I still needed to make some changes to make them work. I had to ask very specifically what I wanted, otherwise, Copilot started suggesting different web services. I wanted it to just call endpoints that were already created. Furthermore, I need to specifically call the getSentiment endpoint when I received a quote and map the sentiment to human-readable text. And this is my final version after some minor changes from my side: const QuoteGenerator = () => { // Hook to store text in state const [quoteText, setQuoteText] = React.useState('') const [sentimentText, setSentimentText] = React.useState('') // Function to get quotes from API /api/get-quote const getQuote = () => { fetch('/api/get-quote') .then(response => response.json()) .then(json => { setQuoteText(json.quote) getSentiment(json.quote) }) } // Function to get sentiment from API /api/get-sentiment\ const getSentiment = (text) => { fetch('/api/get-sentiment?text=' + text) .then(response => response.json()) .then(json => { setSentimentText(json.sentiment) }) } // Function to be called when user clicks on button to generate new quote const onClick = () => { getQuote() } const mapSentimentToText = { 'neg': 'Negative', 'pos': 'Positive', 'neutral': 'Neutral' } return ( <div> <QuoteTextBox quote={quoteText} /> <SentimentTextBox sentimentText={mapSentimentToText[sentimentText]} /> <button onClick={onClick}>Generate New Quote</button> </div> ) } export default QuoteGenerator The final application After experimenting with my simple quote-generating app, I found that Copilot gives enough help to create a simple application. I didn’t have high expectations and initially thought I would need to change a lot of code to make the application work. However, Copilot surprised me. In some places, it gave me nonsense suggestions, but in other places, the suggestions were so good that I can’t believe Copilot made them. Copilot pros and cons To recap my experience with Copilot, I’ve compiled the pros and cons of working with it so you can decide whether Copilot is something you can use daily or not. Copilot pros The main advantage of using Copilot is that it provides autocomplete on steroids. As an autocomplete tool, I believe it is currently the best on the market; there is nothing even close to as useful as Copilot. Copilot also shows developers multiple ways to solve different problems that may not be so obvious. When in need of a code snippet, the 10 suggestions functionality is great and can often be used in place of Stack Overflow for efficiency. In all, Copilot is fun to use. For all the tech geeks, it is something new to play around with and it makes daily work a bit more interesting. Copilot cons While its functionality provides greater efficiency, users must remember it’s a tool, not a human developer replacement. Because Copilot is not a panacea, users cannot solely rely on it for all their code. Most of its suggestions require changes to fit specific needs. And finally, I noticed Copilot was suggesting to use React classes for small components with little logic instead of functional components with Hooks. Because it was trained on openly available code on GitHub, Copilot might provide some depreciated suggestions for coding. Conclusion GitHub Copilot is not something that can just listen to a project idea and code everything for you. It is also not taking over developer jobs, either. But it is something that can make coding easier. GitHub Copilot is good with small tasks; when you start asking it something more complex, you often get nonsense. Nevertheless, it is a very good tool for both beginner and experienced developers alike. “1 week with GitHub Copilot: Building an app using…” Very insightful article, Thanks Well a lot of programming languages have had IDs that have done most of this for years. Without AI. Also the comments generated well those are the kind you probably should never ride anyways. Most, should be why and then I say I won’t be able to do that. Maybe it’ll get better and be useful.
https://blog.logrocket.com/building-github-copilot-app/
CC-MAIN-2022-21
en
refinedweb
Bug #2486 rsc logger seems to have problems with stringstreams Description When running the following program #include <stdio.h> #include <rsc/logging/Logger.h> using namespace std; int main() { rsc::logging::LoggerPtr logger = rsc::logging::Logger::getLogger("testlogger"); stringstream s; for (uint i = 0; i < 5; ++i) { s << i << " "; } cout << s.str() << endl; RSCERROR(logger, "rsc::logging: " << s.str()); return EXIT_SUCCESS; } I get the following output: 0 1 2 3 4 1455195279558 testlogger [ERROR]: rsc::logging: But I would expect, that the rsc logger also outputs the values from the stringstream. What is wrong here? Associated revisions History #1 Updated by J. Wienke over 6 years ago - Status changed from New to Resolved - % Done changed from 0 to 100 Applied in changeset rsc|6891d9d30349e33e29085243977e4ac67b9cee3f. Also available in: Atom PDF
https://code.cor-lab.de/issues/2486
CC-MAIN-2022-21
en
refinedweb
Periodic Tasks¶ Introduction¶ celery beat is a scheduler; It kicks off tasks at regular intervals, that are then executed by available worker nodes in the cluster. By default the entries are taken from the beat_schedule setting, but custom stores can also be used, like storing the entries in a SQL database. You have to ensure only a single scheduler is running for a schedule at a time, otherwise you’d end up with duplicate tasks. Using a centralized approach means the schedule doesn’t have to be synchronized, and the service can operate without using locks. Time Zones¶ The periodic task schedules uses the UTC time zone by default, but you can change the time zone used using the timezone setting. An example time zone could be Europe/London: timezone = 'Europe/London' This setting must be added to your app, either by configuring it directly using ( app.conf.timezone = 'Europe/London'), or by adding it to your configuration module if you have set one up using app.config_from_object. See Configuration for more information about configuration options. The default scheduler (storing the schedule in the celerybeat-schedule file) will automatically detect that the time zone has changed, and so will reset the schedule itself, but other schedulers may not be so smart (e.g., the Django database scheduler, see below) and in that case you’ll have to reset the schedule manually. Django Users Celery recommends and is compatible with the new USE_TZ setting introduced in Django 1.4. For Django users the time zone specified in the TIME_ZONE setting will be used, or you can specify a custom time zone for Celery alone by using the timezone setting. The database scheduler.models import PeriodicTask >>> PeriodicTask.objects.update(last_run_at=None) Entries¶ To call a task periodically you have to add an entry to the beat schedule list. from celery import Celery from celery.schedules import crontab app = Celery() @app.on_after_configure.connect def setup_periodic_tasks(sender, **kwargs): # Calls test('hello') every 10 seconds. sender.add_periodic_task(10.0, test.s('hello'), name='add every 10') # Calls test('world') every 30 seconds sender.add_periodic_task(30.0, test.s('world'), expires=10) # Executes every Monday morning at 7:30 a.m. sender.add_periodic_task( crontab(hour=7, minute=30, day_of_week=1), test.s('Happy Mondays!'), ) @app.task def test(arg): print(arg) @app.task def add(x, y): z = x + y print(z)’re wondering where these settings should go then please see Configuration. You can either set these options on your app directly or you can keep a separate module for configuration. If you want to use a single item tuple for args, don’t forget that the constructor is a comma, and not a pair of parentheses. Using a timedelta for the schedule means the task will be sent in 30 second intervals (the first task will be sent 30 seconds after celery beat starts, and then every 30 seconds after the last run). A Crontab like schedule also exists, see the section on Crontab schedules. Like with cron, the tasks may overlap if the first task doesn’t complete before the next. If that’s a concern you should use a locking strategy to ensure only one instance can run at a time (see for example Ensuring a task is only executed one at a time). Available Fields¶ task The name of the task to execute. schedule args kwargs options. Crontab schedules¶ If you want more control over when the task is executed, for example, a particular time of day or day of the week, you can use the crontab schedule type: from celery.schedules import crontab app.conf.beat_schedule = { # Executes every Monday morning at 7:30 a.m. 'add-every-monday-morning': { 'task': 'tasks.add', 'schedule': crontab(hour=7, minute=30, day_of_week=1), 'args': (16, 16), }, } The syntax of these Crontab expressions are very flexible. Some examples: See celery.schedules.crontab for more documentation. Solar schedules¶ If you have a task that should be executed according to sunrise, sunset, dawn or dusk, you can use the solar schedule type: from celery.schedules import solar app.conf.beat_schedule = { # Executes at sunset in Melbourne 'add-at-melbourne-sunset': { 'task': 'tasks.add', 'schedule': solar('sunset', -37.81753, 144.96715), 'args': (16, 16), }, } The arguments are simply: solar(event, latitude, longitude) Be sure to use the correct sign for latitude and longitude: Possible event types are: All solar events are calculated using UTC, and are therefore unaffected by your timezone setting. In polar regions, the sun may not rise or set every day. The scheduler is able to handle these cases (i.e., a sunrise event won’t run on a day when the sun doesn’t rise). The one exception is solar_noon, which is formally defined as the moment the sun transits the celestial meridian, and will occur every day even if the sun is below the horizon. Twilight is defined as the period between dawn and sunrise; and between sunset and dusk. You can schedule an event according to “twilight” depending on your definition of twilight (civil, nautical, or astronomical), and whether you want the event to take place at the beginning or end of twilight, using the appropriate event from the list above. See celery.schedules.solar for more documentation. Starting the Scheduler¶ To start the celery beat service: $ celery -A proj beat You can also embed beat inside the worker by enabling the workers -B option, this is convenient if you’ll never run more than one worker node, but it’s not commonly used and for that reason isn’t recommended for production use: $ celery -A proj worker -B Beat needs to store the last run times of the tasks in a local database file (named celerybeat-schedule by default), so it needs access to write in the current directory, or alternatively you can specify a custom location for this file: $ celery -A proj beat -s /home/celery/var/run/celerybeat-schedule Note To daemonize beat see Daemonization. Using custom scheduler classes¶ Custom scheduler classes can be specified on the command-line (the -.
https://docs.celeryq.dev/en/v5.1.2/userguide/periodic-tasks.html
CC-MAIN-2022-21
en
refinedweb
In your tests you might encounter specialized popups, which are generated via Javascript, and which are called ‘user prompts’. These are very basic in functionality, and they come in three variants: an ‘alert’ which only displays an informational message and an ‘OK’ button; a ‘confirm’ which displays an informational message, together with an ‘OK’ and ‘Cancel’ button; a ‘prompt’ which displays an informational message, possibly an input field for typing into, and an ‘OK’ and ‘Cancel’ button. Such a user prompt will be displayed usually when a user clicks a button, which triggers the prompt to be displayed. Understanding what type of user prompt will be displayed when a user clicks a button can be done by inspecting the HTML code of the button. It will have an attribute called ‘onclick’, whose value is the name of a Javascript function that will execute when the button is clicked. The location of the function can be either in the HTML file itself, or in a different file which is imported in the HTML file. You will find this information in the <script> section of your HTML file. If you find the function with the name equal to the ‘onclick’ attribute value, there you have it. If not, you will find an ‘import’ declaration, such as: <script src=”someExternalJsFile”>, where “someExternalJsFile” is the name of the file where the function which triggers a user prompt is defined. The function you are looking for is of the following format: <script> function nameOfFunction() { ... } </script> Of course, a script which triggers a user prompt to be displayed might do more than just show you the prompt. Based on what you click, some additional code might be executed in the script. That will depend on what product you are working on. However, the code which simply displays the user prompts is as follows: - Alert: this is a simple prompt with a text displayed (“theAlertMessage” in this example) and an OK button: alert("theAlertMessage"); - Confirm: this is a prompt with a text displayed (“theConfirmMessage” in this example) and an OK and Cancel buttons confirm("theConfirmMessage"); - Prompt: - this is a prompt with a text displayed (“thePromptMessage” in this example), an empty input field in which the user can type, and an OK and Cancel buttons: prompt("thePromptMessage"); - this is a prompt with a text displayed (“thePromptMessage” in this example), a pre-filled input field (with the text “thePromptInputField”) in which the user can type, and an OK and Cancel buttons: prompt("thePromptMessage", “thePromptInputField”); Examples Setup The HTML page that will be used in this post for showing how to work with prompts contains three buttons. Clicking on each of them will trigger a different type of user prompt to be displayed. ……… <button id="alertButton" onclick="alertFunction()">Alert button</button> <button id="confirmButton" onclick="confirmFunction()">Confirm button</button> <button id="promptButton" onclick="promptFunction()">Prompt button</button> <p id="userClicked"></p> <script> function alertFunction() { alert("This is the alert box"); } function confirmFunction() { var confirmBoolean = confirm("Confirm modal"); if (confirmBoolean == true) { document.getElementById("userClicked").innerHTML = "OK"; } else { document.getElementById("userClicked").innerHTML = "Cancel"; } txt; } function promptFunction() { var promptOption = prompt("Type something"); if (promptOption != null) { document.getElementById("userClicked").innerHTML = "OK"; } else { document.getElementById("userClicked").innerHTML = "Cancel"; } } </script> ……………... After this page is opened in the browser, when the button with id ‘alertButton’ is clicked, the ‘alertFunction()’ function from the <script> section of this page is executed. It triggers an ‘alert’ to be displayed. This alert displays the ‘This is the alert box’ text, and it also has an ‘OK’ button. When the button with id ‘confirmButton’ is clicked, the ‘confirmFunction()’ function from the <script> section of this page is executed. It triggers a ‘confirm’ to be displayed. This confirm displays the ‘Confirm modal’ text,. When the button with id ‘promptButton’ is clicked, the ‘promptFunction()’ function from the <script> section of this page is executed. It triggers a ‘prompt’ to be displayed. This prompt displays the ‘Type something’ text, has a typeable input field,. Note: the paragraph which displays what the user clicked is created in this example only for demonstration purposes. It is up to the application you are developing to add some specific behavior based on what the user clicks on inside the ‘prompt’ or ‘confirm’. The import section of the test ( ) will contain the following entries: import browser.BrowserGetter; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.openqa.selenium.Alert; import org.openqa.selenium.WebDriver; import org.openqa.selenium.support.PageFactory; import tutorialsolution.pages.UserPromptsPage; import java.io.File; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.TestInstance.Lifecycle.PER_CLASS; Because the examples in this post use JUnit 5, the junit jupiter related imports are used for the setup methods, for the test methods and for the assertion parts. The BrowserGetter, WebDriver and PageFactory imports are used for starting the browser, storing the driver instance and initializing the PageObject class elements. The UserPromptsPage is imported because that is the PageObject class where the WebElements for this test are created. The relevant import for demonstrating user prompts is the Alert class. The @BeforeAll method contains the browser and PageObject class initialization, and the code which opens the ‘userPrompts.html’ page, where the code for the user prompt demo is stored. The browser will be closed in the @AfterAll class. @BeforeAll public void beforeAll() { //initialize the Chrome browser here driver = browserGetter.getChromeDriver(); //initialize page object class page = PageFactory.initElements(driver, UserPromptsPage.class); driver.get(new File("src/main/resources/userPrompts.html").getAbsolutePath()); } @AfterAll public void afterAll() { driver.quit(); } The PageObject class ( contains the WebElements corresponding to the buttons which, when clicked, trigger the alert/confirm/prompts. It also contains the WebElement of the paragraph in which, when the user clicks a button on confirm/prompt, a text corresponding to which button was clicked is displayed: @FindBy(css = "#alertButton") public WebElement alertButton; @FindBy(css = "#confirmButton") public WebElement confirmButton; @FindBy(css = "#promptButton") public WebElement promptButton; @FindBy(css = "#userClicked") public WebElement userClicked; 1. Alert The alert type of user prompt: - Displays: - A text - An OK button - Has the following JS code: alert(“theAlertMessage”); - Can be interacted with from Selenium by: - Clicking the OK button - Reading its text In case more than one interaction with the alert is made in a test, it is worth storing a handle to the alert by creating an ‘Alert’ object variable. Getting the handle to it is easily done in the following code: Alert alert = driver.switchTo().alert(); Now, in order to read the text of the alert or to click the OK button, while the alert is displayed, you can call the relevant methods for these actions directly on the ‘alert’ variable. Reading the label of the alert is done by using the ‘getText()’ method : alert.getText() Clicking on the OK button of this alert is easily done by using the ‘accept()’ method on the ‘alert’ variable: alert.accept() Once you defined the variable, you don’t need to call the ‘driver.switchTo()’ method, if you closed the alert and opened it again. Once the variable is defined for an alert, you can use it across your test, but only for that particular alert, as it returns a handle to that alert. If you only need to perform one action on the alert in your test (maybe just closing it), you don’t need to create a separate variable for the alert. It is not worth creating a variable which will only be used once. Therefore, in such a case, you could easily close the alert by writting the following code in your test, where you are chaining the method calls (first you switch to the alert, then click on it): driver.switchTo().alert().accept(); This approach also has the benefit of writing less lines of code. Note: when using the alert related method, like ‘accept()’ or ‘getText()’, you need to make sure you are doing this while the user prompt, which ever it is (alert,confirm or prompt) is displayed. If you try to use these methods when the alert is not displayed you will encounter the following ‘NoAlertPresentException’ Exception: org.openqa.selenium.NoAlertPresentException: no alert open Example Scenario 1. Click on the button which opens an alert. Check that the text of the alert is ‘This is the alert box’. Then, close the alert. Clicking on the button which will trigger the alert to be displayed is straightforward (see Example Setup section): page.alertButton.click(); Now that the alert is displayed, create a new variable which will store a handle to the alert, so that you can interact with the alert in the tests: Alert alert = driver.switchTo().alert(); This variable is of type ‘Alert’. Now you can read the text of the alert using the ‘getText()’ method and compare it to the expected one. assertEquals("This is the alert box", alert.getText()); The last step of this test requires closing the alert, by using the ‘accept()’ method: alert.accept(); Scenario 2. Click on the button which opens an alert. Close the alert. For this test, there is only one action that needs to be performed on the alert, namely closing it once it is open. Therefore, there is no need to store the handle to the alert into a new variable. Instead, the entire test will consist of two steps: clicking the button which triggers the alert, then closing the alert: page.alertButton.click(); driver.switchTo().alert().accept(); 2. Confirm The confirm type of user prompt: - Displays: - A text - An OK button - A Cancel button - Has the following JS code: confirm(“theConfirmMessage”); - Can be interacted with from Selenium by: - Clicking the OK button (accept) - Clicking the Cancel button (dismiss) - Reading its text In case more than one interaction with the alert is made in a test, it is worth storing a handle to the confirm by creating an ‘Alert’ object variable. From a Selenium point view, whether the user prompt is an alert, a confirm or a prompt, the handle to a user prompt is stored in an ‘Alert’ object variable. There is no ‘Confirm’ or ‘Prompt’ variable. Getting the handle to it is easily done in the following code, which is also identical to the way you would get the handle to an alert or to a prompt: Alert alert = driver.switchTo().alert(); Retrieving the text of the ‘confirm’ is also done just as for the alert from the previous subchapter: alert.getText() It is the same with clicking on the ‘OK’ button of the prompt: alert.accept() Up to now, these methods could be used on an alert type of user prompt too. The difference between a ‘confirm’ and an ‘alert’ si that the ‘confirm’ user prompt also has a ‘Cancel’ button, which can be clicked from a test. Doing so is done by calling the ‘dimiss()’ method on the ‘alert’ variable: alert.dismiss() In case only one interaction with the ‘confirm’ is required in the test, there is no need to create a new variable only for the one interaction. Instead, the desired methods for interactions can be called as follows (this is the example for clicking ‘OK’): driver.switchTo().alert().accept(); Similarly, closing the ‘confirm’ by clicking the ‘Cancel’ button in a one-liner can be done: driver.switchTo().alert().dismiss(); Example Scenario 1.1. Click the button which triggers a ‘confirm’ to be displayed. Check that the text on the ‘confirm’ is ‘Confirm modal’. Click the ‘OK’ button on the ‘confirm’. Check that the field which displays what the user clicked now displays ‘OK’. The first step is to click the button which triggers the ‘confirm’ to be displayed. Then, the handle to the newly opened ‘confirm’ will be stored to a variable of type ‘Alert’. page.confirmButton.click(); Alert alert = driver.switchTo().alert(); Checking that the ‘confirm’ text is the expected one is done via the ‘getText()’ method: assertEquals("Confirm modal", alert.getText()); Now, the ‘confirm’ can be closed, by clicking the ‘OK’ button. alert.accept(); At this point, in this test, in the paragraph whose corresponding WebElement is named ‘userClicked’, the text ‘OK’ is displayed. To check this, the following assertion will be used: assertEquals("OK", page.userClicked.getText()); Scenario 1.2. After scenario 1.1 is executed successfully, in the same test, open the ‘confirm’ again. Close the ‘confirm’ by clicking the ‘Cancel’ button. Check that the field which displays what the user clicked now displays ‘Cancel’. Opening the ‘confirm’ again is done just as the first step of Scenario 1.1.: page.confirmButton.click(); Close the ‘confirm’ by clicking the ‘Cancel’ button. This is done by using the ‘dismiss()’ method from Selenium. Now, think about what happened previously: first you opened the ‘confirm’ and you got a handle to it. Then you closed it. Now it opens again. Luckily there is no need to regenerate the handle to the ‘confirm’ (like it is the case with switching to windows). Once you created the ‘alert’ variable for the ‘confirm’ you can reuse that variable even if you closed, then reopened the ‘confirm’. alert.dismiss(); Now, since the ‘Cancel’ button was clicked, check that the field which displays what the user clicked now displays ‘Cancel’: assertEquals("Cancel", page.userClicked.getText()); Scenario 2. Open a ‘confirm’ type of user prompt. Close it by clicking the ‘Cancel’ button. Check that the paragraph which displays what the user clicked shows the text ‘Cancel’. This is a short test, since there is only one interaction with the ‘confirm’ and there is no need to store the ‘confirm’ handle to a variable: page.confirmButton.click(); driver.switchTo().alert().dismiss(); assertEquals("Cancel", page.userClicked.getText()); 3. Prompt The prompt type of user prompt: - Displays: - A text - An input field, with or without a predefined text - An OK button - A Cancel button - Has the following JS code: prompt(“thePromptMessage”); or prompt(“thePromptMessage”, “thePromptInputField”); - Can be interacted with from Selenium as: - Clicking the OK button (accept) - Clicking the Cancel button (dismiss) - Reading its text - Typing in the input field In case more than one interaction with the ‘prompt’ is made in a test, it is worth storing a handle to the ‘prompt’ by creating an ‘Alert’ object variable. As mentioned in the previous subchapter, no matter what type of user prompt appears in the test, the type of variable used for storing its handle will be ‘Alert’. Storing the handle is done just as for the other types of user prompts: Alert alert = driver.switchTo().alert(); Retrieving the text of the ‘prompt’ is also done just as for the ‘alert’ and ‘confirm’ from the previous subchapter: alert.getText() It is the same with clicking on the ‘OK’ button of the prompt: alert.accept() Clicking the ‘Cancel’ button of the ‘prompt’ is done by calling the ‘dimiss()’ method on the ‘alert’ variable: alert.dismiss() Aditionally, the user can type in an input field displayed on the ‘prompt’. This can be done using the ‘sendKeys()’ method from Selenium. Note that at the time of writing this post, this functionality does not work on ChromeDriver(). Its’ usage is: alert.sendKeys(“textToType”) Just as before, if there is no need to create a new variable in the test, the ‘prompt’ related methods can be called directly in the form: driver.switchTo().alert().dismiss(); Example Scenario 1. Open a new ‘prompt’ and check that the text displayed on it is ‘Type something’. Click the ‘OK’ button on the prompt, and check that the paragraph which displays what the user clicked now shows the text ‘OK’. Open the ‘prompt’ again, then close it by clicking the ‘Cancel’ button and check that the paragraph which dispays what the user clicked now shows ‘Cancel’. Just as in the previous examples, for ‘alerts’ and ‘confirms’, first a button is clicked which triggers the ‘prompt’ to be displayed. Then, the handle to the ‘prompt’ is stored in an ‘Alert’ variable. page.promptButton.click(); Alert alert = driver.switchTo().alert(); Checking the text of the ‘prompt’ and closing it (via the ‘Ok’ button) are covered by the following code: assertEquals("Type something", alert.getText()); alert.accept(); Now the check that the paragraph displaying what the user clicked shows the text ‘OK’ is done through this assertion: assertEquals("OK", page.userClicked.getText()); The next steps of this test are to reopen the prompt, then close it by clicking the ‘Cancel’ button, and finally checking that the label displaying what button was clicked is correct: age.promptButton.click(); alert.dismiss(); assertEquals("Cancel", page.userClicked.getText()); Scenario 2. Open a new ‘prompt’ and close it by clicking the ‘Cancel’ button. Check that the paragraph which dispays what the user clicked now shows ‘Cancel’. The code which covers this scenario is similar to previous subchapters: page.promptButton.click(); driver.switchTo().alert().dismiss(); assertEquals("Cancel", page.userClicked.getText()); GitHub location of example code PageObject class: Test class: Test methods: alertGetTextAndAccept, alertAccept, confirmGetTextAcceptAndDismiss, confirmAcceptAndDismiss, promptGetTextAcceptAndDismiss, promptAcceptAndDismiss HTML code: One thought on “Working with user prompts in Selenium” A good read. Thanks for the info.
https://imalittletester.com/2020/06/10/working-with-user-prompts-in-selenium/?replytocom=105534
CC-MAIN-2022-21
en
refinedweb
Whenever benefits to using a Web API over a native plugin, including: - Reduce app bloat: By design, native plugins bring in additional code to a project, increasing app download size for your users. A Web API, however, is already available. - Increase app performance: Less plugin code leads to better overall performance. This is especially a factor in app startup timing, where most plugins are initialized and loaded into memory. - Reduce app maintenance: Web APIs are less likely to degrade over time as new mobile operating system updates are released. Browser vendors regularly ship critical security updates as well – no action required by you or your app users. - Faster development cycles: Less reliance on native plugins decreases the need to test on device hardware, which slows down development. That’s what makes ionic serveso powerful – build your entire app locally in the browser, then test on a device towards the end of the development cycle. - Better cross-platform support: Web APIs make it easier to bring your app to more platforms. For example, the ability to deploy an iOS or Android app as a PWA. A Real World Example: Switching from File Plugin to Fetch API There’s an easier way to read a file on a device, which potentially replaces the need for the Cordova File plugin entirely, by using the Fetch Web API. This is particularly useful when paired with the Cordova Camera plugin: // Capture photo using the device camera const tempPhoto = await this.camera.getPicture(options); // Convert from file:// protocol to WebView safe one (avoid CORS) const webSafePhoto = this.webview.convertFileSrc(tempPhoto); // Retrieve the photo image data const response = await fetch(webSafePhoto); I discovered this while building an encrypted image demo app. The demo’s main goal was to save an image captured from the device camera into Ionic Offline Storage. The challenge was that Offline Storage required the image data to be stored as an array buffer, a data format that the Camera plugin didn’t provide. One solution was to use the Cordova File plugin. This felt clunky and confusing to understand. To make it work, I had to use the File plugin to read the photo file into a FileEntry object, then convert it into a Blob, then into an ArrayBuffer: import { File } from '@ionic-native/file/ngx'; public async saveCameraPhoto() { const options: CameraOptions = { quality: 100, destinationType: this.camera.DestinationType.FILE_URI, encodingType: this.camera.EncodingType.JPEG, mediaType: this.camera.MediaType.PICTURE } const tempPhoto = await this.camera.getPicture(options); let fileEntry = await this.file.resolveLocalFilesystemUrl(tempPhoto) as any; fileEntry.file((file) => { const fileReader = new FileReader(); fileReader.onloadend = () => { let blob = new Blob("image/jpeg", fileReader.result as ArrayBuffer); const imageDoc = new MutableDocument(“doc”); imageDoc.setBlob(“blob”, blob); await this.database.save(imageDoc); } fileReader.readAsArrayBuffer(file); }); } In contrast, using the Fetch API only required a couple of lines of code. const response = await fetch(webSafePhoto); const photoArrayBuffer = await response.arraybuffer(); The complete example: public async takePicture() { const options: CameraOptions = { quality: 100, destinationType: this.camera.DestinationType.FILE_URI, encodingType: this.camera.EncodingType.JPEG, mediaType: this.camera.MediaType.PICTURE } const tempPhoto = await this.camera.getPicture(options); const webSafePhoto = this.webview.convertFileSrc(tempPhoto); const response = await fetch(webSafePhoto); // Different data response options: const photoBlob = await response.blob(); const photoArrayBuffer = await response.arraybuffer(); } Cleaner, simpler code that accomplished exactly what I needed. 🤓 Is a Web API the Right Choice for My App? While there are many benefits to using a Web API over a native plugin, take some time to evaluate the situation based on your app’s needs. Considerations include: - Functionality: Chances are high that the Web API’s features will differ from the plugin’s. If requirements change in the future, will the Web API be able to cover them? In my Fetch API example, it only retrieves data, so it’s not a complete replacement for the File plugin. If I needed to write a File, I’d go back to using the plugin. - Performance: Web APIs are generally very performant given they are built into the browser. It still makes sense to test as needed, though. - Platform Support: Is the Web API available to my users today, as well as any additional platforms I may support in the future? Fortunately, checking platform support is easy thanks to two sites: - WhatWebCanDo.Today describes the features of all APIs available. - CanIUse.com covers browser support for each API. I recommend beginning your search on WhatWebCanDo.Today to determine exactly which APIs you might leverage, then do more research on CanIUse.com to ensure the API will be available and fully supported on all of the platforms you’re interested in. Using Fetch as an example, we can see that it has wide support across all browsers. As Ionic developers targeting iOS and Android, pay close attention to both iOS Safari and Android Browser support: In this case, support began in iOS 10 (10.3) and Android 5 (Chromium 76), so should be safe to use in an Ionic app. Web API First The uniquely powerful benefit of web-based hybrid apps is the ability to leverage both web and native technology as needed. While every app’s needs are different, explore Web API options first before reaching for a plugin. Though not for everyone, you might be pleasantly surprised at how far they can get you. For more interesting Web API examples, check out my Ionic Native encrypted storage demo app. What are some creative ways you’ve used native web APIs recently? Or plugins you’ve replaced in favor of a web API? Share your insights below.
https://ionicframework.com/blog/replacing-native-plugins-with-web-apis/
CC-MAIN-2022-21
en
refinedweb
5 reasons to go with CSS in JS for your next application CSS is awesome, and it’s easy to get started with. But front-end applications have been scaling at a massive, and complex rate that I don’t believe the current CSS architecture is designed for the job. I still believe that the current CSS architecture has a place in this crazy world for small sites, and even small applications. I’m going to list a set of problems that I’ve come across with CSS over the 9 years of developing for the web. And I believe CSS in JS solves these problems. I will be demonstrating how CSS in JS solves these issues by using 2 libraries Styled Components and React. CSS problem #1: Global namespace I created a style sheet that contains CSS code for a container element. The container style will increase in size if it also contains the class name home. Now I have created the home page HTML, imported the stylesheet, and have added the class names to the HTML elements. But wait, I need an about page! Let’s create that now. I’ve now created the about HTML page, imported the style sheet, and created a new container element. Great, right? Not exactly. The style sheet that I imported contains styles from the home page. And there is nothing to stop me from using class names that was designed for the home page. Over time this simple site will grow to have thousands of lines of CSS, and HTML code. And CSS rules that have been defined in the past will be re-used across the site. The problem lies when a engineer attempts to change a class rule. It has a very high potential of breaking or changing other parts of the site that were not meant to be modified. CSS in JS allows us to keep styles encapsulated to a React element. I’ve created 2 components here. The first component is named, Title. Title is responsible only for styling., The second component is Greet. Greet is responsible using the styled component that I created and displaying the greet message to the user. Title been defined as a local style. No other React component or HTML element will be able to access these styles. Safe! CSS problem #2: Implicit dependencies This is called style of writing SASS/CSS is called BEM. Ever heard of it? Probably not. BEM is one of many CSS methodologies. And the objective with a CSS methodology is to reduce the lack of built-in scoping mechanism. OOCSS is a method to separate containers and content with CSS “objects”. We also have: - SMACSS - SUITCSS - Atomic Nonetheless, each of these solutions are just a quick patch solution. CSS problem #3: Dead code elimination Why download CSS code that isn’t going to be used? CSS in JS can dynamically clean up CSS code that is not being used. CSS problem #4: Minification CSS out of the box doesn’t have a feature to minify code. For big applications unminified CSS code can get fairly big, especially with crazy amount of white space (indentation) we add to the stylesheet. To minify CSS code you’ll have to use a third party service online or setup dev task to minify your code. Which just creates another dependency your CSS. CSS problem #5: Sharing constants CSS supports a sharing constants with their built-in function called var(). But it does not support IE. And it barely supports Edge 15. We can say, “Microsoft stop support of these browsers.” But according to W3Schools, which they get 50 million visits per month. They say 4% comes from IE and Edge. That’s a total of 2 million users using IE and Edge. Not really numbers that we can ignore. And with a recent project with Verizon Media, the application needed to support IE 9 still. So var(), goes right out the door. For the moment. Another con is that CSS variables cannot be accessed on the server side either. Let’s take the React example above and modify it a bit to see how we can use constants across our application. I created a new file named constants.js, and inside that file it contains a value for the primary text color, FireBrick. I than updated the Greet component to use the new constant I created. First I imported the new constant into the Greet.js file. Then I use a technique called interpolation inside the Title component. The hard-coded color value was swapped for the constant. While I’m at it, I’ll create a new component called Button, and it will use the same constant. The only difference is that primaryTextColor is now being used in 2 css properties for the Button component. The components will stay consistent now. CSS in JS benefits Besides solving those 5 issues above, it comes with some additional benefits. - Generates minimum CSS requires - Good runtime performance - Supports dynamic styling - Easy to pre-render important CSS Conclusion At the end of the day we’re not getting rid of CSS. We’re just adding JavaScript to enhance CSS. The old CSS architecture is perfectly fine for small sites, and small applications. But it may not be appropriate choice for medium to big size applications in 2019. Sure, we can add SASS, methodologies, and even CSS modules into the mix, but again, those are small patches that require strict rules, and tooling. Those are not solutions for the future. I would say that CSS in JS is not the ultimate solution, but it’s the best one we have so far. Let me know your thoughts and comments on Twitter. I like to tweet about code and post helpful code snippets. Follow me there if you would like some too!
https://linguinecode.com/post/5-reasons-css-in-js
CC-MAIN-2022-21
en
refinedweb
Skolt Sami is one of the languages that is supported by UralicNLP. The goal of this website is to provide free FST transducers for multiple languages, mostly as nightly builds. You can use the Skolt Sami analyzer and generator with UralicNLP Install UralicNLP: pip install uralicNLP python -m uralicNLP.download -l sms Usage from uralicNLP import uralicApi uralicApi.lemmatize(word, "sms") uralicApi.analyze(word, "sms") uralicApi.generate(word, "sms") Please, refer to UralicNLP documentation for more information. You can also download the transducers directly here:
https://models.uralicnlp.com/nightly/sms/
CC-MAIN-2022-21
en
refinedweb
Razor Syntax Razor Syntax allows you to embed code (C#) into page views through the use of a few keywords (such as “@”), and then have the C# code be processed and converted at runtime to HTML. In other words, rather than coding static HTML syntax in the page view, a user can code in the view in C# and have the Razor engine convert the C# code into HTML at runtime, creating a dynamically generated HTML web page. @page @model IndexModel <h2>Welcome</h2> <ul> @for (int i = 0; i < 3; i++) { <li>@i</li> } </ul> The @page Directive In a Razor view page (.cshtml), the @page directive indicates that the file is a Razor Page. In order for the page to be treated as a Razor Page, and have ASP.NET parse the view syntax with the Razor engine, the directive @page should be added at the top of the file. There can be empty space before the @page directive, but there cannot be any other characters, even an empty code block. @page @model IndexModel <h1>Welcome to my Razor Page</h1> <p>Title: @Model.Title</p> The @model Directive The page model class, i.e. the data and methods that hold the functionality associated with a view page, is made available to the view page via the @model directive. By specifying the model in the view page, Razor exposes a Model property for accessing the model passed to the view page. We can then access properties and functions from that model by using the keyword Model or render its property values on the browser by prefixing the property names with @Model, e.g. @Model.PropertyName. @page @model PersonModel // Rendering the value of FirstName in PersonModel <p>@Model.FirstName</p> <ul> // Accessing the value of FavoriteFoods in PersonModel @foreach (var food in Model.FavoriteFoods) { <li>@food</li> } </ul> Razor Markup Razor pages use the @symbol to transition from HTML to C#. C# expressions are evaluated and then rendered in the HTML output. You can use Razor syntax under the following conditions: Anything immediately following the Code blocks must appear within A single line of code that uses spaces should be surrounded by parentheses, @page @model PersonModel // Using the `@` symbol: <h1>My name is @Model.FirstName and I am @Model.Age years old </h1> // Using a code block: @{ var greet = "Hey threre!"; var name = "John"; <h1>@greet I'm @name!</h1> } // Using parentheses: <p>Last week this time: @(DateTime.Now - TimeSpan.FromDays(7))</p> Razor Conditionals Conditionals in Razor code can be written pretty much the same way you would in regular C# code. The only exception is to prefix the keyword if with the else or else if conditions doesn’t need to be preprended with the @symbol. Afterward, any @symbol. // if-else if-else statment: @{ var time = 9; } @if (time < 10) { <p>Good morning, the time is: @time</p> } else if (time < 20) { <p>Good day, the time is: @time</p> } else { <p>Good evening, the time is: @time</p> } Razor Switch Statements In Razor Pages, a switch statement begins with the switch. The condition is then written in parentheses and finally the switch cases are written within curly brackets, @symbol followed by the keyword {}. @{ string day = "Monday"; } @switch (day) { case "Saturday": <p>Today is Saturday</p> break; case "Sunday": <p>Today is Sunday</p> break; default: <p>Today is @day... Looking forward to the weekend</p> break; } Razor For Loops In Razor Pages, a for loop is prepended by the @symbol followed by a set of conditions wrapped in parentheses. The @symbol must be used when referring to C# code. @{ List<string> avengers = new List<string>() { "Spiderman", "Iron Man", "Hulk", "Thor", }; } <h1>The Avengers Are:</h1> @for (int i = 0; i < @avengers.Count; i++) { <p>@avengers[i]</p> } Razor Foreach Loops In Razor Pages, a foreach loop is prepended by the @symbol followed by a set of conditions wrapped in parentheses. Within the conditions, we can create a variable that will be used when rendering its value on the browser. @{ List<string> avengers = new List<string>() { "Spiderman", "Iron Man", "Hulk", "Thor", }; } <h1>The Avengers Are:</h1> @foreach (var avenger in avengers) { <p>@avenger</p> } Razor While Loops A while loop repeats the execution of a sequence of statements as long as a set of conditions is true, once the condition becomes false we break out of the loop. When writing a while loop, we must prepend the keyword while with the @symbol and write the condition within parentheses. @{ int i = 0; } @while (i < 5) { <p>@i</p> i++; } Razor View Data In Razor Pages, you can use the ViewData property to pass data from a Page Model to its corresponding view page, as well as share it with the layout, and any partial views. ViewData is a dictionary that can contain key-value pairs where each key must be a string. The values can be accessed in the view page using the @symbol. A huge benefit of using ViewData comes when working with layout pages. We can easily pass information from each individual view page such as the title, into the layout by storing it in the ViewData dictionary in a view page: @{ ViewData["Title"] = "Homepage" } We can then access it in the layout like so: ViewData["Title"]. This way, we don’t need to hardcode certain information on each individual view page. // Page Model: Index.cshtml.cs public class IndexModel : PageModel { public void OnGet() { ViewData["Message"] = "Welcome to my page!"; ViewData["Date"] = DateTime.Now(); } } // View Page: Index.cshtml @page @model IndexModel <h1>@ViewData["Message"]</h1> <h2>Today is: @ViewData["Date"]</h2> Razor Shared Layouts In Razor Pages, you can reduce code duplication by sharing layouts between view pages. A default layout is set up for your application in the _Layout.cshtml file located in Pages/Shared/. Inside the _Layout.cshtml file there is a method call: RenderBody(). This method specifies the point at which the content from the view page is rendered relative to the layout defined. If you want your view page to use a specific Layout page you can define it at the top by specifying the filename without the file extension: @{ Layout = "LayoutPage" } // Layout: _LayoutExample.cshtml <body> ... <div class="container body-content"> @RenderBody() <footer> <p>@DateTime.Now.Year - My ASP.NET Application</p> </footer> </div> </body> // View Page: Example.cshtml @page @model ExampleModel @{ Layout = "_LayoutExample" } <h1>This content will appear where @RenderBody is called!</h1> Razor Tag Helpers In Razor Pages, Tag Helpers change and enhance existing HTML elements by adding specific attributes to them. The elements they target are based on the element name, the attribute name, or the parent tag. ASP.NET provides us with numerous built-in Tag Helpers that can be used for common tasks - such as creating forms, links, loading assets, and more. // Page Model: Example.cshtml.cs public class ExampleModel : PageModel { public string Language { get; set; } public List<SelectListItem> Languages { get; } = new List<SelectListItem> { new SelectListItem { // asp-for: The name of the specified model property. // asp-items: A collection of SelectListItemoptions that appear in the select list. <select asp-</select> <br /> <button type="submit">Register</button> </form> // HTML Rendered: <form method="post"> <select id="Language" name="Language"> <option value="C#">C#</option> <option value="Javascript">Javascript</option> <option value="Ruby">Ruby</option> <br> </select> <button type="submit">Register</button> </form> Razor View Start File When creating a template with ASP.NET, a ViewStart.cshtml file is automatically generated under the /Pages folder. The ViewStart.cshtml file is generally used to define the layout for the website but can be used to define common view code that you want to execute at the start of each View’s rendering. The generated file contains code to set up the main layout for the application. // ViewStart.cshtml @{ Layout: "_Layout" } Razor View Imports The _ViewImports.cshtml file is automatically generated under /Pages when we create a template with ASP.NET. Just like the _ViewStart.cshtml file, _ViewImports.cshtml is invoked for all your view pages before they are rendered. The purpose of the file is to write common directives that our view pages need. ASP.NET currently supports a few directives that can be added such as: @namespace, @using, @addTagHelpers, and @inject amongst a few other ones. Instead of having to add them individually to each page, we can place the directives here and they’ll be available globally throughout the application. // _ViewImports.cshtml @using YourProject @namespace YourProject.Pages @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers Razor Partials Partial views are an effective way of breaking up large views into smaller components and reduce complexity. A partial consists of fragments of HTML and server-side code to be included in any number of pages or layouts. We can use the Partial Tag Helper, <partial>, in order to render a partial’s content in a view page. // _MyPartial.cshtml <form method="post"> <input type="email" name="emailaddress"> <input type="submit"> </form> // Example.cshtml <h1> Welcome to my page! </h1> <h2> Fill out the form below to subscribe!:</h2> <partial name="_MyPartial" />
https://www.codecademy.com/learn/learn-asp-net/modules/asp-net-razor-syntax/cheatsheet
CC-MAIN-2022-21
en
refinedweb
Object Selection Based on Color Thresholding HSV (hue, saturation, value) colorspace is a model to represent the colorspace similar to the RGB color model. Since the hue channel models the color type, it is very useful in image processing tasks that need to segment objects based on its color In this example code below , we convert the image to HSV color space, and create a color selection using inrange thresholding. A masked image is created using a bitwise AND operation as shown below: import cv2 as cv import numpy as np img = cv.imread('./images/pokemon.jpg') cv.imshow('Original Img',img) hsv = cv.cvtColor(img, cv.COLOR_BGR2HSV) lower_blue = np.array([50,50,50]) upper_blue = np.array([130,255,255]) mask = cv.inRange(hsv, lower_blue, upper_blue) cv.imshow('Mask',mask) res = cv.bitwise_and(img,img, mask= mask) cv.imshow('Selected image',res) cv.waitKey() Original image before masking: Mask Output image after masking: References: Relevant Courses April 14, 2021
https://www.tertiaryinfotech.com/selection-based-on-color/
CC-MAIN-2022-21
en
refinedweb
From!... Just a note: this board was for the QPD not the Bull's eye detector. tcs_daq #!/usr/bin/python # a short script to output low frequency sine wave to EPICS channels import epics import math import time import os import random a =.. Here's the error: Traceback (most recent call last): . Here are some pictures of the ring heater segments destined for the H2 Y-arm this year. These still need to be put onto ResourceSpace. For archive purposes, attached is a write-up of all the HWS measurements I've made to date for the SRM CO2 projector mock-up.). I changed the HWS code to the new git.ligo HWS version. I've set up some symbolic links to these directories to mimic the old directory structure, so ... I checked the lab this morning. It was dry and there wall was in the same state as yesterday. The 200W Thermopile power head from Thorlabs arrive today. The scanned delivery note and calibration info are attached.. Does this work? Yes. I noticed that the TCS lab temperature sensor batteries died. Apparently they died two days ago. I swapped in some new batteries this morning.... - Discussed the further project with Dr. Brooks. -Tried to derive formula for the test mass inside cryogenic shield(infinitely long shield from one side) -Continued with the same cryogenic model created and varied the length of outer shield and studied the temperature variation inside. -Compared the temperature difference given by COMSOL with manually calculated one. -Created a COMSOL model for cryogenically shielded test mass with compensation plate. -Analyzed the behavior of the model in different size configurations. -Created a COMSOL model for variation of temperature in two mass system. -Used the above model for cryogenic conditions. -checked it analytically. -Derived formula for manual calculation of temperature due to total influx. -Compared the results by COMSOL and by the formula. -Discussed the project outline for next 6 weeks. -made a write up for the tasks. (attached) -Analyzed the variation of temperature of the test mass with input power for different lengths of the shield. -Updated 3 week progress report with new additions and deletions. -Attended LIGO lecture which was very interesting and full of information. -Attented LIGO orientation meeting and safety session. -Prepared 3 week report've started an 80C cure of two materials bonded by EPOTEK 353ND. The objective is to see (after curing) how much the apparent glass transition temperature is increased over a room-temperature cure.
http://nodus.ligo.caltech.edu:8080/TCS_Lab/?new_entries=0&rsort=Subject
CC-MAIN-2022-21
en
refinedweb
Server side rendering #About For server side rendered apps, there will be instances when the access token has expired. In these cases, you need to use the refresh token to get a new access and a new refresh token. However, the refresh token is only sent to one API endpoint - the refresh API. This means that for all other APIs, you will not have the refresh token as an input. Therefore, for refreshing a session during SSR, we must first send a response that manually refreshes the session and then reloads the page. The attemptRefreshingSession function# - Via NPM - Via Script Tag import SuperTokens from 'supertokens-website'; await SuperTokens.attemptRefreshingSession(); await supertokens.
https://supertokens.com/docs/website/usage/server-side-rendering
CC-MAIN-2022-21
en
refinedweb
Written in front: This tutorial refers to the official documentation EdgeX Foundry Hands On Tutorial The tools used are: Ubuntu system (with docker and docker-compose installed), postman tool and MQTTBox tool ( mqtt service construction tutorial) The data is not collected by real sensor devices, but random numbers are generated by python programs. I am also a novice in the Internet of Things. All codes are drawn according to gourds. If there are mistakes or mentally handicapped operations, please point out directly in the comment area Greatful! - *You can follow my steps to generate files in sequence, or you can download all files at one time. Here is an address to download all files: EdgeX_Tutorial 1. Create a folder Download the docker-compose file and pull the image mkdir geneva1 cd geneva1 Here is a docker-compose address: (This docker-compose file is in the tutorial, which is different from the docker-compose file of the official official project. It does not have functions such as ui. I don’t know if the file of the official project can be used, and try again later try) compose After downloading, save it in the geneva1 folder and rename it to: docker-compose.yml Pull the image: docker-compose up later docker-compose ps verify As shown in the figure: 2. Create the device There are three steps to creating a device - Create value descriptors - upload device profile - create device 2.1 Create value descriptors value descriptors describe the data format and labels of Edgex, our data is just random numbers, created using postman postman mode select post ip>:48080/api/v1/valuedescriptor Set the Body to "raw" and "JSON" (I'll explain why later) { "name": "number", "description": "Random number",//Description Write whatever you want "min": "0", "max": "200", "type": "Int64", "uomLabel": "number1", "defaultValue": "0", "formatting": "%s", "labels": [ "aaaaa", "bbbbb" ] } If there is no problem, a string of ID s will be generated, don't remember, just know that it means success If your data has multiple attributes, change the content of the body description and post it a few more times. 2.2 Upload device profile A device profile is essentially a template that describes a device, its data format, and supported commands. It's a text file written in YAML format, uploaded to EdgeX, and referenced later whenever a new device is created. Only one configuration file is required per device type. Similarly, we also use postman to upload postman mode select post ip>:48081/api/v1/deviceprofile/uploadfile Finally as shown: Here is number_porduce.yaml (draw the scoop according to the gourd, do not spray) name: "number_produce" // remember this name manufacturer: "liu" model: "aaaa" labels: - "rpi" //I don't know why it's rpi description: "suiji chansheng shuzi" deviceResources: - name: number description: "suiji chansheng shuzi" properties: value: { type: "Int64", readWrite: "RW", minimum: "0", maximum: "100", size: "4", LSB: "true", defaultValue: "0"} If there is no problem, a string of ID s will be generated. 2.3 Create device Since we are generating the device with rest, use the device service "edgex device rest" postman mode select post ip>:48081/api/v1/device body is { "name": "number_device", "description": "suijishushengcheng", "adminState": "unlocked", "operatingState": "enabled", "protocols": { "example": { "host": "dummy", "port": "1234", "unitID": "1" } }, "labels": [ "suijishu" ], "location": "Tokyo", "service": { "name": "edgex-device-rest" }, "profile": { "name": "number_produce" //Corresponds to the name of number_porduce.yaml above } } If there is no problem, a string of ID s will be generated. 3. Upload data 3.1 First create a random folder and create a python virtual environment - sudo apt install python3-venv -y - . ./venv/bin/activate - pip install requests 3.2 Copy the python file used to generate the data (getData.py) //getData.py import requests import json import random import time edgexip = 'xxx.xxx.xxx.xxx'//Change to your own ip running edgex number = 66 def generateSensorData(number): number = random.randint(number-5,number+5) print("Sending nums: Value %s" % (number)) return (number) if __name__ == "__main__": sensorTypes = ["number"] while(1): (number) = generateSensorData(number) url = ' % edgexip payload = number headers = {'content-type': 'application/json'} response = requests.post(url, data=json.dumps(payload), headers=headers, verify=False) time.sleep(3) 3.3 python3 ./genSensorData.py As shown in the figure: Fourth, export the data to the mqtt server Here we choose to use the kuiper rule engine to export the data, and we can also use the APP SERVICE to export, you can see the official documentation for details. Here is a brief introduction to the kuiper rule engine, which has three steps: - Create a data stream, which is the data you upload - Create a rule - enforce the rules 4.1 Create data flow, use postman { "sql": "create stream number_test() WITH (FORMAT=\"JSON\", TYPE=\"edgex\")" } 4.2 Create rules { "id": "mqtt_export_rule1", "sql": "SELECT * FROM number_test", /// must be the same name as the previous step "actions": [ { "mqtt": { "server": "tcp://broker.hivemq.com:1883", //mqtt shared server address "topic": "EdgeXFoundryMQTT_01", //Subscribed topics "username": "someuser", "password": "somepassword", "clientId": "someclientid" } }, { "log": {} } ] } 4.3 Open the MQTTBox software The red box is the server address of the previous step, after save The topic of subscription should be the same as the one in the rule. Next, you will receive the data sent by edgex. This data format is defined by the previous value description. This is just to implement a simple data upload function. Later, I will continue to explore how to use the rule engine to process the passed data. Will write again!
https://algorithm.zone/blogs/how-to-write-code-to-upload-data-to-mqtt-cloud-server-through-edgexfoundry.html
CC-MAIN-2022-21
en
refinedweb
Voice Intro Contents - Getting Started - Supported Platforms - Install Instructions - Key Components - Interest Groups Usage Demystified -. Join our discord server to chat with the community or one of our team members when available. Supported Platforms - Windows - UWP - macOS - Linux - Android (for 64-bit support read this) - iOS - PlayStation 4 (requires a special add-on that can be downloaded here. Read more about access to consoles here.) - PlayStation 5 (requires a special add-on that can be downloaded here. Read more about access to consoles here.) - Nintendo Switch (requires a special add-on that can be downloaded here. Read more about access to consoles here.) - MagicLeap (Lumin OS, requires a special add-on that can be downloaded here. Read more about Magic Leap here.) - HoloLens 2 (ARM64 requires a special add-on that can be downloaded here.) - Xbox One (requires a special add-on that can be downloaded here. Read more about access to consoles here.) - Xbox Series X and Xbox Series S (requires a special add-on that can be downloaded here. Read more about access to consoles here.) Install Instructions The minimal Unity version required is 2018.4.22f1. Photon Voice 2 can be downloaded and imported from the Unity Asset Store here. Photon Voice 2 package includes PUN2. PUN 2 already includes Photon Realtime Unity SDK as it depends on it, Photon Chat and Photon Unity libraries. You can clean up PUN2 or clean up Photon Chat from the project if you want to but the other parts are required for Photon Voice to work. For compatibility with other Photon packages and to guarantee smooth updates, we do not recommend moving Photon assets outside of root Photon folder ("Assets\Photon"). Photon Voice 2 is not compatible with PUN Classic though. Photon Voice Classic is to be used with PUN Classic but both packages will be going away soon. Clean Import When you import Photon Voice 2 in a project already containing PUN 2; to avoid any conflicts errors due to versions mismatch, it's recommended to clean up Photon assets before: - If you don't use another Photon package (e.g. Photon Bolt) delete "Assets\Photon" folder. - If you imported another Photon package in parallel then delete the following folders: - "Assets\Photon\PhotonChat" - "Assets\Photon\PhotonRealtime" - "Assets\Photon\PhotonUnityNetworking" - "Assets\Photon\PhotonLibs" You could also follow this step if you want to do a clean import after encountering an issue after updating Photon Voice 2 or importing another Photon package. Update We do not recommend importing PUN 2 on top of Photon Voice 2. We always try to release a Photon Voice 2 version just after a PUN 2 update so you could get the latest PUN 2 from Photon Voice 2. If you encounter an issue when updating Photon Voice 2 from the Unity Asset Store try doing a clean import. audio stream or before getting the information of an incoming stream via its creation event. That event and the data it contains are important to 'link' a local Speaker component to a remote audio stream. In the following section we will explain how the Speaker should be used. SpeakerFactory The SpeakerFactory method will be called every time a new remote audio stream info is received. The SpeakerFactory is used to bind a local Speaker component to an incoming audio streams transmitted via a remote Recorder component, this way the audio stream's two ends transmitter and receiver will be linked together. We support a one-to-one relationship between a remote Recorder and local Speaker. By default, you cannot mix and play multiple incoming audio streams using a single Speaker component instance. A Speaker is linked once to a single Recorder, it cannot be linked to the same audio stream multiple times. Also, by default, you cannot play a single incoming audio stream using multiple Speaker component instances. In the factory, you need to return a Speaker component that will be used to play the received audio frames from that remote audio stream. You could create a new Speaker component or re use an old one or just return null to skip playing all future incoming audio frames from that same remote audio stream. The parameters passed to the SpeakerFactory method helps you identify the origin or the source of the audio stream. The code in the body of the SpeakerFactory should be used to find the most suitable candidate Speaker component if any (or creates a new one if needed) to play the audio frames that will be received from the incoming audio stream originating from a remote Recorder component. The SpeakerFactory method accepts 3 parameters and returns a Speaker component that will be used to play incoming audio using the AudioSource component attached to the same GameObject. The 3 parameters accepted by the SpeakerFactory method are: playerId: the actor number of the player where the audio stream is originating from. voiceId: the number of the audio stream originating from the same playerId. userData: custom object set in the Recorder component that is transmitting the audio audio audio stream will be removed. Interest Groups Usage Demystified Photon Voice uses Photon Realtime's "Interest Groups" to separate mutually exclusive "voice channels" belonging to different "voice conversations". Select "Who To Listen To" Each actor needs to subscribe to interest groups it's interested in. By default, all actors listen to interest group 0 which could be seen as a global interest group for voice broadcast. If you want to listen to voice sent to other groups you need to subscribe to those groups. You can also unsubscribe from previously subscribed ones. The operation to do all this is: // without PUN integration: voiceConnection.Client.OpChangeGroups(groupsToRemove, groupsToAdd); // with PUN integration: PhotonVoiceNetwork.Instance.Client.OpChangeGroups(groupsToRemove, groupsToAdd); Select "Who To Talk To" Each actor needs to decide to which interest group it wants to transmit audio to. The target interest group can be set using: recorder.InterestGroup = targetGroup; Use Cases In all cases, you always listen to default interest group 0 and you can transmit voice to a single interest group at the same time per Recorder component. Use cases could be grouped into three different categories: 1. Single Global Group If you use one single group, at a time, to transmit voice to in all clients and all Recorder components, there is a shortcut to set or switch this global group: // without PUN integration: voiceConnection.Client.GlobalInterestGroup = targetGroup; // with PUN integration: PhotonVoiceNetwork.Instance.Client.GlobalInterestGroup = targetGroup; In this case no need to call OpChangeGroups or set Recorder.InterestGroup as it's done internally for you. Notes: - If targetGroupis equal to 0then you have the default behaviour. No need to explicitly set it as a global group unless you changed something and want to reset setup. - If targetGroupis not equal to 0then you can still receive voice streams transmitted to that same group. - All Recordercomponents transmitting will use the same globally set target group in this case. 2. Listen To A Single Group This is not the same as the previous category as it allows the following: - Set a different target group per Recorder. - The group to listen to can be different from the group to talk to. A. Default Group // A. unsubscribe from all groups, this is optional if groups were not changed before // without PUN integration: voiceConnection.Client.OpChangeGroups(new byte[0], null); // with PUN integration: PhotonVoiceNetwork.Instance.Client.OpChangeGroups(new byte[0], null); // B. set target interest group photonVoiceRecorder.InterestGroup = targetGroup; B. Other Group // A. subscribe to the group to listen to // without PUN integration: voiceConnection.Client.OpChangeGroups(new byte[0], new byte[1] { groupToListenTo }); // with PUN integration: PhotonVoiceNetwork.Instance.Client.OpChangeGroups(new byte[0], new byte[1] { groupToListenTo }); // B. set target interest group photonVoiceRecorder.InterestGroup = targetGroup; 3. Listen To Multiple Groups A. Listen To All Pre-Existing Groups // A. subscribe to all pre-existing groups // without PUN integration: voiceConnection.Client.OpChangeGroups(null, new byte[0]); // with PUN integration: PhotonVoiceNetwork.Instance.Client.OpChangeGroups(null, new byte[0]); // B. set target interest group photonVoiceRecorder.InterestGroup = targetGroup; Later, you may need to subscribe to groups created after this call. B. Listen To A List Of Groups // A. subscribe to a custom list of groups // without PUN integration: voiceConnection.Client.OpChangeGroups(new byte[0], groupsToListenTo); // with PUN integration: PhotonVoiceNetwork.Instance.Client.OpChangeGroups(new byte[0], groupsToListenTo); // B. set target interest group photonVoiceRecorder.InterestGroup = targetGroup; You can speak to a group other than those you listen to. i.e. groupsToListenTo could not contain targetGroup. C. Listen To All Possible Groups This should be used carefully as it may subscribe the client to groups that will never be used. using System; using System.Linq; // [...] byte[] allByteValues = Enumerable.Range(1, 255).SelectMany(BitConverter.GetBytes).ToArray(); // A. subscribe to all possible groups // without PUN integration: voiceConnection.Client.OpChangeGroups(null, allByteValues); // with PUN integration: PhotonVoiceNetwork.Instance.Client.OpChangeGroups(null, allByteValues); // B. set target interest group photonVoiceRecorder.InterestGroup = targetGroup; How To Use Photon Voice Without PUN Quick Way - Add a VoiceConnection component to the scene and enable "Don't Destroy On Load". - Set AppSettings in VoiceConnection.Settings. - Add a Recorder to the scene, update its properties and assign it to VoiceConnection.PrimaryRecorder. - Add a Speaker prefab (a prefab that has a Speaker component) and assign it VoiceConnection.SpeakerPrefab. - Join a room. To do so use any of Photon Realtime's matchmaking operations (see "ConnectAndJoin.cs" utility script for example). Advanced Options - Add a VoiceConnection component to the scene. - Set AppSettings in VoiceConnection.Settings. - Add a Recorder to the scene, update its properties and assign it to VoiceConnection.PrimaryRecorder. 3.a. Optionally enable Recorder.TransmitEnabledto start transmission as soon as ready. 3.b. Optionally enable Recorder.DebugEchoModeto hear yourself (a local Speaker needs to be linked, see step 4). - Decide how to link Speaker components with remote audio). - [If not enabled in 3.a.] Once in a room start transmitting by setting Recorder.TransmitEnabledto true. - [If not enabled in 3.b.] Optionally enable Recorder.DebugEchoModeon the transmitting recorder to hear yourself. How To Remove PUN If you want to use Photon Voice without PUN, you can keep PUN inside your project or simply remove it. There is an Editor shortcut for this: "Window" -> "Photon Voice" -> "Remove PUN". Alternatively, you can do this manually. You can always add the files back at any time by importing Photon Voice 2 from the Asset Store. How To Remove Photon Chat If you want to use Photon Voice without Photon Chat, you can keep Photon Chat inside your project or simply remove it. There is an Editor shortcut for this: "Window" -> "Photon Voice" -> "Remove Photon Chat". Alternatively, you can do this manually by deleting "Photon\PhotonChat" folder. You can always add the files back at any time by importing Photon Voice 2 from the Asset Store.
https://doc.photonengine.com/zh-tw/voice/current/getting-started/voice-intro
CC-MAIN-2022-21
en
refinedweb
> 13 Iam facing some another issue now. Iam getting some sort of compilation error it seems. I have ‘Common.java’ class inside ‘base’ package. Its a program for starting firefoxdriver. That, I have kept it in separate package to made it a one time effort and modularity purpose. Iam calling this class file inside the child class ‘tc_01.java’. This TC_01.jave program is in another package ‘testing’. This TC_01.java file is actually accessing driver from Common.java and start browser and try some login and logout actions. My child class TC_01.java is showing me compilation error and Error Message on Mouse Hover is – > “field Common.driver is not visible”. Here is my code :-> # Package- base; Class File – Common.java :-> package base; import java.util.concurrent.TimeUnit; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; public class Common { public FirefoxDriver driver; @BeforeMethod } public void BM(){ System.setProperty(“webdriver.gecko.driver”,”D://Rajiv//Selenium//geckodriver.exe”); driver = new FirefoxDriver(); driver.get(“ driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); @AfterMethod } } public void CM(){ driver.close(); # Pakage – testing; Class – Tc_01.java package testing; import java.util.concurrent.TimeUnit;Method; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import base.Common; public class TC_01 extends Common{ public FirefoxDriver driver; @Test public void TM(){ System.out.println(“Selenium Webdriver Script in Firefox browser using Gecko Driver | AutomationPractice.com PAGE LAUNCHED”); WebDriverWait wait = new WebDriverWait(driver, 30); wait.until(ExpectedConditions.visibilityOfElementLocated(By.id(“search_query_top”))); try{ /*String expectedTitle = “My Store”; System.out.println(“ExpectedTile = “+expectedTitle ); String actualTitle = driver.getTitle(); System.out.println(“The actual Title of the Page is = “+actualTitle); Assert.assertEquals(actualTitle, expectedTitle);*/ System.out.println(“Control has reached here”); driver.findElementByClassName(“login”).click(); driver.findElementById(“email”).sendKeys(“*****@yahoo.com”); driver.findElementById(“passwd”).sendKeys(“*****”); driver.findElementById(“SubmitLogin”).click(); driver.findElementByClassName(“logout”).click(); } } } System.out.println(“Sucessfully Logout from the Application”); }catch (Exception e){ e.printStackTrace(); Can you please guide me what mistake iam doing? Thanks Rajiv Can you please provide the exact stacktrace for the error you are getting? Thanks. I was able to find the root cause for this issue. It wasted my 3 days before i asked for help here in this forum. As i had analysed initially, i had mentioned my driver properties in parent class and was accessing it in Child Class. There was some name mismatch (Letter ‘oh’ was incorrectly written number ‘0’ in extending child class with parent name). When it was trying to inherit the properties from parent, it was not accessible and giving me compilation error. I renamed the parent class name to the same name that i was giving while extending in Child Class. And, it worked. Thanks again to all to this forum. It is such a wonderful forum to discuss your issue between each other and getting its resolution. I’m facing one issue. Scenario : 1st @Test method for Updating a functionality and 2nd @Test method (DependsOnMethod = 1st @test method) for Verifying the updated functionality My data provider has 10 test data to execute and if any of the test execution is failed, then i should stop the entire data provider execution and exit the flow. Also i shouldn’t run the 2nd @test since its depends on 1st @test method. How do we can achieve this. Regarding the dataprovider: you cannot stop running the remainder of the dataprovider in case one of the value from it triggers a test failure. That is how it was designed. Each test run with a value from the dataprovider can be seen as an independent method run. I suggest for the scenario you mentioned to just have the 2 tests turned into one test. I am not sure what your tests are supposed to do, but i think you can just create one test with the data provider that runs all the steps from the two tests. This way, if a test fails due to the value from the data provider, the code that used be the second test will not run. In case the code from the second test should not run at all if any failures were encountered due to the values in the data provider, you can just remove the data provider and use a “for” instead. This way, with the “for” you iterate through all the values that were in the data provider before. If everything looks good, the code from the previous second test will run. Otherwise the test fails in the “for” and no more code will be run.
https://imalittletester.com/2014/06/09/testng-custom-listeners-itestlistener/?like_comment=120&_wpnonce=e3c1012e47
CC-MAIN-2022-21
en
refinedweb
Light-weight packet serializer Project description Packeteer: The packet serializer Packeteer is a light-weight packet serializer capable of translating between raw bytes and custom packet objects; Objects which are easier to understand, display, and work with import socket from packeteer import packets, fields HOST = '127.0.0.1' PORT = '1234' class Request(packets.BigEndian): """ Request packet """ fields = [ fields.UInt8('type'), fields.UInt8('size'), fields.Raw('data', size='size') ] class Response(packets.BigEndian): """ Response packet """ fields = [ fields.Bool('success'), fields.Uint32('transfered'), ] if __name__ == '__main__': data = b'Hello World' request = RequestPacket(type=0, data=data) response = ResponsePacket() with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.connect() s.sendall(request) raw = s.recv(response.size()) response.unpack(raw) print(repr(response)) # <Packet: Response packet> # success: True # transfered: 11 Installation Packeteer is available on PyPi, and can be installed with pip directly $ pip install packeteer Requirements Operating systems Packeteer has no OS dependencies, and should be compatible wherever python can run; However, it is only verified for Ubuntu 18.04. If you discover any issues in other environments, please open a new issue or submit a pull request. Python Packeteer was developed and tested against python 2.7, 3.5, 3.6, and 3.7. Dependencies Packeteer depends on the following packages: - future - six For development and testing, these optional dependencies are also required: - pytest - pytest-cov - tox Documentation Defining packets Defining packets is as simple as deriving a new class from either packets.BigEndian or packets.LittleEndian (Depending on the byte ordering of your packet structure) import copy from packeteer import packets, fields class MyPacketBE(packets.BigEndian): name = 'Custom (Big Endian)' fields = [ fields.Bool('OK'), fields.Int32('value', default=42) ] class MyPacketLE(packets.LittleEndian): """ Custom (Little Endian) """ fields = copy.deepcopy(MyPacketBE.fields) Take notice that the packet definition is built using the fields variable, and the built-in field types; Field types and there options are explained in the fields section of the documentation. The packet name is an optional value that can be set directly, otherwise it will be coppied from the classes doc-string. If no name is found, the name will be given a default value. The name is only used for human readibility when using repr() Working with packets Creating new instances When packet objects are constructed without any parameters, their default values are stored in each field from packeteer import packets, fields class MyPacket(packets.BigEndian): """ Custom (Big Endian) """ fields = [ fields.Bool('OK'), fields.Int32('value', default=42) ] packet = MyPacket() print(repr(packet)) # <Packet: Custom (Big Endian)> # OK: False # value: 42 Packets can also be constructed with non-default values by using the field names to set values packet = MyPacket(OK=True) print(repr(packet)) # <Packet: Custom (Big Endian)> # OK: True # value: 42 packet2 = MyPacket(value=100) print(repr(packet2)) # <Packet: Custom (Big Endian)> # OK: False # value: 100 Working with packet values Field values can be accessed like a list (By index) or like a dictionary (By key) packet = MyPacket() print(packet[0], packet[1]) # False 42 print(packet['OK'], packet['value']) # False 42 Values can also be set in the same fashion packet = MyPacket() packet[0] = True packet[1] = 100 print(packet['OK'], packet['value']) # True 100 Packing/Unpacking The entire purpose of this library is to work with bytes, so it should come to no surprise that packet instances can be serialized into their raw bytes and back. packet = MyPacket() raw = b'\x01\x00\x00\x00\xFF' packet.unpack(raw) print(repr(packet)) # <Packet: Custom (Big Endian)> # OK: True # value: 255 raw2 = packet.pack() print(raw == raw2) # True Packet instances can be constructed directly from bytes as well using the from_raw() call packet = MyPacket.from_raw(b'\x01\x00\x00\x00\xFF') print(repr(packet)) # <Packet: Custom (Big Endian)> # OK: True # value: 255 Fields The different components of the packet are referred to as fields, which are a collection of the associated value, meta data, and supporting functions. Packeteer comes with the following field types: - fields.Padding: (1 Byte) N/A - fields.Bool: (1 Byte) Boolean - fields.Char: (1 Byte) Character - fields.Int8: (1 Byte) Signed Integer - fields.UInt8: (1 Byte) Unsigned Integer - fields.Int16: (2 Byte) Signed Integer - fields.UInt16: (2 Byte) Unsigned Integer - fields.Int32: (4 Byte) Signed Integer - fields.UInt32: (4 Byte) Unsigned Integer - fields.Int64: (8 Byte) Signed Integer - fields.UInt64: (8 Byte) Unsigned Integer - fields.Float: (4 Byte) Float value - fields.Double (8 Byte) Float value - fields.Raw: (n Byte) Raw byte data as a single value - fields.String: (n Bytes) Unicode String as a single value The majority of the types are self explanatory and work identically to the others, but some like padding, string, and raw behave differently and are looked at further in the following sections Padding fields.Padding is a special field type that is 1 byte wide per character. Padding bytes are nameless and not associated with any value; They can't be accessed, but they are counted when packing and unpacking. from packeteer import packets, fields class PaddedPacket(packets.BigEndian): """ Padded """ fields = [ fields.Padding(), fields.UInt8('value'), fields.Padding(default=b'\xff') ] packet = PaddedPacket(value=170) print(repr(packet)) # <Packet: Padded> # value: 170 print(packet[0]) # 170 print(packet[1]) # IndexError raw = packet.pack() print(repr(raw)) # '\x00\xAA\xFF' packet.unpack(b'\x00\x7f\xff') print(repr(packet)) # <Packet: Padded> # value: 127 Raw data and strings fields.Raw is a raw byte store of a given size (The size argument is required). If the data is too large for the field, it will be truncated to fit. Likewise if it is too short, it will be padded with null bytes. fields.String is an extension of fields.Raw that stores it's internal value as a unicode string with the encoding of your choosing (Defaults to utf8). The internal value has any trailing null byte padding removed until it is serialized. from packeteer import packets, fields class DataPacket(packets.BigEndian): """ Data Packet """ fields = [ fields.Raw('raw', size=12), fields.String('string', size=12, encoding='utf8') ] packet = DataPacket(raw=b'Hello World', string='Hello World') print(repr(packet)) # <Packet: Raw Packet> # raw: b'Hello World\x00' # string: u'Hellow World' List fields There are often times when you need to have a variable list of values in a packet (Think about a repeating set of values depending on a given count value). fields.List takes care of this. fields.List requires an additional argument of the field the list contains, with the rest of the arguments given as keywords that the underlying field type requires. from packeteer import packets, fields class ListPacket(packets.BigEndian): """ List Packet """ fields = [ fields.UInt8('count') fields.List('messages', fields.String, size=128), ] messages = ['foo', 'bar', 'Hello World'] packet = ListPacket(count=len(messages), messages=messages) print(repr(packet)) # <Packet: List Packet> # count: 3 # messages: [u'foo', u'bar', u'Hello World'] 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/packeteer/
CC-MAIN-2022-21
en
refinedweb
HOUSTON -- Is an energy revolution about to be unleashed south of the border? With a handful of other major reforms successfully pushed through, President Enrique Peña Nieto is next moving his nation toward serious consideration of energy sector reforms, as he looks to change the way the state oil monopoly Petróleos Mexicanos (PEMEX) does business. Many Mexico observers are skeptical, because such change has been proposed before without results. But experts believe things might be drastically different this time around, and the energy industry in this city is paying very close attention as it stands to earn billions of dollars in new contracts to help Mexico increase its oil and gas output, should the laws change. Last month in London, Peña Nieto said he was looking to make huge changes to Mexican energy law. He and his political party, the Institutional Revolutionary Party, have been hinting at possible changes to the nation's constitution, which currently makes it impossible for outside firms to develop oil and gas reserves. Though most doubt the rules can be changed to allow private companies to own mineral resources directly, many speculate that certain profit-sharing arrangements could be introduced that would allow companies to book Mexican oil and gas assets as partly their own, as long as they are being produced. Professor Stephen Zamora, head of the Center for U.S. and Mexican Law at the University of Houston, confirmed that change is indeed in the air. But specific policy changes have yet to be proposed, he said. "They're still very tight-lipped about what the reforms are actually going to consist of," Zamora said. "They want to do something in order to attract foreign technology and foreign investment, and Mexico has a lot of resources." Gabriel Salinas, a native of Mexico and associate at the international law firm Mayer Brown, laid out four possible scenarios that could play out as Peña Nieto prepares the Mexican Congress and public to seriously address the question, something expected over the latter half of this year. One possibility is that nothing happens, Salinas said. Oil is a very touchy subject in the country, and the day the government expropriated all oil companies and reserves in 1938 is celebrated as a national holiday. The idea of greater foreign participation could prove too unpopular. But Salinas believes it's possible that some skeptical voters and lawmakers could change their minds as they become more educated on possible reforms and what could be at stake if nothing happens. Mexico's largest oil field is in perpetual decline, and decades of underinvestment by a politically hamstrung PEMEX is leading to a steady drop in crude oil production. If the trend isn't halted or reversed, Mexico may one day find itself having to import oil to feed its growing economy. Another possible scenario could see the government making minimal administrative reforms to PEMEX that would free it up to act more like a private oil company. Rules could also be adjusted to permit more private companies to participate in the downstream side of the business, improving the nation's hydrocarbon transportation infrastructure, something that could make shale gas development in Mexico's portion of the Eagle Ford Shale more tenable. However, as Salinas pointed out, Peña Nieto has promised a "transformational" change, which suggests he wants to see changes to the constitution. As a member of the political party that expropriated the industry in the first place, Peña Nieto may have the political capital to pull it off, he argued. "The next months are really key," Salinas said. "Basically, the Mexican Congress is ready to start discussing this. They agreed to have two sessions during the summer, which is out of the regular schedule, to kind of iron out all the pending issues they need to so they can focus on the energy reform during the fall. So there seems to be a better chance than any time for constitutional reforms to be discussed." Getting creative with profit sharing Though no specific proposals have been made public yet, speculation in academic circles is focused on Mexico developing a type of creative profit-sharing system, as well as devising ways to let companies claim Mexican energy resources as their own, even though they wouldn't technically be so. Current law does not allow oil and gas companies to have private ownership or claim to hydrocarbon reserves in Mexico. Both Zamora and Salinas don't think this will change anytime soon. It's a key problem, because private oil and gas companies need to be able to book certain recoverable reserve volumes as collateral to obtain financing from large banks. This is why publicly traded companies are eager to annually tout reserve replacement ratios of 100 percent or greater. A third way needs to be devised. Salinas thinks the government could get around this problem by introducing joint ventures between PEMEX and private companies, deals that could be contracted in a way that keeps the oil as the property of the Mexican people but awards the companies a sufficient profit for helping to produce it. "This has been heating up in the last few weeks, particularly based on President Nieto's statements and some of the top officials," Salinas noted. "They said the reforms might involve constitutional reforms and they've talked about private participation in profit-sharing agreements, joint ventures with PEMEX." Zamora at the University of Houston predicts that Mexico could also introduce more multiservice contracts into the industry. Small changes to PEMEX contracting rules have already helped Houston-based oil field service companies win contracts for work on deepwater offshore exploration in Mexican waters. "When the government first expropriated oil companies and created PEMEX early on, they still allowed concession contracts ... even under the same constitutional provisions as exist today," Zamora said. "Then they changed the law to make it absolutely not a question that a foreign investor would be able to have anything approaching a concession." He also believes the government could find success winning over support for oil and gas reform by invoking the North American Free Trade Agreement. Though that treaty leaves out oil and gas, the precedent it set for the integration of several industries in Canada, the United States and Mexico may make it seem more natural to the public at large that energy production could follow. "Integration is really good -- maybe we should think about integration in energy as well?" Zamora said. 'Like reading tea leaves' Not all Mexico experts agree, however. Dagobert Brito, a political economy professor at Rice University, advised the Mexican government in the late 1990s on models for pricing natural gas in its economy. He argued that constitutional change is "absolutely necessary" if Mexico hopes to increase oil and gas production, but he's very skeptical of Peña Nieto's chances of succeeding this time around. "Reading Mexico's congressional politics is like reading tea leaves," Brito said. "I started working for the Mexican government as adviser back in '96, and back then they tried to figure out a way to cut a deal." He also pointed out that Mexico's democracy is relatively young, and lawmakers may be too inexperienced to pull off serious constitutional amendments. Plus, Peña Nieto's party, the PRI, will have to strike a deal with the opposition National Action Party, which it just ousted from power in the most recent election. The transformation from dictatorship to democracy could make oil reform more difficult, Brito said. "This is my opinion, but they've been talking about tricks for at least 20 years, you know, can we come up with some technicality so that [private companies] can book the reserves," he said. "I think if that were possible, it would have been done. But you never know." But Salinas still sees some promising signs that U.S. oil and gas companies may soon be returning to Mexico to expand the current energy production renaissance to all of North America. If so, it would be another sign of Mexico's emergence as a more advanced economic powerhouse, a development that's been overshadowed by media coverage of drug trade violence. One of Latin America's fastest-growing economies is experiencing surging manufacturing industries and a rapidly expanding middle class. Opening up the oil and gas sector would generate jobs and energy that could further fuel this transformation. The rapid pace of reforms rolled out by the new administration hints at what's possible. "It's been pretty significant actually," Salinas said. "It's been a little more than six months of his administration, and President Nieto has already managed to push through two major constitutional reforms, one in telecommunications and the other in the education sector, and he has already proposed a comprehensive financial reform." "He's expected to soon propose the energy reform and fiscal reform this fall," he added. "The political momentum and the timing is as best as it's ever been before." Republished with permission. Copyright 2013 Environment & Energy Publishing, LLC Related Capabilities News - - - - - November 042020
https://www.mayerbrown.com/en/news/2013/07/talk-of-changes-to-mexicos-oil-monopoly-stirs-caut
CC-MAIN-2022-21
en
refinedweb
Lots of our clients (similar to Formulation One, Honeycomb, Intuit, SmugMug, and Snap Inc.) use the Arm-based AWS Graviton2 processor for his or her workloads and luxuriate in higher worth efficiency. Beginning at this time, you may get the identical advantages on your AWS Lambda features. Now you can configure new and current features to run on x86 or Arm/Graviton2 processors. With this alternative, it can save you cash in two methods. First, your features run extra effectively as a result of Graviton2 structure. Second, you pay much less for the time that they run. In reality, Lambda features powered by Graviton2 are designed to ship as much as 19 p.c higher efficiency at 20 p.c decrease price. With Lambda, you might be charged based mostly on the variety of requests on your features and the period (the time it takes on your code to execute) with millisecond granularity. For features utilizing the Arm/Graviton2 structure, period prices are 20 p.c decrease than the present pricing for x86. The identical 20 p.c discount additionally applies to period prices for features utilizing Provisioned Concurrency. Along with the value discount, features utilizing the Arm structure profit from the efficiency and safety constructed into the Graviton2 processor. Workloads utilizing multithreading and multiprocessing, or performing many I/O operations, can expertise decrease execution time and, as a consequence, even decrease prices. That is notably helpful now that you need to use Lambda features with as much as 10 GB of reminiscence and 6 vCPUs. For instance, you may get higher efficiency for internet and cellular backends, microservices, and knowledge processing programs. In case your features don’t use architecture-specific binaries, together with of their dependencies, you may swap from one structure to the opposite. That is typically the case for a lot of features utilizing interpreted languages similar to Node.js and Python or features compiled to Java bytecode. All Lambda runtimes constructed on high of Amazon Linux 2, together with the customized runtime, are supported on Arm, excluding Node.js 10 that has reached finish of help. If in case you have binaries in your operate packages, you should rebuild the operate code for the structure you wish to use. Features packaged as container photographs must be constructed for the structure (x86 or Arm) they’ll use. To measure the distinction between architectures, you may create two variations of a operate, one for x86 and one for Arm. You possibly can then ship site visitors to the operate through an alias utilizing weights to distribute site visitors between the 2 variations. In Amazon CloudWatch, efficiency metrics are collected by operate variations, and you may take a look at key indicators (similar to period) utilizing statistics. You possibly can then examine, for instance, common and p99 period between the 2 architectures. You too can use operate variations and weighted aliases to regulate the rollout in manufacturing. For instance, you may deploy the brand new model to a small quantity of invocations (similar to 1 p.c) after which improve as much as 100 p.c for a whole deployment. Throughout rollout, you may decrease the load or set it to zero in case your metrics present one thing suspicious (similar to a rise in errors). Let’s see how this new functionality works in follow with a number of examples. Altering Structure for Features with No Binary Dependencies When there aren’t any binary dependencies, altering the structure of a Lambda operate is like flipping a swap. For instance, a while in the past, I constructed a quiz app with a Lambda operate. With this app, you may ask and reply questions utilizing an internet API. I exploit an Amazon API Gateway HTTP API to set off the operate. Right here’s the Node.js code together with a number of pattern questions in the beginning: const questions = [ question: "Are there more synapses (nerve connections) in your brain or stars in our galaxy?", answers: [ "More stars in our galaxy.", "More synapses (nerve connections) in your brain.", "They are about the same.", ], correctAnswer: 1, , query: "Did Cleopatra stay nearer in time to the launch of the iPhone or to the constructing of the Giza pyramids?", solutions: [ "To the launch of the iPhone.", "To the building of the Giza pyramids.", "Cleopatra lived right in between those events.", ], correctAnswer: zero, , query: "Did mammoths nonetheless roam the earth whereas the pyramids had been being constructed?", solutions: [ "No, they were all exctint long before.", "Mammooths exctinction is estimated right about that time.", "Yes, some still survived at the time.", ], correctAnswer: 2, , ]; exports.handler = async (occasion) => { console.log(occasion); const technique = occasion.requestContext. const path = occasion.requestContext. const splitPath = path.change(/^/+|/+$/g, "").break up("/"); console.log(technique, path, splitPath); var response = ; if (splitPath[0] == "questions") { if (splitPath.size == 1) console.log(Object.keys(questions)); response.physique = JSON.stringify(Object.keys(questions)); else { const questionId = splitPath[1]; const query = questions[questionId]; if (query === undefined) response = ; else { if (splitPath.size == 2) else const answerId = splitPath[2]; if (answerId == query.correctAnswer) response.physique = JSON.stringify(); else response.physique = JSON.stringify( appropriate: false ); } } } return response; }; To begin my quiz, I ask for the checklist of query IDs. To take action, I exploit curl with an HTTP GET on the /questions endpoint: Then, I ask extra info on a query by including the ID to the endpoint: I plan to make use of this operate in manufacturing. I anticipate many invocations and search for choices to optimize my prices. Within the Lambda console, I see that this operate is utilizing the x86_64 structure. As a result of this operate will not be utilizing any binaries, I swap structure to arm64 and profit from the decrease pricing. The change in structure doesn’t change the way in which the operate is invoked or communicates its response again. Which means the mixing with the API Gateway, in addition to integrations with different functions or instruments, aren’t affected by this transformation and proceed to work as earlier than. I proceed my quiz with no trace that the structure used to run the code has modified within the backend. I reply again to the earlier query by including the variety of the reply (ranging from zero) to the query endpoint: That’s appropriate! Cleopatra lived nearer in time to the launch of the iPhone than the constructing of the Giza pyramids. Whereas I’m digesting this piece of data, I notice that I accomplished the migration of the operate to Arm and optimized my prices. Altering Structure for Features Packaged Utilizing Container Photographs After we launched the aptitude to bundle and deploy Lambda features utilizing container photographs, I did a demo with a Node.js operate producing a PDF file with the PDFKit module. Let’s see methods to migrate this operate to Arm. Every time it’s invoked, the operate creates a brand new PDF mail containing random knowledge generated by the faker.js module. The output of the operate is utilizing the syntax of the Amazon API Gateway to return the PDF file utilizing Base64 encoding. For comfort, I replicate the code ( app.js) of the operate right here: const PDFDocument = require('pdfkit'); const faker = require('faker'); const getStream = require('get-stream'); exports.lambdaHandler = async (occasion) => const doc = new PDFDocument(); const randomName = faker.identify.findName(); doc.textual content(randomName, ); doc.textual content(faker.tackle.streetAddress(), ); doc.textual content(faker.tackle.secondaryAddress(), ); doc.textual content(faker.tackle.zipCode() + ' ' + faker.tackle.metropolis(), ); doc.moveDown(); doc.textual content('Expensive ' + randomName + ','); doc.moveDown(); for(let i = zero; i < three; i++) doc.textual content(faker.lorem.paragraph()); doc.moveDown(); doc.textual content(faker.identify.findName(), ); doc.finish(); pdfBuffer = await getStream.buffer(doc); pdfBase64 = pdfBuffer.toString('base64'); const response = statusCode: 200, headers: 'Content material-Size': Buffer.byteLength(pdfBase64), 'Content material-Kind': 'software/pdf', 'Content material-disposition': 'attachment;filename=take a look at.pdf' , isBase64Encoded: true, physique: pdfBase64 ; return response; ; To run this code, I want the pdfkit, faker, and get-stream npm modules. These packages and their variations are described within the bundle.json and package-lock.json information. I replace the FROM line within the Dockerfile to make use of an AWS base picture for Lambda for the Arm structure. Given the possibility, I additionally replace the picture to make use of Node.js 14 (I used to be utilizing Node.js 12 on the time). That is the one change I want to change structure. For the following steps, I comply with the publish I discussed beforehand. This time I exploit random-letter-arm for the identify of the container picture and for the identify of the Lambda operate. First, I construct the picture: Then, I examine the picture to examine that it’s utilizing the fitting structure: To make sure the operate works with the brand new structure, I run the container domestically. As a result of the container picture consists of the Lambda Runtime Interface Emulator, I can take a look at the operate domestically: It really works! The response is a JSON doc containing a base64-encoded response for the API Gateway: Assured that my Lambda operate works with the arm64 structure, I create a brand new Amazon Elastic Container Registry repository utilizing the AWS Command Line Interface (CLI): I tag the picture and push it to the repo: Within the Lambda console, I create the random-letter-arm operate and choose the choice to create the operate from a container picture. I enter the operate identify, browse my ECR repositories to pick the random-letter-arm container picture, and select the arm64 structure. I full the creation of the operate. Then, I add the API Gateway as a set off. For simplicity, I go away the authentication of the API open. Now, I click on on the API endpoint a number of instances and obtain some PDF mails generated with random knowledge: The migration of this Lambda operate to Arm is full. The method will differ in case you have particular dependencies that don’t help the goal structure. The power to check your container picture domestically helps you discover and repair points early within the course of. Evaluating Totally different Architectures with Perform Variations and Aliases To have a operate that makes some significant use of the CPU, I exploit the next Python code. It computes all prime numbers as much as a restrict handed as a parameter. I’m not utilizing the absolute best algorithm right here, that may be the sieve of Eratosthenes, however it’s compromise for an environment friendly use of reminiscence. To have extra visibility, I add the structure utilized by the operate to the response of the operate. import json import math import platform import timeit def primes_up_to(n): primes = [] for i in vary(2, n+1): is_prime = True sqrt_i = math.isqrt(i) for p in primes: if p > sqrt_i: break if i % p == zero: is_prime = False break if is_prime: primes.append(i) return primes def lambda_handler(occasion, context): start_time = timeit.default_timer() N = int(occasion['queryStringParameters']['max']) primes = primes_up_to(N) stop_time = timeit.default_timer() elapsed_time = stop_time - start_time response = return I create two operate variations utilizing completely different architectures. I exploit a weighted alias with 50% weight on the x86 model and 50% weight on the Arm model to distribute invocations evenly. When invoking the operate by means of this alias, the 2 variations working on the 2 completely different architectures are executed with the identical chance. I create an API Gateway set off for the operate alias after which generate some load utilizing a number of terminals on my laptop computer. Every invocation computes prime numbers as much as a million. You possibly can see within the output how two completely different architectures are used to run the operate. Throughout these executions, Lambda sends metrics to CloudWatch and the operate model ( ExecutedVersion) is saved as one of many dimensions. To raised perceive what is occurring, I create a CloudWatch dashboard to watch the p99 period for the 2 architectures. On this approach, I can examine the efficiency of the 2 environments for this operate and make an knowledgeable resolution on which structure to make use of in manufacturing. For this explicit workload, features are working a lot sooner on the Graviton2 processor, offering a greater consumer expertise and far decrease prices. Evaluating Totally different Architectures with Lambda Energy Tuning The AWS Lambda Energy Tuning open-source challenge, created by my buddy Alex Casalboni, runs your features utilizing completely different settings and suggests a configuration to attenuate prices and/or maximize efficiency. The challenge has recently been updated to let you compare two results on the same chart. This is useful to match two variations of the identical operate, one utilizing x86 and the opposite Arm. For instance, this chart compares x86 and Arm/Graviton2 outcomes for the operate computing prime numbers I used earlier within the publish: The operate is utilizing a single thread. In reality, the bottom period for each architectures is reported when reminiscence is configured with 1.eight GB. Above that, Lambda features have entry to greater than 1 vCPU, however on this case, the operate can’t use the extra energy. For a similar cause, prices are secure with reminiscence as much as 1.eight GB. With extra reminiscence, prices improve as a result of there aren’t any extra efficiency advantages for this workload. I take a look at the chart and configure the operate to make use of 1.eight GB of reminiscence and the Arm structure. The Graviton2 processor is clearly offering higher efficiency and decrease prices for this compute-intensive operate. Availability and Pricing You should use Lambda Features powered by Graviton2 processor at this time in US East (N. Virginia), US East (Ohio), US West (Oregon), Europe (Frankfurt), Europe (Eire), EU (London), Asia Pacific (Mumbai), Asia Pacific (Singapore), Asia Pacific (Sydney), Asia Pacific (Tokyo). The next runtimes working on high of Amazon Linux 2 are supported on Arm: - Node.js 12 and 14 - Python three.eight and three.9 - Java eight ( java8.al2) and 11 - .NET Core three.1 - Ruby 2.7 - Customized Runtime ( offered.al2) You possibly can handle Lambda Features powered by Graviton2 processor utilizing AWS Serverless Software Mannequin (SAM) and AWS Cloud Improvement Equipment (AWS CDK). Help can be out there by means of many AWS Lambda Companions similar to AntStack, Test Level, Cloudwiry, Contino, Coralogix, Datadog, Lumigo, Pulumi, Slalom, Sumo Logic, Thundra, and Xerris. Lambda features utilizing the Arm/Graviton2 structure present as much as 34 p.c worth efficiency enchancment. The 20 p.c discount in period prices additionally applies when utilizing Provisioned Concurrency. You possibly can additional scale back your prices by as much as 17 p.c with Compute Financial savings Plans. Lambda features powered by Graviton2 are included within the AWS Free Tier as much as the prevailing limits. For extra info, see the AWS Lambda pricing web page. You could find assist to optimize your workloads for the AWS Graviton2 processor within the Getting began with AWS Graviton repository. Begin working your Lambda features on Arm at this time.
https://cloudsviewer.com/2021/09/29/aws-lambda-functions-powered-by-aws-graviton2-processor-run-your-functions-on-arm-and-get-up-to-34-better-price-performance/
CC-MAIN-2022-21
en
refinedweb
For realized that there was something fishy with my own dataset, so I fired up jupyter-notebook to gain some more insight in the IP structure of my dataset. My standard tool when dealing with packet analysis in Python is scapy. For visualization the quasi-standard is matplotlib. When dealing with graphs, I found NetworkX to be very reliable on bigger datasets. So let’s get started. First the usual dance: import networkx as nx import matplotlib.pyplot as plt from scapy.all import * %matplotlib inline When fiddling around, I noticed that a large-scale directed graph tends to get confusing very quickly as the arrowheads on long edges get distorted. An undirected graph is just as fine for me, because I just want to get a general impression of the datasets IP connection structure. G = nx.Graph() connections = set() nodes = set() Don’t forget to use sets to automatically filter out duplicate IP addresses. Now we will go through the dump packet by packet, extract the IP header data and add the relevant data to our sets. connections holds tuples containing source and destination, while nodes is a set of all existing IP addresses contained in the set. with PcapReader('/datasets/pcaps/internal-clean.pcap') as pcap_reader: for p in pcap_reader: if IP in p: nodes.add(p[IP].src) nodes.add(p[IP].dst) connections.add((p[IP].src, p[IP].dst)) Notice that I don’t use rdpcap as this would try to load the whole pcap into RAM. Even with my dataset of roughly 550MB, the scapy datastructures took in more of 3GB RAM and filled my swap of 4GB completely. Analyzing the data with my machine took approximately five minutes. I am aware that it would have been more efficient to throw away the payloads of the pcap or even convert it into NetFlow format. However that would have been out of the scope of this quick and dirty hack. 🙂 Now let’s add the data to our graph and prepare the figure size of matplotlib. The graph will get pretty big and the above figsize results in an image with 7250×5793 pixels. As there is a lot of data to look at, it’s always good to be able to zoom in and have a closer look at some hosts. G.add_nodes_from(nodes) G.add_edges_from(connections) plt.rcParams['figure.figsize'] = 150, 120 Now all we need to do is apply a layout to the graph and draw it using the NetworkX method that uses matplotlib by default. I found the Fruchterman-Reingold force-directed algorithm at >50 iterations to be the most visually pleasing and ordered. If you want to try your luck, a random layout might also yield good results. pos = nx.spring_layout(G, scale=1.0, iterations=100) nx.draw(G, pos, node_color='c',edge_color='k', with_labels=True) The above code results in the following image:
https://dmuhs.blog/2018/09/14/visualizing-ip-connections-in-python/
CC-MAIN-2022-21
en
refinedweb
Introduced in React version 16.8 (February 2019), React Hooks adds support for state management and lifecycle events to functional components. Hooks lets you write React applications using only functional components. With Hooks, you get such powerful functionality, you might decide to migrate your codebase. In this blog post, we’ll explore the benefits of using Hooks in your ReactJS application. We’ll also implement our own “Redux” state management layer using Hooks, so you can see what you will need to do to migrate. How You May Benefit from Hooks A functional component in React is a JavaScript function that accepts props and returns a React element. Functional components are easier to read, debug, and test than class components. They also have better performance benefits. However, prior to the release of Hooks, functional components did not have state or lifecycle methods. Instead, if a developer needed state management or lifecycle methods, they had to use class components, which are significantly more complex. Working with Hooks, you get all the benefits of class components together with the ease of functional components: • Reusable code: You can isolate stateful management logic from the visual aspect of your components more easily. When you do, you can reuse that logic and test both parts separately. You can read more about this and see examples of custom hooks in the official React documentation. • Improved code structure: You can restructure complex components more easily by splitting them into smaller pieces. This means you can avoid having non-related logic in traditional lifecycle events. (It’s very common to see a lot of different things for different purposes in functions like componentDidMount and componentDidUpdate.) • Smaller and more performant applications: Function components transpile into smaller pieces of code than class components. You get smaller bundles and, as a result, faster loading applications. • More testable code: By definition, function components are easier to test. This is because a pure function accepts N parameters and returns the same output given the same combination of inputs (this holds true as long as you implement your components as pure functions). • More maintainable code: Function components are easier to read and easier to digest, especially for new developers joining an existing team with an existing code base. This benefit also applies for existing team members. • Higher quality development processes: Taken all together, these benefits have a very positive impact on the overall development process. When you use Hooks in your codebase, you may achieve faster iterations, faster learning curves, higher quality development, improved user experiences, smaller error margins, and much more. Build Your Own “Redux” State Management Using Hooks As soon as Hooks launched, many development teams planned to migrate all their codebase from Redux, a popular state management tool frequently used with React, to Hooks. In this article, we will show how you can build your own “Redux” state management implementation using React Hooks. About Our Sample Application For this article, we created a sample app to manage a small soccer league. The app has three navigation levels: • Main: shows a list of all soccer leagues • Teams: shows a list of teams belonging to a specific league • Players: shows a list of all the players belonging to a specific team Simple, right? Nothing fancy. Disclaimer: The code in this article is Gist-based, derived from the actual code base written TypeScript. The application supports two different languages (Spanish and English). Language selection is a common enough feature. We will use the localization implementation in the step-by-step build process for the state management layer. Here’s a screen grab of the app running. You can view the app’s functionality here. Code Structure If you’re familiar with Redux, you will recognize the “store” directory and its typical scaffold: an inner directory for each reducer and so on. We’ll follow the same structure in this example, but we will rename the “store” directory to “state”: • Root of the project • state • localization • types • actions • reducer • middlewares • selectors • context State Type We’ll use the localization feature to build our “Redux” state management. First, we create the type of data we expect to handle on the localization reducer: export interface LocalizationState { languageId: string; language?: any | null | undefined; languages: Language[]; } We have just three properties: • languageId: ID of the current language • languages: list of available languages • language: JSON object with all the translations for the current language Actions Once we know the data, we must define the actions we might use to modify the state. For this step, we create a custom hook “useActions” to define our actions. We pass the “dispatch” function that we get from the “useReducer” hook (covered later on) into the custom hook: import { ACTION_TYPES } from './reducer'; import { LocalizationState } from './types'; export const useActions = (state: LocalizationState, dispatch: Function) => ({ updateLanguage: (languageId: string) => dispatch({ type: ACTION_TYPES.UPDATE_LANGUAGE, payload: languageId }), updateLanguages: (languages: Language[]) => dispatch({ type: ACTION_TYPES.UPDATE_LANGUAGES, payload: languages }) }); There are just two actions available to dispatch: • updateLanguage: change the current language • updateLanguages: feed the list of languages from the back-end So far, these are simple steps. Reducer With state type and actions in place, let’s define our reducer: import { LocalizationState } from './types'; const { REACT_APP_DEFAULT_LANGUAGE_ID: defaultLanguageId } = process.env; const initialState: LocalizationState = { languageId: defaultLanguageId || 'es-CR', language: undefined, languages: [] }; const ACTION_TYPES = { UPDATE_LANGUAGE: 'localization/UPDATE_LANGUAGE', FETCH_LANGUAGE: 'localization/FETCH_LANGUAGE', FETCH_LANGUAGE_REQUEST: 'localization/FETCH_LANGUAGE_REQUEST', FETCH_LANGUAGE_SUCCESS: 'localization/FETCH_LANGUAGE_SUCCESS', FETCH_LANGUAGE_FAILURE: 'localization/FETCH_LANGUAGE_FAILURE', UPDATE_LANGUAGES: 'localization/UPDATE_LANGUAGES' }; const reducer = (state = initialState, action: any) => { switch (action.type) { case ACTION_TYPES.UPDATE_LANGUAGE: return { ...state, languageId: action.payload }; case ACTION_TYPES.FETCH_LANGUAGE_SUCCESS: return { ...state, language: action.payload }; case ACTION_TYPES.UPDATE_LANGUAGES: return { ...state, languages: action.payload }; default: return state; } }; export { initialState, reducer, ACTION_TYPES }; As on a typical Redux reducer, this is only a function “listening” to actions and modifying the state accordingly. Note that, although “updateLanguage” and “updateLanguages” are the two actions defined in our actions module, we are also listening for the “FETCH_LANGUAGE_SUCSESS” action, which won’t be dispatched directly. Instead, the middleware we create in the next step will dispatch it. Middleware import { ACTION_TYPES } from './reducer'; // This is not the Redux store, is the local storage of the device import store from 'store'; export const applyMiddleware = (dispatch: Function) => async (action: any) => { dispatch(action); if (action.type !== ACTION_TYPES.UPDATE_LANGUAGE) { return; } dispatch({ type: ACTION_TYPES.FETCH_LANGUAGE_REQUEST }); try { const url = `/locales/${action.payload}.json`; const response = await fetch(url); const language = await response.json(); dispatch({ type: ACTION_TYPES.FETCH_LANGUAGE_SUCCESS, payload: language }); store.set('languageId', action.payload); } catch (e) { dispatch({ type: ACTION_TYPES.FETCH_LANGUAGE_FAILURE, payload: e }); } }; Note the following: • This middleware will use the dispatch function returned by the useReducer hook (see below). • We’re doing more than just “hooking” this middleware to the “updateLanguage” action and executing the logic to load the corresponding translations for the selected language. We’re also storing the languageID on the device’s local storage so it can be reused when the user starts the application again. This makes it possible for the application to display all the on-screen text using the preferred language. • This very simple scenario shows the power of middleware. Middleware was one of my main concerns when I started to see all the enthusiasm about moving from Redux to Hooks. • One alternative to this approach is to update the languageID directly on the component. However, this method could make maintenance challenging. If you provide users with several places to manage their preferred language, usability suffers. Selectors Selectors are optional and defined by your own requirements. In this case, we have a few selectors, and the most important one resolves a localized string based on a key. Again, we create a custom hook: import { LocalizationState } from './types'; export const useSelectors = (state: LocalizationState) => ({ localize: (key: string): string => { let localizedText = ''; // Fancy logic to resolve a localized text based on a key return ''; }, availableUnselectedLanguages: (): Language[] => { const { languageId: currentLanguageId } = state; return state.languages.filter(l => l.languageId !== currentLanguageId); }, activeLanguage: (): Language | undefined => { const { languageId: currentLanguageId } = state; return state.languages.find(l => l.languageId === currentLanguageId); } }); Context API Now we’re ready for some fun! The next step in creating a “Redux” State Management layer doesn’t involve a typical Redux setup, so we’ll explain every step. A key concept is the context API, which lets us share state to a specific part of an application. You can also share state to all levels of the application, if you expose the context provider at a very high level. This is what we’re doing in our example. Let’s define the type of data our localization context will handle: import { LocalizationState } from './types'; import { useActions } from './actions'; import { useSelectors } from './selectors'; type ContextType = { state: LocalizationState; actions: ReturnType<typeof useActions>; selectors: ReturnType<typeof useSelectors>; }; To provide a simple API to the developers from this localization context, we support three properties: • state: the data itself • actions: the set of actions that our custom “useActions” hook will provide • selectors: selectors provided by our custom “useSelectors” hook Because we’re using TypeScript and the context API requires an initial value satisfying the value type we just defined, we must create an initial instance with dummy functions for the actions and the selectors: import React, { createContext } from 'react'; import { initialState } from './reducer'; import { LocalizationState } from './types'; import { useActions } from './actions'; import { useSelectors } from './selectors'; type ContextType = { state: LocalizationState; actions: ReturnType<typeof useActions>;); With the context created and initialized, we create a component to wrap and expose the context provider (to use later on the App module): }; Note the following things happening: 1. We create a “LocalizationProvider” component just to mix all the things and expose the provider of the context we just created. 2. We create our reducer using the “useReducer” hook which returns a state value and a dispatch function. 3. We “enhance” our dispatch function by applying the middleware we previously created. 4. We hook our actions and selectors by calling our custom “useActions” and “useSelectors” hooks. 5. We put together the state returned by the “useReducer” hook, the actions, and the selectors to get the final value we need to provide to our context. 6. We export both the context provider and the context itself. We will see how to use both within the next steps. The final version of the context module looks like this: import React, { FC, createContext, useReducer } from 'react'; import { initialState, reducer } from './reducer'; import { applyMiddleware } from './middleware'; import { useActions } from './actions'; import { useSelectors } from './selectors'; import { LocalizationState } from './types'; type ContextType = { state: LocalizationState; actions: ReturnType<typeof use Actions>; }; Exposing the Context Provider Now that we have the context and its provider, we make it available at the application scope. On the App module, import the LocalizationProvider we just created and make it available at the very top level: import React from 'react'; import { LocalizationProvider } from './state/localization/context'; import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'; // Components import Menu from './components/Menu'; // Pages import Leagues from './pages/Leagues/Leagues'; import League from './pages/League/League'; import Team from './pages/Team/Team'; const App: React.FC = () => ( <LocalizationProvider> <Router> <div id="app"> <Menu /> <Switch> <Route path="/" exact component={Leagues} /> <Route path="/league/:leagueId?" component={League} /> <Route path="/team/:teamId?" component={Team} /> </Switch> </div> </Router> </LocalizationProvider> ); export default App; Note: In this example we use just one context, but you can create and expose all the different contexts you need in this same way. Hooking Components to Contexts You might think, “That context is wrapping my whole app! Will I need to re-render my entire app each time something changes in a context?” No, you don’t. We will re-render only those components that are hooked to the context that is changing. How? By hooking them using the context that we export, and by using the “useContext” hook, as the menu component does here: import React, { FC, useContext } from 'react'; import { LocalizationContext } from '../state/localization/context'; const Menu: FC = () => { // Localization context const localizationContext = useContext(LocalizationContext); const { selectors: { localize }, actions: { updateLanguage }, state: { languages, languageId: currentLanguageId } } = localizationContext; const onLanguageClick = (language: Language) => { updateLanguage(language.languageId); }; return ( <> ... some UI components ... <Toolbar> <Typography>{localize('components.mainMenu.language')}</Typography></Toolbar> <Divider /> <List className={classes.list}> {languages.map(l => ( <ListItem button key={l._id} onClick={() => onLanguageClick(l)}><ListItemText primary={l.name} /> <ListItemIcon> <Checkbox edge="end" checked={l.languageId === currentLanguageId} /> </ListItemIcon> </ListItem> ))} </List> ... some UI components ... </> ); }; export default Menu; Now you have your own “Redux” style state management in React, without using Redux. Your Migration to Hooks: A Path to Improved Development Our soccer league app example gives you a solid preview of all the benefits you can realize from Hooks. Reusable code, more performant applications, and improved overall quality of development efforts are just a few benefits. React is well established, and the React roadmap is following patterns defined by Hooks. You’ll find that support for React Hooks is widespread and increasing every day, including with popular modules such as Axios, Apollo, React Router, and more. You can be confident in a long-term investment in Hooks, and we recommend you consider migration. Consolidating practices, patterns, and architecture decisions could be a win for your development team and your entire organization. Want to read more about React? Check out my last blog post on building an Instagram-like app using React Native!
https://gorillalogic.com/blog/how-to-build-your-own-redux-state-management-implementation-based-on-hooks/
CC-MAIN-2022-21
en
refinedweb
Author: Russ Cox Last Updated: March 20, 2018 Discussion: We propose to add awareness of package versions to the Go toolchain, especially the go command. The first half of the blog post Go += Package Versioning presents detailed background for this change. In short, it is long past time to add versions to the working vocabulary of both Go developers and our tools, and this proposal describes a way to do that. Semantic versioning is the name given to an established convention for assigning version numbers to projects. In its simplest form, a version number is MAJOR.MINOR.PATCH, where MAJOR, MINOR, and PATCH are decimal numbers. The syntax used in this proposal follows the widespread convention of adding a “v” prefix: vMAJOR.MINOR.PATCH. Incrementing MAJOR indicates an expected breaking change. Otherwise, a later version is expected to be backwards compatible with earlier versions within the same MAJOR version sequence. Incrementing MINOR indicates a significant change or new features. Incrementing PATCH is meant to be reserved for very small, very safe changes, such as small bug fixes or critical security patches. The sequence of vgo-related blog posts presents more detail about the proposal. I propose to add versioning to Go using the following approach. Introduce the concept of a Go module, which is a group of packages that share a common prefix, the module path, and are versioned together as a single unit. Most projects will adopt a workflow in which a version-control repository corresponds exactly to a single module. Larger projects may wish to adopt a workflow in which a version-control repository can hold multiple modules. Both workflows will be supported. Assign version numbers to modules by tagging specific commits with semantic versions such as v1.2.0. (See the Defining Go Modules post for details, including how to tag multi-module repositories.) Adopt semantic import versioning, in which each major version has a distinct import path. Specifically, an import path contains a module path, a version number, and the the path to a specific package inside the module. If the major version is v0 or v1, then the version number element must be omitted; otherwise it must be included. The packages imported as my/thing/sub/pkg, my/thing/v2/sub/pkg, and my/thing/v3/sub/pkg come from major versions v1, v2, and v3 of the module my/thing, but the build treats them simply as three different packages. A program that imports all three will have all three linked into the final binary, just as if they were my/red/pkg, my/green/pkg, and my/blue/pkg or any other set of three different import paths. Note that only the major version appears in the import path: my/thing/v1.2/sub/pkg is not allowed. Explicitly adopt the “import compatibility rule”: If an old package and a new package have the same import path, the new package must be backwards compatible with the old package. The Go project has encouraged this convention from the start of the project, but this proposal gives it more teeth: upgrades by package users will succeed or fail only to the extent that package authors follow the import compatibility rule. The import compatibility rule only applies to tagged releases starting at v1.0.0. Prerelease (vX.Y.Z-anything) and v0.Y.Z versions need not follow compatibility with earlier versions, nor do they impose requirements on future versions. In contrast, tagging a commit vX.Y.Z for X ≥ 1 explicitly indicates “users can expect this module to be stable.” In general, users should expect a module to follow the Go 1 compatibility rules once it reaches v1.0.0, unless the module's documentation clearly states exceptions. Record each module‘s path and dependency requirements in a go.mod file stored in the root of the module’s file tree. To decide which module versions to use in a given build, apply minimal version selection: gather the transitive closure of all the listed requirements and then remove duplicates of a given major version of a module by keeping the maximum requested version, which is also the minimum version satisfying all listed requirements. Minimal version selection has two critical properties. First, it is trivial to implement and understand. Second, it never chooses a module version not listed in some go.mod file involved in the build: new versions are not incorporated simply because they have been published. The second property produces high-fidelity builds and makes sure that upgrades only happen when developers request them, never unexpectedly. Define a specific zip file structure as the “interchange format” for Go modules. The vast majority of developers will work directly with version control and never think much about these zip files, if at all, but having a single representation enables proxies, simplifies analysis sites like godoc.org or continuous integration, and likely enables more interesting tooling not yet envisioned. Define a URL schema for fetching Go modules from proxies, used both for installing modules using custom domain names and also when the $GOPROXY environment variable is set. The latter allows companies and individuals to send all module download requests through a proxy for security, availability, or other reasons. Allow running the go command in file trees outside GOPATH, provided there is a go.mod in the current directory or a parent directory. That go.mod file defines the mapping from file system to import path as well as the specific module versions used in the build. See the Versioned Go Commands post for details. Disallow use of vendor directories, except in one limited use: a vendor directory at the top of the file tree of the top-level module being built is still applied to the build, to continue to allow self-contained application repositories. (Ignoring other vendor directories ensures that Go returns to builds in which each import path has the same meaning throughout the build and establishes that only one copy of a package with a given import path is used in a given build.) The “Tour of Versioned Go” blog post demonstrates how most of this fits together to create a smooth user experience. Go has struggled with how to incorporate package versions since goinstall, the predecessor to go get, was released eight years ago. This proposal is the result of eight years of experience with goinstall and go get, careful examination of how other languages approach the versioning problem, and lessons learned from Dep, the experimental Go package management tool released in January 2017. A few people have asked why we should add the concept of versions to our tools at all. Packages do have versions, whether the tools understand them or not. Adding explicit support for versions lets tools and developers communicate more clearly when specifying a program to be built, run, or analyzed. At the start of the process that led to this proposal, almost two years ago, we all believed the answer would be to follow the package versioning approach exemplified by Ruby‘s Bundler and then Rust’s Cargo: tagged semantic versions, a hand-edited dependency constraint file known as a manifest, a machine-generated transitive dependency description known as a lock file, a version solver to compute a lock file satisfying the manifest, and repositories as the unit of versioning. Dep, the community effort led by Sam Boyer, follows this plan almost exactly and was originally intended to serve as the model for go command integration. Dep has been a significant help for Go developers and a positive step for the Go ecosystem. Early on, we talked about Dep simply becoming go dep, serving as the prototype of go command integration. However, the more I examined the details of the Bundler/Cargo/Dep approach and what they would mean for Go, especially built into the go command, a few of the details seemed less and less a good fit. This proposal adjusts those details in the hope of shipping a system that is easier for developers to understand and to use. Semantic versions are a reasonable convention for specifying software versions, and version control tags written as semantic versions have a clear meaning, but the semver spec critically does not prescribe how to build a system using them. What tools should do with the version information? Dave Cheney‘s 2015 proposal to adopt semantic versioning was eventually closed exactly because, even though everyone agreed semantic versions seemed like a good idea, we didn’t know the answer to the question of what to do with them. The Bundler/Cargo/Dep approach is one answer. Allow authors to specify arbitrary constraints on their dependencies. Build a given target by collecting all its dependencies recursively and finding a configuration satisfying all those constraints. Unfortunately, the arbitrary constraints make finding a satisfying configuration very difficult. There may be many satisfying configurations, with no clear way to choose just one. For example, if the only two ways to build A are by using B 1 and C 2 or by using B 2 and C 1, which should be preferred, and how should developers remember? Or there may be no satisfying configuration. Also, it can be very difficult to tell whether there are many, one, or no satisfying configurations: allowing arbitrary constraints makes version solving problem an NP-complete problem, equivalent to solving SAT. In fact, most package managers now rely on SAT solvers to decide which packages to install. But the general problem remains: there may be many equally good configurations, with no clear way to choose between them, there may be a single best configuration, or there may be no good configurations, and it can be very expensive to determine which is the case in a given build. This proposal's approach is a new answer, in which authors can specify only limited constraints on dependencies: only the minimum required versions. Like in Bundler/Cargo/Dep, this proposal builds a given target by collecting all dependencies recursively and then finding a configuration satisfying all constraints. However, unlike in Bundler/Cargo/Dep, the process of finding a satisfying configuration is trivial. As explained in the minimal version selection post, a satisfying configuration always exists, and the set of satisfying configurations forms a lattice with a unique minimum. That unique minimum is the configuration that uses exactly the specified version of each module, resolving multiple constraints for a given module by selecting the maximum constraint, or equivalently the minimum version that satisfies all constraints. That configuration is trivial to compute and easy for developers to understand and predict. A module‘s dependencies must clearly be given some control over that module’s build. For example, if A uses dependency B, which uses a feature of dependency C introduced in C 1.5, B must be able to ensure that A's build uses C 1.5 or later. At the same time, for builds to remain predictable and understandable, a build system‘s always possible to use a relatively recent version of D (D 1.98 or D 1.97, respectively). But when A uses both B and C, a SAT solver-based build silently selects the much older (and buggier) D 1.2 instead. To the extent that SAT solver-based build systems actually work, it is because dependencies don’t choose to exercise this level of control. But then why allow them that control in the first place? Although the hypothetical about prime and even versions is clearly unlikely, real problems do arise. For example, issue kubernetes/client-go#325 was filed in November 2017, complaining that the Kubernetes Go client pinned builds to a specific version of gopkg.in/yaml.v2 from September 2015, two years earlier.. The issue was closed after a change in February 2018 to update the specific YAML version pinned to one from July 2017. But the issue is not really “fixed”: Kubernetes still pins a specific, increasingly old version of the YAML library. The fundamental problem is that the build system allows the Kubernetes Go client to do this at all, at least when used as a dependency in a larger build. This proposal aims to balance allowing dependencies enough control to ensure a successful build with not allowing them so much control that they break the build. Minimum requirements combine without conflict, so it is feasible (even easy) to gather them from all dependencies, and they make it impossible to pin older versions, as Kubernetes does. Minimal version selection gives the top-level module in the build additional control, allowing it to exclude specific module versions or replace others with different code, but those exclusions and replacements only apply when found in the top-level module, not when the module is a dependency in a larger build. A module author is therefore in complete control of that module‘s build when it is the main program being built, but not in complete control of other users’ builds that depend on the module. I believe this distinction will make this proposal scale to much larger, more distributed code bases than the Bundler/Cargo/Dep approach. Allowing all modules involved in a build to impose arbitrary constraints on the surrounding build harms not just that build but the entire language ecosystem. If the author of popular package P finds that dependency D 1.5 has introduced a change that makes P no longer work, other systems encourage the author of P to issue a new version that explicitly declares it needs D < 1.5. Suppose also that popular package Q is eager to take advantage of a new feature in D 1.5 and issues a new version that explicitly declares it needs D ≥ 1.6. Now the ecosystem is divided, and programs must choose sides: are they P-using or Q-using? They cannot be both. In contrast, being allowed to specify only a minimum required version for a dependency makes clear that P‘s author must either (1) release a new, fixed version of P; (2) contact D’s author to issue a fixed D 1.6 and then release a new P declaring a requirement on D 1.6 or later; or else (3) start using a fork of D 1.4 with a different import path. Note the difference between a new P that requires “D before 1.5” compared to “D 1.6 or later.” Both avoid D 1.5, but “D before 1.5” explains only which builds fail, while “D 1.6 or later” explains how to make a build succeed. The example of ecosystem fragmentation in the previous section is worse when it involves major versions. Suppose the author of popular package P has used D 1.X as a dependency, and then popular package Q decides to update to D 2.X because it is a nicer API. If we adopt Dep's semantics, now the ecosystem is again divided, and programs must again choose sides: are they P-using (D 1.X-using) or Q-using (D 2.X-using)? They cannot be both. Worse, in this case, because D 1.X and D 2.X are different major versions with different APIs, it is completely reasonable for the author of P to continue to use D 1.X, which might even continue to be updated with features and bug fixes. That continued usage only prolongs the divide. The end result is that a widely-used package like D would in practice either be practically prohibited from issue version 2 or else split the ecosystem in half by doing so. Neither outcome is desirable. Rust‘s Cargo makes a different choice from Dep. Cargo allows each package to specify whether a reference to D means D 1.X or D 2.X. Then, if needed, Cargo links both a D 1.X and a D 2.X into the final binary. This approach works better than Dep’s, but users can still get stuck. If P exposes D 1.X in its own API and Q exposes D 2.X in its own API, then a single client package C cannot use both P and Q, because it will not be able to refer to both D 1.X (when using P) and D 2.X (when using Q). The dependency story in the semantic import versioning post presents an equivalent scenario in more detail. In that story, the base package manager starts out being like Dep, and the -fmultiverse flag makes it more like Cargo. If Cargo is one step away from Dep, semantic import versioning is two steps away. In addition to allowing different major versions to be used in a single build, semantic import versioning gives the different major versions different names, so that there's never any ambiguity about which is meant in a given program file. Making the import paths precise about the expected semantics of the thing being imported (is it v1 or v2?) eliminates the possibility of problems like those client C experienced in the previous example. More generally, in semantic import versioning, an import of my/thing asks for the semantics of v1.X of my/thing. As long as my/thing is following the import compatibility rule, that's a well-defined set of functionality, satisfied by the latest v1.X and possibly earlier ones (as constrained by go.mod). Similarly, an import of my/thing/v2 asks for the semantics of v2.X of my/thing, satisfied by the latest v2.X and possibly earlier ones (again constrained by go.mod). The meaning of the imports is clear, to both people and tools, from reading only the Go source code, without reference to go.mod. If instead we followed the Cargo approach, both imports would be my/thing, and the meaning of that import would be ambiguous from the source code alone, resolved only by reading go.mod. Our article “About the go command” explains:. It is an explicit goal of this proposal's design to preserve this property, to avoid making the general semantics of a Go source file change depending on the contents of go.mod. With semantic import versioning, if go.mod is deleted and recreated from scratch, the effect is only to possibly update to newer versions of imported packages, but still ones that are still expected to work, thanks to import compatibility. In contrast, if we take the Cargo approach, in which the go.mod file must disambiguate between the arbitrarily different semantics of v1 and v2 of my/thing, then go.mod becomes a required configuration file, violating the original goal. More generally, the main objection to adding /v2/ to import paths is that it‘s a bit longer, a bit ugly, and it makes explicit a semantically important detail that other systems abstract away, which in turn induces more work for authors, compared to other systems, when they change that detail. But all of these were true when we introduced goinstall‘s URL-like import paths, and they’ve been a clear success. Before goinstall, programmers wrote things like import "igo/set". To make that import work, you had to know to first check out github.com/jacobsa/igo into $GOPATH/src/igo. The abbreviated paths had the benefit that if you preferred a different version of igo, you could check your variant into $GOPATH/src/igo instead, without updating any imports. But the abbreviated imports also had the very real drawbacks that a build trying to use both igo/set variants could not, and also that the Go source code did not record anywhere exactly which igo/set it meant. When goinstall introduced import "github.com/jacobsa/igo/set" instead, that made the imports a bit longer and a bit ugly, but it also made explicit a semantically important detail: exactly which igo/set was meant. The longer paths created a little more work for authors compared to systems that stashed that information in a single configuration file. But eight years later, no one notices the longer import paths, we’ve stopped seeing them as ugly, and we now rely on the benefits of being explicit about exactly which package is meant by a given import. I expect that once /v2/ elements in import paths are common in Go source files, the same will happen: we will no longer notice the longer paths, we will stop seeing them as ugly, and we will rely on the benefits of being explicit about exactly which semantics are meant by a given import. In the Bundler/Cargo/Dep approach, the package manager always prefers to use the latest version of any dependency. These systems use the lock file to override that behavior, holding the updates back. But lock files only apply to whole-program builds, not to newly imported libraries. If you are working on module A, and you add a new requirement on module B, which in turn requires module C, these systems will fetch the latest of B and then also the latest of C. In contrast, this proposal still fetches the latest of B (because it is what you are adding to the project explicitly, and the default is to take the latest of explicit additions) but then prefers to use the exact version of C that B requires. Although newer versions of C should work, it is safest to use the one that B did. Of course, if the build has a different reason to use a newer version of C, it can do that. For example, if A also imports D, which requires a newer C, then the build should and will use that newer version. But in the absence of such an overriding requirement, minimal version selection will build A using the exact version of C requested by B. If, later, a new version of B is released requesting a newer version of C, then when A updates to that newer B, C will be updated only to the version that the new B requires, not farther. The minimal version selection blog post refers to this kind of build as a “high-fidelity build.” Minimal version selection has the key property that a recently-published version of C is never used automatically. It is only used when a developer asks for it explicitly. For example, the developer of A could ask for all dependencies, including transitive dependencies, to be updated. Or, less directly, the developer of B could update C and release a new B, and then the developer of A could update B. But either way, some developer working on some package in the build must take an explicit action asking for C to be updated, and then the update does not take effect in A's build until a developer working on A updates some dependency leading to C. Waiting until an update is requested ensures that updates only happen when developers are ready to test them and deal with the possibility of breakage. Many developers recoil at the idea that adding the latest B would not automatically also add the latest C, but if C was just released, there's no guarantee it works in this build. The more conservative position is to avoid using it until the user asks. For comparison, the Go 1.9 go command does not automatically start using Go 1.10 the day Go 1.10 is released. Instead, users are expected to update on their own schedule, so that they can control when they take on the risk of things breaking. The reasons not to update automatically to the latest Go release applies even more to individual packages: there are more of them, and most are not tested for backwards compatibility as extensively as Go releases are. If a developer does want to update all dependencies to the latest version, that's easy: go get -u. We may also add a go get -p that updates all dependencies to their latest patch versions, so that C 1.2.3 might be updated to C 1.2.5 but not to C 1.3.0. If the Go community as a whole reserved patch versions only for very safe or security-critical changes, then that -p behavior might be useful. The work in this proposal is not constrained by the compatibility guidelines at all. Those guidelines apply to the language and standard library APIs, not tooling. Even so, compatibility more generally is a critical concern. It would be a serious mistake to deploy changes to the go command in a way that breaks all existing Go code or splits the ecosystem into module-aware and non-module-aware packages. On the contrary, we must make the transition as smooth and seamless as possible. Module-aware builds can import non-module-aware packages (those outside a tree with a go.mod file) provided they are tagged with a v0 or v1 semantic version. They can also refer to any specific commit using a “pseudo-version” of the form v0.0.0-yyyymmddhhmmss-commit. The pseudo-version form allows referring to untagged commits as well as commits that are tagged with semantic versions at v2 or above but that do not follow the semantic import versioning convention. Module-aware builds can also consume requirement information not just from go.mod files but also from all known pre-existing version metadata files in the Go ecosystem: GLOCKFILE, Godeps/Godeps.json, Gopkg.lock, dependencies.tsv, glide.lock, vendor.conf, vendor.yml, vendor/manifest, and vendor/vendor.json. Existing tools like dep should have no trouble consuming Go modules, simply ignoring the go.mod file. It may also be helpful to add support to dep to read go.mod files in dependencies, so that dep users are unaffected as their dependencies move from dep to the new module support. A prototype of the proposal is implemented in a fork of the go command called vgo, available using go get -u golang.org/x/vgo. We will refine this implementation during the Go 1.11 cycle and merge it back into cmd/go in the main repository. The plan, subject to proposal approval, is to release module support in Go 1.11 as an optional feature that may still change. The Go 1.11 release will give users a chance to use modules “for real” and provide critical feedback. Even though the details may change, future releases will be able to consume Go 1.11-compatible source trees. For example, Go 1.12 will understand how to consume the Go 1.11 go.mod file syntax, even if by then the file syntax or even the file name has changed. In a later release (say, Go 1.12), we will declare the module support completed. In a later release (say, Go 1.13), we will end support for go get of non-modules. Support for working in GOPATH will continue indefinitely. We have not yet converted large, complex repositories to use modules. We intend to work with the Kubernetes team and others (perhaps CoreOS, Docker) to convert their use cases. It is possible those conversions will turn up reasons for adjustments to the proposal as described here.
https://go.googlesource.com/proposal/+/master/design/24301-versioned-go.md
CC-MAIN-2019-13
en
refinedweb
Adventures in USRP tuning These days, USRP radios are prevalent in our corner of radio science. Where I'm writing from at MIT Haystack Observatory, we have many USRP flavors in use: N200, B210, B210 mini, and X310. Readers who are otherwise unfamiliar with USRPs may recognize the name from an earlier post on the EISCAT 3D demonstrator array, which is using new custom N3x0 units. As a product line, I like USRPs because they are flexible, have the performance I want, and can be obtained at a reasonable price. Perhaps the most important feature, though, is that the USRPs run on and integrate well with open source software. At least, that's the key to this adventure. We recently acquired some X310s with UBX daughterboards to test them out as transmit units for geospace radar. Things were working reasonably well: set the center frequency of 440 MHz, feed the radio a waveform of our choosing, and the RF transmission would appear at the output as desired. Well, almost as desired. You see, the output at the tuning frequency is known to have a spurious tone, so directly tuning to the center frequency on transmit or receive is not recommended. In practice, the unwanted DC component is not so significant that it ruins the transmitted waveform. But being the perfectionist type, I wanted to see if I could eliminate it anyway. The typical solution is to tune to an offset frequency and do the final frequency shift digitally. The UHD software layer that runs the USRPs makes this easy; all one has to do is request a particular offset. However, requesting 440 MHz + 10 MHz offset (to keep the spurious signal well outside our waveform band) resulted in... an actual center frequency of 439999999.991 Hz and an offset of 10000000.009 Hz. Hmm. That gets rid of the DC spur, but now the tuning is subtly off. A 9 millihertz offset might work for most applications, but we want phase coherence over many pulses with a receiver that doesn't necessarily have the same small offset from 440 MHz. Time to investigate. Anyone not interested in the details of USRP tuning should move right along. After carefully reading the UHD source code (yay open source!) and experimenting with settings, I now think I know what is going on. Given a desired center frequency and local oscillator (LO) offset, the first thing the UHD software will do is calculate the desired RF frequency as (center_freq + lo_offset). It will then ask the daughterboard to try to tune that frequency, resulting in an actual RF frequency that may be slightly different. Then given the actual RF frequency and the desired center frequency, the software will calculate the desired digital signal processing (DSP) frequency as (actual_rf_freq - center_freq). Then it will ask the mainboard to set that digital frequency offset using the FPGA, resulting in an actual DSP frequency that may be slightly different. How this actually plays out depends on both on the USRP mainboard (X310, N200, B210, etc.) and on the tuner daughterboard in use (UBX, TwinRX, BasicRX, etc.). (Disclaimer: I'm going to make general statements here assuming that it works for all USRPs, but I haven't checked that and in actuality the details could be a little different. YMMV.) The common component for all of the radios is the DSP frequency correction on board the FPGA of the mainboard, so I'll start there. This is accomplished through a CORDIC stage on the FPGA, so the possible frequency steps end up being the mainboard clock rate divided by 2^32. So for the X3xx series with a clock rate of 200 MHz, this means possible DSP offsets must be a multiple of (200e6/2^32) = .046566 Hz. A DSP offset of 2 MHz, for instance, is not exactly possible (closest is 2.0000000018626451 MHz), but 1.5625 MHz, 3.125 MHz, 6.25 MHz, 12.5 MHz are (among many others). Of course, it is also necessary at a minimum to keep the DSP offset within half the bandwidth of the analog low-pass filter used by the daughterboard, so offsets can't be arbitrarily large. The other component is the RF tuning done by the daughterboard card, and for those there seems to be much more variety in architecture. Many will at some point involve a phase-locked loop (PLL) that tracks a desired frequency given a smaller reference, usually the daughterboard clock frequency divided by an integer divider. That reference frequency is then multiplied by either an integer factor (N) or a fractional factor of the form (N + K/4095), depending on the PLL mode used. UHD will let you adjust any of the following if the device supports it: the PLL mode between integer and fractional, the daughterboard clock frequency, and the integer divider that gives the PLL reference from the clock frequency. The latter is done by setting the tuning step size, which only applies in integer mode of the PLL. For specifics about what each daughterboard supports, the best resource I found is the source code itself. So practically, there are 6 settings that I'm aware of that help you control USRP tuning: - Desired center frequency (center_freq) - Desired offset frequency (lo_offset) - Mainboard clock rate (master_clock_rate=X) - Daughterboard clock rate (dboard_clock_rate=X) - PLL mode (mode_n=[integer/fractional]) - Integer-mode tuning step size (int_n_step=X) from gnuradio import uhdThe clock rates are set as part of the device string: u = uhd.usrp_source( device_addr=','.join([ "addr=192.168.10.2", "master_clock_rate=200e6", "dboard_clock_rate=20e6", ]), ... )The remaining settings are given as a tune_request object and passed to the set_center_freq method: req = uhd.tune_request( center_freq, lo_offset, args=uhd.device_addr(','.join([ "mode_n=integer", "int_n_step=100e3", ])), ) u.set_center_freq(req, ch_num) Returning to the inciting case, we now have a better way of setting a tuning offset while still resulting in a center frequency of exactly 440 MHz using the X310 and UBX daughterboard. First, set the daughterboard clock rate to 20 MHz, both because it is recommended and because it allows us to control the input frequency into the PLL. Then, set the PLL mode to "integer" and give a tuning step size of 100 kHz, which is possible because (20e6/100e3) = 200 gives a small integer divider for getting the PLL reference frequency from the daughterboard clock frequency. Now we know we can exactly tune any RF frequency that is a multiple of 100 kHz. Finally, knowing that the master clock rate is 200 MHz so that possible DSP offsets must be a multiple of (200e6/2^32), choose a desired LO offset of 12.5 MHz (=200e6/16). This gives a desired RF frequency of 452.5 MHz, which is a multiple of 100 kHz. This results in a 440 MHz tuning that is exact. Incidentally, we now know that the original direct exact tuning of 440 MHz was a bit of a fluke: it just so happens that 440 MHz is an exact fractional multiple of the default UBX clock rate of 50 MHz, i.e. (8 + 3276/4095)*50e6 = 440e6. If you've made it this far, hopefully you will find this information useful! Now go forth and tune some USRPs. Awesome! Many times I've trawled mailing lists and source code for this information. Good that you wrote up a nice one stop summary on tuning!
http://www.radio-science.net/2017/12/adventures-in-usrp-tuning.html
CC-MAIN-2019-13
en
refinedweb
Local and remote notifications get the user’s attention by displaying an alert, badging your app’s icon, or playing sounds. These interactions occur when your app isn’t running or is in the background. They let users know that your app has relevant information for them to view. Push messaging should be integrated using Apple Push Notification service. Woosmap Mobile SDK uses iOS regionMonitoring to send location based notifications. Regions are a shared system resource, and the total number of regions available systemwide is limited. For this reason, Core Location limits to 20 the number of regions that may be simultaneously monitored by a single app. Enable Remote-Notifications Woosmap uses background modes to track when push messages are received on a user’s device before the message is opened. To enable push messaging, select your project from the Project Navigator, choose your application’s target, open the Capabilities tab, and within Background Modes, add tick the Remote notifications checkbox. You can also specify this key directly through your Info.plist as follow: <key>UIBackgroundModes</key> <array> <string>remote-notifications</string> </array> If you already support push notifications in your app, skip to the section below about uploading your push certificate. Create Apple Push Notification Certificate Log in to the Apple Developer console and go to Certificates, Identifiers & Profiles. - Select Identifiers > App IDs and then select your app. - Click Edit to update the app settings. - If not already enabled, tick the Push Notifications service checkbox to enable it. - If you already have a certificate created which you can use, download it and proceed to the next step. If not, click Create Certificate…. - Follow the instructions on the next webpage to create a certificate request on your Mac, and click Continue. - On the Generate your certificate page, click Choose File and choose the certificate request file you just created (with a .certSigningRequestextension) and then click Continue. - Download the generated certificate to your Mac and then open the .cerfile to install it in Keychain Access. Because Apple treats development and production as separate instances, we strongly suggest to create separate projects based on intended use, such as one for your development environment and one for the production environment. Upload Apple Push Notification Certificate To allow Woosmap to send push messages on your behalf, you must provide Woosmap with the certificate you generated. - Launch Keychain Access on your Mac. - In the Category section, select My Certificates. - Find the certificate you generated and expand it to disclose its contents. You’ll see both a certificate and a private key. - Select both the certificate and the key, and select File > Export Items… from the menu and save it as .pemformat. Then, you’ll have to send us your certificate as well as the password of certificate to let us import it for your desired project. Please, use the contact form if we’re no already in touch. Asking Permission to Use Notifications Because the user might consider notification-based interactions disruptive, you must obtain permission to use them. Request Authorization at Launch Time Make your authorization request during your app’s launch cycle. In your app’s launch-time code, get the shared UNUserNotificationCenter object and call its requestAuthorization(options:completionHandler:) method, as shown below. Specify all of the interaction types that your app employs. The example requests authorization to display badge, alerts and play sounds. import WoosmapNow import UserNotifications let notificationCenter = UNUserNotificationCenter.current() // Request permission to display alerts and play sounds. notificationCenter.requestAuthorization(options: [.alert, .sound]) { (granted, error) in UIApplication.shared.registerForRemoteNotifications() } Handle remote notification Tells the delegate that the app successfully registered with Apple Push Notification service. For success registration func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data){ Now.shared.setRemoteNotificationToken(remoteNotificationToken: deviceToken) } And failed registration func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { NSLog("Error on getting remote notification token : \(error.localizedDescription)") } Rich push notifications (optional) Requires iOS 10.0 or above. If you want rich notifications (Image, subtitles and more…), proceed to the following steps. Create Notification Service Extension - In Xcode, navigate to File > New > Target and select Notification Service Extension. - Click Next, fill out the Product Name as NotificationService, and click Finish. - Click Activate on the prompt shown to activate the service extension. Xcode will now create a new top level folder in your project with the name NotificationService. Update service extension classes Replace NotificationService.swift with the below code. import UserNotifications import WoosmapNowNotification class NotificationService: WoosmapNowNotification { } Woosmap is tagging its Notifications payload with a woosmap key in userInfo’s dict. If your app is already using a NotificationExtension you can filter received payload by handling only those without this flag. Tracking opened notifications Woosmap provides a method to notify our backends that the sent notification has been opened by the user. userInfo is the notification payload. It can be provided by the didReceiveRemoteNotification method from AppDelegate. Now.shared.notificationOpened(userInfo: userInfo) Beware that this AppDelegate method is called only when the app received a remote notification AND is running (in background or foreground). This means that you should check for your App’s current state. Or it can be provided by the didFinishLaunchingWithOptions if your app wasn’t running. Now.shared.notificationOpened(userInfo: launchOptions![UIApplicationLaunchOptionsKey.remoteNotification]) Please, refer to our iOS Simple App hosted on GitHub for a sample app.
https://developers.woosmap.com/mobile/ios/ios-push-messaging.html
CC-MAIN-2019-13
en
refinedweb
Is your application, server, or service delivering the appropriate speed of need? How do you know? Are you 100-percent certain that your latest feature hasn’t triggered a performance degradation or memory leak? There's only one way to verify - and that's by regularly checking the performance of your app. But which tool should you use for this? In this blog post, we'll review the pros and cons of the leading open-source solutions for load and performance testing. If you're like many, chances are you've already seen this great list of 53 of the most commonly used open source performance testing tools. However, the truth is many of these tools aren’t necessarily suited to our needs. Some are limited to the HTTP protocol. Some haven’t been updated for years. Most aren’t flexible enough to provide parametrization, correlation, assertions and distributed testing capabilities. Given the challenges most of us face today, I would whittle this down to a short list of the following four options that we will review in this post: - The Grinder - Gatling - Tsung - JMeter - Locust We’ll cover the main features of each tool, show a simple load-test scenario, and display sample reports. At the end, you'll find a comparison matrix to help you decide which tool is best for your project. Just as a short note, if you are looking for a way to automate these open source tools, BlazeMeter created Taurus, our own open source test automation tool that exends and abstracts most of the above tools (as well as Selenium), and helps to overcome various challenges. Taurus provides a simple way to create, run and analyze performance tests. Make sure to check it out. THE TEST SCENARIO AND INFRASTRUCTURE For our comparisons we will use a simple a HTTP GET request from 20 threads with 100,000 iterations. Each tool will send requests as fast as it can. The server side (application under test): CPU: 4x Xeon L5520 @ 2.27 GHz RAM: 8GB OS: Microsoft Windows Server 2008 R2 x64 Application Server: IIS 7.5.7600.16385 The client side (load generator): CPU: 4x Xeon L5520 @ 2.27 GHz RAM: 4GB OS: Ubuntu Server 12.04 64-bit Load test tools: 1. THE GRINDER The Grinder is a free Java-based load-testing framework available under a BSD-style open-source license. It was developed by Paco Gomez and is maintained by Philip Aston. Over the years, the community has also contributed many improvements, fixes, and translations. The Grinder consists of: - The Grinder Console - This GUI application controls various Grinder agents and monitors results in real time. The console can be used as a basic interactive development environment (IDE) for editing or developing test suites. - Grinder Agents - Each of these are headless load generators can have a number of workers to create the load Key Features of The Grinder: - TCP proxy to record network activity into the Grinder test script - Distributed testing that scales with an the increasing number of agent instances - Power of Python or Closure, combined with any Java API, for test script creation or modification - Flexible parameterization, which includes creating test data on the fly and the ability to use external data sources like files and databases - Post-processing and assertion with full access to test results for correlation and content verification - Support of multiple protocols The Grinder Console Running a Sample Test Grinder Test Results: The Gatling Project is another free and open source performance testing tool, primarily developed and maintained by Stephane Landelle. Gatling has a basic GUI that's limited to test recorder only. However, the tests can be developed in easily readable/writable domain-specific language (DSL). Key Features of Gatling: HTTP Recorder An expressive self-explanatory DSL for test development Scala-based Production of higher load using an asynchronous non-blocking approach Full support of HTTP(S) protocols and can also be used for JDBC and JMS load testing Multiple input sources for data-driven tests Powerful and flexible validation and assertions system Comprehensive informative load reports The Gatling Recorder Window: An Example of a Gatling Report for a Load Scenario If you are interested in more information about Gatling, view our on-demand webcast Load Testing at Scale Using Gatling and Taurus. TSUNG Tsung (previously known as IDX-Tsunami) is the only non-Java-based open-source performance-testing tool in this review. Tsung relies on Erlang, so you’ll need to have it installed (for Debian/Ubuntu, it’s as simple as "apt-get install erlang”). Tsung was launched in 2001 by Nicolas Niclausse, who originally implemented a distributed-load-testing solution for Jabber (XMPP). Several months later, support for more protocols was added and, in 2003, Tsung was able to perform HTTP Protocol load testing. Today, it’s a fully functional performance-testing solution with the support of modern protocols like websockets, authentication systems, and databases. Key Features of Tsung: - Inherently distributed design - Underlying multithreaded-oriented Erlang architecture simulates thousands of virtual users on mid-range developer machines - Support of multiple protocols - A test recorder that supports HTTP and Postgres - Metrics for operating systems for both the load generator and application under test can be collected via several protocols - Dynamic scenarios and mixed behaviors. Flexible load scenarios let you define and combine any number of load patterns in a single test - Post processing and correlation - External data sources for data driven testing - Embedded easily-readable load reports that can be collected and visualized during load Tsung doesn’t provide a GUI for test development or execution. So you’lll have to live with shell scripts, which are: - Tsung-recorder, a bash script that records a utility capable of capturing HTTP and Postgres requests and that creates a Tsung config file from them - Tsung, a main bash control script to start/stop/debug and view test status - Tsung_stats.pl, a Perl script to generate HTML statistical and graphical reports. It requires the gnuplot and Perl Template library. For Debian/Ubuntu, the commands are: - apt-get install gnuplo - apt-get install libtemplate-perl The main tsung script invocation produces the following output: Running the test: Querying the current test status: Generating the statistics report with graphs can be done via the tsung_stats.pl script: Open report.html with your favorite browser to get the load report. A sample report for a demo scenario is provided below: A Tsung Statistical Report A Tsung Graphical Report APACHE JMETER Apache JMeter™ is the only desktop application in this review. It has a user-friendly GUI, making test development and debugging much easier. The earliest version of JMeter available for download is dated March 9, 2001. Since then, JMeter has been widely adopted and is now a popular open-source alternative to proprietary solutions like Silk Performer and LoadRunner. JMeter has a modular structure, in which the core is extended by plugins. This means that all implemented protocols and features are plugins that have been developed by the Apache Software Foundation or online contributors. Key Features of JMeter: Cross-platform. JMeter can run on any operating system with Java Scalable. When you need a higher load than a single machine can create, JMeter can execute in a distributed mode, meaning one master JMeter machine controls a number of remote hosts. Multi-protocol support. The following protocols are all supported out-of-the-box: HTTP, SMTP, POP3, LDAP, JDBC, FTP, JMS, SOAP, TCP Multiple implementations of pre- and post-processors around sampler. This provides advanced setup, teardown parametrization, and correlation capabilities Various assertions to define criteria Multiple built-in and external listeners to visualize and analyze performance test results Integration with major build and continuous integration systems, making JMeter performance tests part of the full software development life cycle The JMeter Application With an Aggregated Report on the Load Scenario: LOCUST Locust in a Python-based open source framework, which enables writing performance scripts in pure Python language. The main uniqueness of this framework is that it was developed by developers and for developers. The main Locust targets are web applications and web-based services, however, if you are comfortable with Python scripting, you can test almost anything you want. In addition to that, it is worth mentioning that Locust has a completely different way to simulate users, which is fully based on the events approach and gevent coroutine as the backbone for this process. This process allows simulating thousands of users even on a regular laptop, and executing even very complex scenarios that have many steps. Locust Key Features: - Cross-platform, because Python can be run on any OS - High scalability on regular machines due to events based implementation - Power assertion ability, limited only by your own Python knowledge (you can read this article to learn more about Locust assertions) - Nice web-based load monitoring - Code-based scripts implementation that is handy to use with version control (Git, SVN...) - Scalability, because you can run Locust distributed with many agents - The ability to test almost anything with the implementation of custom samplers based on pure Python code Basic test script example: from locust import HttpLocust, TaskSet, task class SimpleLocustTest(TaskSet): @task def get_something(self): self.client.get("/") class LocustTests(HttpLocust): task_set = SimpleLocustTest You can run the script by using this command: locust -f locustfile.py --host= After the script execution, you will find the detailed reporting on: HOW BLAZEMETER LOAD TESTING CLOUD COMPLEMENTS AND STRENGTHENS JMETER While Apache JMeter represents a strong and compelling way to perform load testing, of course, we recommend supplementing that tool with BlazeMeter Load Testing Cloud, which lets you simulate up to 1 million users in a single developer-friendly, self-service platform. With BlazeMeter, you can test the performance of any mobile app, website, or API in under 10 minutes. Here’s why we think the BlazeMeter/JMeter combination is attractive to developers: • Simple Scalability – It’s easy to create large-scale JMeter tests. You can run far larger loads far more easily with BlazeMeter than you could with an in-house lab. • Rapid-Start Deployment – BlazeMeter’s recorder helps you get started with JMeter right away, and BlazeMeter also provides complete tutorials and tips. • Web-Based Interactive Reports – You can easily share results across distributed teams and overcome the limitations of JMeter’s standalone UI. • Built-In Intelligence – The BlazeMeter Cloud provides on-demand geographic distribution of load generation, including built-in CDN-aware testing. THE GRINDER, GATLING, TSUNG, LOCUST AND JMETER PUT TO THE TEST Let’s compare the load test results of these tools with the following metrics: Average Response Time (ms) Average Throughput (requests/second) Total Test Execution Time (minutes) First, let’s look at the average response and total test execution times: As shown in the graphs, Locust has the fastest response times with the highest average throughout, followed by JMeter, Tsung and Gatling. The Grinder has the slowest times with the lowest average throughput. FEATURES COMPARISON TABLE And finally, here’s a comparison table of the key features offered by each testing tool: RESOURCES Want to find out more about these tools? Log onto the websites below - or post a comment here and I’ll do my best to answer! The Grinder - Gatling - Tsung - Locust - JMeter JMeter Plugins: Blazemeter’s Plugin for JMeter: On a Final Note... As I mentioned at the start, you might also want to read more about Taurus. When it comes to performance testing, a lot of these are really great...but not perfect. Automation and integration with other systems can be a pain, and the tool itself comes with a steep learning curve. Taurus is an open source test automation tool that provides a simple way to create, run and analyze performance tests. Want to Learn More About Load Testing With Open Source Tools? Do you have questions about open source testing tools? View our webinar Ask the Expert: Open Source Testing with JMeter, Gatling, Selenium, and Taurus. This special interactive presentation and Q&A was hosted by Andrey Pokhilko, founder of JMeter-Plugins.org, a core JMeter contributor, and creator and lead developer on the Taurus project. Do you want to try out JMeter? Learn for free from our JMeter academy. Start testing now! To try out BlazeMeter, which enhances JMeter features, request a demo, or just put your URL or JMX file in the vox below and your test will start in minutes. To run Locust, Gatling, The Grinder and Tsung automatically and more easily, try out Taurus. The parts about Locust were contributed by Yuri Bushnev. You might also find these useful: Taurus: A New Star in the Test Automation Tools Constellation Navigating your First Steps Using Taurus Interested in writing for our Blog? Send us a pitch!
https://www.blazemeter.com/blog/open-source-load-testing-tools-which-one-should-you-use?utm_source=Blog&utm_medium=BM_blog&utm_campaign=monitoringtools
CC-MAIN-2019-13
en
refinedweb