text stringlengths 454 608k | url stringlengths 17 896 | dump stringclasses 91
values | source stringclasses 1
value | word_count int64 101 114k | flesch_reading_ease float64 50 104 |
|---|---|---|---|---|---|
09 September 2010 13:44 [Source: ICIS news]
Correction: In the ICIS story headlined “Indorama restarts Lithuania PET plant after unplanned outage” dated 9 September 2010, please read in the last paragraph … Indorama has a 150,000 tonne/year PET plant at Workington, UK, and 200,000 tonne/year plant at Rotterdam, the Netherlands … instead of … 200,000 tonne/year PET plant at Workington, UK, and 150,000 tonne/year plant at Rotterdam…. A corrected story follows.
LONDON (ICIS)--Indorama Ventures has restarted its 200,000 tonne/year polyethylene terephthalate (PET) plant at ?xml:namespace>
“[Disruption to customers] has been mitigated to a minimum. We have backed it up with supply from other operations,” said the source.
The unit was shut down because of a mechanical failure, which has since been fixed, the source added.
The shutdown came amid proposed rises in European PET prices.
Producers said they aim to increase September prices by up to €50/tonne compared with the previous month’s range, which was assessed by ICIS at €1,050-1,100/tonne ($1,329-1,392/tonne) FD (free delivered) Europe.
The prices targets were attributed to higher feedstock costs, such as monoethylene glycol (MEG) and paraxylene (PX), at a time of limited imports, according to market sources.
Spot PET was reported around €1,100/tonne, up from the mid-€1,000s/tonne seen in August, buyers and sellers agreed.
Indorama has a 200,000 tonne/year PET plant at
($1 = €0.79)
For more on PET | http://www.icis.com/Articles/2010/09/09/9392279/corrected-indorama-restarts-lithuania-pet-plant-after-unplanned-outage.html | CC-MAIN-2014-42 | refinedweb | 251 | 61.36 |
Note: gcc compilation examples are given at the end of this Module. (extern) and static (static) classes.
Declaration for external variable is as follows:
extern int var;
External variables may be declared outside any function block in a source code file the same way any other variable is declared; by specifying its type and name (extern keyword may be omitted).
Typically if declared and defined at the beginning of a source file, the extern keyword can be omitted. If the program is in several source files, and a variable is defined in let say file1.c and used in file2.c and file3.c then the extern keyword must be used in file2.c and file3.c.
But, usual practice is to collect extern declarations of variables and functions in a separate header file (.h file) then included by using #include directive.
Memory for such variables is allocated when the program begins execution, and remains allocated until the program terminates. For most will access the local variable cell.
The following program example demonstrates storage classes and scope.
/* storage class and scope */
#include <stdio.h>
void funct1(void);
void funct2(void);
/* external variable, scope is global to main(), funct1()
and funct2(), extern keyword is omitted here, coz just one file */
int globvar = 10;
int main()
{
printf("\n****storage classes and scope****\n");
/* external variable */
globvar = 20;
printf("\nVariable globvar, in main() = %d\n", globvar);
funct1();
printf("\nVariable globvar, in main() = %d\n", globvar);
funct2();
printf("\nVariable globvar, in main() = %d\n", globvar);
return 0;
}
/* external variable, scope is global to funct1() and funct2() */
int globvar2 = 30;
void funct1(void)
{
/* auto variable, scope local to funct1() and funct1()
cannot access the external globvar */
char globvar;
/* local variable to funct1() */
globvar = 'A';
/* external variable */
globvar2 = 40;
printf("\nIn funct1(), globvar = %c and globvar2 = %d\n", globvar, globvar2);
}
void funct2(void)
{
/* auto variable, scope local to funct2(), and funct2()
cannot access the external globvar2 */
double globvar2;
/* external variable */
globvar = 50;
/* auto local variable to funct2() */
globvar2 = 1.234;
printf("\nIn funct2(), globvar = %d and globvar2 = %.4f\n", globvar, globvar2);
}
External variables may be initialized in declarations just as automatic variables; however, the initializers must be constant expressions. The initialization is done only once at compile time, i.e. when memory is allocated for the variables.
In general, it is a good programming practice to avoid using external variables as they destroy the concept of a function as a 'black box' or independent module..
As we have seen, external variables have global scope across the entire program (provided extern declarations are used in files other than where the variable is defined), and have a lifetime over the entire program run.
Similarly, static storage class provides a lifetime over the entire program, however; it provides a way to limit the scope of such variables, and static storage class is declared with the keyword static as the class specifier when the variable is defined.
These variables are automatically initialized to zero upon memory allocation just as external variables are. Static storage class can be specified for automatic as well as external variables such as:
static extern varx;.
/* static storage class program example */
#include <stdio.h>
#define MAXNUM 3
void sum_up(void);
int main()
{
int count;
printf("\n*****static storage*****\n");
printf("Key in 3 numbers to be summed ");
for(count = 0; count < MAXNUM; count++)
sum_up();
printf("\n*****COMPLETED*****\n");
return 0;
}
void sum_up(void)
{
/* at compile time, sum is initialized to 0 */
static int sum = 0;
int num;
printf("\nEnter a number: ");
scanf("%d", &num);
sum += num;
printf("\nThe current total is: %d\n", sum);
}
While the static variable, sum, would be automatically initialized to zero, it is better to do so explicitly.
In any case, the initialization is performed only once at the time of memory allocation by the compiler. The variable sum retains its value during program execution.
Each time the sum_up() function is called, sum is incremented by the next integer read. To see the different you can remove the static keyword, re-compile and re-run the program.
A running program is called a process and when a program is run, its executable image is loaded into memory area that normally called a process address space in an organized manner.
This is a physical memory space and do not confuse yourself with the virtual address space explained in Module W.
Process address space is organized into three memory areas, called segments: the text segment, stack segment, and data segment (bss and data) and can be illustrated below.
Figure: z.1
The text segment (also called a code segment) is where the compiled code of the program itself resides.
The following Table summarizes the segments in the memory address space layout as illustrated in the previous Figure.
In the disk file (object files) the segments were called sections.
By using a C program, the segments can be illustrated below.
Figure z.2
In C language memory allocation through the variables in C programs is supported by two kinds of memory allocation as listed in the following Table.
Dynamic allocation is not supported by C variables; there is no storage class called ‘dynamic’, and there can never be a C variable whose value is stored in dynamically allocated space. All must be done manually using related functions.
The only way to refer to dynamically allocated space is through a pointer. Because it is less convenient, and because the actual process of dynamic allocation requires more computation time, programmers generally use dynamic allocation only when neither static nor automatic allocation will serve.
The dynamic allocation done by using functions and the memory used is heap area.
The stack is where memory is allocated for automatic variables within functions. A stack is a Last In First Out (LIFO) storage where new storage is allocated and de-allocated at only one end, called the top of the stack. Every function call will create a stack (normally called stack frame) and when the function exit, the stack frame will be destroyed.
By referring the following program example and Figure z.
#include <stdio.h>
int a();
int b();
int c();
int a()
{
b();
c();
return 0;
}
int b()
{ return 0; }
int c()
{ return 0; }
int main()
{
a();
return 0;
}
By taking just the stack area, the following Figure illustrates what had happened to the stack when the above program is run. At the end there should be equilibrium.
Figure z.3: Stack frame and function call assembly example:
/* example of __cdecl */
push arg1
push arg2
call function
add ebp, 12 ;stack cleanup
And for __stdcall example:
/* example of __stdcall */
push arg1
push arg2
call function
/* no stack cleanup, it will be done by callee */
It is a long story if we want to go into the details of the function calls, but this section provides a good introduction :o).
The heap segment provides more stable storage of data for a program; memory allocated in the heap remains in existence for the duration of a program.
Therefore, global variables (external storage class), and static variables are allocated on the heap. The memory allocated in the heap area, if initialized to zero at program start, remains zero until the program makes use of it. Thus, the heap area need not contain garbage.
In ANSI C (ISO/IEC C), there is a family of four functions which allow programs to dynamically allocate memory on the heap.
In order to use these functions you have to include the stdlib.h header file in your program. Table z.4 summarized these functions.
Keep in mind that there are other functions you will find for dynamic memory allocation, but they are implementation dependant.
In practice, one must always verify whether the pointer returned is NULL. If malloc() is successful, objects in dynamically allocated memory can be accessed indirectly by dereferencing the pointer, appropriately cast to the type of required pointer.
The size of the memory to be allocated must be specified, in bytes, as an argument to malloc(). Since the memory required for different objects is implementation dependent, the best way to specify the size is to use the sizeof operator. Recall that the sizeof operator returns the size, in bytes, of the operand.
For example, if the program requires memory allocation for an integer, then the size argument to malloc() would be sizeof(int).
However, in order for the pointer to access an integer object, the pointer returned by malloc() must be cast to an int *.
The typical code example may be in the following form:
int *theptr;
theptr = (int *)malloc(sizeof(int));
Now, if the pointer returned by malloc() is not NULL, we can make use of it to access the memory indirectly. For example:
if (theptr != NULL)
*theptr = 23;
Or, simply:
if (theptr)
*theptr = 23;
printf("Value stored is %d\n", *theptr);
Later, when the memory allocated above may no longer be needed we have to free up the memory using:
free((void *) theptr);
This will de-allocate the previously allocated block of memory pointed to by theptr or simply, we could write:
free(theptr);
theptr is first converted to void * in accordance with the function prototype, and then the block of memory pointed to by theptr is freed.
It is possible to allocate a block of memory for several elements of the same type by giving the appropriate value as an argument. Suppose, we wish to allocate memory for 200 float numbers. If fptr is a:
float *
Then the following statement does the job:
fptr = (float *) malloc(200 * sizeof(float));
fptr pointer points to the beginning of the memory block allocated, that is the first object of the block of 200 float objects, fptr + 1 points to the next float object, and so on.
In other words, we have a pointer to an array of float type. The above approach can be used with data of any type including structures.
In C++ the equivalent construct used are new for memory allocation and delete for de-allocation.
-----------------------------------o0o -----------------------------------
Check the best selling C and C++ books at Amazon.com.
C and buffer overflow tutorial: stack frame activity.
C and Assembler, Compiler and Linker. | http://www.tenouk.com/ModuleZ.html | crawl-001 | refinedweb | 1,690 | 50.57 |
java.util.TreeMap.tailMap() Method
Description
The tailMap(K fromKey,boolean inclusive) method is used to return a view of the portion of this map whose keys are greater than (or equal to, if inclusive is true) fromKey. The returned map is backed by this map, so changes in the returned map are reflected in this map, and vice-versa.
Declaration
Following is the declaration for java.util.TreeMap.tailMap() method.
public NavigableMap<K,V> tailMap(K fromKey,boolean inclusive)
Parameters
fromKey--This is the low endpoint of the keys in the returned map.
inclusive--This is true if the low endpoint is to be included in the returned view.
Return Value
The method call returns a view of the portion of this map whose keys are greater than (or equal to, if inclusive is true) fromKey.
Exception
ClassCastException--This exception is thrown if fromKey is not compatible with this map's comparator.
NullPointerException--This exception is thrown if fromKey is null and this map uses natural ordering, or its comparator does not permit null keys.
IllegalArgumentException--This exception is thrown if this map itself has a restricted range, and fromKey lies outside the bounds of the range.
Example
The following example shows the usage of java.util.TreeMap.tailMap()
package com.tutorialspoint; import java.util.*; public class TreeMapDemo { public static void main(String[] args) { // creating maps TreeMap<Integer, String> treemap = new TreeMap<Integer, String>(); Sorted tail map"); treemapincl=treemap.tailMap(2,true); System.out.println("Tail map values: "+treemapincl); } }
Let us compile and run the above program, this will produce the following result.
Getting tail map Tail map values: {2=two, 3=three, 5=five, 6=six} | http://www.tutorialspoint.com/java/util/treemap_tailmap_inclusive.htm | CC-MAIN-2016-07 | refinedweb | 278 | 55.24 |
The trick to this is creating a custom field and overloading
pre_save. Pay special attention to the
self.attname member that is set to the value. The source for
DateField is a good example. Make sure that if you add any new attributes to the field in it's
__init__ method you also add a corresponding
deconstruct method.
Tuesday, July 19, 2016
Derived Django Database Field
The trick to this is creating a custom field and overloading
Monday, July 18, 2016
Mocking Django App
I'm sure this is completely wrong. I needed a Django model for testing, but I don't have a Django app or even a Django project. I'm developing a Django model reader for Carousel, and so I needed a model to test it out with. Sure I could have created a quick django project, but that seemed silly, and my first instinct was to import
django.db.models, make a model and use it, but this raised:
ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
Most normal people would turn back now, but instead I imported
django.conf.settings and called
settings.configure() just like it said to do. Now I got this error:
AppRegistryNotReady: Apps aren't loaded yet.
So now I felt like I was getting somewhere. But where? Googling told me to import
django and run
setup which I did and that raised:
RuntimeError: Model class __main__.MyModel doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.
Wow! Normally
RuntimeError is a scary warning, like you dumped your core, but this just said I needed to add the app to
settings.INSTALLED_APPS, which makes perfect sense, and it also complained that my model wasn't actually part of an app and even explained how to explicitly declare it. Some more Googling and I discovered that
app_label is a model option that can be set in
class Meta. So I did as told, and it worked!
from django.db import models from django.conf import settings import django MYAPP = 'myapp.MyApp' settings.configure() django.setup() settings.INSTALLED_APPS.append(MYAPP)}
Caveats
So I should stop here and point out that that evidently the order of these commands matters, because if I add the fake app to
INSTALLED_APPS before calling
django.setup() then I get this:
ImportError: No module named myapp
And unfortunately, I just figured this out now, in this post. But this isn't what I originally did. Yes, I'm completely crazy. First I added a fake module called
'myapp' to
sys.modules setting it to a mock object, but that didn't work. I got back
TypeError: 'Mock' object is not iterable because, as I found out later, there has to be an
AppConfig subclass in the app module. But since I didn't know that yet, I did the only logical thing and put the module in a list. What? Yes, did I mention I'm an idiot? This nonsense yielded the following stern warning:
ImproperlyConfigured: The app module [
] has no filesystem location, you must configure this app with an AppConfig subclass with a 'path' class attribute.
But this is where I found out about
AppConfig in the Django docs which is covered quite nicely. Following the nice directions, I did as told and subclassed
AppConfig, added
path and also
name which I learned from the docs, monkeypatched my mock module with it, and used the dotted name of the app
myapp.MyApp now. I felt like I was getting closer, since I only got:
AttributeError: __name__ which seemed like a problem with my pretend module. Another monkeypatch and we have my final ludicrously ridiculous hack.
from django.db import models from django.conf import settings import django from django.apps import AppConfig import sys import mock class MyApp(AppConfig): """ Apps subclass ``AppConfig`` and define ``name`` and ``path`` """ path = '.' # path to app name = 'myapp' # name of app # make a mock module with ``__name__`` and ``MyApp`` member myapp_module = mock.Mock(__name__='myapp', MyApp=MyApp) MYAPP = 'myapp.MyApp' # full path to app sys.modules['myapp'] = myapp_module # register module settings.configure() settings.INSTALLED_APPS.append(MYAPP) django.setup()}
Yay?
Carousel Python Model Simulation Framework
Carousel - A Python Model Simulation Framework
I want to introduce Carousel, a project that my employer, SunPower has been supporting for use in prediction models..
The Framework
A Carousel basic model consists of 5 built in layers:
- Data
- Formulas
- Calculations
- Simulations
- Outputs
Layers
Carousel is extensible by creating more advanced models and layers. A Carousel model is a collection of layers. Carousel layers share a common base class. Each layer also has a corresponding object and a registry where objects are stored. All layers have a load method that loads all of the layer objects specified into the model. When a model is loaded it loads the objects specified for each layer.
Example
Consider a load shifting algorithm for residential or commercial rooftop solar power. The model might have a performance calculation, a load calculation, a cost calculation and an optimization algorithm that determines how home or business appliances are operated to minimize overall yearly cost of the system.
The performance calculation contains several formulas which require input data from an internal database of solar panel parameters and an online API of weather conditions, so the user creates a data source and reader for each of these. There are some data readers already included in Carousel and once a data reader is created it can be reused in many different projects. Maybe the user submits a pull request to Carousel to add the new API and database reader. The load calculation contains formulas for how the appliances are used. The input data for the appliances are entered into a generic worksheet so the user creates a data source for appliances and uses the
XLRDReader to collect the data for each appliance from their worksheets.
The user organizes the formulas into 4 modules, that correspond to each of the calculations, but some formulas are reused since they are generic. For example, data frame summation formulas are used with different time series to create daily, monthly and annual outputs. The user maps out the calculations and specifies their interdependence to other formulas. For example, the cost calculation depends on the load and performance calculations and the optimization algorithm depends on the cost.
The user specifies each output name, initial value and other attributes. Specifications for each layer can be in a JSON parameter file or directly in the code as class attributes; Carousel will interpret either at runtime when it creates the model. Finally the user creates a simulation which in this case is unique because instead of marching through time or space, the simulation iterates over potential load shifting solutions from the algorithm. The user decides which data or outputs to log during the simulation and which to save in reports. Now that the model is created, the user loads the model and sends it the "start" command. After the simulation is complete, the user can examine the outputs and their variances. The outputs will have been automatically converted to the units specified in the model.
Data Layer
The data layer handles all inputs to the models. The data layer object is a data source. Each data source has a data reader. A data source is a document, API, database or other place from which input data for the model can be obtained. The data source and reader provide a framework for specifying how data is acquired. For example a data source for stock market prices might be a public API. An implementation of the stock market API data source specifies the names and attributes of each input data that will be read from the API and how the data reader should read them. The data source is similar to a deserializer because it describes how the data from the source should be interpreted by the model and creates an object in the data registry.
Formula Layer
The formula layer handles operations on input data that generate new outputs. It differs from the calculation layer which handles how formulas are combined together. The formula layer object is a formula, and each formula has a formula importer. For example the Python formula importer can import formulas that are written as Python functions.
Calculation Layer
Calculations are combinations of formulas. Each calculation also has a map of what data and output are used as arguments and what outputs the return values will be. Calculations also implement calculators. Currently there is a static calculator and a dynamic calculator, but new calculators can be implemented that can be reused in other models. The calculation also implements indexing into data and output registries in order retrieve items by index or at a specific time.
Output Layer
Outputs are just like data except they don't need a reader because they are only generated from calculations. Each output is like a serializer because it determines how output objects will be reported or displayed to the user.
Simulation Layer
The simulation layer determines the order of calculations based on the calculation dependencies. It first executes all of the static calculations and then loops over dynamic calculations, displaying logs and saving periodic reports as specified.
Model
The model is a low level class that can be extended to add new layers or implement new simulation commands. Currently only the basic model is implemented. A new model might contain a post processing layer that generates plots and reports from outputs.
Registry
Every layer has a dictionary called a registry that contains all of the layer objects and metadata corresponding to the layer attributes. The registry implements a register method that doesn't allow an item to registered more than once. Each layer registry is subclassed from the base registry so that specific layer attributes can be associated to each key. For example, data sources and outputs have a
variance attribute while formulas have an
args attribute.
Running Model Simulations
After a model has been described using the framework, it can be loaded. Then any or all of the model simulations can be executed from the model. The simulation specifies
commands to the model that user sends using the models
command method. Currently the basic model can execute the simulation
start command.
Units and Uncertainty
Carousel uses the Pint units wrapper to convert units as specified. Uncertainty is propagated using the UncertaintyWrapper package which was developed for Carousel. It can wrap Python extensions and non-linear algorithms without changing any code. It propagates covariance and sensitivity across all formulas.
Future Work
A basic version of Carousel is ready now. There is an example of a photovoltaic module performance model in the documentation online at GitHub. Some ideas for new features are listed in the Carousel wiki on GitHub.
- Data validation
- Reuse 3rd party serializer/deserializer for data layer
- Model integrity check
- Database data reader
- REST API data reader
- Online repository to share data readers, simualtions, formulas and layers
- Automatic solver selection
- Post processing layer
- Testing tools
- Concurrency and speedups
- Remote process and Carousel client
Source, Docs, Issues and Wiki
Previous Presentations
Carousel was presented at the 5th Sandia PVPMC Workshop hosted by EPRI in Santa Clara in May 2016
Acknowledgement
Carousel and UncertaintyWrapper were developed with the support of SunPower Corp. They are distributed with a BSD 3-clause license. | http://poquitopicante.blogspot.com/2016_07_01_archive.html | CC-MAIN-2017-39 | refinedweb | 1,911 | 54.63 |
CS::Utility::StringHash< Tag > Class Template Reference
A string-to-ID hash table. More...
#include <csutil/strhash.h>
Detailed Description
template<typename Tag>
class CS::Utility::StringHash< Tag >
A 43 of file strhash.h.
Constructor & Destructor Documentation
Member Function Documentation
Delete all stored strings.
- Deprecated:
- Use Empty() instead.
Definition at line 191 153 of file strhash.h.
Remove specified string.
- Returns:
- True if a matching string was in thet set; else false.
Reimplemented in csStringHashReversible.
Definition at line 160 of file strhash.h.
Remove all stored strings.
Reimplemented in csStringHashReversible.
Definition at line 180 of file strhash.h.
Assignment operator.
Reimplemented in csStringHashReversible.
Definition at line 76 of file strhash.h..
Definition at line 97 of file strhash.h. or csStringHashReversible, in which reverse lookups are optimized.
Definition at line 124 of file strhash.h.
Request the ID for the given string.
- Returns:
- The string's ID or csInvalidStringID if the string has not yet been registered.
Reimplemented in csStringHashReversible.
Definition at line 109 of file strhash.h.
The documentation for this class was generated from the following file:
Generated for Crystal Space 2.1 by doxygen 1.6.1 | http://www.crystalspace3d.org/docs/online/api/classCS_1_1Utility_1_1StringHash.html | CC-MAIN-2013-20 | refinedweb | 190 | 55.61 |
Every developer has one, that little utility class or collection of functions with that you use over and over again in every project. Just like the person creating said class, every developers utilities class is different and each has some cool tricks up his or her sleeve. The entire idea behind NativeScript Swiss Army Knife is just to get everyone that wants to contribute to contribute and share those little functions.
SwissArmyKnife contains function called setAndroidNavBarTranslucentFlag that Brand Martin added and that is the one I want to show off for the moment. setAndroidNavBarTranslucentFlag does just what it says, it sets the normally boring black android nav bar to translucent so you can see your content under it. Setting androids translucent flag is not something that’s hard to do at all in NativeScript, because you call native APIs, but having it abstracted out into SwissArmyKnife makes using it much more convenient and is the entire point of the plugin.
Since i’m a big fan of TypeScript and it’s strong typings (code completion FTW!) for demo purposes all examples will be in TypeScript. All functions in Swiss Army Knife are static so all you need to do is import the SwissArmyKnife like so:
import { SwissArmyKnife} from
'nativescript-swiss-army-knife/nativescript-swiss-army-knife'
;
After that whenever you want to make the nav bar translucent simply call
SwissArmyKnife.setAndroidNavBarTranslucentFlag();
Giving you the effect you see above.
And if for some reason you want to undo the effect, simply call the corresponding reset function
SwissArmyKnife.resetAndroidNavBarTranslucentFlag();
And you’ll get the Black navigation bar back.
NativeScript Swiss Army Knife contains many more great functions like this for Android and iOS. To see a listing of all the current functions is available at the NativeScript Swiss Army Knife GitHub page and npm page. If you have a function you’d like to add for the community don’t hesitate to make a pull request and add don’t forget to add yourself as a contributor to the package.json and README markdown files.
(expect a newsletter every 4-8 weeks)
Ready to try NativeScript? Build your first cross-platform mobile app with our free and open source framework.
If you see an area for improvement or have an idea for a new feature, we'd love to have your help! | https://www.nativescript.org/blog/check-out-the-nativescript-swiss-army-knife | CC-MAIN-2017-17 | refinedweb | 390 | 60.14 |
I'm a total beginner to HTTP requests, but I'd like to write a Python app that uses Sony's API for controlling its Wi-Fi cameras. For now, I'm just trying to talk to the camera at all, but my get request keeps failing. I have all the docs (the UPnP documentation, SSDP doc, user's manual, etc.) but I think I'm missing something really fundamental. According to Sony's doc, I need to:
#!/usr/bin/python
def main():
import requests
DISCOVERY_MSG = ('M-SEARCH * HTTP/1.1\r\n' +
'HOST: 239.255.255.250:1900\r\n' +
'MAN: "ssdp:discover"\r\n' +
'MX: 3\r\n' +
'ST: urn:schemas-sony-com:service:ScalarWebAPI:1\r\n' +
'USER-AGENT: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_5) AppleWebKit/536.30.1 (KHTML, like Gecko) Version/6.0.5 Safari/536.30.1\r\n\r\n')
try:
r = requests.get(DISCOVERY_MSG)
except:
print('Didn\'t work')
if __name__ == '__main__':
main()
I think this has little to do with UPnP: Sony just happens to use SSDP for discovery, and the defacto SSDP specification happens to be in the UPnP architecture document.
As for the problem:
requests.get() does an ordinary HTTP GET (or would if you provided the correct arguments), when you should send UDP multicast message(s) and handle the responses instead.
If you really intend to do this yourself, be prepared to learn a bit of networking and understand the SSDP protocol (see UPNP UDA part 1 for that). But my suggestion is to use an SSDP library or copy working open source code -- that way you can concentrate on actually providing new things (like an implementation of the sony protocol). | https://codedump.io/share/lZlbUeu27kAT/1/how-to-implement-ssdp--upnp-trying-to-use-sony39s-camera-api | CC-MAIN-2017-09 | refinedweb | 286 | 56.86 |
Hi, I need help writing a program that allows you to read an English-French dictionary into two arrays. The English words are stored in one file alphabetically while the French words are stored in the other file corresponding to the English words. This means that the program would ask the user to type a random word and then it would print its French equivalent. The dictionary has to store up to 50 words and use the following function prototypes:
int read_in(char[][Word Length], char[][Word Length]);
void sort_words(char[][Word Length], char[][Word Length], int);
void search_words(char[][Word Length],char[][Word Length], int);
void write_out(char[][Word Length],char[][Word Length], int);
I'm using Word Length equals to 30. This is what I have so far:
#include <iostream> #include <fstream> #include <string> using namespace std; const int max_word_len = 30; int read_in(char[][max_word_len], char[][max_word_len]); void sort_words(char[][max_word_len], char[][max_word_len], int); void search_words(char[][max_word_len],char[][max_word_len], int); void write_out(char[][max_word_len],char[][max_word_len], int); int main () { const int max_word_count = 50; char english[max_word_count][max_word_len]; char french[max_word_count][max_word_len]; int word_count = read_in(english, french); string line; ifstream myfile; ofstream outfile; myfile.open("English.txt"); if (myfile.is_open()) { while (myfile.good()) { getline (myfile,line); cout<<line<<endl; } myfile.close(); } else cout << "Unable to open the file"; return 0; }
I know it's not complete, I'm trying to tackle each function one at a time but I'm sure how to proceed next. I would appreciate any help. Thank you. | https://www.daniweb.com/programming/software-development/threads/415468/english-to-french-translation-program | CC-MAIN-2019-09 | refinedweb | 254 | 50.46 |
<int> numbers = GetIntList(…);! 🙂
What about IEnumerator<T> and ICollection<T>? AFAICS the non-generic versions of these interfaces are co-variant, so inheritance should be possible.
ICollection<T> is not co-variant for example has:
void Add(T item);
So for ICollection<int> you would have:
void Add(int item); //from ICollection<T>
void Add(object item); //from ICollection
So you run into the problem Anders mentions where you lost the strong-typing of ICollection<T>.
Does that help?
It would be nice if there were a mechanism to specify that my new class should implement IList<T>, as well as auto-implementing EXPLICIT interface members for the parent interface (IList).
So, I would have:
public void int Add(T item);
void int IList.Add(object item);
Where the IList interface would still be present, but if I wanted to be boneheaded and use it other than intended, I would have to knowingly (one would assume) cast the object to an IList before being able to add a non-T object: ((IList)myObject).Add(nonT);
If you wanted to make sure that would fail, you could have the compiler auto-generate the explicit IList interfaces do a cast and redirect through the public interfaces:
public class MyList : IList<T>
{
public void Add ( T item )
{
// Add to innerList
}
void IList.Add ( object item )
{
this.Add ( (T)item );
}
}
Which would cause an InvalidCastException if the item weren’t a valid T.
I realize at first glance it seems that this would cause unnecessary boxing if T is a value type, but if the developer does the explicit cast from T to object, then the performance hit is completely on their own head.
The developer could, of course, override this functionality by explicity extending IList in their code, and implementing their own explicit (or not) versions of the non-typed interface.
public class MyList : IList<T>, IList
{
public void Add ( T item )
{
// Add to innerList
}
public void Add ( object item )
{
if ( item is T )
this.Add( (T)item );
else
// Do something other than throw an InvalidCastException
}
}
Brad,
ICollection (non-<T>) does not seem to have an Add method (at least not in 1.1, and the current docs on msdn2 still don’t show one), so there wouldn’t be a problem with an Add(object) method. Am I missing something?
Just a crazy idea; why not turn it arround and have IList inherit from IList<T> i.e.
Interface IList<t> { … }
Interface IList: IList<object> {/*Note NOTHING goes here*/}
All code going foreward could use IList<T> and could access any collection, regardless of whether it is strongly typed or not.
Furthermore, I would argue that for much of the code that currently uses IList, switching to IList<T> would be a nonbreaking change. (Some of the code would have to be rewritten so other types interacting with the collection would be strongly typed through generics. This transition does not have to be in the current version because whenever you do it, its not a breaking change.)
I am sure an idea this obvious has been considered and rejected, I’m just curious about why it breaks down.
IMHO for a class that implements a generic interface (like IList<T>) it would be useful to have an "adaptor" class that implements non-generic interface and forwards the calls to the real one. That way IList<T> can be converted into IList only when needed.
PingBack from | https://blogs.msdn.microsoft.com/brada/2005/01/18/why-does-ienumerable-inherits-from-ienumerable/ | CC-MAIN-2017-13 | refinedweb | 574 | 58.52 |
$ cnpm install react-oly-gate
Npm:
To add the Authentication gate and the Centralizer to your project:
npm i -S oly-sdk react-oly-gate
import {Oly} from '@olympusat/oly-sdk'; import {Gate} from '@olympusat/react-oly-gate'; import getOlySdkOptions from "./olySdkOptions"; import getOlyGateOptions from "./olyGateOptions"; new Oly(getOlySdkOptions()); new Gate(getOlyGateOptions());
If a referrer is set in localstorage, then the sdk will redirect to that url on login.
localStorage.setItem('olyauth.referrer',window.location.href);
This is the Id of your User Pool
The Id of the User Pool in Cognito that you'd like to use
The Id of the Federated Identities Pool set up in Cognito. The APP_CLIENT_ID & USER_POOL_ID of your User Pool should be added as Cognito Authentication Providers in the Federated IDentity Pool settings.
##ENDPOINT_USERS The GraphQL endpoint for your users service.
The GraphQL endpoint for your apps service.
The application must have a route named "auth" that will be used as our callback and a safe route to host the Gate component
Notes: The auth services works through the Users api. There are public methods in the auth service that the user service triggers on load to reveal the auth gate.
utils.OlyAuthMeta is where you theme the auth gate from.
If you run into issues, first check that these packages are exactly these versions. AWS changed their sdk at some point after, introducing breaking changes
"aws-sdk":"2.7.9", "amazon-cognito-identity-js":"1.8.0" | https://npm.taobao.org/package/react-oly-gate | CC-MAIN-2019-43 | refinedweb | 244 | 53.41 |
Taking on data science work in Pandas, it can be important to drop duplicate data. In this post, you’ll learn all the ways to drop duplicates in Pandas.
Throughout this tutorial, we’ll use a sample dataset. To get started, let’s load Pandas and create a dataframe:
import pandas as pd df = pd.DataFrame.from_dict({'Name': ['Nik', 'Evan', 'Sam', 'Nik', 'Sam'], 'Age': [30, 31, 29, 30, 30], 'Height':[180, 185, 160, 180, 160]}) print(df)
This returns the following table:
Name Age Height 0 Nik 30 180 1 Evan 31 185 2 Sam 29 160 3 Nik 30 180 4 Sam 30 160
Pandas Drop Duplicates
To remove duplicates in Pandas, you can use the .drop_duplicates() method. This method drops all records where all items are duplicate:
df = df.drop_duplicates() print(df)
This returns the following dataframe:
Name Age Height 0 Nik 30 180 1 Evan 31 185 2 Sam 29 160 4 Sam 30 160
Drop Duplicates of Certain Columns in Pandas
By default, Pandas will ensure that values in all columns are duplicate before removing them. If you want to remove records even if not all values are duplicate, you can use the subset argument.
For example, if you wanted to remove all rows only based on the name column, you could write:
df = df.drop_duplicates(subset='Name')
This returns the following:
Name Age Height 0 Nik 30 180 1 Evan 31 185 2 Sam 29 160
The keep argument also accepts a list of columns. This will check only for duplicates across a list of columns.
For example, you can remove duplicates based on duplicates in the Name and Age columns by writing:
df = df.drop_duplicates(subset=['Name', 'Age']) print(df)
This returns:
Name Age Height 0 Nik 30 180 1 Evan 31 185 2 Sam 29 160 4 Sam 30 160
Check out some other Python tutorials on datagy, including our complete guide to styling Pandas and our comprehensive overview of Pivot Tables in Pandas!
Keep First or Last Value – Pandas Drop Duplicates
When removing duplicates, Pandas gives you the option of keeping a certain record. The keep argument accepts ‘first’ and ‘last’, which keep either the first or last instance of a remove record. This can be combined with first sorting data, to make sure that the correct record is retained.
If you wanted to keep the first record when removing duplicates based on the name column, you could write:
df = df.drop_duplicates(subset='Name', keep='first') print(df)
This returns:
Name Age Height 0 Nik 30 180 1 Evan 31 185 2 Sam 29 160
Conclusion
In this post, you learned how to remove duplicates in Pandas, including removing duplicates based on a subset of columns, and identifying whether to keep the first or last instance.
To learn more about the drop_duplicates function, check out the official documentation here.
Pingback: Data Cleaning and Preparation in Pandas and Python • datagy | https://datagy.io/pandas-drop-duplicates/ | CC-MAIN-2022-27 | refinedweb | 487 | 64.75 |
import "github.com/jrwren/juju/api/uniter"
action.go charm.go endpoint.go environ.go relation.go relationunit.go service.go settings.go unit.go uniter.go
NewState creates a new client-side Uniter facade. Defined like this to allow patching during tests.
CharmsURL takes an API server address and an optional environment tag and constructs a base URL used for fetching charm archives. If the environment tag empty or invalid, it will be ignored.
Action represents a single instance of an Action call, by name and params.
NewAction makes a new Action with specified name and params map.
Name retrieves the name of the Action.
Params retrieves the params map of the Action.
Charm represents the state of a charm in the environment.
ArchiveSha256 returns the SHA256 digest of the charm archive (bundle) bytes.
NOTE: This differs from state.Charm.BundleSha256() by returning an error as well, because it needs to make an API call. It's also renamed to avoid confusion with juju deployment bundles.
TODO(dimitern): 2013-09-06 bug 1221834 Cache the result after getting it once for the same charm URL, because it's immutable.
ArchiveURL returns the url to the charm archive (bundle) in the environment storage.
String returns the charm URL as a string.
URL returns the URL that identifies the charm.
Endpoint represents one endpoint of a relation. It is just a wrapper around charm.Relation. No API calls to the server-side are needed to support the interface needed by the uniter worker.
Environment represents the state of an environment.
func (e Environment) Name() string
Name returns the human friendly name of the environment.
func (e Environment) UUID() string
UUID returns the universally unique identifier of the environment.
Relation represents a relation between one or two service endpoints.
Endpoint returns the endpoint of the relation for the service the uniter's managed unit belongs to.
Id returns the integer internal relation key. This is exposed because the unit agent needs to expose a value derived from this (as JUJU_RELATION_ID) to allow relation hooks to differentiate between relations with different services.
Life returns the relation's current life state.
Refresh refreshes the contents of the relation from the underlying state. It returns an error that satisfies errors.IsNotFound if the relation has been removed.
String returns the relation as a string.
func (r *Relation) Tag() names.RelationTag
Tag returns the relation tag.
func (r *Relation) Unit(u *Unit) (*RelationUnit, error)
Unit returns a RelationUnit for the supplied unit.
RelationUnit holds information about a single unit in a relation, and allows clients to conveniently access unit-specific functionality.
func (ru *RelationUnit) Endpoint() Endpoint
Endpoint returns the relation endpoint that defines the unit's participation in the relation.
func (ru *RelationUnit) EnterScope() error
EnterScope ensures that the unit has entered its scope in the relation. When the unit has already entered its relation scope, EnterScope will report success but make no changes to state.
Otherwise, assuming both the relation and the unit are alive, it will enter scope.
If the unit is a principal and the relation has container scope, EnterScope will also create the required subordinate unit, if it does not already exist; this is because there's no point having a principal in scope if there is no corresponding subordinate to join it.
Once a unit has entered a scope, it stays in scope without further intervention; the relation will not be able to become Dead until all units have departed its scopes.
NOTE: Unlike state.RelatioUnit.EnterScope(), this method does not take settings, because uniter only uses this to supply the unit's private address, but this is not done at the server-side by the API.
func (ru *RelationUnit) LeaveScope() error
LeaveScope signals that the unit has left its scope in the relation. After the unit has left its relation scope, it is no longer a member of the relation; if the relation is dying when its last member unit leaves, it is removed immediately. It is not an error to leave a scope that the unit is not, or never was, a member of.
func (ru *RelationUnit) PrivateAddress() (string, error)
PrivateAddress returns the private address of the unit and whether it is valid.
NOTE: This differs from state.RelationUnit.PrivateAddress() by returning an error instead of a bool, because it needs to make an API call.
func (ru *RelationUnit) ReadSettings(uname string) (params.RelationSettings, error)
ReadSettings returns a map holding the settings of the unit with the supplied name within this relation. An error will be returned if the relation no longer exists, or if the unit's service is not part of the relation, or the settings are invalid; but mere non-existence of the unit is not grounds for an error, because the unit settings are guaranteed to persist for the lifetime of the relation, regardless of the lifetime of the unit.
func (ru *RelationUnit) Relation() *Relation
Relation returns the relation associated with the unit.
func (ru *RelationUnit) Settings() (*Settings, error)
Settings returns a Settings which allows access to the unit's settings within the relation.
func (ru *RelationUnit) Watch() (watcher.RelationUnitsWatcher, error)
Watch returns a watcher that notifies of changes to counterpart units in the relation.
Service represents the state of a service.
CharmURL returns the service's charm URL, and whether units should upgrade to the charm with that URL even if they are in an error state (force flag).
NOTE: This differs from state.Service.CharmURL() by returning an error instead as well, because it needs to make an API call.
Life returns the service's current life state.
Name returns the service name.
OwnerTag returns the service's owner user tag.
Refresh refreshes the contents of the Service from the underlying state.
String returns the service as a string.
func (s *Service) Tag() names.ServiceTag
Tag returns the service's tag.
func (s *Service) Watch() (watcher.NotifyWatcher, error)
Watch returns a watcher for observing changes to a service.
func (s *Service) WatchRelations() (watcher.StringsWatcher, error)
WatchRelations returns a StringsWatcher that notifies of changes to the lifecycles of relations involving s.
Settings manages changes to unit settings in a relation.
Delete removes key.
func (s *Settings) Map() params.RelationSettings
Map returns all keys and values of the node.
TODO(dimitern): This differes from state.Settings.Map() - it does not return map[string]interface{}, but since all values are expected to be strings anyway, we need to fix the uniter code accordingly when migrating to the API.
Set sets key to value.
TODO(dimitern): value must be a string. Change the code that uses this accordingly.
Write writes changes made to s back onto its node. Keys set to empty values will be deleted, others will be updated to the new value.
TODO(dimitern): 2013-09-06 bug 1221798 Once the machine addressability changes lands, we may need to revise the logic here to take into account that the "private-address" setting for a unit can be changed outside of the uniter's control. So we may need to send diffs of what has changed to make sure we update the address (and other settings) correctly, without overwritting.
type State struct { *common.EnvironWatcher *common.APIAddresser // contains filtered or unexported fields }
State provides access to the Uniter API facade.
Action returns the Action with the given tag.
func (st *State) ActionFinish(tag names.ActionTag, status string, results map[string]interface{}, message string) error
ActionFinish captures the structured output of an action.
func (st *State) AllMachinePorts(machineTag names.MachineTag) (map[network.PortRange]params.RelationUnit, error)
AllMachinePorts returns all port ranges currently open on the given machine, mapped to the tags of the unit that opened them and the relation that applies.
BestAPIVersion returns the API version that we were able to determine is supported by both the client and the API Server.
Charm returns the charm with the given URL.
func (st *State) Environment() (*Environment, error)
Environment returns the environment entity.
ProviderType returns a provider type used by the current juju environment.
TODO(dimitern): We might be able to drop this, once we have machine addresses implemented fully. See also LP bug 1221798.
Relation returns the existing relation with the given tag.
RelationById returns the existing relation with the given id.
Service returns a service state by tag.
Unit provides access to methods of a state.Unit through the facade.
Unit represents a juju unit as seen by a uniter worker.
AddMetrics adds the metrics for the unit.
func (u *Unit) AssignedMachine() (names.MachineTag, error)
AssignedMachine returns the unit's assigned machine tag or an error satisfying params.IsCodeNotAssigned when the unit has no assigned machine..
CharmURL returns the charm URL this unit is currently using.
NOTE: This differs from state.Unit.CharmURL() by returning an error instead of a bool, because it needs to make an API call.
ClearResolved removes any resolved setting on the unit.
ClosePort sets the policy of the port with protocol and number to be closed.
TODO(dimitern): This is deprecated and is kept for backwards-compatibility. Use ClosePorts instead.
ClosePorts sets the policy of the port range with protocol to be closed.
ConfigSettings returns the complete set of service charm config settings available to the unit. Unset values will be replaced with the default value for the associated option, and may thus be nil when no default is specified.
Destroy, when called on a Alive unit, advances its lifecycle as far as possible; it otherwise has no effect. In most situations, the unit's life is just set to Dying; but if a principal unit that is not assigned to a provisioned machine is Destroyed, it will be removed from state directly.
DestroyAllSubordinates destroys all subordinates of the unit.
EnsureDead sets the unit lifecycle to Dead if it is Alive or Dying. It does nothing otherwise.
HasSubordinates returns the tags of any subordinate units.
IsPrincipal returns whether the unit is deployed in its own container, and can therefore have subordinate services deployed alongside it.
NOTE: This differs from state.Unit.IsPrincipal() by returning an error as well, because it needs to make an API call.
func (u *Unit) JoinedRelations() ([]names.RelationTag, error)
JoinedRelations returns the tags of the relations the unit has joined.
Life returns the unit's lifecycle value.
MeterStatus returns the meter status of the unit.
Name returns the name of the unit.
OpenPort sets the policy of the port with protocol and number to be opened.
TODO(dimitern): This is deprecated and is kept for backwards-compatibility. Use OpenPorts instead.
OpenPorts sets the policy of the port range with protocol to be opened.
PrivateAddress returns the private address of the unit and whether it is valid.
NOTE: This differs from state.Unit.PrivateAddress() by returning an error instead of a bool, because it needs to make an API call.
TODO(dimitern): We might be able to drop this, once we have machine addresses implemented fully. See also LP bug 1221798.
PublicAddress returns the public address of the unit and whether it is valid.
NOTE: This differs from state.Unit.PublicAddres() by returning an error instead of a bool, because it needs to make an API call.
TODO(dimitern): We might be able to drop this, once we have machine addresses implemented fully. See also LP bug 1221798.
Refresh updates the cached local copy of the unit's data.
RequestReboot sets the reboot flag for its machine agent
func (u *Unit) Resolved() (params.ResolvedMode, error)
Resolved returns the resolved mode for the unit.
NOTE: This differs from state.Unit.Resolved() by returning an error as well, because it needs to make an API call
Service returns the service.
ServiceName returns the service name.
func (u *Unit) ServiceTag() names.ServiceTag
ServiceTag returns the service tag.
SetCharmURL marks the unit as currently using the supplied charm URL. An error will be returned if the unit is dead, or the charm URL not known.
SetStatus sets the status of the unit.
String returns the unit as a string.
Tag returns the unit's tag.
func (u *Unit) Watch() (watcher.NotifyWatcher, error)
Watch returns a watcher for observing changes to the unit.
func (u *Unit) WatchActions() (watcher.StringsWatcher, error)
WatchActions returns a StringsWatcher for observing the ids of Actions added to the Unit. The initial event will contain the ids of any Actions pending at the time the Watcher is made.
func (u *Unit) WatchAddresses() (watcher.NotifyWatcher, error)
WatchAddresses returns a watcher for observing changes to the unit's addresses. The unit must be assigned to a machine before this method is called, and the returned watcher will be valid only while the unit's assigned machine is not changed.
func (u *Unit) WatchConfigSettings() (watcher.NotifyWatcher, error)
WatchConfigSettings returns a watcher for observing changes to the unit's service configuration settings. The unit must have a charm URL set before this method is called, and the returned watcher will be valid only while the unit's charm URL is not changed.
func (u *Unit) WatchMeterStatus() (watcher.NotifyWatcher, error)
WatchMeterStatus returns a watcher for observing changes to the unit's meter status.
Package uniter imports 11 packages (graph). Updated 2016-07-26. Refresh now. Tools for package owners. This is an inactive package (no imports and no commits in at least two years). | https://godoc.org/github.com/jrwren/juju/api/uniter | CC-MAIN-2018-26 | refinedweb | 2,209 | 59.4 |
i18n-ing a Silva extension
Silva i18n procedures
Introduction
The Silva i18n procedure follows the Zope 3 internationalization effort, like using the messages to translate as message ids, and re-using its i18n tools.
Setting up a sandbox
Requirements:
- Silva 1.2
- Formulator 1.8
- 1.0 version of
- i18nextract, the Zope3 i18n tool for extracting .pot files and mergeing .po files.
A modified stand-alone version can be downloaded here.
I18n-ing
Mark strings for translation in Page templates, Python code, and Zope Python scripts. In the first i18n pass i18ndude (option: find-untranslated) can be used, but this gives a lot of false positives and also fails if translatable strings contain unicode characters. In new development strings should be marked immediately.
Create an i18n directory in the extension product directory. In this directory the <domain>.pot (message template) and translation .po files will be stored. The naming convention for domain is to use the product name in lower case, using underscores to separate words, eg. silva_document or silva_external_sources. Dashes don't work!
Create a message template file
i18nextract -d <domain> -p <product dir> -o i18n
Check the template file and change the Language-team headers after creation. Make sure your editor and/or terminal is set to UTF-8 encoding (or use poedit)! I quote Martijn: 'There can be only one encoding'. More specific documentation follows.
Translating
If there is no existing translation, copy the <domain>.pot to <domain>-<languagecode>.po and add the the Language-code, Language-name and domain metadata. See the example below for German:
"Language-code: de\n"
"Language-name: Deutsch\n" "Domain your_silva_extension\n"
For more information about domain names see the domain names section.
If the translation file is out of sync with the template file, use:
i18nmergeall -l i18n
to get newly generated msgids and remove obsolete ones in the .po file.
Also here the encoding warning applies: if you edit the translation files,
make sure your editor and/or terminal is set to UTF-8 encoding!
(Real world) Examples
See and for a good introduction to i18n.
Page templates
HTML example:
<html xlmns="" xmlns: <body> <h1 i18n:A header</h1> <a title="Go to the Infrae website" i18n:The Infrae website</a><br /> <span i18n:Your username is <tal:block tal:username</tal:block>. </span> </body> </html>
This piece of TAL contains all the necessary information to internationalize pagetemplates:
The opening tag (<html>) contains an XML namespace declaration for the i18n namespace and an i18n:domain (both mandatory). The namespace declaration needs to set so Zope knows what to do with the i18n: directives and the domain needs to be set so Zope (and the i18n extract tools) know which dictionary to use. Important: the i18n namespace has to be declared with! Other URI's are not recognized by the extraction tools and therefore no messages are created!
The <h1> element is an example of basic content translation. Adding empty i18n:translate attributes like this one will be the most common operation that will be performed on pagetemplates by developers. In certain cases the attribute can have a messageid as content, this might improve development in certain cases, but makes maintaining translations a lot harder, so should be avoided if possible.
The <a> element contains, apart from an i18n:translate like the <h1> has, an i18n:attributes directive, which makes Zope translate the contents of the attribute(s) mentioned in the contents (; seperated).
The <span> element is an example of an i18n:translate with a string interpolation: its content is partially static, partially dynamic. This can be solved by creating a new element inside the element with the translatable content, which contains the dynamic part and an 'i18n:name' directive. This string will be made available in the .pot and .po files later on with the name as a dynamic element, in our case the .pot and .po files will contain the following messageid declaration:
msgid "Your username is ${username}."
Zope python scripts and Product code Zope Python scripts (both ZODB and fs ones) should get the same treatment: developers will have to import a function and make sure all string literals that do not get used from code anywhere are passed into that function so they get wrapped with some sort of object.
Let's examine the import:
# we import a MessageIDFactory which generates MessageIDUnicode objects from Products.Silva.i18n import translate as _
The 'translate' function imported is either a reference to the MessageIDFactory of PlacelessTranslationService, or, if importing PlacelessTranslationService failed, a function that returns whatever came in. This function must be imported with the name '_', since the i18n extract tools search for those calls to generate the .pot files.
Note that this imports the MessageIDFactory for the 'silva' domain, and with a specific switch to make all the translations unicode strings. Take care that you don't use e.g. use str() calls on the objects, that may potentially break your code if the translated string contains non-ascii characters.
Some examples:
from Products.Silva.i18n import translate as _ # this method returns what once used to be a string-literal, now it returns # a MessageIDUnicode object that gets converted to a translated string # somewhere by Zope before displaying it def foo(): return _("foo")
This is the most simple case, where a simple string-literal gets wrapped with a messageid and the code doesn't process it anymore. Zope will, before viewing it, convert the MessageID to a translated (unicode in our case) string so it will be displayed translated to the user.
A more complicated case:
from Products.Silva.i18n import translate as _ # sometimes you want to generate explicit strings so you can use them in # string operations later on, to convert a MessageIDUnicode to a string object # use the 'unicode' call (in Silva everything is stored as unicode) def bar(): msg = '' for i in range(10): msg += unicode(_("bar")) return msg
If you want to perform string operations such as adding other strings, joining elements of an array which contains MessageID objects, etc. you will have to convert the MessageID objects to unicode strings first. Calling 'unicode()' on them this way results in a plain, translated, unicode string which you can use to do with whatever you're used to. Obviously there's no need to add unicode() calls everywhere, only if you (or some other bit of the code) want to process them it makes sense to call it explicitly.
String interpolations don't work the same anymore. Consider this:
# this will fail msg = _('Foo %s baz' % bar)
It is not possible for the extraction tools to get a messageid created from this bit of code, since the string isn't a string literal but contains dynamic elements. Therefore string interpolation requires a somewhat different syntax, that allows doing the interpolation later in the process (on stringification):
from Products.Silva.i18n import translate as _ # string interpolations are not possible anymore, since that would make the # translateble string dynamic (it can't be found in the message catalog if it's # not a static string), to do this we use the following syntax def baz(some_var): msg = _('You entered the value ${var} for some_var') msg.mapping = {'var': some_var} return msg
If the python code happens to be in a Zope Python script, we need to use the set_message method on MessageID to prevent Zope security kicking in:
msg = _('You entered the value ${var} for some_var') msg.set_mapping({'var': some_var})
Formulator forms
The form XML needs just one elements on the form:
<i18n_domain>silva</i18n_domain>
The extraction tool will automatically extract titles and descriptions from the *.form files. Message ids will be constructed in that domain.
Any error messages explicitly defined in the form will be looked up in the form domain.
In Formulator 1.7 and before this all worked differently, but this is all you'd need to do now.
Domain names
Each extension gets a new domain, see the rule for this above.
If you have text in a form or Python code, the domain is specified there; explicitly in the form, and usually implicitly in the Python code, in which case (at the time of writing), the domain will be 'silva'. You can also explicitly supply a domain in Python code: _('My message', 'explicit_domain').
If there is a domain specified during message id construction in the form or Python code, the domain given in the page template that shows this message is ignored; instead, correctly, the domain from the message id is used in the lookup procedure.
Pitfalls
There are a number of issues, especially in Product code and Python scripts, that require special attention. These are mainly cases where translating seems appropriate, usually involving an innocent looking plain string literal, but in which it turns out that the string is later used for another purpose than displaying in the public view (sometimes strings get even shown in the public view and used for some other purpose).
Even though the work is generally quite boring, it requires you to pay attention at all times!
The problems we ran into so far:
- String literals were used as a dictionary key, attribute name, etc.
- String literals were used as class names for the CSS
- String literals were used to send emails to multiple people (which is actually a bit hard to solve: we present those strings directly to users, so ideally we would want to translate them, but the problem is that there are more recipients that potentially speak different languages, for now I think we should just skip those cases and consider a solution later on)
- The resources/sidebar_template.pt is cached. Translating text in it will result in cached translation, which will result in weird effects. We need to refactor this so that translations are not cached.
In all the mentioned cases, translating will break (usually with very uninformative tracebacks!) the code, so translation should not be done. However, it is very easy to make a mistake, so make sure to test often and thoroughly.
If you run into a bug that you have just created, and the amount of code changed is small, that bug is probably way easier to locate then when you run into one that was created a while ago, by someone else or in a large set of changes.
Localizing dates and times
We haven't done so yet. This is how Plone does it:
Zope 3 has another way again which we researched that may be more powerful. | http://m.infrae.com/products/silva/archive/contributing/i18n-ing_silva_extensions | CC-MAIN-2017-39 | refinedweb | 1,761 | 59.64 |
Opened 6 years ago
Closed 6 years ago
Last modified 6 years ago
#19274 closed Cleanup/optimization (fixed)
Separate DB connection creation and session state initialization
Description
Currently when creating a new connection we create the connection and initialize it in one go (in _cursor()). Even if a backend splits getting a new connection and initializing the session variable this is not done consistently between backends.
The reason for this split is that this gives nice access point for external pooling implementations. A pool can wrap the backend and the methods "get_new_connection()" and "close()". Instead of actually creating new connections and closing the connection we can just get a connection from the pool and initialize the state of it. The real backend doesn't need to know anything about the pool wrapper.
The pool wrapper implementation would be something like this:
def get_new_connection(): if pooled_connections_available(): return connection from pool else: return super().get_new_connection() def init_connection(): do possible pool specific initialization super().init_connection() def close(): put the connection back to pool
I think this would allow connection pools for Django but with no need to implement them in core. In addition this should add readability of ._cursor() implementations.
Change History (5)
comment:1 Changed 6 years ago by
comment:2 Changed 6 years ago by
I have now a working implementation in:
The work divides into three parts:
- Backend conversion as mentioned in the ticket description
- Removing the assumption that connection's self.settings_dict changes will be reflected in the global settings
- Random test fixed (one Oracle specific fix, some fixes into how to create additional connections for testing and some fixes to accessing the connection.connection variable)
After the fixes the work in passes on all core backends. The pooling implementation in django_pooled is somewhere between ugly and hideous. What is interesting is that django_pooled shows that one can have generic pooling implementation outside core, and that it actually works.
The separation of self.settings_dict from global settings is needed for the above pooling implementation (and I believe any pooling implementation wants that). The basic problem is that you need to tell Django to use the pool in ENGINE, and then you need to have the real engine somewhere (OPTIONS -> WRAPS in django_pooled). You need to alter the settings before passing to the real backend, but you can't do that to the global settings, otherwise the information is lost for next connection creation.
Gis backends aren't converted yet.
comment:3 Changed 6 years ago by
I have update the patch series at
Gis isn't yet updated, though it seems the only change needed is in spatialite. In addition I would like to remove some checks done against the ENGINE string, this isn't nice for subclassers.
The full test suite does pass using. The implementation in django_pooled isn't meant for any kind of production use, but it does prove that creating a connection pool outside core is possible.
I am planning to push the patch series as-is. The changes are mostly mechanical - moving code from ._cursor() to the new methods. Still, it would be great if somebody had the time to double-check my changes, I am pretty good at making stupid little mistakes in this sort of thing...
Sounds good to me. | https://code.djangoproject.com/ticket/19274 | CC-MAIN-2018-51 | refinedweb | 548 | 52.9 |
Tabbed Forms - Making the web look like Excel
One of the things I'm working on for my day job right now is the ability to display an Excel-like UI for editing a form. So I did a search on Google tonight and found DHTML Kitchen. On this site, they had exactly what I was looking for - a howto for creating a tabbed panel system. So I've used this example to create a prototype of what I can do. This is pretty slick b/c now I can give the users a UI that looks like the Excel they're used to, and I can use the same ValidatorForm for the entire page. It even supports remembering which tab you last selected, and also allows navigation to a tab. The DHTML Kitchen also appears to have all kinds of other goodies to checkout. I'll definitely be adding it to my list of cool bookmarks.
If someone could verify that this prototype works in IE 5.5 - that'd be awesome! This is the browser we have to support at work and all my browsers are 6.0+. In return, I offer you the source in a single zip file :-) After playing with this a bit after posting - it seems like it's got a couple of issues in IE 6. The first is that a double line shows up at the bottom of the top tabs after refreshing. Clicking on any tab at the top snaps the tab bar back into place. The second is performance - it's taking 3-8 seconds to load the page - yikes! I'm still going to use it though, and hopefully optimize and fix these issues later. Posted in The Web at Jan 11 2003, 11:45:23 PM MST 4 Comments
My First Attempt at ConvertUtils
My first attempt at using ConvertUtils is turning out to be a painful one - most likely due to my own ignorance. Let's see if you can help me out. I have a Hibernate Bag, which is really a java.util.List on my User object. When I run the User object through XDoclet, I create a UserForm (extends ValidatorForm). The form has an ArrayList on for any instances of List or Set on the object (set through a custom struts_form.xdt template). So I created a ListConverter to convert a List object to an ArrayList. Sounds pretty simple right?! Here's my
ListConverter.java:
public class ListConverter implements Converter { //~ Instance fields ======================================================== protected Log log = LogFactory.getLog(ListConverter.class); //~ Methods ================================================================ /** * Convert a List to an ArrayList * * @param type the class type to output * @param value the object to convert */ public Object convert(Class type, Object value) { if (log.isDebugEnabled()) { log.debug("entering 'convert' method"); } // for a null value, return null if (value == null) { return null; } else if (value instanceof Set && (type == Set.class)) { return new ArrayList((Set) value); } else if (value instanceof List && (type == List.class)) { return new ArrayList((List) value); } else { throw new ConversionException("Could not convert " + value + " to ArrayList!"); } } }
When I run
BeanUtils.copyProperties(userForm, user), I get:
Could not convert cirrus.hibernate.collections.Bag@e2892b to ArrayList!
On another class, where I am trying to convert a List of Longs, I get:
Could not convert [-1, 1, 30129] to ArrayList!
I'm registering my custom converter in a static block of my BaseManager class. My *Manager classes do all the conversions, so this seems logical:
static { ConvertUtils.register(new StringConverter(), String.class); ConvertUtils.register(new LongConverter(), Long.class); ConvertUtils.register(new ListConverter(), ArrayList.class); if (log.isDebugEnabled()) { log.debug("Converters registered..."); } }
Since I'm in a major time crunch, I'll try simply making my getter/setters on my UserForm to be List. I'd like to use ConvertUtils though, so hopefully someone has a solution.
This brings me to a RANT and I think it's my first official one. My last three projects have always started small, and the goal has always been a prototype of functionality. A prototype that turns into a production system. All fricken three of them. All were supposed to take about 3 months to develop initially. The last two projects took at least 6 months. This one has a one month deadline, but the scope is a lot smaller than the previous two. But still, it's always the same scenario - the clients want a prototype, but turn it into a production system. Since it's a prototype, I tend to write "workarounds" for design patterns (see above) that I can't figure out. Is this good? It probably doesn't hurt since no one will ever look at my code - right?! When's the last time you looked at a co-workers code? (The more == the better). And the truth is, as long as it works - it's probably good enough. However, I as a developer, get heartburn when I think about maintaining the system that I created under the impression that it was a prototype. Maybe one of these days I'll figure out all the best practices to creating a robust web application, and then I'll know everything - so I won't have to write workarounds for my lack of knowledge. If you see some pigs flying, you can think to yourself - "Wow, Raible must've figured it all out" ;-) Posted in Java at Jan 11 2003, 04:04:43 PM MST 1 Comment
Tomcat 4.1.x Tip - Contexts
Did you know that with Tomcat 4.1.x you can actually take an application's context out of the
server.xml file and put it in a
contextName.xml file in the
$CATALINA_HOME/webapps directory? This makes it much easier to install and configure your webapps. Using this feature, you can easily setup Tomcat for your webapp using an Ant task. Here's the one I'm using for AppFuse:
<target name="setup-tomcat" if="tomcat.home" description="copies mysql jdbc driver and application's context to tomcat"> <echo level="info"> Copying MySQL JDBC Driver to ${tomcat.home}/common/lib </echo> <copy todir="${tomcat.home}/common/lib"> <fileset dir="${hibernate.dir}/lib" includes="mm*.jar"/> </copy> <echo level="info"> Copying ${webapp.name}.xml to ${tomcat.home}/webapps </echo> <copy todir="${tomcat.home}/webapps"> <fileset dir="metadata/web" includes="${webapp.name}.xml"/> </copy> </target>
Posted in Java at Jan 11 2003, 08:01:51 AM MST 1 Comment
Links to this site and the information found I saw Russ's "Links To Me" link on his site, and tried it for this site. There I found a great idea from Patrick Chanezon regarding WebTest:
...once you go declarative, you can begin to build tools to generate the declaration.
One could build a Mozilla XUL based tool that would generate this XML based on an interactive testing session in the browser.
Now THAT is a great idea! Any takers? Posted in Java at Jan 11 2003, 07:48:45 AM MST Add a Comment
The Worst E-Mail I've gotten in a while This is an awful e-mail to get when you're planning on working all weekend:
From: skimail@vailresorts.com Sent: Saturday, January 11, 2003 12:00 AM Subject: 6 in. of New Snow at Beaver Creek
Posted in General at Jan 11 2003, 07:02:15 AM MST Add a Comment
E-Mailing errors when an error-page is displayed I'm implementing an interesting feature this morning. When a user views the error-page of the application, an e-mail is sent to an administrator with a StackTrace. By error-page, I mean the "errorPage" attribute in a JSP's page declaration.
<%@ page language="java" errorPage="/errorPage.jsp" contentType="text/html; charset=utf-8" %>
I'm using the mailer taglib to do this, but can't help thinking that Log4j already provides similar functionality. Doesn't it have an SMTPAppender or something like that. I briefly scanned their site, but didn't see anything. If you know how to configure this functionality - hook me up! Posted in Java at Jan 11 2003, 06:20:17 AM MST 4 Comments
Returned: Virtual PC 6
After being severly disappointed in my purchase of Connectix's Virtual PC 6, I've returned it. Since I bought it online and downloaded it, it was as simple as sending an e-mail and destroying the software. I had no problems getting rid of the software as it's too damn slow to be tolerable. I don't blame this on Virtual PC, I blame it on the slowness of Apple's CPU. Megahertz don't matter - baaahhh! When I get my 2GHz PowerBook, I might re-purchase this product, but no need for now. I'll settle for using Microsoft's RDC to get my Windows emulation.
So if you're a Mac fan and you're purchasing a new Mac with the hopes of running Virtual PC - you'd better get the dual processor G4, you're gonna need it! Posted in Mac OS X at Jan 11 2003, 05:26:00 AM MST 1 Comment
Eclipse | http://raibledesigns.com/rd/date/20030111 | crawl-002 | refinedweb | 1,518 | 65.73 |
This, world-wide may.
Figure 28-1 address.
Figure 28-2 shows name-to-address resolution outside the local domain., most significantly, name-to-address mapping. in.named is a public domain TCP/IP program primary server and should have at least one secondary server to provide backup. "Zones" explains primary and secondary servers in detail.
To be a DNS client, a machine must run the resolver. The resolver is neither a daemon nor a single program; rather,.
When a machine's /etc/nsswitch.conf file specifies hosts: dns (or any other variant that includes dns in the hosts line), the resolver libraries are automatically used. If the nsswitch.conf file specifies some other name service before dns, that name service is consulted first for host information and only if that name service does not find the host in question are the resolver libraries used.
For example, if the hosts line in the nsswitch.conf file specifies hosts: nisplus dns, the NIS+ name service will first be searched for host information. If the information is not found in NIS+, then the DNS resolver is used. Since name.
The Solaris operating environment includes the dynamic library routines that make up the resolver. Solaris Naming Setup and Configuration Guide, contains instructions for setting up a host as a DNS client.
The entire collection of DNS administrative domains throughout the world are organized in a hierarchy called the DNS namespace. This section shows how the namespace organization affects both local domains and the Internet.
Like the UNIX 28-3,. For example, Mktg.Corp.Ajax.Com. from Figure 28-3.
If your company is large enough, it may support a number of domains,organized into a local namespace. Figure 28-4 shows a domain hierarchy that might be in place in a single company. The top-level, or "root" domain for the organization is ajax.com, which has three sub-domains, Figure 28-4 is, conceptually, a "leaf" of the huge DNS namespace supported on the global Internet.
The DNS namespace for the Internet is organized hierarchically as shown in Figure 28-5. It consists of the root directory, represented as a dot (.) and two top level domain hierarchies, one organizational and one geographical. Note that the com domain introduced in Figure 28-3 is one of a number of top-level organizational domains in existence on the Internet.
At the present time, the organizational hierarchy divides its namespace into the top-level domains listed shown in Table 28-1. It is probable that additional top-level organizational domains will be added in the future.Table 28-1 name service without connecting to the Internet, you can use any name your organization wants for its your domains and subdomains, if applicable. However, if your site plans wants to join the Internet, it must register its domain name with the Internet governing bodies.
To join the Internet, you have to:
Register your DNS domain name with the an appropriate Internet governing body.
Obtain a network IP address from that governing body.
There are two ways to accomplish this:
You can communicate directly with the appropriate Internet governing body or their agent. In the United States, InterNIC is the company that currently handles network address and domain registration matters. prepended to the name of the Internet hierarchy to which it belongs. For example, the ajax domain shown in Figure 28-4 has been registered as part of the Internet com hierarchy. Therefore, its Internet domain name becomes ajax.com.
Figure 28-6 shows the position of the ajax.com domain in the DNS namespace on the Internet.
The ajax.com subdomains now have the following names.
DNS does not require domain names to be capitalized, though they may syntax:
The fully qualified domain names for the ajax domain and its subdomains are:
Note the dot at the furthest right position of the name.
D...
If your site is not connected to the Internet, you must set up one or more of your servers to perform as root domain name servers. The boot files of all DNS name servers on your network must point to a common cache file (usually called named.ca) that identifies the root domain name servers. You then create a cache file that identifies your root name servers.
Since a single machine can be the primary domain name server for more than one machine, the easiest way to create a root domain name server is to have the server for your highest level domain also be the server for the logical "." domain.
For example, suppose you have given your network the domain name solo. The DNS master name server is dnsmaster.solo.(with a trailing dot). In this case, you would make dnsmaster the root master server for the "." domain.
If your network has more than one top-level domain, the root domain server name should be the primary name server for all top-level domains. For example, if your network is divided into two separate, non-hierarchal domains named solo and private, the same server must be root master server for both of them. Following the example above that would mean that dnsmaster.solo. is root domain master for both the solo and the private domains.
D, Table 28-2 compares BIND file names from these three sources:Table 28-2 BIND File Name Examples
BIND 8.1 adds a new configuration file, /etc/named.conf, that replaces the /etc/named.boot file. The /etc/named.conf file establishes the server as a primary, secondary,. may change in the future; thus, you should be consistent in your use of lower and uppercase.
The following characters have special meanings:Table 28-4 Special Resource Record Characters
Most resource records have the current origin appended to names if they are not terminated by a dot (.) This is useful for appending the current domain name to the data, such as machine names, but may primary or secondary line of the named.conf file.
The.. | http://docs.oracle.com/cd/E19455-01/806-1387/6jam692f0/index.html | CC-MAIN-2017-34 | refinedweb | 999 | 56.76 |
CIDER 0.9 is finally out and it’s our best release yet (believe it or not)! It took a lot more time than I originally anticipated, but at least we managed to ship in time for EuroClojure!
There are a ton of important changes and new features in 0.9 and now I’ll go quickly through some of them.
Debugger
Believe it or not CIDER now has a debugger! This was like the most requested feature ever, so I’m sure at least some of you are excited. The debugger was developed by the awesome Artur Malabarba. He even wrote a post about it and I guess you should read it.
Dependency isolation
CIDER’s dependencies will no longer affect your projects (read this as introduce dependency conflicts in them). All the dependencies are now isolated using source rewriting (simply put – they live in different namespaces than the original libraries). This magic is done by mranderson. Thanks to Benedek Fazekas for creating this small but super helpful tool!
Rich code completion
Completion candidates are now annotated with information about the namespace and the type of the thing being completed. It’s pretty neat.
The screenshot above features
company-mode. The annotations are
not supported in
auto-complete-mode (that’s a limitation of AC, not
a limitation of CIDER).
Misc additions
Here’s a short list of other important additions:
- Support for Piggieback 0.2
- New code formatting commands (based on cljfmt)
- New EDN data formatting commands
Changes
There were also a few important changes. Most notably we had to kill source-tracking code evaluation, as it wasn’t playing nice with ClojureScript. This was also a hacky solution and I still hope than one day this will be properly supported in nREPL itself. In simple terms – var definitions evaluated by themselves won’t have any location metadata set for them, which will make it impossible to go their definition. You can also help out by voicing your support for this nREPL ticket’s patch to be merged.
You’ll also notice that some commands that didn’t prompt for
confirmation in the past do so now (e.g.
find-var). This was done mostly for
consistency with Emacs’s own commands that do similar things. The
behavior is configurable via
cider-prompt-for-symbol. If a ton of
people dislike the new defaults reverting them is on the table.
All the Gory Details
There were truly a ton of changes and there’s little point in me repeating them here. If you want to know everything have a look at the release notes.
The Road Ahead
Going forward our top priority will be merging some functionality from
refactor-nrepl and
clj-refactor into
CIDER itself. Think of things like
find-usages,
extract-definition, etc. Refining the debugger will be another top
priority.
We’ll also try to do some important internal changes:
- reorganize the entire codebase in a more sensible manner
- rework nREPL response handling
- rework the REPL to use
comint-mode
- improve quitting and restarting
Depending of how well we progress on those tasks the next release will be either 0.10 or 1.0. I won’t make any commitments about its release date (but judging from past it will likely be 3 to 6 months from now).
If you’re wondering why things are moving more slowly lately, here’s the answer for you – I’ve been super busy since the beginning of the year and haven’t had much time for open-source projects. I’m hoping this will change, but only time will tell. I’m very happy that a lot of people contributed to the development of CIDER 0.9. The project definitely doesn’t have a bus factor of one. :–)
Special thanks to Michael Griffiths who did a ton of great work on this release. You rock!
P.S. Recently I talked on the Cognicast about CIDER (in general and 0.9 in particular). You might find this episode interesting.
P.P.S. I’m rarely on IRC these days.
#cider on
slack and our
gitter channel are the
official CIDER chats as far as I’m concerned. | http://batsov.com/ | CC-MAIN-2015-35 | refinedweb | 698 | 65.01 |
This article provides the configuration steps and code to build a Ruby on Rails application deployed on Heroku that uses the Force.com Toolkit for Ruby to connect to the Force.com platform. While Getting Started with the Force.com Toolkit for Ruby gets you up and running and connecting to Force.com, this article provides deeper examples specific to Heroku, in particular providing examples and configuration details - including a complete example of a Rails app running on Heroku that connects to Force.com to retrieve a list of contacts.
Let's look at how to create a simple app, set up your environment, Bundler and routes.
Before getting started, please make sure you follow Getting Started with the Force.com Toolkit for Ruby. This will set up your local machine with the appropriate gems for connecting to Force.com. We are going to use these gems, and modify the configuration steps to allow us to deploy our app to Heroku. Once you have completed the steps up until the Testing the Toolkit section, we can continue.
Alright, you have read the Getting Started Guide. You now have a basic understanding on how to configure the toolkit. Let's take that knowledge and expand it to work with Heroku. Go ahead and create a new Rails project:
rails helloforcedotcom
With our basic app created, let's configure our app to use Bundler to manage gem dependencies. Bundler is also key for deploying applications to Heroku with the best practice of including all your dependencies in the slug file.
Builder relies on a file,
Gemfile, contained within your application's root dir. You can add specific project dependencies here. You will need to create this file, and then add the following line to bundle in all standard dependencies. Remember we are going to deploy to Heroku soon and need to make sure all our dependencies are available in the cloud.
While we have the
Gemfile open, let's add a line to tell the Bundler that our app requires a versioned dependency for Rails, and another line for a Ruby Toolkit requirement, facets. Your gem file should now look like this:
source :rubygems gem 'rails', '2.3.8' gem 'facets', '2.8.4'
With our Gemfile created and saved, open up the trusty command line and enter the following command from within the
helloforcedotcom directory to run the bundler.
bundle install
We obviously want some sort of UI to view our data from Force.com. Let's add a controller and a simple view. We will use this controller to retrieve data from Force.com later, but for now it will be pretty empty. From a command line, enter the following:
ruby script/generate controller home index
That's it. Rails just generated a number of files including
app/views/home/index.html.erb and an index action in the
home controller. You can check out the code created by the generate command and see the simplicity of Ruby. Open the
app/controllers/home_controller.rb file for example. You should see something like the following:
class HomeController < ApplicationController def index end end
What this code is telling us is there there is a method called index. By default the method is empty but it will automatically handle routing to the
index.html.erb view just by naming definition. Nice, isn't it.
The last thing we want to do is remove the default home page for our app to ensure users are presented with our
index.html.erb file instead of index.html. From the command line, within the
helloforcedotcom directory, enter the following command:
rm public/index.html
Once the index.html file is removed, we need to tell our app what controller is our default. You can change a Rails apps routes (the paths to controller and views) in
app/config/routes.rb. Simply scroll down to approximately line 34, and change the map.root value to the following:
map.root :controller => "home"
From your favorite editor (I use TextMate on the Mac, and typically create a project by adding existing files to my *workspace*. In this instance I would add the helloforcedotcom folder) edit
app/views/home/index.html.erb to say something witty like:
<h1>Hello Contacts!</h1>
We will update this file shortly to display a list of Contact records from Force.com.
Let recap what we have done. Up until this point everything has been pretty well the same as a local Rails app, and the steps covered in the Getting Started Guide. The only additional step we have added is the use of Bundler. Next we will start updating our configuration to support deployment to Heroku.
At the time of writing, the new asf-soap-adapter provided in the Ruby toolkit relies on the previous adapter when deployed to Heroku. As a result, in addition to adding the
config.gem reference in your environment.rb file as detailed in the Getting Started Guide, you also need to add a reference in your
Gemfile:
gem 'asf-soap-adapter', :require => 'activerecord-activesalesforce-adapter'
Save the
Gemfile, and from the command line, run
bundle install
Database configurations are contained in
config/database.yml by default. When deploying applications to Heroku, Heroku generates a database.yml for you to connect to Postgres. We want to connect to Force.com though. Let's create a new .yml file in the config directory called
salesforce.yml, and add the following configuration. Heroku requires a
production environment specified, and the toolkit requires an environment called
salesforce-default-realm. In order to centralize our config we can leverage the ability to include common attributes to make maintenance easier going forward:
common: &common adapter: activesalesforce url: username: [your force.com username] password: [force.com password + token] api_version: 20.0 development: <<: *common production: <<: *common salesforce-default-realm: <<: *common
Now that we have our new .yml file, we need to tell our rails app to load this configuration. Edit your
config/environment.rb and add the following line directly after the
config.gem line you added as part of the Ruby Toolkit setup:
config.database_configuration_file = File.join(RAILS_ROOT, 'config', 'salesforce.yml')
Once complete, your
environment.rb file should look like this:
# "asf-soap-adapter", :lib => 'asf-soap-adapter' config.database_configuration_file = File.join(RAILS_ROOT, 'config', 'salesforce.yml') config.time_zone = 'UTC' end
That's it. Our application is configured. You can test it locally using the Rails console with the following commands:
script/console
>> Salesforce::Contact.first
And if everything is configured correctly, you should be presented with data:
-> <Salesforce::Contact id: "003T000000GqvJsIAJ", ... >
Next, we are going to add a little logic to our Controller we created earlier, then deploy it to Heroku.
With our adapter configured, we are going to update our controller to perform a query against Force.com to retrieve the id, first name, and last name of the first 100 Contacts. Let's jump in.
Using your favorite editor, open
app/controllers/home_controller.rb and add the following lines of code:
def index sql = "select id, FirstName, LastName from Contact limit 100" @contacts = Salesforce::SfBase.query_by_sql(sql) end
The code above performs a very simple query against the Force.com database returning a list of contacts and assigning them to the
@contacts collection.
Now we have our collection of contacts, we want to display them on a page. Edit the
app/views/home/index.html.erb file adding the following code to loop through and display the contacts.
<h3>Existing Contacts</h3> <p> <% @contacts.each do |contact| %> Hello <b><%= contact.FirstName %> <%= contact.LastName %> </b> <br/> <% end %> </p>
Ok, our application is all complete. All we need to do is add it to Git and push it to Heroku. The process is very simple. Here's what you have to do.
The first step to deploying our app to the cloud is to create a Heroku account, and install the Heroku gem. By now, you are a RubyGems ninja and know all you need to do is run the following command:
sudo gem install heroku
With Heroku installed, we want to make things secure. SSH is the key here. (sorry I couldn't avoid the pun!) The Heroku docs, give a good walk through on how to set up your SSH keys and add them to Heroku so you can use them with Git to push your code.
Now we have our basic app running on our local machine, and initial Heroku setup out of the way, it's time to get our code into Git. You should have already installed Git as part of the installing the Ruby toolkit for Force.com, but if you haven't used Git before, in a nutshell, it is a distributed version control system perfectly designed for collaborative development on the web. Oh, and Git works amazingly well with Heroku. Who could ask for more!
Let's quickly double check Git is installed and setup correctly. Go ahead and open a terminal and type the following command. If you receive a version number in response, you are ready to go.
git --version
Once Git is installed, open your terminal window and change directories to our application,
helloforcedotcom, if you are not there already, then enter the following commands:
git init
git add .
git commit -a
Add a comment such as "adding application for the first time" and continue.
Great. Your app is now in Git. I told you it was easy.
Next, we need to tell Heroku about our app. From the command line, enter the following:
heroku create
The Heroku create command creates a unique app name on Heroku, usually something whimsical and fun like
simple-sunset-1234. Unfortunately, this is not always what you want. If you want to add a specific app name you can execute the following command:
heroku create yourappname
For our sample app, I'm going to be really creative and call it
helloforcedotcom. Assuming your app name is unique, the create command will give you a response similar to the following:
The very last thing which we need to do is push our application up to Heroku. This is where Git shines. From your terminal, enter the following command. This command is instructing Git to push the master branch of our app to heroku. This is the incredible power and simplicity of Heroku at its finest. Don't blink, you are now deploying to the cloud!
git push heroku master
If everything goes well, you should be presented with something similar to the following:
It's payoff time, go ahead and open a browser and enter your URL. For example,. You could alternatively use the handy
heroku open command from your terminal to do it for you.
If everything worked as planned you should be presented with the a web page similar to the following which displays a list of Contacts from Force.com:
Congratulations. You have now created an application deployed on Heroku which uses the Ruby Toolkit for Force.com to connect to Force.com and display a list of Contacts. Not bad!
Things have a habit of going wrong right when you don't want them to. If you were developing locally you would typically look at the stack trace in your web servers output log. Don't worry, Heroku provides similar functionality to access the remote logs. Simply enter the following command. (Note: I have added the --appname parameter to this command to refer to my app. It's good practice to get in the habit of naming your apps with meaningful names; It just makes life easier, although Heroku is smart enough to know which app your are working on depending on the directory you are in.)
heroku logs --app helloforcedotcom
Of course, if log files aren't your thing, why not open up an interactive console to your remote app:
heroku console --app helloforcedotcom
This article provides the configuration steps required to build Ruby on Rails applications that use the Force.com Toolkit for Ruby, and deploy them onto Heroku. We started with with a simple Rails app, updated the configuration files, and included a simple controller to fetch a list of data from Force.com. While this application was simplistic in its function, it is valuable to have a clean sample application to build upon.
With a basic understanding of Git and Heroku, you can quickly deploy your application into the cloud, and if desired, collaborate with other team members. By leveraging the toolkit, Ruby developers can also code in a fashion which they are already comfortable with, eliminating the need to learn new syntax or protocols for connecting to your data in the cloud.
Quinton Wall is a Sr. Developer Evangelist at Salesforce.com, and an aspiring fantasy author. He is a regular speaker at cloud and developer events around the world, active contributor to the developer blogs, and twittersphere. When he is not working with the Force.com platform, or writing books, you can find him on the web. | https://developer.salesforce.com/page/Using_the_Force.com_Toolkit_for_Ruby_on_Heroku | CC-MAIN-2015-40 | refinedweb | 2,168 | 66.23 |
In this section, you will learn about strings in switch statements which is recently added feature in Java SE 7.
Using JDK 7, you can pass string as expression in switch statement. The switch statement compares the passed string with each case label and execute the case block which have matched string. The comparison of string in switch statement is case sensitive.
The example code for the above is given below :
public class StringsInSwitch {); } System.out.println(typeOfDay); return typeOfDay; } public static void main(String args[]) { new StringsInSwitch().getTypeOfDayWithSwitchStatement("Friday"); } }
OUTPUT
If you enjoyed this post then why not add us on Google+? Add us to your Circles
Liked it! Share this Tutorial
Discuss: Strings in Switch statement
Post your Comment | http://www.roseindia.net/java/jdk7/J7StringsInSwitch.shtml | CC-MAIN-2014-42 | refinedweb | 121 | 66.94 |
C::TinyCompiler::Perl - Enabling Perl's full C-API in your C::TinyCompiler context
use C::TinyCompiler; # Declare the compiler context with the Perl bindings: my $context= C::TinyCompiler->new('::Perl'); # Or add them afterwards: my $context = C::TinyCompiler->new; $context->apply_packages('::Perl'); # Create a function that tells us how many arguments we sent: $context->code('Body') = q{ void test_func(AV * inputs, AV * outputs) { printf("You sent %d arguments\n", av_len(inputs)); } }; # Compile and call: $context->compile; $context->call_function('test_func', 1, 2, 3);
This module provides access to the full Perl C API in your compiler context. This is a very blunt tool, but it is guaranteed to always reflect the API of whichever version of Perl you use to run your script. It is equivalent to including the following in your
Head code section:
#include "EXTERN.h" #include "perl.h" #include "XSUB.h"
where it determines the path to your Perl's include directory during your script's compile phase. On my machine, the resulting text of this pull-in is equivalent to approximately 8,000 or 10,000 lines of real code, depending on how you define real (as well as many blank lines), which is why I consider it to be quite a blunt tool.
(What follows is what I *hope* happens, though it is not yet the reality.) This weight is the motivation for the C::TinyCompiler::Perl::* sub-modules. They pull in and define only the exact code that you need.
This module may lead to some interesting error messages. Here's a reference.
This compile-time error will indicate that C::TinyCompiler::Perl was not able to find the CORE directory in your Perl libs. This is a big issue because the header files that C::TinyCompiler::Perl wants to include in your compiler context can only be found in this directory. If you run into this problem, it means you do not have your Perl header files stored in a customary place. If you don't know how to fix this, you should reach out to me or to the Perl community (i.e. PerlMonks) for help.
If you see anything with this text in it, you have encountered an error (probably a compile error) in code that you added to your compiler's Head section after you added the C::TinyCompiler::Perl package. Check any and all code that you added. Using "line_numbers" in C::TinyCompiler may help narrow-down the errant line in your code.
David Mertens,
<dcmertens.perl at gmail.com>
Please report any bugs or feature requests at the project's main github page:.
You can find documentation for this module with the perldoc command.
perldoc C::TinyCompiler::Perl
You can also look for information at:
Code copyright 2012 Northwestern University. Documentation copyright 2012-2013 David Mertens.
This program is free software; you can redistribute it and/or modify it under the terms of either: the GNU General Public License as published by the Free Software Foundation; or the Artistic License.
See for more information. | http://search.cpan.org/~dcmertens/C-TinyCompiler-0.04/lib/C/TinyCompiler/Perl.pm | CC-MAIN-2014-35 | refinedweb | 506 | 63.49 |
Use scripts to alter faction standing
From NWNWiki
[edit] Use scripts to alter faction standing
There are several ways to do this. It all depends on what your doing at hand. Here is a list of all the functions you can use to alter Faction.
AdjustFactionReputation AdjustReputation ChangeFaction ChangeToStandardFaction ClearAllFactionMembers ClearPersonalReputation SetIsEnemy SetIsTemporaryEnemy SetIsTemporaryFriend SetIsTemporaryNeutral SetPCDislike SetPCLike SetStandardFactionReputation SurrenderToEnemies
AdjustReputation() Is probably the most used of these functions. In a conversation, lets say you want the NPC to attack if the PC selects a specific text line. This would then go into the "Actions Taken" script node.
#include "NW_I0_GENERIC" void main() { object oPC = GetPCSpeaker(); AdjustReputation(oPC,OBJECT_SELF,-100); DetermineCombatRound(oPC); }
Notice the DetermineComabatRound(oPC) line, without this the NPC will change to Red to the PC, but will just stand there looking stupid. The DetermineCombatRound call makes the NPC "re-perceive" the Already Perceived PC.
This will make the NPC hostile to the PC, if you want them to be hostile to the entire PC party, use AdjustFactionReputation() instead. This function is different in that it makes the NPC faction hate the Entire PC faction which is his party.
#include "nw_i0_plot" #include "NW_I0_GENERIC" void main() { object oPC = GetPCSpeaker(); AdjustReputation(oPC,OBJECT_SELF,-100); DetermineCombatRound(oPC); }
Like wise, you can make a Hostile creature like a PC or other faction by changing the -100 to +80. Why not +100?. Unless you want the creature to be "green" to the PC and not be able to attack ever again (in non-pvp server) then you don't want to adjust them to 100. The game engine will see that Creature as an "ally", kind of like another PC, and if your playing non-PVP, you won't be able to attack them again.
A Note to remember, A PCs faction can not be changed. You must always change how a NPC faction views a PC. When PCs are solo, they each have their own faction, When PCs are grouped, each PC in the group shares the same faction.
If you want to actually change a faction of a NPC, then use ChangeFaction() for custom factions, and use ChangeToStandardFaction() to change to one of the standard factions. Standard factions are; STANDARD_FACTION_COMMONER STANDARD_FACTION_DEFENDER STANDARD_FACTION_HOSTILE STANDARD_FACTION_MERCHANT
Lets say we want to change a NPC from FactA to a FactB faction during a conversation. You "Actions Taken" acript might look something like this.
void main() { //Get a creature object of the FactB faction object oFactBMember = GetObjectByTag("Tag_of_FactB_Member"); ChangeFaction(OBJECT_SELF,oFactBMember); }
Now during that convo, the NPC will change from his current faction, to that of the FactB creature.
The SetIsTemporary* Functions, will alter a NPCs Faction (how it view another object or PC) temporarily. You can specify how long the NPC likes or dislikes the other faction. It can also be used to change how the NPC feel permanently by setting the bDecays parameter to FALSE. All depends how you need to handle the situation.
To make a PC like, or Dislike (red) another PC, use the SetPCDislike() & SetPCLike() Functions. This is how you can make one PC glow "red" when mouse over by another PC. Keep in mind this also makes that PC view you as Red also.
That’s the basic run down on factions, if you would like more specifics of any one of the functions listed above and how to use it, (not a specific script request plz) let me know. | http://nwn.wikia.com/wiki/Use_scripts_to_alter_faction_standing | crawl-002 | refinedweb | 568 | 52.19 |
C passes variables by value. So if you pass 2 int’s x and y to the function square(), it creates a copy of both variables, populates them with the same value as x and y and hands them over to the function to process.
int square(int x, int y) { return x * y; } int main(void) { square(a, b); }
The same thing happens with pointers. A char *a points to location 0x000000 (or NULL) in memory. The variable is then passed to a function initString(). Now a copy of the pointer is created, which also points to the value 0x000000 and is processed by the initString() function. Within initString(), new memory is allocated using malloc() to the variable a.
void initString(char *x) { x = malloc(6 * sizeof(char)); sprintf(x, "%s", "Hello"); } int main(void) { char *a = NULL; initString(a); printf("%s\n", a); }
Output
(null)
What happens in this case is that a fresh pointer variable is created, which happens to point at the same location as a, which is initially NULL. Then memory is allocated to this pointer in the initString() function, so it begins to point to the location returned by malloc(). When the function returns, the x variable is destroyed (and the memory allocated to it is now unreferenced, which creates a memory leak). In the meantime, a is still pointing to NULL.
Now let us change the signature of the initString() function.
void initString(char **x) { *x = malloc(6 * sizeof(char)); sprintf(*x, "%s", "Hello"); } int main(void) { char *a = NULL; initString(&a); printf("%s\n", a); }
Output
Hello
In this case, a is still pointing to NULL. However, instead of passing a directly, initString() is handed over a reference to the pointer a – a pointer to a pointer. This causes a pointer variable to be created which points to the memory location of a. Now, the dereference operator (*) can be used to locate the address of a. Thus the memory address returned by malloc() can be assigned to a.
This method is not needed if you have already allocated memory to a char array in the calling function. This is because the pointer parameter in the callee function also refers to the same memory address allocated in the caller function.
Here’s a quick working example that demonstrates the differences between a pointer and a pointer-to-pointer when passed on to a function.
#include <stdio.h> #include <stdlib.h> void initString1(char *a) { a = malloc(6 * sizeof(char)); strcpy(a, "Hello"); printf("initString1():\t%s\t%p\t%p\n", a, a, &a); } void initString2(char **a) { *a = malloc(6 * sizeof(char)); strcpy(*a, "World"); printf("initString2():\t%s\t%p\t%p\n", *a, *a, &*a); } int main(int argc, int *argv[]) { char *b = NULL; printf("Function |\tValue\tPoints to\tAddress\n", b, b, &b); initString1(b); //strcpy(b, "World"); // Crashes printf("main() :\t%s\t%p\t%p\n", b, b, &b); initString2(&b); strcpy(b, "Hello"); printf("main() :\t%s\t%p\t%p\n", b, b, &b); return 0; } | http://www.notadesigner.com/tag/c-lang/ | CC-MAIN-2018-51 | refinedweb | 511 | 59.64 |
C Standard library functions or simply C Library functions are inbuilt functions in C programming.
The prototype and data definitions of these functions are present in their respective header files. To use these functions we need to include the header file in our program. For example,
If you want to use the
printf() function, the header file
<stdio.h> should be included.
#include <stdio.h> int main() {
printf("Catch me if you can."); }
If you try to use
printf() without including the
stdio.h header file, you will get an error.
Advantages of Using C.
4. The functions are portable
With ever-changing real-world needs, your application is expected to work every time, everywhere. And, these library functions help you in that they do the same thing on every computer.
Example: Square root using sqrt() function
Suppose, you want to find the square root of a number.
To can compute the square root of a number, you can use the sqrt() library function. The function is defined in the
math.h header file.
#include <stdio.h> #include <math.h> int main() { float num, root; printf("Enter a number: "); scanf("%f", &num); // Computes the square root of num and stores in root. root = sqrt(num); printf("Square root of %.2f = %.2f", num, root); return 0; }
When you run the program, the output will be:
Enter a number: 12 Square root of 12.00 = 3.46 | https://cdn.programiz.com/c-programming/library-function | CC-MAIN-2020-40 | refinedweb | 235 | 76.62 |
XML file should be recognizable by root element. Current implementation and UI
spec allow recognition only be namespace.
I think this one can also be set to WONTFIX. The help topic (once the help
button is enabled...) will explain that if you want to distinguish a file type
by root element, you should set the XML file's namespace here.
It's still a valid RFE even if there is a documented workaround. :-)
:-) Ok. In that case, I think what I'm proposing is that the panel should let
the user specify the namespace or the XML root element, or both.
*** Issue 64149 has been marked as a duplicate of this issue. ***
Workaround is simply to go through the wizard and then edit the MIME resolver
file to use some other criteria, acc. to its DTD and documentation, available here:
I think the workaround is fine. So I'm closing as WONTFIX.
*** Bug 157819 has been marked as a duplicate of this bug. ***
*** Bug 202788 has been marked as a duplicate of this bug. ***
Still occasionally asked for. Would be a good candidate for NetFIX, I think - code is limited to one package and easy enough to test.
OK, I added the keyword and put the issue to the pool:
I'd like to NetFIX [1] this bug. Is it possible? [1]
Jesse, are you willing to review and integrate the patch?
Sure!
I'm struggling on finding the module I have to work on. Can someone tell me which module I should work on?
Found another issue while fixing this. Reported a separate bug, see bug 206780 . Currently Im blocked by this issue.
That was reported against 7.0.1. If you are preparing a patch you need to be working against trunk (7.2 dev) sources.
Bug fixed. The patch is attached for review. Few test cases have also been added to cover the new feature addition.
Created attachment 115914 [details]
patch1
Please don't resolve bug as fixed before the code is actually integrated into the codebase. Thanks.
The patch does not apply against trunk sources (conflict in NewLoaderIterator.java). Probably you need to look at what has happened recently in bug #191777 and to a lesser extent in bug #207219. | https://netbeans.org/bugzilla/show_bug.cgi?id=62176 | CC-MAIN-2014-15 | refinedweb | 374 | 76.52 |
Hello, I have an 'Exam' module which selects new random set of questions and displays it, well this is the idea n;). Here is what I have so far: >>> import random >>> n_question = 5 >>> q = {1:'1q', 2:'2q', 3:'3q', 4:'4q', 5:'5q', 6:'6q', 7:'7q', 8:'8q', 9:'9q', 0:'0q'} >>> if len(q) > n_question: ... q_keys = random.sample(q.keys(), n_question) ... else: ... q_keys = q.keys() ... >>> q_keys.sort() >>> a = [q[x] for x in q_keys] >>> a ['1q', '4q', '5q', '7q', '8q'] >>> a ['1q', '4q', '5q', '7q', '8q'] This only returns the same questions, what am I doing wrong? How do I return a different set? I would like to have a group of similar questions and then select a random set out of this to make up my final namespace (a), thus avoiding similar questions being selected from the pool of questions. Is there a more elegant solution which will pull a random selection of questions? Cheers -- Norman -- Norman Khine 7 rue Ponscarme, Paris, 75013, France tel +33 870 628 934 fax +33 142 724 4437 %>>> "".join( [ {'*':'@','^':'.'}.get(c,None) or chr(97+(ord(c)-83)%26) for c in ",adym,*)&uzq^zqf" ] ) | https://mail.python.org/pipermail/tutor/2007-October/057703.html | CC-MAIN-2017-30 | refinedweb | 195 | 75.44 |
Basetypes, Collections, Diagnostics, IO, RegEx...
We get an ongoing number of questions about formatting numbers in .NET. The documentation seems to be notoriously difficult to find. I thought I'd give a quick overview here, with a sample.
First note for future reference: to find the write page in the documentation, type in "custom numeric format strings" or "standard numeric format strings" when using the index in the documentation viewer. If you're interested in datetime formatting, try "custom date and time format strings" or "standard date and time format strings".
Formatting is automatically culture-sensitive. So writing out numbers will take the CurrentCulture into account when it formats the values. In the sample below, I use the IFormattable interface to simply force the issue. But changing the System.Threading.Thread.CurrentThread.CurrentCulture would be just as effective.
The next thing to note is that there are a variety of existing format specifiers which define, and support specific formatting. For example, "C" is used to format a number as a currency (which as you can guess, varies wildly with culture). All you need to do is pass the ToString method a formatting specifier (followed by an optional numeric value, indicating the number of decimal places generally). Supported specifiers include fixed point format (F), Number format (N), Exponential format (E) and percentage format (P).
If you're wondering where these values determine how they get formatted, they basically use the NumberFormatInfo associated with the CultureInfo you're using to perform the formatting. If you do nothing else, then it's the CurrentCulture for the currentthread. The NumberFormatInfo has a variety of properties which are used to format numbers for that culture (such as CurrencyDecimalSeparator, and PercentPositivePattern).
You can also specify custom formats if you want, using traditional characters, such as # and 0 (# indicates the formatter should display a numeric value if there is one, or nothing otherwise. 0 indicates that a numeric value should be displayed, or if there is none, then display a zero). For example, "00.00" as a format, will always at least display "00.00". If the number in question is actually 1234, then it will display "1234.00", and if it is actually 0.0234, it will display "00.02". Essentially, digits to the left of the decimal are the minimum number to display (but more significance is always shown), while digits to the right of the decimal are a maximum to display.
A couple of notes on the side:
- A format specifier (used for traditional, well-defined formats) is always a single character long, followed by an optional digit. If you specific a single character that is not recognized, you'll get an exception (For example, "L"). But on the flipside, if you specify more than one character, we'll assume you have a custom format string, so any unrecognized characters in the format are simply written out as literal values. For example, if you try to format an integer using "GG" all you'll see in the output is "GG", since we simply view those as literals
- In the sample below, you'll see "{0, -20}". The ", -20" part formats the output to be the specified width (20). The negative sign says align the text to the left. This gives the output a nice, tabular format
- While I have chosen to use the formats as part of the ToString method in the instance (t.ToString("G")), you could actually stick it into format section specified for the WriteLine call, after the 25, like so: "{1, 25:G}". This can make things simpler
- You'll see question marks in this demo for some cultures, because the Console can't print those characters (such as the currency symbo for the euro)
- for more information on CultureInfo's, see the documentation in the CultureInfo topic. This includes a list of the different cultures you can use
Example: I wrote this using generic collections of course, but to ensure you can take it and run it on V1.1, I've added standard collections back in.
using System;// using System.Collections.Generic;using System.Collections;using System.Globalization;using System.Threading;
class Demo { // List<CultureInfo> li; ArrayList li; public static void Main() {
Demo d = new Demo(); Decimal d1 = .00000398234m; Double d2 = 2345987.39876; d.WriteFormats(d1);
d.WriteFormats(d2); }
public Demo() { // li = new List<CultureInfo>(); li = new ArrayList(); li.Add(new CultureInfo("en-US")); li.Add(new CultureInfo("en-GB")); li.Add(new CultureInfo("fr-FR")); li.Add(new CultureInfo("es-MX")); li.Add(new CultureInfo("hi-IN")); li.Add(new CultureInfo("ja-JP")); }
public void WriteFormats (IFormattable t) { Console.WriteLine("{0}Value passed was a {1}", Environment.NewLine, t.GetType());
foreach (CultureInfo ci in li) { Console.WriteLine("{0}Culture is {1}", Environment.NewLine, ci); Thread.CurrentThread.CurrentUICulture = ci;
Console.WriteLine("{0,-20}{1,25}", "General Format:", t.ToString("G", ci)); Console.WriteLine("{0,-20}{1,25}", "Fixed Point Format:", t.ToString("F", ci)); Console.WriteLine("{0,-20}{1,25}", "Exponential Format:", t.ToString("E", ci)); Console.WriteLine("{0,-20}{1,25}", "Percentage Format", t.ToString("P", ci)); Console.WriteLine("{0,-20}{1,25}", "Number Format:", t.ToString("N", ci)); Console.WriteLine("{0,-20}{1,25}", "Number Format (9):", t.ToString("N9", ci)); Console.WriteLine("{0,-20}{1,25}", "Currency Format ():", t.ToString("C", ci)); Console.WriteLine("{0,-20}{1,25}", "Currency Format (9):", t.ToString("C9", ci)); Console.WriteLine("{0,-20}{1,25}", "Custom Format 1:", t.ToString("00.00", ci)); Console.WriteLine("{0,-20}{1,25}", "Custom Format 2:", t.ToString("#,00.##", ci)); }
Console.WriteLine("{0}Press Enter to continue...", Environment.NewLine); Console.ReadLine(); }}
output (for 2345987.39876):
Culture is en-US en-G (): £2,345,987.40Currency Format (9): £2,345,987.398760000Custom Format 1: 2345987.40Custom Format 2: 2,345,987.4
Culture is fr-FR ?Currency Format (9): 2 345 987,398760000 ?Custom Format 1: 2345987,40Custom Format 2: 2 345 987,40Culture is es-M hi-INGeneral Format: 2345987.39876Fixed Point Format: 2345987.40Exponential Format: 2.345987E+006Percentage Format 23,45,98,739.88 %Number Format: 23,45,987.40Number Format (9): 23,45,987.398760000Currency Format (): ?? 23,45,987.40Currency Format (9): ?? 23,45,987.398760000Custom Format 1: 2345987.40Custom Format 2: 23,45,987.4
Culture is ja-JPGeneral (): ¥2,345,987Custom Format 1: 2345987.40Custom Format 2: 2,345,987.4
PingBack from | http://blogs.msdn.com/bclteam/archive/2004/10/17/243636.aspx | crawl-002 | refinedweb | 1,064 | 53.37 |
IntroductionI think that adding a splash form to a windows application is good decision in terms of design but also those kinds of windows forms are used for commercial, ergonomics and psychological purposes. Splash screens are often used to display information to the final user while an application is loading. So that it can give him a glance about what he is going to bring into play and this short moment can affect deeply the user either positively or negatively. In this tutorial, I propose a method of how to do this programmatically.Within VS2005-VB.NET IDE the problem is solved because we can add a splash screen as an item proposed by the IDE as is mentioned in the figure 1 below:Figure 1But within C# IDE this kind of items are not provided as the figure 2 shows:Figure 2To resolve the problem I invite you to follow those steps:First of all we create new windows application within C# IDE, in this case we can use either Visual Studio 2005, VS C# express edition that you can download form Microsoft official web site or Sharp Develop 2.0 witch is an open source IDE for developing DOT Net applications that you can download for free.Add a new project by clicking File --> New project
Figure 3
Figure 4So now we go to the important stage in this tutorial. In the solution explorer as shown belowFigure 5Select 'Program.cs' and open it so that the code appears. It is from this point that the application will be started. The following code will be displayed in the editor:Figure 6When we fire up the program, Form1 appears due to this fragment of code:Application.Run (new Form1 ());In order to display the Form2, witch is the Splash-From in your case, for a few moments before showing the Form1, you have to implement the following code instead of this one above (See figure 6)
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace SplashProject
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
/* a new static timer instance, it's important for starting and handeling the time during it the splash form is displayed*/
static System.Windows.Forms.Timer myTimer = new System.Windows.Forms.Timer();
// Counter is an integer that help us to fix the number of seconds during them the Splash form is displayed
static int counter = 0;
// b is a boolean related to the event if the Spalsh form will be disposed or not
static bool b = false;
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
/*-----------------The modification of the void Main method behavior----------------*/
// New instance of Form2
Form2 oForm2 = new Form2();
//Add event handler to myTimer.Tick event
myTimer.Tick+=new EventHandler(myTimer_Tick);
//Fix myTimer interval to 1000 witch is 1 second
myTimer.Interval = 1000;
//Start myTimer
myTimer.Start();
/* This is the conditional loop during it the Form2 will appear as Splash form */
while (b == false)
{
//Display oForm2
oForm2.Show();
/*This is very important to add this line of code because it is responsable for
dispalying oForm2 during the time provided to this action*/
Application.DoEvents();
if (b == true)
{
/*Disposing oForm2 when the time is out */
oForm2.Dispose();
/*Going out of this while loop*/
break;
}
Application.Run(new Form1());
}
}
/*This is the surcharged method that handels myTimer.Tick*/
static void myTimer_Tick(Object sender, EventArgs e)
// Stop the timer
myTimer.Stop();
/* Here we chose 4 seconds or a little more to dispaly the splash form oForm2, and then to dispose it */
if (counter < 4)
// Enable the counter
myTimer.Enabled = true;
// Increment the counter
counter++;
// The condition related to witch the Spalsh form will be disposed
if (counter == 4) b = true;
}}In deed, if you want to precise the position and the size of your Splash-Form programmatically, you can implement the Form2_Load(Object sender, EventArgs e) {} according to two ways and you can chose one among those mentioned below:
//The first way
private void Form2_Load(object sender, EventArgs e)
this.Location = new Point(200, 200);
this.Size = new Size(300, 300);
}
//The second way
this.Top = 200;
this.Left = 200;
this.Width = 300;
this.Left = 300;
}This is my manner to add a Splash screen or a Splash-Form programmatically using C# 2.0
©2016
C# Corner. All contents are copyright of their authors. | http://www.c-sharpcorner.com/UploadFile/yougerthen/add-a-splash-form-to-a-windows-application/ | CC-MAIN-2016-44 | refinedweb | 724 | 53.1 |
* Wang.
> 1. there is no necessity that namespace must be classid space.
Agreed.
> 2. considering the resemblance of streams (they usually are the same
> application), the rate control can be simplified. TBF or HTB is overkill.
Argueable.
> 3. grouped rate control method is not suitable for single stream.
I'm not sure what you mean with this.
> 4. fairness on streams, and total guarantee ( rate * n) can guarantee n
> streams very well
Agreed, we can put this into the allocator by letting the user specify
limits and run a rate estimator.
> 5. per stream rate limit and total limit ( rate * n * 1.xx ) make sense
> for bandwidth efficiency.
Agreed, make the allocator create HTB classes and you can have it.
> 6. precisely counting of streams is necessary (when streams is more than
> expected, existing streams are guaranteed, new streams are not
> guaranteed, so at least some will work, not all don't work)
Also agreed, I did not lose too many thoughts on this yet but it's
not hard to implement.
> What FRG does:
>
> 1. the namespace is conntracks of streams;
> 2. rate control algorithm is very simple, based on the token bucket;
> 3. grouped rate control (HTB) is only used to do total guarantee
> 4. provides fairness on streams, and there is m * rate guarantee for
> dynamic m streams;
> 5. per stream rate limit, total limit ( rate * max_streams * 1.05)
> 6. precisely counting of streams, and guarantees existing max_streams
> stream..
So basically the direction we want to go is to strict separate the
classification from the queueing to allow the user to customize
everything by replacing small components. It might be worth to read
up on the discussion on "ematch" and "action" over the last 3 months.
Cheers, Thomas | http://oss.sgi.com/archives/netdev/2005-04/msg01772.html | CC-MAIN-2016-40 | refinedweb | 291 | 73.07 |
Difference between revisions of "Provisional API Guidelines"
Revision as of 17:36, 23 February 2006
Contents
Overview)
- non-API.
<div id="pre_freeze"/>
Provisional APIs prior to a non-API package. If provisional API is in a non-API. All non-API packages should be exported and marked x-internal.
Javadoc
The primary indicator of provisional API:
* <p> * EXPERIMENTAL..
Provisional APIs after the API freeze
After the API freeze, there is really no such thing as "provisional API". Either it is complete and committed platform API, or it is internal. API that is new in the current release cycle is still subject to change, but changes after this point are rare and require approval from the Eclipse project PMC. However, it is still useful for committers to distinguish truly internal code from code that may move into API in a later development cycle. Thus a reasonable working definition of provisional API after the API freeze is: internal code that may become API in a future release.
Package naming
All provisional API must be in a package whose name contains the segment "internal". The "internal.provisional" naming convention can be used, but is not required, to separate provisional API from true internal code within the internal package namespace.
Bundle manifest
All API packages should be exported unconditionally by the bundle manifest. All non-API packages, including packages containing provisional API, should be exported and marked x-internal.
Javadoc
No special javadoc treatment for provisional API is needed. Note that @since tags also have little value for provisional API at this point. If provisional API is added in the 4.0 development period, but promoted to real API in the 5.0 development period, the correct tag for that API will be @since 5.0. Since provisional API after the API freeze does not know what release it will appear in, the @since tag is not useful..
There are no additional restrictions on changing provisional APIs after the API freeze. Since all such API is in internal packages after this point, it can change arbitrarily without notice up to and including the final build of the release. | http://wiki.eclipse.org/index.php?title=Provisional_API_Guidelines&diff=2451&oldid=2450 | CC-MAIN-2017-34 | refinedweb | 354 | 55.74 |
;
[download]
First we get a namespace by declaring a package name. This helps ensure our module's functions and variables remain separate from any script that uses it.
Use strict is a very good idea for modules to restrict the use of global variables. See use strict warnings and diagnostics or die for more details.
We need to use the Exporter module to export our functions from the MyModule:: namespace into the main:: namespace to make them available to scripts that 'use' MyModule.
We pacify strict with the use vars declaration of some variables. We can use an 'our' declaration in 5.6+
We now set a $VERSION number and make Exporter part of MyModule using the @ISA. See perlboot for all the gory details on what @ISA is or just use it as shown.
@EXPORT contains a list of functions that we export by default, in this case nothing. Generally the less you export by default using @EXPORT the better. This avoids accidentally clashing
with functions defined in the script using the module. If a script wants a function let it ask.
).
%EXPORT_TAGS. For convenience we define two sets of export tags. The ':DEFAULT' tag exports only &func1; the ':Both' tag exports both &func1 &func2. This hash stores labels pointing to array references. In this case the arrays are anonymous.
We need the 1; at the end because when a module loads Perl checks to see
that the module returns a true value to ensure it loaded OK. You could put any true value at the end (see Code::Police) but 1 is the convention.
#!";
[download]
We use MyModule in MyScript.pl as shown. Uncomment the examples to see what happens. Just uncomment one at a time.
Case 1: Because our module exports nothing by default we get errors as &funct1 and &funct2 have not been exported thus do not exist in the main:: namespace of the script.
Case 2: This works OK. We ask our module to export the &func1 so we can use it. Although &func2 was not exported we reference it with its full package name so this works OK..
Case 4: We specified the export of both our functions with the ':Both' thus this works.
When you issue a use MyModule; directive perl searchs the @INC array for a module with the correct name. @INC usually contains:
/perl/lib
/perl/site/lib
.
The . directory (dot dir) is the current working directory. CORE modules are installed under perl/lib whereas non-CORE modules install under perl/site/lib. You can add directories to the module search path in @INC like this:
BEGIN { push @INC, '/my/dir' }
# or
BEGIN { unshift @INC, '/my/dir' }
# or
use lib '/my/dir';
[download].
use Foo::Bar does not mean look for a module called "Foo::Bar.pm" in the @INC directories. It means search @INC for a *subdir* called "Foo" and a *module* called "Bar.pm"..
Hope this explains how it works.
cheers
tachyon.
s&&rsenoyhcatreve&&&s&n.+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print
Are
$W++).
Thanks.
Great Tutorial, It helped to clear up the muddy water created by my Perl Black Book.
Thanks again,
Greg W..
Great."].
My savings account
My retirement account
My investments
Social Security
Winning the lottery
A Post-scarcity economy
Retirement?! You'll have to pull the keyboard from my cold, dead hands
I'm independently wealthy
Other
Results (73 votes),
past polls | http://www.perlmonks.org/?node_id=102347 | CC-MAIN-2014-42 | refinedweb | 567 | 75.4 |
First of all, why you may want to use such service? Despite the fact that currently there are so many different channels of communication (including various messaging apps), Email is still a default and universal way to do it.
- Literally every enterprise service supports email notifications, even if it’s integration capabilities are rather limited. So, with Email Bot you can automatically process such notifications.
- Email is good, simple, reliable and familiar way to communicate with humans. Send an email – get response. Everyone can do it. So, email bot can make basic routine operations, like organizing the external meetings, pretty much like a human secretary.
- It’s easier to code Email bot than any other interface, and the code can be reused for other communication channels, for example messaging apps.
I get email messages from IMAP server in python3 using easyimap module.
It is very simple to use. You make a connection to the server, get the IDs of the messages and can retrieve MailObject by ID. Description of MailObject is here. Here is a separate post about sending and receiving email message in Python. Look there for details. The only useful thing that easyimap can’t do is to delete messages. You know, the mailbox can overflow. You can get the code for deleting from this stackoverflow topic.
IMAP Server
I’m receiving emails from IMAP server. IMAP uses port 143 and SSL/TLS encrypted IMAP uses port 993. So, if you connect to the server using telnet, you should see some like this:
$ telnet imap.corporation.com 143 Trying 10.10.117.18... Connected to imap.corporation.com. Escape character is '^]'. * OK The Microsoft Exchange IMAP4 service is ready.
First of all, I create an empty json file for processed messages: ‘{}’. Then I analyze latest 100 email messages searching for one that starts with the command “IMPORTANT COMMAND”. When I find it, I send back “Hello!” with the citation of original message and save mail_id to processed messages dict (and file) to skip it on next iteration. And all this in cycle with 5 seconds sleep:
import html2text import easyimap import re import json import time From: " + mail.from_addr + '\n' citation += u"> Date: " + mail.date + '\n' citation += u"> Body: " + html2text.html2text(mail.body) send_email([str(mail.from_addr)], subject, message + "\n\n" + citation) processed_messages[str(mail_id)] = {'subject':subject, 'message':message, 'ts':int(time.time())} f = open("messages.json","w") f.write(json.dumps(processed_messages)) f.close() print(str(mail_id) + " processed!") time.sleep(5)
So that actually it, a very simple email bot. Instead of replying with “Hello” each time, you can send any results of request processing. Here is a
send_email function, that I use for sending emails via SMTP server:
import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText def send_email(receivers, subject, text): sender = login + '@corporation.com' msg = MIMEMultipart() msg['From'] = sender msg['To'] = ", ".join(receivers) msg['Subject'] = subject msg.attach(MIMEText(text)) smtpObj = smtplib.SMTP('smtp.corporation.com:25') try: smtpObj.login(login, password) except: print("Login attempt failed") smtpObj.sendmail(sender, receivers, msg.as_string()) print("SENT: " + msg.as_string())
Service
The last part is to make Email bot start at the boot of Operating System and restart on crash. This can be done in various ways. For example, you can write and schedule in cron a Bash script that will check whether the process is currently running and, if it’s not, will launch it.
But there is a much better option. You can create a systemd service. In this case, the Operating System will monitor status of the python script and restart it when it’s necessary. You just need to create a text file and set there the working directory and a path to the script:
# cat /etc/systemd/system/emailbot.service [Unit] Description=STerraBot service After=network.target StartLimitInterval=0 [Service] Type=simple Restart=always RestartSec=1 User=j.smith WorkingDirectory=/home/j.smith/EmailBot ExecStart=/home/j.smith/EmailBot/run_email_bot.py [Install] WantedBy=multi-user.target
Note: I used old parameter StartLimitInterval, because new parameter StartLimitIntervalSec leads to an error in CentOS 7.
To make the service start automatically on OS boot run enable command:
# systemctl enable emailbot # systemctl status emailbot ● emailbot.service - EmailBot service Loaded: loaded (/etc/systemd/system/emailbot.service; enabled; vendor preset: enabled) Active: active (running) since Fri 2019-02-15 20:31:59 MSK; 23s ago Main PID: 2439 (run_email_bot.p) Tasks: 1 Memory: 18.4M CPU: 305ms CGroup: /system.slice/emailbot.service └─2439 /usr/bin/python3 /home/j.smith/EmailBot/run_email_bot.py Feb 15 20:31:59 botserver.corporation.com systemd[1]: emailbot.service: Service hold-off time over, scheduling restart. Feb 15 20:31:59 botserver.corporation.com systemd[1]: Stopped EmailBot service. Feb 15 20:31:59 botserver.corporation.com systemd[1]: Started EmailBot service.. | https://avleonov.com/2019/02/18/how-to-make-email-bot-service-in-python/ | CC-MAIN-2020-29 | refinedweb | 805 | 53.37 |
§Cache APIs Migration
§New packages
Now
cache has been split into a
cacheApi component with just the API, and
ehcache that contains the Ehcache implementation. If you are using the default Ehcache implementation, simply change
cache to
ehcache in your
build.sbt:
libraryDependencies ++= Seq( ehcache )
If you are defining a custom cache API, or are writing a cache implementation module, you can just depend on the API:
libraryDependencies ++= Seq( cacheApi )
§Removed APIs
The deprecated Java class
play.cache.Cache was removed and you now must inject an
play.cache.SyncCacheApi or
play.cache.AsyncCacheApi.
§New Sync and Async Cache APIs
The Cache API has been rewritten to have a synchronous and an asynchronous version. The old APIs will still work but they are now deprecated.
§Java API
The interface
play.cache.CacheApi is now deprecated and should be replaced by
play.cache.SyncCacheApi or
play.cache.AsyncCacheApi.
To use,
play.cache.SyncCacheApi just inject it:
public class SomeController extends Controller { private SyncCacheApi cacheApi; @Inject public SomeController(SyncCacheApi cacheApi) { this.cacheApi = cacheApi; } }
And then there is the asynchronous version of the API:
public class SomeController extends Controller { private AsyncCacheApi cacheApi; @Inject public SomeController(AsyncCacheApi cacheApi) { this.cacheApi = cacheApi; } }
See more details about how to use both APIs at specific documentation.
§Scala API
The trait
play.api.cache.CacheApi is now deprecated and should be replaced by
play.api.cache.SyncCacheApi or
play.api.cache.AsyncCacheApi.
To use
play.api.cache.SyncCacheApi, just inject it:
class Application @Inject() (cache: SyncCacheApi) extends Controller { }
Basically the same for
play.api.cache.AsyncCacheApi:
class Application @Inject() (cache: AsyncCacheApi) extends Controller { }
See more details about how to use both APIs at specific documentation.
Next: JPA Migration | https://www.playframework.com/documentation/2.8.1/CacheMigration26 | CC-MAIN-2020-34 | refinedweb | 280 | 59.6 |
Introduction: Nitrogen on copper¶
This section gives a quick (and incomplete) overview of what ASE can do.
We will calculate the adsorption energy of a nitrogen molecule on a copper surface. This is done by calculating the total energy for the isolated slab and for the isolated molecule. The adsorbate is then added to the slab and relaxed, and the total energy for this composite system is calculated. The adsorption energy is obtained as the sum of the isolated energies minus the energy of the composite system.
Here is a picture of the system after the relaxation:
Please have a look at the following script
N2Cu.py:
from ase import Atoms from ase.calculators.emt import EMT from ase.constraints import FixAtoms from ase.optimize import QuasiNewton from ase.build import fcc111, add_adsorbate h = 1.85 d = 1.10 slab = fcc111('Cu', size=(4, 4, 2), vacuum=10.0) slab.set_calculator(EMT()) e_slab = slab.get_potential_energy() molecule = Atoms('2N', positions=[(0., 0., 0.), (0., 0., d)]) molecule.set_calculator(EMT()) e_N2 = molecule.get_potential_energy() add_adsorbate(slab, molecule, h, 'ontop') constraint = FixAtoms(mask=[a.symbol != 'N' for a in slab]) slab.set_constraint(constraint) dyn = QuasiNewton(slab, trajectory='N2Cu.traj') dyn.run(fmax=0.05) print('Adsorption energy:', e_slab + e_N2 - slab.get_potential_energy())
Assuming you have ASE setup correctly (Installation) run the script:
python N2Cu.py
Please read below what the script does.
Atoms¶
The
Atoms object is a collection of atoms. Here
is how to define a N2 molecule by directly specifying the position of
two nitrogen atoms:
>>> from ase import Atoms >>> d = 1.10 >>> molecule = Atoms('2N', positions=[(0., 0., 0.), (0., 0., d)])
You can also build crystals using, for example, the lattice module
which returns
Atoms objects corresponding to
common crystal structures. Let us make a Cu (111) surface:
>>> from ase.build import fcc111 >>> slab = fcc111('Cu', size=(4,4,2), vacuum=10.0)
Adding calculator¶
In this overview we use the effective medium theory (EMT) calculator, as it is very fast and hence useful for getting started.
We can attach a calculator to the previously created
Atoms objects:
>>> from ase.calculators.emt import EMT >>> slab.set_calculator(EMT()) >>> molecule.set_calculator(EMT())
and use it to calculate the total energies for the systems by using
the
get_potential_energy() method from the
Atoms class:
>>> e_slab = slab.get_potential_energy() >>> e_N2 = molecule.get_potential_energy()
Structure relaxation¶
Let’s use the
QuasiNewton minimizer to optimize the
structure of the N2 molecule adsorbed on the Cu surface. First add the
adsorbate to the Cu slab, for example in the on-top position:
>>> h = 1.85 >>> add_adsorbate(slab, molecule, h, 'ontop')
In order to speed up the relaxation, let us keep the Cu atoms fixed in
the slab by using
FixAtoms from the
constraints module. Only the N2 molecule is then allowed
to relax to the equilibrium structure:
>>> from ase.constraints import FixAtoms >>> constraint = FixAtoms(mask=[a.symbol != 'N' for a in slab]) >>> slab.set_constraint(constraint)
Now attach the
QuasiNewton minimizer to the
system and save the trajectory file. Run the minimizer with the
convergence criteria that the force on all atoms should be less than
some
fmax:
>>> from ase.optimize import QuasiNewton >>> dyn = QuasiNewton(slab, trajectory='N2Cu.traj') >>> dyn.run(fmax=0.05)
Note
The general documentation on structure optimizations contains information about different algorithms, saving the state of an optimizer and other functionality which should be considered when performing expensive relaxations.
Input-output¶
Writing the atomic positions to a file is done with the
write() function:
>>> from ase.io import write >>> write('slab.xyz', slab)
This will write a file in the xyz-format. Possible formats are:
Reading from a file is done like this:
>>> from ase.io import read >>> slab_from_file = read('slab.xyz')
If the file contains several configurations, the default behavior of
the
write() function is to return the last
configuration. However, we can load a specific configuration by
doing:
>>> read('slab.traj') # last configuration >>> read('slab.traj', -1) # same as above >>> read('slab.traj', 0) # first configuration
Visualization¶
The simplest way to visualize the atoms is the
view()
function:
>>> from ase.visualize import view >>> view(slab)
This will pop up a
ase.gui window. Alternative viewers can be used
by specifying the optional keyword
viewer=... - use one of
‘ase.gui’, ‘gopenmol’, ‘vmd’, or ‘rasmol’. (Note that these alternative
viewers are not a part of ASE and will need to be installed by the user
separately.) The VMD viewer can take an optional
data argument to
show 3D data:
>>> view(slab, viewer='VMD', data=array)
Molecular dynamics¶
Let us look at the nitrogen molecule as an example of molecular
dynamics with the
VelocityVerlet
algorithm. We first create the
VelocityVerlet object giving it the molecule and the time
step for the integration of Newton’s law. We then perform the dynamics
by calling its
run() method and
giving it the number of steps to take:
>>> from ase.md.verlet import VelocityVerlet >>> from ase import units >>> dyn = VelocityVerlet(molecule, dt=1.0 * units.fs) >>> for i in range(10): ... pot = molecule.get_potential_energy() ... kin = molecule.get_kinetic_energy() ... print('%2d: %.5f eV, %.5f eV, %.5f eV' % (i, pot + kin, pot, kin)) ... dyn.run(steps=20) | https://wiki.fysik.dtu.dk/ase/gettingstarted/surface.html | CC-MAIN-2020-16 | refinedweb | 852 | 51.24 |
Getting Started with Global Beans in Fuse Tooling 10.0.0
>>IMAGE.
This tutorial shows how to create a customizable service that uses a global Java bean and Camel XML. By the end, you will have a simple Fuse integration project, which includes a Camel test that verifies the bean logic.
The main steps in this tutorial are:
- Create a Fuse integration project.
- Create a bean in the project.
- Finish the bean class.
- Create a route.
- Create a test.
- Finish the generated test.
Prerequisites: Eclipse Oxygen is required. During installation of Red Hat Developer Studio 11.0, you should have selected installation of JBoss Fuse Tooling.
Step 1: Create a Project
First, we have to create a project for where we can put our code.
- In the Developer Studio menu bar, click File->New->Fuse Integration Project.
- In the new project wizard, in the Project Name field, enter
global-bean-tutorial.
- Accept all defaults to create a new, empty Fuse project.
- Click Finish.
Fuse tooling will then build a new Blueprint Camel project, which can take a few moments.
Step 2: Create our Global Bean
Create a simple Java bean to use in the Camel route:
- In the route editor, click the Configurations tab and then click Add.
- In the “Create new global element…” dialog, click Bean and then click OK.
- In the “Add Bean” dialog, in the Id field, enter
GreetingBean.
- To the right of the Class field, click the + button to create a new class.
- In the “New Java Class” wizard:
- In the Package field, enter
org.example.
- In the Name field, enter
Greeting.
- Click Finish.
- In the “Add Bean” dialog, click Finish.
Step 3: Finish the Bean Class
The previous step created a rough outline for the Java bean. To finish the bean class and make it do something, change the code to something like this:
package org.example; import java.util.ArrayList; import java.util.List; public class Greeting { private List messageCache = new ArrayList<>(); private String greetingText = "Hello"; public Greeting() { // empty } public Greeting(String newGreeting) { greetingText = newGreeting; } public String hello(String msg) { String helloMsg = greetingText + " " + msg; messageCache.add(helloMsg); return helloMsg; } public String toString() { return messageCache.toString(); } }
This simple bean has one method,
hello(String);
, that
- Attaches a greeting string to the beginning of the method argument.
- Caches the modified string.
- Returns the modified string.
The
hello(String) method provides a way to customize the greeting in the constructor and to retrieve the cache. A Camel route can use these various points of entry into the bean code.
Step 4: Create a Route
Create a route that will use the bean:
- In the route editor, click the Design tab.
- In the Palette, under Components, click and drag Direct onto the Route_route1 container. This tutorial uses the Direct component to keep the example simple. You can, of course, use a File component, JMS component, or some other component.
- With the new “direct” component in the route selected:
- Open the Properties view.
- Click the Details tab.
- In the Uri field, change the value to
direct:beanTutorial.
- In the Palette, under Components, click and drag the Bean component onto the direct component.
- With the Bean_bean1 component selected, in the Properties view:
- Select the Details tab.
- In the Ref field, display the dropdown list.
- Select the GreetingBean, which appears here because you previously added it as a global bean. This creates a reference to the global bean and inserts it into the route.
- In the Palette, drag another Direct component onto the Bean in the route.
- With the second “direct” component in the route selected, in the Properties view:
- In the Uri field, change the value to direct:beanTutorialOut. This creates the final destination for the route.
- Save the route.
Step 5: Create a Test
In the project you created in step 1, create a test:
- In the Project Explorer view, in the src folder, create a new folder named
test.
- In the test folder, create a new folder named
java.
- In the Developer Studio menu bar, select File -> New -> Camel Test Case.
- In the New Camel JUnit Test Case wizard:
- Make sure the Source Folder path is
global-bean-tutorial/src/test/java.
- In the Package field, enter
org.example.
- To the right of the Camel XML file under test field, click Browse.
- Select the blueprint.xml file and click OK.
- In the Name field, enter
GreetingTest.
- Click Finish.
Step 6: Finish the Generated Test
The Camel Test Case wizard generates a test class that extends
CamelBlueprintTestSupport and provides some templated code. To finish the generated test, provide some sample input and output messages and then send them to the project’s Camel route.
Change your class to resemble the following:
package org.example; import org.apache.camel.EndpointInject; import org.apache.camel.Produce; import org.apache.camel.ProducerTemplate; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.mock.MockEndpoint; import org.apache.camel.test.blueprint.CamelBlueprintTestSupport; import org.junit.Test; public class GreetingTest extends CamelBlueprintTestSupport { // Input message bodies to test with protected Object[] inputBodies = { "This is one bean example.", "This is another bean example." }; // Expected message bodies protected Object[] expectedBodies = { "Hello This is one bean example.", "Hello This is another bean example."}; // Templates to send to input endpoints @Produce(uri = "direct:beanTutorial") protected ProducerTemplate inputEndpoint; // Mock endpoints used to consume messages from the output // endpoints and then perform assertions @EndpointInject(uri = "mock:output") protected MockEndpoint outputEndpoint; @Test public void testCamelRoute() throws Exception { // Create routes from the output endpoints to our mock // endpoints so we can assert expectations context.addRoutes(new RouteBuilder() { @Override public void configure() throws Exception { from("direct:beanTutorialOut").to(outputEndpoint); } }); // Define some expectations outputEndpoint.expectedBodiesReceivedInAnyOrder(expectedBodies); // Send some messages to input endpoints for (Object inputBody : inputBodies) { inputEndpoint.sendBody(inputBody); } // Validate our expectations assertMockEndpointsSatisfied(); } @Override protected String getBlueprintDescriptor() { return "OSGI-INF/blueprint/blueprint.xml"; } }
With these changes in place, in the Project Explorer view, right-click the
GreetingTest class and select Run As -> JUnit Test. Your test should pass.
The next route editor bean tutorial article in this series will show how to:
- Update the route to be more specific about which bean method to call.
- Customize the greeting by passing a constructor argument.
- Update the test according to the route and bean updates.
Click here to for an overview of Red Hat JBoss Fuse a lightweight and modular integration platform.. | https://developers.redhat.com/blog/2017/08/23/getting-started-with-global-beans-in-fuse-tooling-10-0-0/ | CC-MAIN-2018-13 | refinedweb | 1,056 | 51.34 |
Hi Buddy ,
i failed to call function of DLL which is developed in C++
the function of DLL in C++ as below
#include "stdafx.h"
int add(int a, int b)
{
return a + b;
}
my script at testcomplete is as below
sub test
dim a
set Def_Dll=DLL.DefineDLL("test_dll")
Call Def_DLL.DefineProc("addA",vt_i4,vt_i4,vt_i4)
Call Def_DLL.DefineAlias("add", "addA")
set Lib=Dll.Load("C:\Users\H208139\Desktop\test_dll\Debug\test_dll.dll","test_dll")
a=Lib.add(1,2)
log.Message(a)
end sub
test result
bject doesn't support this property or method: 'Lib.add'
I'm not 100% certain.... but you are defining the procedure/method and giving it an Alias of addA. The DefineProc should be using the method name as it is called in the DLL.... So, with that, shouldn't your code be...
sub test dim a set Def_Dll=DLL.DefineDLL("test_dll") Call Def_DLL.DefineProc("add",vt_i4,vt_i4,vt_i4) Call Def_DLL.DefineAlias("addA", "add") set Lib=Dll.Load("C:\Users\H208139\Desktop\test_dll\Debug\test_dll.dll","test_dll") a=Lib.addA(1,2) log.Message(a) end sub
Hi,
Check that your DLL meets requirements from....
Especially those:
-- Only standalone exported routines can be called from TestComplete tests. There is no way to call methods of exported classes.
-- The DLL routine to be called must match the
stdcall calling convention.
Also check the bitness of TestComplete and DLL (...).
Have you tried suggestions given here? What exactly doesn't work when applying them?
yes , I tried suggestions given here, error message is still object doesn't support this property or method: 'Lib.add'
I don't see the
stdcall calling convention in your original dll as Alex mentioned:
@AlexKaras wrote:
The DLL routine to be called must match the
stdcallcalling convention.
At the same time, this is one of the requirements.
I'm not familiar with C++ very well - I suppose you should declare the add routine something like this:
int __stdcall add(int a, int b) { return a + b; }
If you modified the dll, it's worth posting the new one, as well as the updated code.
Hi TanyaGorbunova,
Thanks for your reply
I add the __stdcall at dll ,but the error message is the same : Object doesn't support this property or method: 'Lib.AddA'
My scripts in VBscript as below :
sub test
dim a
Set Def_Environment = DLL.DefineEnvironment(True)
Set Def_DLL = Def_Environment.DefineDLL("test_dll")
set Lib=Def_Environment.Load("C:\Users\H208139\Desktop\test_dll\Debug\test_dll.dll","test_dll")
Call Def_DLL.DefineProc("AddA",vt_int,vt_int,vt_int)
a=Lib.AddA(2,2)
log.Message(a)
end sub
And I attached the modified dll | https://community.smartbear.com/t5/TestComplete-General-Discussions/Call-function-of-DLL-at-testcomplete/td-p/176767 | CC-MAIN-2019-26 | refinedweb | 437 | 60.31 |
Hey guys,
So I wrote a really simple text adventure program that will call different functions that just contain scenarios for the player to either say yes or no to (y or n), and I'm having a few difficulties.
The main error I'm getting is in calling the event1 function in the main section of the program even though it is clearly defined in its own section.
Do I have to initialize it within the main section before I call it?
Here's my code, the error is in red:
Code:#include <iostream> #include <string> #include <Windows.h> // Goal for program: A user inputs a number from 1 to 5, and random events // aka messages will appear as a user further progresses in this // text based game // Super excited, even though this is probably going to be extremely simple looking // to the user, a bit lengthy on my side, but it still probably will just mimic // one of those Pick Your Adventure games // Theme: Fantasy-based text adventure // I'm also going to be utilizing functions instead of just including them in the main // and simply calling them for number that the user inputs from 1 to 5 // I'm going to label each of these functions as "events" aka a series of events // that happen that pertain to individual situations with yes or no events using namespace std; void userInput(int scrollnumber); // This will contain an array of 10 elements and we'll use the second function to // find the largest element in the array int main () { int scrollnumber; userInput(scrollnumber); if (scrollnumber = 1) { event1(); } system("PAUSE"); return 0; } void userInput(int scrollnumber) { cout << "Please enter which one of the five scrolls you wish to read to enter the game world: " << endl; cin >> scrollnumber; return scrollnumber; } event1(scrollnumber) { string answer; cout << "You sank to the ocean floor after your ship has wrecked during a terrible storm. You are slowly choking on water and are becoming unable to maintain composure. There is a treasure chest nearby, would you like to open it? (y or n)" << endl; cin >> answer; if (answer = "y") { cout << "You find water breathing potions inside the chest! You pop open the corks on each of them and drink. You swim to the top and become rescued by a nearby sailor." << endl; } if (answer = "n") { cout << "You die a slow agonizing death as you inhale water inside your lungs. Your body is found by a necromancer and you live once again as a member of his skeleton army." << endl; } else { cout << "Not a valid answer, please try again!" << endl; return event(); } return 0; } | http://forums.devshed.com/programming-42/random-events-text-adventure-errors-950538.html | CC-MAIN-2014-52 | refinedweb | 437 | 57.74 |
VDEVGONE(9) BSD Kernel Manual VDEVGONE(9)
vdevgone - revoke all specified minor numbered vnodes for a device
#include <sys/param.h> #include <sys/vnode.h> void vdevgone(int maj, int minl, int minh, enum vtype type);
The vdevgone() function will revoke all the vnodes corresponding to the specified minor number range for the device with a major number of maj and of type type. Its arguments are: maj The major number of the device. minl The lowest minor number for the device to be revoked. minh The highest minor number for the device to be revoked. type The type of the device; this must be one of: VBLK Device is a block device VCHR Device is a character device The endpoints specified by minl and minh are inclusive.
vfinddev(9), vnode(9)
This man page was originally written for OpenBSD. MirOS BSD #10-current February 18,. | https://www.mirbsd.org/htman/i386/man9/vdevgone.htm | CC-MAIN-2014-10 | refinedweb | 146 | 56.15 |
Pythonista for Python 3.x.
- D4t4Wr4ngl3r231
Are there any plans to release a Python 3.x variant of Pythonista?
Not in the near future. There is <a href="">Python 3.x for iOS</a> though (I'm not affiliated).
- D4t4Wr4ngl3r231
Sadly it is a poor second to Pythonista in terms of stability, usability, functionality, documentation, etc.
I gave up on it once I tried Pythonista ;-)
Noob to Python that I am. I assumed that 3.3 would be better to learn than 2.7. After asking around it appears that 2.7 is just what I need.
Edit: Fixed in Pythonista3 version 3.0 (300001) (currently in beta) which is Python 3.5.1.
I also echo the request to move on up to Python 3.3.1...
Also, how about Python 2.7.3 instead of the current 2.7.0.
import sys print(sys.version_info) # ==> sys.version_info(major=2, minor=7, micro=0, releaselevel='final', serial=0) print(sys.version) # ==> 2.7 (r27:82500, Feb 18 2013, 15:52:51) # ... [GCC 4.2.1 Compatible Apple LLVM 4.2 (clang-425.0.24)]
UPDATE: Pythonista v1.4 now brings the Python version up to Python v2.7.5 which is the same version of Python installed by default on machines running Mac OS X Mavericks.
I agree about 2.7.3, I'm a little behind with that, though I don't think there are a lot of tangible benefits to get from that upgrade. Switching to Python 3.x is a lot more problematic because it's not backward-compatible. If I were to switch the current app to 3.x, a lot of scripts would simply not work anymore. There are also third-party libraries (like PIL, which Pythonista includes) that aren't yet compatible with Python 3.
I would also like a move to Python 3, because that is what we are moving to as our introductory teaching language and it would be fantastic to be able to recommend Pythonista to students. At the moment 2.7 is adequate. I don't know how <a href=>Pillow</a> would fit in as a replacement for PIL..
Pythonista should eventually move over to Python 3. It has improved syntax, new features, and is the current standard. Python 2.7 will be phased out eventually. The only technical reason you mentioned, that lack of PIL on Python 3, is not much of a reason at all. PIL is essentially obsolete now. The Python community is largely moving to better maintained backwards compatible forks of PIL, such as Pillow, which has more features, fewer bugs, and is fully compatible with Python 3.
With that said, there is no urgency in moving Pythonista over to Python 3. I would welcome two separate versions of Pythonista for Python 2 and Python 3, but it isn't really necessary yet.
What I would really appreciate soon is a new version of Pythonista that includes Python 2.7.5 and is compatible with iOS 7. There are many bugs that significantly impair the usability of Pythonista on iOS 7, and roughly 3/4 of all iOS users are running iOS 7 now. If funding is an issue (though it doesn't seem to be), I and likely many other Pythonista users would be willing to help out. | https://forum.omz-software.com/topic/1907/pythonista-for-python-3-x | CC-MAIN-2020-50 | refinedweb | 555 | 77.74 |
02 August 2012 14:16 [Source: ICIS news]
LONDON (ICIS)--Investment bank Credit Suisse on Thursday raised its target share price for Arkema to €80 from €75 after the French specialty producer reported its second-quarter earnings.
Credit Suisse also maintained its “Outperform” rating for the company. The investment bank said Arkema was one of the strongest performers in its sector.
On Wednesday, Arkema reported it had swung to a second-quarter net loss of €12m ($15m), from a net profit of €184m in the same period last year, following the divestment of its vinyl business.
Its sales in the second quarter grew by 15.4% year on year to €1.72bn, while earnings before interest, tax, depreciation and amortisation (EBITDA) for the quarter slipped by 4.7% to €306m, because of tough comparables.
Arkema’s second-quarter results reflect market conditions in the acrylates sector, in which lower feedstock costs would have affected profits despite healthy volumes. The company produces 250,000 tonnes/year of acrylic acid from its site in ?xml:namespace>
Although sales in the acrylates sector were largely healthy, lower feedstock propylene costs in the second quarter pushed prices down. For Arkema, demand in the second quarter picked up from the first, and was largely steady, although down by approximately 4% compared with the second quarter of 2011, when offtake was particularly healthy.
However, orders continued to come in through the quarter, despite concerns regarding the wider economy and as the summer holiday period approached.
“[Acrylic acid] volumes were stable in this business despite poor conditions in the key coatings end market,” said Credit Suisse.
“Specialty acrylics, which has been a focus for bolt-on acquisitions, saw an 'excellent performance' due to niche positioning. We believe this supports above-average margins and returns through the cycle,” it added.
($1 = €0.82)
Additional reporting by Helena Strathe | http://www.icis.com/Articles/2012/08/02/9583443/credit-suisse-raises-its-target-share-price-for-frances.html | CC-MAIN-2014-10 | refinedweb | 310 | 53.81 |
An example of refactoring the monolith into microservices
One legit way of refactoring a 10+ year old application into a more agile one is to break it up into microservices. If you want to try out microservices architectures, probably refactoring a monolith is your only option, since the most important reasons for choosing this type of architecture are very rare on our everyday level: no high load, no need for high scalability, no large developer teams, no fast data.
You don’t want to rewrite it
The drive to rewrite everything from the ground up seems acceptable. Nobody wants to read old, obfuscated spagetthi code. It seems easier to rewrite it then to understand and refactor it module-by-module, line-by-line.
No specification since it is already written
These kind of projects usually don’t have any specification, because the client tells you that everything that she needs can be found in the working legacy application. Go there they say and try it.
Well, of course you can, but a 10 or more years old codebase has a lot of hidden and not actively used and rarely accessed features. Think about a special margin setting that is hardcoded somewhere in the source code and just works for years. Nobody remembers it.
Until one day you deliver the rewritten printing functionality and the client tells you that you forgotten to apply that special margin in some special case. So where can you go for proper and accurate specification for this?
Only to the legacy spaghetti code that no one wants to read.
And a 10 year old application is fully packed of similar features. Hardcoded into view files, that noone knows, global variables (I point to you, PHP) and saved database procedures. That don’t event written anywhere.
So you never will finish the rewrite. It’s a vicious cycle.
No deliverables for years
This is much more problematic. Since you never finish the rewrite, all you have a staging environment with a growing, never used application. Maybe the client accepts the features with pointing out some missing cases and other features (see below), but no one uses the code. That means no real life testing.
The project starts to be the “let’s remove one-two developers from this, they have years/months to finish” project of your company, peoples come and go, nobody knows exactly what she does and for whom. Sometimes when the management realizes that nothing really happens on this project, they force the team to produce some dirty coded features fast to show something to the client.
You can refactor it later — they say.
The missing deliverables has a worse effect: new features must be implemented in both systems. The client pays almost 100 percent more for the feature.
Very angry client
After one year of variably intensive development the client will be very angry. No replacement of the originial software, double priced new features, slow pace. She just put her money into something that never pays back.
Shit legacy code at the end
And finally, at the finish of the project the code will be as spagetthi as the original was. Because of fast written last minute features, frequently replaced developers and broken window effect. At the end the management only quality requirement is “who cares, just finish this shit somehow”.
So no rewrite. Only refactor left
Oh my God, if you can’t rewrite the only option left is refactoring the legacy code? Extract methods? Write stragety pattern instead of switch/cases?
But who wants to extract methods from a 10 year old let’s say PHP code?
Nobody. Really. And if you try, you will definitely fail, because the old code won’t support new language features, so you should work in old, unsupported language versions probably on an unsupported os. For example, adding namespace and autoload support to an old PHP application took me weeks. If there’s no front controller pattern, so every request is routed via apache rewrite rules to flat php files, you have to add a
include('vendor/autoload.php') into every single fucking file. Then test them. All of them.
Then what?
This is the point where mentioning microservices starts to seem reasonable. You take an old application, say PHP, moves it into a docker container, extracts every hardcoded configuration and services from it and you are ready to go.
Because in one month and with the help of a very good devops engineer, you will have a running legacy application. You can deliver this container to the client by replacing the current application with the dockerized one. Instant gains:
- A dockerized legacy app, that can be launched in any environments in minutes. this helps people start working on the project
- if the user management is well written, the legacy can be used as a so called API-Gateway, that manages sessions, users, roles and can be complemented with a json web token to enable microservices authenticate the requests and route them into the appropriate microservice.
- if the user management is badly written, you still have the whole working application in a container. This app can do everything that the legacy did, because it is the same in terms of source code. It always will be there to enable an existing feature with an added API endpoint.
When this huge legacy monolith service is delivered in a modern agile cloud ready (architecturally decoupled) infrastructure, you are ready to extract features from it into dedicated microservices.
It exactly works like the monolith refactoring but instead of moving features into modules, classes etc, you move them into separate services. Take for example the case of a flash application that should be replaced with a new one page app written in React, Angular, or Vue. This separate application can be written, pipelined and operated independently of the architecture or the legacy app as a docker container.
In an architecural standpoint this app once lived id the legacy codebase’s public directory as an .swf file. Now it is a separate application that runs on the same domain or a subdomain. The flash application used xml-s to communicate with the legacy application, so you have two ways to refactor this communication:
- force the new app to speak xml with the old application. But it’s not a long term maintainable idea since sooner or later you definitely move out the accompanied features from the legacy into a dedicated app
- implement an intermediate service (ACL, of anti-corruption layer) that accepts a well formed JSON from the new application and turns into that xml that the legacy speaks. This service is a so called Anti-Corruption Layer.
- …and later move all the needed functions out of the legacy into a new service that speaks the json version, so the frontend app can speak directly to it.
You can imagine how can you extract other functions, for example orders from a webshop almost the same way. This is how an important study on NGINX frames this process of extraction in a very helpful diagram:
If orders is module Z, then the process is:
- write automated functional of acceptance tests on the current monolith codebase (to check later that you don’t break anything)
- isolate orders module in the legacy monolith (it’s the hardest part if it is a spagetthi)
- create interfaces for both incoming and outgoing calls.
- rewrite the module in a separate microservice application
- use some kind of inter process communication for implementing communication between the legacy and the extracted module. This can range from simple HTTPS communication to messaging (in some cases event sourcing) depending on the rate of message exchange etc. But in a simple legacy HTTPS will be more then enough.
This process now can be turned into a steady workflow with frequent deployments using agile methodologies. This means that an architect can plan the next exraction(s) while the developers are working on one, so there’s no need to find out everything in advance. Because (in the case of a legacy application) that is simply impossible.
As Robert C. Martin, alias Uncle Bob says in his new book, The Clean Architecture:
The goal of the architect is to create a shape for the system that recognizes policy as the most essential element of the system while making the details irrelevant to that policy. This allows decisions about those details to be delayed and deferred .
So this way the monolith can be broken up into smaller microservices. These microservices shouldn’t be too small, because too small services need a lot of communication, and these small request-response cycles add up into a large timeout at the end, probably on the frontend. And too large means a new monolith so try to avoid it too.
These microservices can be delivered continuously from feature to feature. Happy client, happy pm, happy developers. | https://medium.com/@balint_sera/an-example-of-refactoring-the-monolith-into-microservices-8eebf092243c | CC-MAIN-2019-39 | refinedweb | 1,487 | 60.95 |
To understand this example, you should have the knowledge of following C++ programming topics:
All years which are perfectly divisible by 4 are leap years except for century years (years ending with 00) which is leap year only it is perfectly divisible by 400.
For example: 2012, 2004, 1968 etc are leap year but, 1971, 2006 etc are not leap year. Similarly, 1200, 1600, 2000, 2400 are leap years but, 1700, 1800, 1900 etc are not.
In this program below, user is asked to enter a year and this program checks whether the year entered by user is leap year or not.
#include <iostream> using namespace std; int main() { int year; cout << "Enter a year: "; cin >> year; if (year % 4 == 0) { if (year % 100 == 0) { if (year % 400 == 0) cout << year << " is a leap year."; else cout << year << " is not a leap year."; } else cout << year << " is a leap year."; } else cout << year << " is not a leap year."; return 0; }
Output
Enter a year: 2014 2014 is not a leap year. | https://cdn.programiz.com/cpp-programming/examples/leap-year | CC-MAIN-2019-47 | refinedweb | 171 | 77.57 |
Reinauer2,097 Points
Compiler says "override" doesn't work with Equals method...
The compiler accepted an overridden Equals method in the video though, so I'm confused. When I take "override" out, it tells me "not all code paths return a value".
using System; namespace Treehouse.CodeChallenges { public class VocabularyWord { public string Word { get; private set; } public VocabularyWord(string word) { Word = word; } public override string ToString() { return Word; } public override bool Equals(VocabularyWord x, VocabularyWord y) { if(x == y) { return true; } } } }
1 Answer
Steven Parker217,443 Points
The error is unrelated to the override.
Whether it reports it or not, the issue is the same with or without override. Examine your method and you'll notice that the only return statement is within an if conditional block. If the conditional turns out to be false, the method would end without executing any return and thus be unable to satisfy the requirement of returning an item of type bool.
You could fix this by putting another return (presumably with the argument "false") after the conditional block.
But in this case there's an even easier fix, just replace the entire method body with this:
return x == y;
Then, without any conditionals, it will return either true or false based on the comparison. | https://teamtreehouse.com/community/compiler-says-override-doesnt-work-with-equals-method | CC-MAIN-2022-40 | refinedweb | 211 | 59.53 |
Are you sure?
This action might not be possible to undo. Are you sure you want to continue?
A Tutorial Introduction
James Lu Jerud J. Mead
Computer Science Department Bucknell University Lewisburg, PA 17387
1
Contents
1 Introduction 2 Easing into Prolog 2.1 Logic Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2.2 The SWI-Prolog Environment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 A Closer Look at Prolog 3.1 Facts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3.2 Rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3.3 Computation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 Lists in Prolog 1 2 2 3 6 6 6 7 12
5 Data Input in Prolog 17 5.1 Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 5.2 Building a Tokenizer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 6 Parsing 6.1 Low-level Parsing with Prolog . 6.2 High-level Parsing with Prolog 6.3 Parsing Expressions . . . . . . 6.4 Parsing Optional Structures . . 7 Building a Symbol Table 8 Prolog Semantics - The Computational 8.1 Unification . . . . . . . . . . . . . . . 8.2 Resolution . . . . . . . . . . . . . . . . 8.3 Queries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22 22 22 24 25 27 Model 32 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
i
1
Introduction
Logic programming is a programming paradigm based on mathematical logic. In this paradigm the programmer specifies relationships among data values (this constitutes a logic program) and then poses queries to the execution environment (usually an interactive interpreter) in order to see whether certain relationships hold. Putting this in another way, a logic program, through explicit facts and rules, defines a base of knowledge from which implicit knowledge can be extracted. This style of programming is popular for data base interfaces, expert systems, and mathematical theorem provers. In this tutorial you will be introduced to Prolog, the primary logic programming language, through the interactive SWI-Prolog system (interpreter). You will notice that Prolog has some similarities to a functional programming language such as Hugs. A functional program consists of a sequence of function definitions — a logic program consists of a sequence of relation definitions. Both rely heavily on recursive definitions. The big difference is in the underlying execution “engine” — i.e., the imperative parts of the languages. The execution engine of a functional language evaluates an expression by converting it to an acyclic graph and then reducing the graph to a normal form which represents the computed value. The Prolog execution environment, on the other hand, doesn’t so much “compute” an answer, it “deduces” an answer from the relation definitions at hand. Rather than being given an expression to evaluate, the Prolog environment is given an expression which it interprets as a question: For what parameter values does the expression evaluate to true? You will see that Prolog is quite different from other programming languages you have studied. First, Prolog has no types. In fact, the basic logic programming environment has no literal values as such. Identifiers starting with lower-case letters denote data values (almost like values in an enumerated type) while all other identifiers denote variables. Though the basic elements of Prolog are typeless, most implementations have been enhanced to include character and integer values and operations. Also, Prolog has mechanisms built in for describing tuples and lists. You will find some similarity between these structures and those provided in Hugs.
CSCI 208
1
Prolog Tutorial
2
Easing into Prolog
In this section you will be introduced to the basic features of the logic programming language Prolog. You will see how to define a knowledge base in terms of facts (unconditionally true) and rules (truth is conditional), how to load the knowledge base into the SWI-Prolog system, and how to query the system.
2.1
Logic Programming
Remember that all programming languages have both declarative (definitional) and imperative (computational) components. Prolog is referred to as a declarative language because all program statements are definitional. In particular, a Prolog program consists of facts and rules which serve to define relations (in the mathematical sense) on sets of values. The imperative component of Prolog is its execution engine based on unification and resolution, a mechanism for recursively extracting sets of data values implicit in the facts and rules of a program. In this section you will be briefly introduced to each of these terms. Facts and Rules Everything in Prolog is defined in terms of two constructs: the fact and the rule. A fact is a Prolog statement consisting simply of an identifier followed by an n-tuple of constants. The identifier is interpreted as the name of a (mathematical) relation and the fact states that the specified n-tuple is in the relation. In Prolog a relation identifier is referred to as a predicate; when a tuple of values is in a relation we say the tuple satisfies the predicate. As a simple example, consider the following Prolog program which defines a directed graph on five nodes – this first example involves only facts. Example 1 – A Directed Graph I edge(a,b). edge(a,e). edge(b,d). edge(b,c). edge(c,a). edge(e,b). This program contains six facts: edge(a,b), edge(a,e), . . ., edge(e,b). Intuitively, these six facts describe the directed graph which has edges from node a to b, a to e, b to d, and so on. The identifier edge is a predicate and the six facts define the edge relation on the graph; the identifiers a, b, c, d, e are abstract constant values representing names for the graph nodes. The constant values are similar to what you might define in an enumerated type in Pascal or C). A fact states that a certain tuple of values satisfies a predicate unconditionally. A rule, on the other hand, is a Prolog statement which gives conditions under which tuples satisfy a predicate. In a sense, a fact is just a special case of a rule, where the condition is always satisfied (i.e., equivalent to “true”). A graph is very interesting, but not of much use if there is no way to specify more complex properties other than edge. The following example illustrates a rule which defines the property of “path of length two” between two edges. Example 2 – A Directed Graph II edge(a,b). edge(a,e). edge(b,d). edge(b,c). edge(c,a). edge(e,b).
CSCI 208
2
Prolog Tutorial
tedge(Node1,Node2) :edge(Node1,SomeNode), edge(SomeNode,Node2). The last three lines of this program constitute a rule which defines a new predicate tedge. The left side of the rule looks just like a fact, except that the parameters of the fact are capitalized indicating they are variables rather than constants. The right side of the rule consists of two terms separated by a comma which is read as “AND”. The way to read this rule is as follows. The pair (Node1,Node2) satisfies the predicate tedge if there is a node SomeNode such that the pairs (Node1,SomeNode) and (SomeNode,Node2) both satisfy the predicate edge. But these examples are not very convincing since we don’t know how a Prolog system would process the facts and rules. In the next section we will investigate a Prolog system and see how we make use of the program above to determine properties of the graph described in the facts.
2.2
The SWI-Prolog Environment
The version of Prolog that we will use is called SWI-Prolog, developed at the Swedish Institute of Computer Science. The SWI-Prolog environment is an interactive system, much like the Hugs functional programming environment. It can be executed in two different forms: from the command line or via an Emacs interface. In either case, before moving ahead you should add the following line to the alias section of your .cshrc file (or whatever your shell’s startup file is called): alias prolog ’/usr/local/bin/prolog -f none’ Don’t forget to activate this alias by entering the shell command source ~/.cshrc Emacs — skip if you don’t use emacs A GNU Emacs mode for SWIprolog is available. If you will not be using Prolog from the emacs editor you can skip to the next section. First, you must add the following lines (as is) to your .emacs file in your home directory. Put these lines in the section labeled “Hooks”. (setq auto-mode-alist (append (list (cons "\\.pl$" ’prolog-mode)) auto-mode-alist)) (autoload ’prolog-mode "~/emacs/prolog.el" "" t) When you have added these lines and load a file whose name ends in ‘.pl’, emacs will automatically go into Prolog mode. To use the emacs mode you create your program, giving it a name with a .pl extension. Once you have created your program, you may invoke the interpreter by the emacs command Control-c Shift-c This will activate Prolog and at the same time load your program into the interpreter. When loading finishes, you may begin querying your program. Remember, every rule in Prolog, as well as each query, ends with a period. The Emacs mode provides the following commands: CSCI 208 3 Prolog Tutorial
M-x run-prolog
Run an inferior Prolog process, input and output via buffer *prolog*. prolog-compile-buffer prolog-compile-region prolog-compile-predicate prolog-consult-buffer prolog-consult-region prolog-consult-predicate
C-c C-c C-c C-c C-c C-c
K k C-k C c C-c
Using the interpreter To start the Prolog interpreter from the command line you enter the command prolog. After a bit of initialization you will see appear the SWI-Prolog prompt: | ?Exiting the system is easy. Just enter ‘halt.’ at the prompt (not the single quote marks!). Do this now and then restart Prolog. Before you can test out the capabilities of the system you must have a Prolog program to work with. Use your text editor to enter the program in Example 2.1. Be sure to give it a name with the a .pl extension — let’s assume you name it ‘first.pl’. To load a file into the interpreter you enter the following, being sure not to forget the final ‘.’. | ?- [’first’]. Notice that the .pl extension is left off — and don’t forget the single quotes, square brackets, and the period! The SWI-Prolog interpreter is similar to the Hugs interpreter in that a program contains a series of definitions (read from a file). The Hugs interpreter allows the user to compute an expression based on the (function) definitions in the program. In the same way, the SWI-Prolog interpreter reads a program and then allows the user to compute a query based on the definitions (facts and rules). A query “asks” the system if there are any data values which satisfy a particular predicate (or combination). Let’s give this a try. 1. At the SWI-Prolog prompt enter the following: ?- edge(a,b). When you hit return the system should respond ‘Yes’ and put up another prompt. Try another which should succeed. What you are entering are queries. The first asks the system if the tuple (a,b) satisfies the predicate edge, and, of course, it does. Try a couple which should fail. What happens if you use a node name which does not occur in one of the facts? You might expect an error, but it just says ‘No’! 2. You can enter compound queries. How does the system respond to these queries? ?- edge(a,b), edge(a,e). ?- edge(a,b), edge(a,c). What is your conclusion about the meaning of the ‘,’ separating the two parts? 3. Now to try out the rule. The predicate tedge defines the notion of “path of length two” between two nodes. Come up with two queries based on tedge which should succeed and two which should fail. 4. Now for one final demonstration of the power of the Prolog system. When an identifier is used in a program and it starts with a lower-case letter, that identifier denotes a constant value. Identifiers which start with an upper-case letter denote variables. Variables are used in queries to get the system to find all values which can be substituted so to make the resulting predicate true. Try the following query. CSCI 208 4 Prolog Tutorial
?- edge(a,X). When you press return the system should respond with a value for X. If you press the semi-colon (no return!) you are asking if there are anymore values which can satisfy the query. If there are more another will be written; if there are no more, then ‘No’ will be written. If you press return rather than the semi-colon, then no more answers will be sought. This ability of Prolog to find all possible answers is a powerful computational tool. Now to really put the idea to the test try the following query and see how many solutions you get. ?- edge(X,Y). 5. Prolog contains some built in relations. For example, the relations ‘<,<=,==,>=,> may be used for testing the usual arithmetic relationships on numbers. The query ‘1 < 3’ succeeds while ‘3 < 3’ fails. Try a few of these. Problem 1 Following the example above, write a Prolog program which describes a directed graph with the following structure. Also include in the program a predicate which defines the ‘path of length 3’ relation. Define it in two ways: first only referencing the edge predicate, and then making use of the tedge predicate. Implement and test.
a
g
b
f
c
e
d
CSCI 208
5
Prolog Tutorial
3
A Closer Look at Prolog
In the previous section you worked with Prolog in the context of a simple example and learned about the basic components of Prolog: facts, rules, and the interpreter. In this section you will take a closer look at these same components.
3.1
Facts
There’s not a lot more to be said about facts. It is important to realize, however, that if a predicate appears in a sequence of facts, that doesn’t mean that it cannot be the head of a (non-fact) rule as well. For example, we can take the predicates edge and tedge from Example 2.1 and define a new, more complex graph. edge(a,b). edge(a,e). edge(b,d). edge(b,c). edge(c,a). edge(e,b). edge(X,Y) :- tedge(X,Y). tedge(Node1,Node2) :edge(Node1,SomeNode), edge(SomeNode,Node2). Add this new rule to your program and see what effect it has on the results of queries such as ?- edge(a,c). ?- edge(a,b). ?- edge(e,c). Notice that each of these queries will respond ’yes’. We will avoid queries which we know should respond ’no’ for a bit because they can behave in odd ways.
3.2
Rules
The real power of any programming language is in its abstraction mechanism. In Prolog the rule provides the mechanism for abstraction. Where a fact can only specify that a tuple of values satisfies a predicate, a rule can specify under what conditions a tuple of values satisfies a predicate. The basic building block of a rule is called an atom: a predicate followed by a tuple of terms, where both constants and variables are terms (we will see that a term can actually have more structure). We see immediately that every fact is an atom. When the tuple satisfies the predicate of the atom we say the atom is true. Every rule is divided into two parts by the symbol ‘:-’: the left-hand side is called the head of the rule while the right-hand side is the body of the rule. In general, we read the rule Atom :- Atom1, ..., Atomn as if each of Atom1,...,Atomn is true, then Atom is also true. We see this structure in the rule defining tedge. tedge(Node1, Node2) :- edge(Node1, SomeNode), edge(SomeNode, Node2). There are three atoms in this rule, with tedge(Node1, Node2) being the head of the rule and the body of the rule consisting of the atoms edge(Node1, SomeNode) and edge(SomeNode, Node2).
CSCI 208
6
Prolog Tutorial
recursive rules Not surprisingly it is recursion which gives rules their real power. Let’s look at a more interesting extension to the directed graph program. Suppose we aren’t satisfied with a predicate which distinguishes pairs of nodes linked by paths of length two. Suppose we want a general predicate which is satisfied by a pair of nodes just in case they are linked by a path in the graph – a path of any (positive) length. Thinking recursively, we can see that there is a path from one node to another if there is an edge between them (a base case), or if there is an edge to an intermediate node from which there is a path to the final node. The following two rules define the path relation for our program. path(Node1,Node2) :edge(Node1,Node2). path(Node1,Node2) :edge(Node1,SomeNode), path(SomeNode,Node2). There are two important characteristics in this example. First, the use of two rules (with the same head) to define a predicate reflects the use of the logical “OR” in a Prolog program. We would read these two rules as: path(Node1,Node2) is true if edge(Node1,Node2) is true or if there is a node SomeNode for which both edge(Node1,SomeNode) and path(SomeNode,Node2) are true. Second, the predicate used in the head of the second rule also appears in the body of that rule. The two rules together show how a recursive definition can be implemented in Prolog. Problem 2 1. Add the predicate path to the program you wrote for Problem 1 in Section 2.2. Test it out to see that it works as expected. Test on nodes which are connected by paths! [You can also test it on non-connected pairs, but beware of odd behavior.] 2. Modify the definition of path so that paths of length zero are allowed. [FACT!]
3.3
Computation
The previous sections have illustrated how Prolog’s declarative statements (facts and rules) can be used to write a program which defines a base of knowledge, in this case, knowledge about a particular directed graph. But a program is of little use if we cannot extract or deduce useful implicit knowledge from it. In the above example, for instance, we might want to deduce all the nodes which can be reached by a path of length less than four starting from node d. The imperative or computational component of Prolog makes such a deduction possible. For the sections which follow we will make use of the program discussed above (complete with path predicate). For convenience it is presented here with line numbers added. Example 3 – A Directed Graph III 1 2 3 4 5 6 7 edge(a,b). edge(a,e). edge(b,d). edge(b,c). edge(c,a). edge(e,b). tedge(Node1,Node2) :edge(Node1,SomeNode), 7 Prolog Tutorial
CSCI 208
edge(SomeNode,Node2). 8 9 path(Node1,Node2) :edge(Node1,Node2). path(Node1,Node2) :edge(Node1,SomeNode), path(SomeNode,Node2).
Ground Queries Computation in Prolog is facilitated by the query, simply a conjunction of atoms. A query represents a question to a Prolog program: is the query true in the context of the program? As an example, consider the following query. edge(a,b) This query is called a ground query because it consists only of value identifiers as parameters to the predicate. When a ground query is posed we expect a yes/no answer. How is the answer determined? In response to the query the Prolog system scans the program looking for a rule or fact which “matches” the query. if we look at the program above we see that the query matches identically the fact on line 1, so the query must be true in the context of the program. That was easy, but how about this query? path(a,b) It is also a ground query, but when we scan the program we don’t find a rule which exactly matches it. The crucial issue here is what we should mean by “match”. When we scan the program we only have two rules, 8 and 9, with the predicate path in the head. Of course, we know that a rule is supposed to mean that the head is true if the body is true. So, if path(a,b) is to be true it will have to be true based on those rules defining path — i.e., those rules with path as the head. But the heads of each of these rules contain variables, not data constants. Not surprisingly, Prolog finds a match when constant and variable identifiers coincide. In this case we see that if variables Node1 and Node2 are replaced by a and b, respectively, then the body of rule 8 is true (edge(a,b) is a fact!). Then the head of the rule with the same substitution must be true. Prolog should conclude that the query is true. To summarize: when Prolog tries to deduce a query it begins by searching for rules with heads which match the predicate of the query. This search is always done from top to bottom, so order of definition does matter. A match is found if the parameters to the query are identical to those of the head of a rule or if the corresponding parameter in the rule head is a variable. But a query needn’t be a single atom; the definition clearly states a query is a conjunction of atoms. But simple logical properties indicate that a conjunction of atoms is true just in case every atom in the conjunction is true. So to determine whether a query is true, the Prolog system must determine whether each atom in the query is true. non-Ground Queries The ground queries mentioned in the previous section are very easy to verify from the program. But queries can also have variables as parameters; such queries are called non-ground queries. Consider the following non-ground query. tedge(a,X) The atom in this query contains as arguments one variable and one constant. Is the query true? Well, its not clear that the question even makes sense. Certainly, if we replace X by the constant d then the query is true. This is the notion of satisfiability. We say that the query is satisfiable relative to the program because there is a substitution for its variable which makes the query true. CSCI 208 8 Prolog Tutorial
Reasoning out this query takes a bit of work; follow closely (write the sequence down yourself!). When we scan the program we find one rule, rule 7, which defines tedge: we focus on this rule. The query almost looks like the head of the rule. We write down the substitution Node1 = a, X = Node2 and ask whether tedge(a,Node2) is true. Of course, the meaning of the rule says that this atom should be true if the body (with the same substitutions made) is also true. So the truth of our original query can be replaced by the truth of a new query. edge(a,SomeNode), edge(SomeNode,Node2) We need to assess the truth of the two atoms in our new query. Let’s first consider edge(a,SomeNode). As we scan the program we see that there are two possible facts which fit; we’ll take the first one, edge(a,b). If we take the substitution SomeNode = b and make the replacement in our query, then the first atom of the query is satisfied. Now for the second atom. After the last substitution that atom has been changed to edge(b,Node2). By a similar process we see that if we take the substitution Node2 = d and apply it to the query, then the query is satisfied. The whole query has now been resolved. If we look at our original query, we want to know what value for X will satisfy tedge(a,X)? By following the series of substitutions, X = Node2, Node2 = d, we find that the substitution X = d satisfies the original query. Unification/Resolution We can identify two distinct activities in this process. Unification refers to the process of taking two atoms (one from the query and the other being a fact or the head of a rule) and determining if there is a substitution which makes them the same. We will look at the underlying algorithm for unification later. The second activity is resolution. When an atom from the query has been unified with the head of a rule (or a fact), resolution replaces the atom with the body of the rule (or nothing, if a fact) and then applies the substitution to the new query. We can make unification and resolution more explicit by processing the original query again. 1. Unify tedge(a,X) and tedge(Node1,Node2), giving the substitution Node1 = a, X = Node2. Resolution: replace tedge(a,X) with edge(Node1,SomeNode),edge(SomeNode,Node2) and apply the substitution above to get the new query: edge(a,SomeNode),edge(SomeNode,Node2) 2. Select the atom edge(a,SomeNode). Unify edge(a,SomeNode) with edge(a,b), giving the substitution SomeNode = b. CSCI 208 9 Prolog Tutorial
Resolution: replace edge(a,SomeNode) by nothing (since we unified with a fact) and apply the substitution above to get the new query: edge(b,Node2) 3. There is only one atom in the query. Unify edge(b,Node2) and edge(b,d), giving the substitution Node2 = d. Resolution: replace edge(b,Node2) by nothing (since we unified with a fact). Since the resulting query is empty, we are done. At this point the substitution can be determined. At this point it is a good idea to pause to observe what has happened with the parameters of the atoms involved in the computation. In our original query we had one constant and one variable. If you consider carefully, you may see that the constant parameter has been passed to each successive atom as a value, while the variable X has been passed a reference. Notice that at no point has there been anything like a traditional computation – just the unification to match up arguments (pass parameters?) and the resolution to reform the query. Backtracking We are actually not finished with the example. You may have noticed that there is another solution: we could redo the computation above and get the substitution X = b or X = c or X = d. The way Prolog does this is, when a query is finally reduced to the empty query, Prolog backtracks to the most recent unification to determine whether there is another fact or rule with which unification can succeed. If there is, an additional solution may be found. Backtracking continues until all possible answers are determined. Problem 3 1. Consider the problem of backtracking in response to the query ‘?- tedge(a,X)’. Assume the graph of Example 3.3. Write out the steps of the unification/resolution above and clearly mark any place where more than one rule or fact must be checked for unification (remember that each one may lead to another solution). Then continue the unification/resolution process via backtracking to determine all possible answers to the query. 2. (Extra Credit!) Your family tree — Probably the most common first example of a logic program is that involving a family tree. Create a set of facts that define for your immediate family the relations: male = { The males in your family. } female = { The females in your family. } parent_of = { The pairs (x,y) where x is the parent of y in your family. } [Don’t go overboard if you have a large family — you don’t want to be typing data till next week!] Note that the predicates male and female are unary, involving only one argument. You need one entry for each person in your family. Next define the following predicates based on the previous three predicates. father, mother, son, daughter, grandfather, aunt, uncle, cousin, ancestor
CSCI 208
10
Prolog Tutorial
Notice that the first of these predicates must be defined in terms of facts, but that the later ones can be defined in terms of the earlier predicates. So if I did this problem I might start with the following and work from there (in the obvious ways). male(jerry). male(stuart). male(warren). female(kathe). female(maryalice). brother(jerry,stuart). brother(jerry,kathe). sister(kather,jerry). parent_of(warren,jerry). parent_of(maryalice,jerry).
CSCI 208
11
Prolog Tutorial
4
Lists in Prolog
Lists in Prolog are represented by square brackets. Similar to Hugs, Prolog also allows for aggregate values of type lists. For example, when calling a predicate, we may pass a list containing elements a,b,c by typing [a,b,c]. The empty list is represented by []. To define rules for manipulating lists, we need list constructors, as well as selectors for pulling apart lists. We saw these operations in Hugs in the form of the ‘:’ operator and the functions head and tail. Prolog combines all of these operations into one, with the help of unification (in a similar way to Hugs using pattern matching). To illustrate, we give below the Prolog program for appending lists. It contains two rules. append([],List,List). append([H|Tail],X,[H|NewTail]) :append(Tail,X,NewTail).
[Remember that we read these rules “left-hand-side is true if the right-hand-side is true.”] A call to append requires three arguments. The natural way to view the intended use of the arguments is that the first two arguments represent the two lists that we want to append, and the third argument returns the result of the append. For example, if we pose the following query to append, ?- append([a,b,c],[d,e],X). we would get back the answer X = [a,b,c,d,e]. To see how append actually works, an explanation of the vertical bar symbol | is needed. It acts both as the constructor and selector for lists. When we write [X|Y], this represents a list whose head is X, and whose tail (i.e. the rest of the list) is Y. Based on this interpretation, unification works exactly as you would expect: [X|Y] [X|Y] [X|Y] [X|Y] unifies with [a,b,c] with the unifier {X = a, Y = [b,c]}. unifies with [a,b,c,d] with the unifier {X = a, Y = [b,c,d]}. unifies with [a] with the unifier {X = a, Y = []}. does not unify with [].
Now recall from the previous section that a variable occurring in the head of a rule is treated universally, while a variable that occurs only in the body is handled existentially. Thus the first rule in the append definition append([],List,List). reads intuitively as: “The result of appending the empty list [] to any list List is just List.” Note this is the first example of a “bodiless” rule that we have seen. A call to this rule will succeed as long as the first argument unifies with [], and the last two arguments unify with one another. Query Unifier Prolog answer -----------------------------------------------------------------?- append([],[b,c,d],[b,c,d]). {List = [b,c,d]} yes ?- append([],[b,c,d],X). {List = [b,c,d], X = [b,c,d]} X = [b,c,d] ?- append(X,Y,Z). {X = [], Y = List, Z = List} X = [], Y = Z ?- append([],[b,c],[b,c,d]). None no The second call in the above table is normally the way we would use append, with the first two arguments instantiated, and the third a variable that will provide an answer. Now consider the second rule, which is the general case of appending a non-empty list to another list. append([H|Tail],List,[H|NewTail]) :append(Tail,List,NewTail).
CSCI 208
12
Prolog Tutorial
All the variables that occur in this rule are universal variables since each occurs in the head of the rule. If we call append with the query: ?- append([a,b,c],[d,e],Result). The atom in the query does not unify with the first rule of append since the list [a,b,c] and [] do not match. The query however, unifies with the head of the second rule of append. According to unification, the resulting unifier is: { H = a, Tail = [b,c], List = [d,e], Result = [a|NewTail] } This substitution is applied to the body of the rule, generating the new query: ?- append([b,c],[d,e],NewTail). Thus by unifying the first argument of the query with the first parameter [H|Tail] in the head of the rule, we “pull apart” the list into its head and tail. The tail of the list then becomes the first argument in the recursive call. This is an example of using | in a way similar to head and tail in Hugs. Let’s examine what happens if we carry the trace all the way through. First, at the Prolog prompt you should enter ‘trace.’, to start the trace facility. After starting tracing every query you enter (including the entries you think of as commands!) will be traced. Just enter <return> when the interpreter hesitates. Enter the specified query (line 1 below) and enter return. The following is an annotated version of (approximately) what should appear on the screen. 1 Call 2 Call 3 Call 4 Call 5 exit 6 exit 7 exit 8 exit append([a,b,c],[d,e],Result). append([b,c],[d,e],NewTail). append([c],[d,e],NewTail1). append([],[d,e],NewTail2). NewTail2 = [d,e] NewTail1 = [c,d,e] NewTail = [b,c,d,e] Result = [a,b,c,d,e] %% %% %% %% %% %% %% %% %% %% %% %% %% %% %% Initial call Result = [a|NewTail] First recursive call NewTail = [b|NewTail1] Second recursive call NewTail1 = [c|NewTail2] Third recursive call Unifying with base case of append. Back substitution of NewTail2 Back substitution of NewTail1 Back substitution of NewTail
In the comments appearing on the right, we indicate the important substitutions to remember. In the first step, as the result of unifying the original query with the head of the second rule of append, the variable Result is unified with [a|NewTail] where NewTail is a variable that has yet to have a value (i.e. uninstantiated). In the second step where the first recursive call takes place, NewTail unifies with [b|NewTail1]. Remember that each time a rule is used, the variables are considered to be new instances, unrelated to the variables in the previous call. This is the reason for the suffix 1 in the variable NewTail1, indicating that this is a different variable than NewTail. When computation reaches step 4, the first argument becomes the empty list []. This unifies with the first rule of append, and in the process the variable NewTail2 is unified with the list [d,e]. At this point, computation terminates and we “unwind” from the recursion. However, in the process of unwinding, we back substitute any variable that is instantiated in the recursion. That is how the final result of the append is constructed. Specifically, in unwinding from the recursive call in step 3, we back substitute the value of the variable NewTail2 inside [c|NewTail2]. The result is the list [c,d,e]. This list becomes the value stored in the variable NewTail1. Next to unwind from the recursive call in step 2, we back substitute the value of NewTail1 into [b|NewTail1]. Since from the previous step we just calculated NewTail1 to be the list [c,d,e], the current back substitution yields the list [b,c,d,e], which becomes the value stored for the variable NewTail. Finally, in the last unwind, the value of NewTail is back substituted inside [a|NewTail], CSCI 208 13 Prolog Tutorial
producing the list [a,b,c,d,e]. This is now the final answer for the variable Result. The back substitution process just described illustrates how | acts as a list constructor that puts together an element with a list. Example 4 – Generating a Chain If we return to Example 3.3, the finite state machine, we can put the list idea to work. We want to define a predicate chain which, when given two nodes will list the nodes in a path from the first node to the second. This list of nodes is referred to as a chain. First, by the nature of Prolog, what we want to do is define a predicate with three parameters chain(X,Y,Z) where the first will match the initial node, the second will match the final node, and the third will match a list consisting of the nodes in a chain. We can think of the first two parameters as input parameters and the third as an output parameter (though it need not be used in this way). The way to arrive at a definition of chain is to think of the conditions under which a chain will exist (taking advantage of recursion when necessary). Since a chain is just a list of nodes in a path, we should be able to make use of the definition of path, taking each element in a path and tacking it onto a list. The first thing that occurs is that if there is an edge from X to Y then there is a chain [X,Y]. This is easy to state in Prolog. chain(X,Y,[X,Y]) :- edge(X,Y). Remember, that we read this definition as “If there is an edge from X to Y then [X,Y] is a chain from X to Y.” Of course, it may be the case that there is a less direct route to Y. But if so, there is always a first step from X to, say, I and then a path from I to Y. Here’s the recursion. If there is a path from I to Y, then there is a chain for the path and we can tack X onto that path. Here is a representation of this in Prolog. chain(X,Y,[X|Z]) :- edge(X,I), path(I,Y), chain(I,Y,Z). If no path can be found to Y then we should have the empty list as the chain. Here is the complete definition of chain. Why is the last line in the form of a fact rather than a rule? chain(X,Y,[X,Y]) :- edge(X,Y). chain(X,Y,[X|Z]) :- edge(X,I), path(I,Y), chain(I,Y,Z). chain(X,Y,[]). There is a subtle point about this example. If you now try to generate chains from, say, a to d, you will find that no solution is generated - in fact the system is in an infinite loop trying to find a path to d. If you recall, Prolog always looks to unify a predicate by starting with its first definition and then pro ceding in order until one is found which unifies. What this means is, if you put the edge definitions which introduce loops into the graph at the end of the definition list for edge, then these definitions will be used last. To see the affect of this try some queries before changing the order and then try the same queries after changing the order.
Example 5 – Reversing a List As another example, the following rules define a Prolog program for reversing lists. It works by recursion and makes use of append. A call to reverse requires two arguments, the first is the input list, and the second is the result of reversing.
CSCI 208
14
Prolog Tutorial
reverse([],[]).
%%% Reversing an empty list is the empty %%% list. reverse([H|Tail],Result) :%%% To reverse a non-empty list, reverse(Tail,Tailreversed), %%% first reverse the tail, append(Tailreversed,[H],Result). %%% append the result to the %%% list [H].
Problem 4 1. Write a Prolog definition for a predicate mem which tests for membership in a list. [How many parameters should it have? How can recursion be used? There is already a predefined function called member which behaves the same way.] Before moving on, here is another application of lists. The use of finite state machines is very common in many sorts of computer applications. What we will look at here is how to simulate a finite state machine, regardless of the language it is to recognize. The simulation actually involves two components. First there must be a mechanism for describing the machine, i.e., its states and transitions. Second, we must define a predicate which simulates the action of the specified machine. Specifying a machine is a matter of defining three components: the state transitions, the start state, the final states. Defining the final states and the start state is easy (as will be illustrated). To define the transition we must indicate for each state and input character what is the next state. Here is an example description. start(s). final(f1). final(f2). delta(s,a,q1). delta(s,b,q2). delta(q1,b,s). delta(q1,a,f1). delta(q2,a,s). delta(q2,b,f2). Can you draw a diagram representing this finite state machine? Now for the simulator. This simulator, by the way, should work for any finite state machine defined in the way just described. What we want is to know what input strings this machine will accept (i.e., process the characters one-at-a-time starting in the start state and ending in a final state with no input characters remaining). The predicate accept is our goal. We want to give a list of characters to the predicate and have it tell us whether the string is accepted by the machine. The following definition is the easy solution. Try it out. Are the actions of accept affected by the order of the components of delta? Rearrange them to see. accept(S) :- start(S), accept(Q,S). accept(Q,[X|XS]) :- delta(Q,X,Q1), accept(Q1,XS). accept(F,[]) :- final(F). %%% %%% %%% %%% This looks strange!!!? Does this make sense that the number of parameters to accept changes?
This definition is pretty strange. But if we consider how Prolog works, by unifying a query with the head of a rule (or a fact), we see that if we enter the query | ?- accept([a,b,b,a]).
CSCI 208
15
Prolog Tutorial
that it can only match the first rule. The reference to accept in the body of that clause, however, will unify only with one of the second two rules. Interesting! This is a kind of overloading, it would appear. Problem 5 1. An interesting problem to consider is how one might define a Prolog program to check whether a given list is a palindrome. To be more exact, we would like to define palindrome so that it behaves in the following way. Query: Result: -----------------------------------------------palindrome([a,b,c]) no palindrome([]) yes palindrome([a,b,a]) yes palindrome([a,b,b,a]) yes There are various ways to implement this predicate, with one solution being exceptionally simple and intuitive. Hint: Think of a finite state machine which has two states – q0 and q1. • Define two palindrome predicates – one taking 1 parameter and the other taking three parameters palindrome(q,X,S) where the first is a state, and the other two are lists. The first is defined in terms of the second as follows. {palindrome(Xs) :- palindrome(q0,Xs,[]). • In state q0 remove things from the list X and add them to S. • In state q1 succeed when the heads of the two lists are the same – i.e., when palindrome(q1,[X|Xs],[X|S]) is true. Problem – how does the transition from q0 to q1 occur?
CSCI 208
16
Prolog Tutorial
5
Data Input in Prolog
As in any language, one of the most complex and detail-oriented aspects is the input and output of data. IO processing in Prolog is no less complex than what we saw in Hugs. We will look at just enough of the input facilities to allow us to read characters (unfiltered) from a file. If you are interested you can check out the other IO facilities in the SWI-Prolog manual.
5.1
Input
In order to see how file input is accomplished in the context of logic programming, lets start with the high level and see if we can figure out what is needed. First, we will find it convenient to access the characters in a file from a Prolog list. This means that we need a predicate which will take a file name (as an input parameter) and then unify a second parameter with the list of characters from the file. file(X,Y) :- ..... %% X is the file name %% Y is the list of file characters
If we have a file called ‘test.data’ we would expect the query ?- file(’test.data’,D). to cause D to be unified with the list of characters from the file and the characters in D to be printed. Of course, before we can pose the query we must complete the definition for the predicate file. How should we do this? If we just think intuitively, file(X,Y) should be true if we can open the file X and Y results from reading the data in X. Well, let’s write that out: file(X,Y) :- open(X,In), %% bind the internal name ’In’ to X readAll(In, Y). That looks OK — open will have to be some built-in predicate which will open the file named by X and unify In with an internal file descriptor. The idea is that having “opened” the file we then use the file descriptor when actually reading the data. What about readAll? We want this predicate to unify Y with the list of characters from the file referenced by In. The definition of open will follow momentarily, but first a quick look at readAll. The idea is to take characters from one list (i.e., the file) and put them on another list (to unify with Y above) only if the characters are OK. This is a recursive activity and can be seen to fall generally into the following pattern. readAll([C|Rest],[C|Answer]) :...., % conditions go here readAll(Rest,Answer). readAll([C|Rest],Answer) :...., % conditions go here readAll(Rest,Answer). %% if C is OK
%% if C is not OK
But in this problem the first argument to readAll is the file descriptor – that means it isn’t really a list and we can’t use this pattern-matching. Instead, we use another special “built-in” predicate ‘get0’ which (internally) matches the next character and moves a file pointer along to the next character (we never see that in our code). This reading of a character will have to be represented as part of the “condition”. Before tackling the definition of readAll, here are definitions you will need from the standard predicate collection which accompanies SWI-Prolog – these are automatically loaded when the system is started. [See the online SWI-Prolog manual – Section 3.13.2.] open/4: The predicate open takes four parameters (or at least that’s how we will use it!) and can be called as follows: open(X, read, In,[eof action(eof code)]
CSCI 208
17
Prolog Tutorial
where X is the file name, read is a constant which indicates how the file will be used, In is the internal designator for the file, and eof action(eof code) is a list of options (it could be longer!) which indicates that when the end-of-file is reached a value of -1 should be returned. get0/2: (That’s a zero, not an Oh!) This predicate takes two parameters: get0(In, C) where In is the internal file designator and C unifies with the next character in the file...next is important since there is some internal mechanism to keep things moving along the input stream. Each time get0 unifies the hidden file pointer is moved along. get0(In,C) doesn’t actually cause C to unify with the next character in the file, but the ASCII code of the next character. This means that our list will actually contain ASCII codes (i.e., integers) rather than characters (i.e., they will display as integer values rather than as characters). close/1: The close predicate takes a file designator and unifies by closing the referenced file. Problem 6 In this problem you will implement the predicate definition for readAll by making use of the built-in predicates just defined. Above we discussed the structure of the predicate file and indicated that it would make use of the open built-in predicate. That structure still works, but now you use the open/4 predicate just described. To get you started, you might try the following mini-problem. Rather than trying to get at all the characters in the file, just write readAll so that it gets the first character of the file. The following definitions should work. file(X,Y) :open(X,read,In,[eof_action(eof_code)]), readAll(In, Y). readAll(In,C) :- get0(In,C). There are things this doesn’t do, for example, check the validity of C or close the file. But if you put it into a file (name it ‘filein.pl’) you can try a query such as file(’filein.pl’,C). When this works, remember, you will get an ASCII code printed rather than a character. Before starting on the general problem there are two things you should consider. First, we want to make sure that the only character codes which end up in our list are those with legal (i.e., printable) values. A reasonable way to handle this is to introduce a predicate legal/1 and facts and rules which define which characters are “legal” (ascii value >= 32 and ascii value = 10, for example) . Second, when the end-of-file is reached remember that get0(C) will unify with the value -1. In this case no character will be put on the list. This should require two different clauses. (Be sure to remember to close the file when you reach the end-of-file!). Finally, rememeber that the way to think when defining the rules for a predicate is “the left side will be true is the right side is true” – i.e., what condition (on the right) will lead to the truth of the condition on the left? Now you can set about implementing the predicate readAll. When done you should be able to test by entering a query based on the file predicate, as indicated at the beginning of the section. [Hint: define two predicates – legal/1 as described above, and eof char/1 which is true for just one value - ‘-1’.] Remember that this file input program (the predicates file, readAll, eof char, legal) should be in a prolog file called filein.pl. Now when you want to use these predicates (most likely just file) you can include the following line as the first line of a program file. CSCI 208 18 Prolog Tutorial
:- consult(filein). This line is treated as a query which must be resolved before the rest of the program is read in.
5.2
Building a Tokenizer
One useful application of the file predicate you just developed is supplying characters from a file to a tokenizer. Remember that a tokenizer recognizes the lexical elements of a language and that these lexical elements can be described by a regular expression or regular grammar. In this section you will write a tokenizer for the FP language. We have two goals in mind. First, we need to implement a finite state machine which will accept the tokens of the FP language. This will be implemented (similar to the FP project tokenizer) by a predicate which will unify with the “next” token in the input stream – call it getToken. Second, we need a higher level predicate which will repeatedly (i.e. recursively) reference the finite state machine (i.e., getToken) to unify with the list of tokens – we will call this predicate getTokens. We will attack the tokenizer in two parts. First we will look at the case where the tokens have a fixed length, in this case having either one or two characters. Then we will look at how to get at the identifier and numeric literal tokens. One and Two-character Tokens Suppose we want to recognize a ‘+’ sign and return the token plus. First, since we are just handling one character it is not necessary to follow a transition in the state machine, just to determine and return the token and the part of the input list which remains. getToken(start,[43|Rest],Rest,plus). Remember that the input list consists of ASCII values, so the 43 above must be the ASCII code for ‘+’. [Prolog doesn’t see the ASCII integer code and the printable character as the same.] Notice that this clause will only unify for the start state and the ASCII code 43 at the head of the input list. If some other ASCII value is at the head of the list then another clause will have to unify. Another thing about the fact given above for getToken. If we look at the four parameters, the first two really behave as “input” parameters and the second as “output” parameters. Now, there is actually no input or output activity as we are used to in C ++ , but that is intuitively what is happening. So when a query with getToken is done, the arguments associated with the second two parameters will supply values which feed into the next predicate in the query. [N.B.: You can find the list of ascii codes (in decimal, octal, and hex!) by executing the UNIX command ‘man ascii’.] A fixed multi-character token (e.g. ‘==’) can be handled as follows: getToken(start,[63,63|Rest],Rest,plus). Revisiting the last two parameters. The final one, plus, is just the enumerated value for the token. The third is there so that we can use recursion on the rest of the list. In other words, when a getToken query is handled, the value bound to Rest will be the part of the input list which hasn’t been consumed yet. That will go in for the second parameter in a subsequent (i.e., recursive) reference to getToken. The Number Token Let’s assume the following finite state machine for the FP tokens. Notice that since the fixed tokens are handled without transitions, only those transitions related to number, identifier, and error tokens are represented.
CSCI 208
19
Prolog Tutorial
d D d S l L l
To recognize numeric (or identifier or error) tokens takes a bit more work than required for the fixed tokens. There are a couple of (related) points to consider. First, the number of characters involved in a numeric token is unknown. Second, we must retain the characters of the token as the value associated with the token returned. This means two things. We must accumulate the characters of the token as they are recognized. We must define an encapsulation “function” for the number token. This segment of code defines the number-token aspect of the getToken predicate. getToken(digits,[C|R],Rest,S,T) :digit(C), getToken(digits,R,Rest,[C|S],T). getToken(digits,[C|R],Rest,S,T) :letter(C), getToken(error,R,Rest,[C|S],T). getToken(digits,R,R,S,number(N)) :reverse(S,S1), atom_chars(N,S1). There are a few things which you should notice. 1. The number of parameters for getToken has expanded to five! This is because we need another to unify with the characters in the token. 2. When digits are encountered they are passed down to the next level, not back up as we have seen before. 3. When a letter is seen we move from the digits state to the error state. Any other character terminates the number token.
l E d d,l
CSCI 208
20
Prolog Tutorial
4. You should try this definition for getToken on a file containing only number tokens (and any other tokens for which you have defined getToken). But use the following clause getToken(digits,R,R,S,number(S)). in place of the third clause above. You will notice that the result is displayed in terms of ASCII codes. The predicate atom chars/2 converts a list of ASCII codes to a character format. If you add that reference to atom chars/2 back in, then you will notice that the characters in the token are backwards! The reverse takes care of that. Problem 7 Now that you have some examples to go on, implement the Prolog version of the FP tokenizer, getToken and test it on individual tokens. Now that you have an implementation for getToken it is necessary to implement a higher level predicate which uses getToken to help generate a return list consisting of the tokens from the file. Problem 8 Remember that getToken is a predicate which takes three arguments as follows. getToken(InList,Token,Rest) %% InList -- the list of input characters %% Token -- the token at the beginning of InList %% Rest -- the part of InList which follows Token The idea is to implement a predicate, say getTokens, which takes two parameters, the input list and a second parameter which will unify with the list of tokens found in the input list. Implement getTokens, remembering that though the top-level definition of the predicate may take only two parameters, a lower-level form of the same predicate could take three. [This hint is important. If you think about it, recursive references to getTokens will actually need three parameters, with the extra one representing the part of the input list remaining after the token.] You will have to wait till later to test this predicate. The following rules will be useful. whiteSpace(32). whiteSpace(10). digit(D) :- 46 < D, D < 59. letter(L) :- 64 < L, > < 91. letter(L) :- 96 < L, L < 123.
CSCI 208
21
Prolog Tutorial
6
Parsing
In this section you will investigate how Prolog is used to parse an input stream. You will make use of the tokenizer written for the last section to write a parser for the grammar of FP given in the Hugs tutorial. Prolog is particularly well suited to parsing since grammar rules have an uncanny resemblance to Prolog clauses. Remember that when parsing for a particular grammar rule there are really two kinds of activities: • checking for a particular token and • parsing another complex grammatical structure. We will deal with each of these in turn.
6.1
Low-level Parsing with Prolog
By low-level parsing we mean the recognition of individual tokens. The idea, of course, is that we have an input stream consisting of tokens and to continue a parsing activity we must check to make sure the next token in the stream is the one we expect to see (according to some grammar rule). This seems pretty straight forward. We need a predicate which will succeed exactly when the input stream is headed by a specified token. Remember that when we use the tokenizer from the previous section the input stream will appear as a list of tokens. Problem 9 1. Define a Prolog predicate match/2 using a single rule or fact (a fact would be nice!) which fits the description just given. Assume the first parameter unifies with a token and the second with a token list. The predicate would be used in one of these ways: match(if, Tin). or match(ident(a), Tin). [Here a is the identifier’s name gleaned from the input stream.] 2. The match/2 predicate is good for checking what the next token is. But there are times when you also want to check the token and then eliminate it from the stream. Define a new predicate eat/3 which does this. You should easily be able to adapt the definition for match/2 to get a definition for eat/3.
6.2
High-level Parsing with Prolog
<FnDef> ::= Ident <ParamList> Assign <FnExpDef>
Consider the following rule from the grammar for the language FP.
One way to read this rule is as follows. If the input string contains an Ident token and a <ParamList> and an Assign token and a <FnExpDef> then it contains a <FnDef>. The use of ‘and ’ emphasizes the conjunctive nature of the right-hand-side of the grammar rule. It seems that we could immediately translate this into Prolog. parseFnDef(..) :parseIdent(..), parseParamList(..), parseAssign(..), parseFnExpDef(..). CSCI 208 22 Prolog Tutorial
In fact, every grammar rule can be converted to a Prolog clause in this way (more or less!). Example 6 – Parsing if..then..else When parsing more than just a single token we cannot count on a Prolog fact to do the job. But the principle should be the same. If we want to recognize an if..then..else statement we need to match the initial part of an input list and pass on the part of the list which was not part of the match. We can consider the following Pascal-style statements and the corresponding list of tokens. if a then b else c; x := 5; [if,ident(a),then,ident(b),else,ident(c),;,ident(x),=,number(’5’),;] [Notice that some tokenizer converted the := to a simple =.] Now what we want is some predicate parseIfThenElse, which will match the first 6 tokens and ‘return’ the rest of the list as unmatched. How should this predicate be defined? Well, a fact will not do it, so we must define a Prolog rule. The left-hand side could be something like parseIfThenElse(Sin,Sout) :- ... where Sin unifies with the original list and Sout unifies with the list remaining after matching the if..then..else structure. We might issue the query with the specified results. | ?- parseIfThenElse([if,ident(a),then,ident(b),else,ident(c),scolon, ident(x),assign,number(’5’),scolon],X). X = [;,x,=,5,;] ? yes How about the right-hand side for the rule for parseIfThenElse? That part of the rule must indicate that the token if is matched and the rest of the list, lets call it X, is returned; then the token a will be matched from the head of X, leaving a list Y; and so on. In other words we can form the rule as follows. parseIfThenElse(Sin,Sout) :parseIf(Sin,R), parseName(R,S), parseThen(S,T), parseName(T,U), parseElse(U,V), parseName(V,W), parseEndIf(W,Sout). Notice that when the last predicate on the right is resolved the variable Sout should have the part of the list not recognized. One final point on this example. You may be wondering where the predicates match/2 and eat/3 are supposed to come in. In fact, the above rule could be rewritten making use of eat/3 as follows, since each predicate is matching a single token. parseIfThenElse(Sin,Sout) :eat(if,Sin,R), eat(ident(_),R,S), eat(then,S,T), eat(ident(_),T,U), CSCI 208 23 Prolog Tutorial
eat(else,U,V), eat(ident(_),V,W), eat(endif,W,Sout). Of course, neither of these rules will be of much use in the general case since the else and then parts are likely to be more complex.
Problem 10 1. Implement a single parse predicate, as illustrated above, for the following grammar rule. parseFnDef(Tin,Tout) :IDENT <ParamList> ASSIGN <FnExpDef> Be sure to make appropriate use of the low-level parsing predicates defined earlier. 2. Implement a single general rule for parseIfThenElse.
Problem 11 A fun but somewhat unrelated problem. Write a predicate separate which takes a list of tokens and returns two token lists, one containing all the number tokens of the input list and the other containing all the identifier tokens from the input list. Any other tokens from the list are discarded. If the file contains the line ‘12 + 13 equals twenty five (25)’ then we should see the following result. ?- tokens(’test’,Y), separate(Y,Ids,Nums). Ids = [id(equals),id(twenty),id(five)] Nums = [num(’12’),num(’13’),num(’25’)] Y = [num(’12’),plus,num(’13’),id(equals),id(twenty),id(five), lp,num(’25’),rp,eof] Yes Your names for tokens may be slightly different, but should be recognizable.
6.3
Parsing Expressions
A common problem in parsing is dealing with alternatives. We can see this problem and also deal with a more complete grammar by implementing a parser for basic arithmetic expressions. Recall the following grammar rules for expressions (a good review!). Exp ::= Term { ’+’ Term } | Term { ’-’ Term } Term ::= Factor { ’*’ Factor } | Factor { ’/’ Factor } Factor ::= number | ident | ’(’ Exp ’)’ This grammar can be written in a bit more convenient way as follows. Exp ExpTail Term TermTail Factor CSCI 208 ::= ::= ::= ::= ::= Term ExpTail empty | ’-’ Term | ’+’ Term Factor TermTail empty | ’*’ Factor | ’/’ Factor number | ident | ’(’ Exp ’)’ 24 Prolog Tutorial
The grammar rules can be implemented in the same manner as in the previous section, except that we have alternatives to deal with; each non-terminal has at least two alternative right-hand sides. We recall that the alternative operator ‘|’ is just a shorthand notation for multiple grammar rules with the same left-hand side. The appropriate parse predicates can at this point be defined by having one clause for each grammar rule, where we expand each alternative rule into multiple rules. I.e., the following list of clauses defines a parser for the expression grammar above. exp(Tin, Tout) expTail(Tin, Tin) expTail(Tin, Tout) expTail(Tin, Tout) term(Tin, Tout) :- Term(Tin,X), expTail(X,Tout). :- . :- eat(plus,Tin,X), term(X,Tout). :- eat(minus,Tin,X), term(X,Tout). :- factor(Tin,X), termTail(X,Tout).
termTail(Tin, Tin) :- . termTail(Tin, Tout) :- eat(mult,Tin,X), factorX,Tout). termTail(Tin, Tout) :- eat(div,Tin,X), factorX,Tout). factor(Tin, Tout) factor(Tin, Tout) factor(Tin, Tout) :- eat(number(_),Tin,Tout). :- eat(ident(_),Tin,Tout). :- eat(lp,Tin,X),exp(X,Y),eat(rp,Y,Tout).
Problem 12 Implement the parser just described and run it on a file containing an expression — do this a few times to convince yourself that the parser works. Notice that in this problem you have used the FP tokenizer to implement a parser for a “language” unrelated to FP.
6.4
Parsing Optional Structures
One of the features of a selection statement is that the else part is optional. How do we deal with optional parts in Prolog-based parsing? In fact, we can pretty much just write down the form of the grammar rules as is. For example, if we write the selection grammar rule as follows: <IfElse> ::= IF <Bexp> THEN <FnExp> <ElsePart> ENDIF Then the corresponding Prolog parse predicates can be written as follows. parseIfElse(Sin,Sout) :eat(if,Sin,R), parseBexp(R,S), eat(then,S,T), parseFnExp(T,U), parseElsePart(U,V), eat(endif,V,Sout). parseElsePart(Sin,Sout) :eat(else,Sin,R), parseFnExp(R,Sout). parseElsePart(Sin,Sin). %% makes it optional Another form of optional parsing occurs when a particular token can start more than one phrase. This occurs in a function expression where an identifier may be alone, signifying the use of a parameter, or followed by a sequence of terms, in which case the identifier is a function name. Once again we can just take the grammar rules describing this ambiguous situation and translate them directly to Prolog. The following rule is an abbreviated version of the FP function expression grammar rule. CSCI 208 25 Prolog Tutorial
<FnExp> ::= NUMBER | IDENT | IDENT <TermList> parseFnExp(Sin,Sout) :eat(number,Sin,Sout). parseFnExp(Sin,Sout) :eat(ident(_),Sin,Sout). parseFnExp(Sin,Sout) :eat(ident(_),Sin,R), parseTermList(R,Sout). Problem 13 Now, using the techniques described above, implement a set of parse predicates for the FP grammar which follows. Be sure to test it out when you are done. <Program> ::= <FnDefList> PERIOD
<FnDefList> ::= <FnDef> | <FnDef> SCOLON <FnDefList> <FnDef> <FnExpDef> ::= IDENT <ParamList> ASSIGN <FnExpDef> ::= <FnExp> | let <FnDefList> in <FnExp>
<ParamList> ::= IDENT | IDENT <ParamList> <FnExp> ::= NUMBER | IDENT | <FnApp> | <Selection>
<Selection> ::= if <BExp> then <FnExp> [<ElsePart>] endif <ElsePart> <BExp> <CompOp> <FnApp> <FnName> <TermList> ::= else <FnExp> ::= <FnExp> <CompOp> <FnExp> ::= LT | LE | GT | GE | EQ | NE ::= <FnName> <TermList> ::= IDENT | ADD | SUBT | MULT | DIV | MOD ::= <Term> | <Term> <TermList> ::= NUMBER | IDENT | LP <FnExp> RP
<Term>
CSCI 208
26
Prolog Tutorial
7
Building a Symbol Table
The parser described in the last section allows us to check a program for syntactic correctness, but doesn’t do anything about insuring proper use of program elements. For example, parsing the function definition f a b = + x b; will succeed, but, in fact, should fail because the identifier x is not a formal parameter of the function being defined. In order to be to deal with this type of error we must build a symbol table as we parse and judge the fitness of the code based on its syntax and the content of the symbol table. In the development of the parser we relied on representing parsing rules in terms of two lists: the input list and the list comprising the data not parsed by the rule. A symbol table has a similar functionality in the parsing process, except that, rather than being torn down as the parsing proceeds, the symbol table is constructed as the parsing proceeds. Where have we seen the building of a list before? How about the predicate separate? The idea there was to take a list A and produce two lists, one containing the integers from A and the other containing the identifiers from A. The technique used in implementing separate is to have an input list and (in this case) two result lists. The separate predicate was the subject of Problem 6.2 – look up your solution and notice the technique used to build the result lists. So, to add a symbol table to our parsing function we can do (in reverse) what we did with the program list in the original parser: for each predicate have an input symbol table and a resulting output symbol table. For example, parseFnDefList can be defined as parseFnDefList(Sin,STin,STout,Sout) :parseFnDef(Sin,STin,STout,Sout). parseFnDefList(Sin,STin,STout,Sout) :parseFnDef(Sin,STin,ST,X), eat(scolon,X,Y), parseFnDefList(Y,ST,STout,Sout). Notice that consuming a semicolon doesn’t involve the symbol table, so that parse predicate makes no reference to it. On the other hand, the definition reflects the fact that if parseFnDefList is matched, the STout should reflect the addition of symbols to STin as a result of repeated successes of the predicate parseFnDef. One question which must be addressed, of course, is how to integrate the above definition into the original parse predicate. Originally, parse was defined as parse(S) :- parseFnDefList(S, []). %% parse(S) :- parseFnDefList(S, [eof] -- is another possibility The parameters to parseFnDefList indicate that the predicate parse will succeed only if when the parsing is done all the input will have been consumed – i.e., the result list is empty. We need to do a similar thing if we add a symbol table. First, we must recognize the necessity to have the parser return the symbol table so it can be used by a subsequent interpreter predicate. Thus, we should define parse as follows parse(S, ST) :- parseFnDefList(S, [], ST, []). In this definition the second parameter to parseFnDefList represents the initial symbol table while the second represents the resulting symbol table. Problem 14 Make a copy of the file containing your parser predicates. In this new file modify your parser predicates to ‘pass’ around a symbol table, as illustrated by the discussion above. What you should do at this point is simply add to the result symbol table any identifier you happen upon, either on the left or right of the assign token. As an example, you might try something like parseFnDef(Sin,STin,STout,Sout) :eat(id(N),Sin,X), CSCI 208 27 Prolog Tutorial
parseParamList(X,[id(N)|STin],STa,Y), eat(assign,Y,Z), parseFnExpDef(Z,STa,STout,Sout). When you execute the query -? tokens(’prog.FP’,S), parse(S, ST). You should get a list containing the identifiers in your program, but there are bound to be duplicates. There are other aspects of the symbol table which we must consider. First, the entries in the symbol table must reflect the values. Since we want to represent scope, it would seem appropriate to make each entry a pair in which the first component is the identifier and the second component is a list of attributes; if an identifier is currently not in scope the attribute list can be empty. One advantage that Prolog presents is that the elements of a list needn’t be of the same type. This means that an attribute list can have a triple to describe a function and a pair to describe an argument. Example 7 – Searching the Symbol Table To see if a particular identifier is in scope requires a simple search predicate. If we have a list of identifiers the following would work. inScope(H, [H|Xs). inScope(H, [Y|Xs]) :- H \== Y, inScope(H,Xs). [The atom "H \== Y" indicate H is different from Y.] But if we have a symbol table as described above, then we must match more than just the identifier – we must match a pair whose first component is the identifier. The following will work. inScope(H, [(H,A)|Xs). inScope(H, [(Y,A)|Xs]) :- H \== Y, inScope(H,Xs). This does what we wanted, but does it really solve the problem? No! Remember that we don’t remove entries from the symbol table when there are no associated attributes – rather, an identifier is out of scope if it has no entry in the symbol table or its entry has an empty attribute list. We didn’t check for that! Here is a correct implementation of inScope. inScope(H, [(H,A)|Xs]) :- A \== []. inScope(H, [(Y,A)|Xs]) :- H \== Y, inScope(H,Xs). To avoid the inevitable “singleton variable” warning, we can rewrite the clauses as follows. inScope(H, [(H,A)|_]) :- A \== []. inScope(H, [(Y,_)|Xs]) :- H \== Y, inScope(H,Xs). We can make another simplification. We can turn the first clause into a fact by using pattern matching to specify that the attribute list must be non-empty. inScope(H, [(H,[_|_])|_]). inScope(H, [(Y,_)|Xs]) :- H \== Y, inScope(H,Xs). Now, what if we want to see if an identifier is of a particular type (function or parameter)? Here we will have to find the identifier in the list, but only succeed if the first item in the attribute list matches the specified type. isFunction(H, [(H,[(function,_,_)|As])|Xs]). isFunction(H, [(Y,_)|Xs]) :- H \== Y, isFunction(H,Xs). CSCI 208 28 Prolog Tutorial
Notice that the attribute entry for a function has three components: one for the type and two others for future use (the level number and the number of parameters, presumably). Searching a symbol table for an identifier of a certain type is one problem to be solved in implementing a symbol table. Another is updating the symbol table. This can be done in three ways: adding a new entry to the symbol table, adding a new attribute entry to the attribute list for an existing entry, or deleting attribute entries no longer needed (i.e., attributes of attributes which are going out of scope). Here is a sample of code from a parser which illustrates what sorts of things are possible. parse(S,ST) :- parseFnDefList(S,[],ST,[]).
parseFnDefList(Sin,STin,STout,Sout) :parseFnDef(Sin,STin,ST,X), eat(scolon,X,Y), parseFnDefList(Y,ST,STout,Sout). parseFnDefList(Sin,STin,STout,Sout) :parseFnDef(Sin,STin,ST,Sout).
parseFnDef(Sin,STin,STout,Sout) :parseFnName(Sin,STin,STa,X), enterScope(STa, STb) parseParamList(X,STb,STc,Y), eat(assign,Y,Z), parseFnExpDef(Z,STc,STd,Sout), leaveScope(STd, STout). parseParamList(Sin,STin,STout,Sout) :parseParamName(Sin,STin,ST,X), parseParamList(X,ST,STout,Sout). parseParamList(Sin,STin,STin,Sin) :-
parseParamName([N|Sin],STin,STout,Sin) :identifier(N), paramNotInTable(N,STin), addParamToTable(N,STin,STout).
parseFnExpDef(Sin,STin,STout,Sout) :parseLet(Sin,STin,STout,X), parseFnExp(X,STout,Sout). parseLet(Sin,STin,STout,Sout) :eat(let,Sin,X), parseFnDefList(X,STin,STout,Y), eat(in,Y,Sout).
parseFnExp(Sin,ST,Sout) parseFnExp(Sin,ST,Sout) parseFnExp(Sin,ST,Sout) parseFnExp(Sin,ST,Sout) CSCI 208
::::-
checkName(Sin,arg,ST,Sout). eat(num(_),Sin,Sout). parseIfThenElse(Sin,ST,Sout). parseFunctionApp(Sin,ST,Sout). 29 Prolog Tutorial
parseFunctionApp(Sin,ST,Sout) :checkFName(Sin,ST,X), parseTermList(X,ST,Sout).
parseIfThenElse(Sin,ST,Sout) :eat(if,Sin,X), parseBExp(X,ST,Y), eat(then,Y,Z), parseFnExp(Z,ST,W), parseELSEpart(W,ST,Sout). parseELSEpart(Sin,ST,Sout) :eat(else,Sin,X), parseFnExp(X,ST,Sout). parseELSEpart(Sin,ST,Sin).
parseTermList(Sin,ST,Sout) :parseTerm(Sin,ST,X), parseTermList(X,ST,Sout). parseTermList(Sin,ST,Sin).
parseTerm(Sin,ST,Sout) :eat(num(_),Sin,Sout). parseTerm(Sin,ST,Sout) :checkName(Sin,arg,ST,Sout). parseTerm(Sin,ST,Sout) :eat(lp,Sin,X), parseFnExp(X,ST,Y), eat(rp,Y,Sout).
parseFnName([N|Sin],STin,STout,Sin) :identifier(N), fnNotInTable(N,STin), addFnToTable(N,STin,STout). checkName([N|Sin],Type,ST,Sin) :identifier(N), defined((N,Type),ST). checkFName(Sin,ST,Sout) :checkName(Sin,fn,ST,Sout). checkFName([+|Sin],ST,Sin). checkFName([-|Sin],ST,Sin). checkFName([*|Sin],ST,Sin). checkFName([/|Sin],ST,Sin). Problem 15
CSCI 208
30
Prolog Tutorial
These predicates form a partially completed parser with symbol table, but there are some things needing completion. What needs completing are the implementations for the new predicates used here, such as fnNotInTable, addFnToTable, defined, etc. 1. Complete the definitions for the predicates which have not yet been defined. These should use some of the techniques discussed earlier in this section. 2. Complete the predicates enterScope and leaveScope. You will have to introduce into the symbol table a value for the current level and the level for each attribute set. When you complete this problem you will have a complete parser except for code translation. How would you propose implementing that code translation part of the parser? We have discussed in class the code generation needed for a function definition, and all it takes is to build a list of machine instructions and store them in a code table. Sounds easy enough! Give it a try...
CSCI 208
31
Prolog Tutorial
8
Prolog Semantics - The Computational Model
In the earlier sections we have tried to give an intuitive idea of the syntax and semantics of Prolog. In this section we will look more carefully at the computational model which defines the semantics of Prolog. Remember that computation in Prolog centers on the extraction from a program of the sets of values which satisfy a query, where a query is just a conjunction of atoms. The computation cycle has two steps. 1. Select an atom from the query and determine if there is a fact or the head of a rule with which the atom can be unified. If there is none, then the query fails. 2. Resolve the query with the fact or rule by replacing the atom by the body of the rule (in the case of a fact this just means the elimination of the atom). This cycle is repeated until the query fails or the query is eliminated. In the sub-sections which follow we will look in detail at the two steps of the cycle.
8.1
Unification
Unification is the process of finding a unifier for two atoms. In order to unify, two atoms must have the same structure, if we ignore constants and variables. Since atoms can contain function applications nested within their arguments, we require a recursive (i.e., stack based) algorithm. Let’s begin with a couple of definitions which will make the statement of the algorithm clearer. Definition 1 A term is defined inductively as follows: 1. A variable or a constant is a term. 2. If f is an n-ary function name and t1 , . . . , tn are terms, then f (t1 , . . . , tn ) is also a term. 3. Any expression is a term only if it can be constructed following steps 1. and 2. above.
Definition 2 Let p be an n-ary predicate and t1 , ..., tn be terms. Then p(t1 , ..., tn ) is an atom. Intuitively, the unification algorithm first checks that the two specified atoms start with the same predicate symbol – if not the atoms don’t unify. If the predicate symbols are the same then the algorithm checks that the terms comprising the parameter list are of the same structure. A stack is created containing the pairs of corresponding terms (from the two atoms). At this point the algorithm repeatedly removes a pair of terms from the top of the stack and compares their structures. As long as they match the algorithm continues; if a critical difference is encountered then the atoms can’t be unified and the algorithm terminates. The algorithm will continue to process the pairs from the stack until the stack is empty, at which time a unifier (in fact an mgu) will have been determined. Before continuing you should review the definitions in Section 8.3 for substitution, instance, unifier, and mgu. Definition 3 A Unification Algorithm Let A 1(t 1,...,t n) and A 2(s 1,...,s m) be two atoms.
CSCI 208
32
Prolog Tutorial
Algorithm: If A_1 and A_2 are different predicates or n <= m Then output Failed. Else Initialize the substitution to empty, the stack to contain the pairs (t_i,s_i), and Failure to false. While the stack is not empty & not Failure do pop (X,Y) from the stack case X is a variable that does not occur in Y: substitute Y for X in the stack and in the substitution add X=Y to the substitution Y is a variable that does not occur in X: substitute X for Y in the stack and in the substitution add Y=X to the substitution X and Y are identical constants or variables: continue X is f(x_1,...,x_n) and Y is f(y_1,...,y_n) for some function f and n>0: push (x_i,y_i), i=1,...,n, on the stack otherwise: Failure = true
If Failure, then output Failed Else output the substitution
There are a couple of things to point out about the algorithm: 1. An important thing to point out here is that if two atoms unify, then this algorithm always returns the most general unifier for the two atoms. 2. In the first two components of the case-statement the phrase “does not occur in” is referred to as the occurs check. This condition guards against a substitution such as X = f (X), which cannot be unified finitely. An interesting point is, the occurs check is very expensive computationally, so most implementations of Prolog omit it. This makes the implementation faster, but also makes the implementation unsafe. Example 8 – A Unification Example I exnum
Consider the two atoms p(a, f (Y )) and p(X, f (g(X))) – do they unify? Running the algorithm on these atoms leaves the following trace. 1. Initially: Since the predicates are the same we set the stack to be [(a, X), (f (Y ), f (g(X)))] and θ = φ. CSCI 208 33 Prolog Tutorial
2. Pop (a, X) from the stack, leaving [(f (Y ), f (g(X)))]. By the second case we set θ = {X = a} and apply θ to the stack, giving [(f (Y ), f (g(a)))]. 3. Pop (f (Y ), f (g(a))) from the stack, leaving [ ]. By the fourth case, we adjust the stack to be [(Y, g(a))], with no adjustment to θ. 4. Pop (Y, g(a)) from the stack, leaving [ ]. By the first case we modify θ = {X = a, Y = g(a)} – since the stack is empty we don’t have to apply θ. 5. The stack is empty to θ = {X = a, Y = g(a)} is the mgu for the two atoms.
Example 9 – A Unification Example II
exnum
Consider the two atoms p(a, f (X)) and p(X, f (b)) – do they unify? A quick examination leads us to believe the answer is no, because X would have to have both a and b as its substituted value. How does this come out of the algorithm? The following list reflects what happens during each pass through the algorithm. 1. Initially: Since the predicates are the same we set the stack to be [(a, X), (f (X), f (b))] and θ = φ. 2. Pop (a, X) from the stack, leaving [(f (X), f (b))]. By the second case we set θ = {X = a} and apply θ to the stack, giving [(f (a), f (b))]. 3. Pop (f (a), f (b)) from the stack, leaving [ ]. By the fourth case, we adjust the stack to be [(a, b)], with no adjustment to θ. 4. Pop (a, b) from the stack, leaving [ ]. By the third case, since a and b are different constants, the algorithm must return failed.
8.2
Resolution
After the Prolog interpreter has accepted a query from the user the interpreter goes through a cycle which involves two activities: unification and resolution. We have just seen the unification algorithm. Before focusing on the resolution process, we will look at the actions of the interpreter in a bit more detail. When the interpreter inputs a query it has a program, consisting of facts and rules, and a query which is a conjunction of atoms. The interpreter executes the following algorithm. While the query is not empty do select an atom from the query select a fact or rule with which the atom unifies If there is none, then return {\bf failed} Else If a fact was selected Then remove the atom from the query Else If a rule was selected replace the atom in the query by the body of the selected rule return succeeded This algorithm ignores many details, but carries the essence of the interpreter’s activities. The adjustment to the query which occurs if unification succeeds is the resolution process. We will now detail what happens during resolution. CSCI 208 34 Prolog Tutorial
You will have noticed that in the algorithm above there is no mention of the mgu which results from the unification process. If all Prolog was meant to do was to say “success” or “failure”, then the description above would be adequate. But the system should also return information about what variable substitutions satisfy a query. So we have to look more closely at the resolution process to see how the substitution values are determined. Actually, there are two issues here. First, how do we use the mgu’s returned by the unification algorithm to determine substitution values? Second, how do we make sure that we can return all possible substitution values? This second question involves a process called backtracking and is what happens when the user responds with a semi-colon to a returned substitution. determining substitutions backtracking
8.3
Queries
In the previous sections the notion of query was introduced. In this section we will take a closer look at queries and how they are processed. Queries allow questions to be posed regarding information contained in a program. In the case that a query contains no variables, then the question posed is one with a yes/no answer. This type of query is called ground query. For example, the query ?- edge(a,b). asks whether there is an edge from a to b. If the query is implied by the program, Prolog will return the answer yes. Otherwise the answer no is returned. Note that a period is also necessary following a query. A slightly more complex query is one that contains more than a single atom. For example, the query ?- edge(a,b),edge(e,b). poses the question: “Is there an edge from node a to node b AND from node e to node b?”. Hence similar to commas occurring in bodies of rules, a comma that appears inside a query is treated as a conjunction. With respect to the program shown in Example 2.1, it is easy to see Prolog will answer yes to both of the queries ?- edge(a,b). %% and ?- edge(a,b),edge(e,b).’ On the other hand, Prolog answers no to the query ?- edge(b,a). since there is no edge from node b to node a. Atoms in a query may contain variables. These are called non-ground queries. The query ?- edge(a,X). is an example of a non-ground query. Variables that occur inside a query are treated existentially. This implies that their meaning is similar to variables that occur in the body of a rule but do not appear in the head of the same rule. The query ?- edge(a,X). therefore, is posing the question: “Does there exist a node X such that there is an edge from node a to X?”. Referring again to the program in Example 2.1, we would clearly expect Prolog to return a yes since node a is connect to nodes b and e. Indeed, this is the response of Prolog. However, in addition, Prolog will supply a witness (in this case a node) for the variable X in the query that explains why the query is true. Therefore, a witness for X in this query must either be b or e. To further clarify this, if we pose the query ?- edge(a,X). CSCI 208 35 Prolog Tutorial
Prolog responds by the answer X = b indicating the response “There is an X such that edge(a,X) is true, and b is one such X.” The Prolog mechanism for finding witnesses for variables is called unification. One may think of it as a generalized pattern-matching operation. The next few definitions formalizes this. Definition 4 A substitution is a finite set of equalities {X1 = t1 , X2 = t2 , . . . , Xn = tn } where each Xi is a variable and ti is a term, X1 , . . . , Xn are distinct variables, and Xi is distinct from ti . Each Xi = ti is called a binding for Xi . Typically, we denote substitutions by the Greek letters θ, γ, σ, possibly subscripted.
Example 10 – A Substitution The set θ = {X = a, Y = b} is a substitution, but γ = {X = a, X = b} and σ = {X = a, Y = Y } are not since in γ, the same variable X occurs twice on the left hand side of a binding. In σ, the binding Y = Y violates the condition that each Xi must be distinct from ti in the definition of substitution.
Definition 5 Suppose θ is a substitution and E is an expression. Then Eθ, the instance of E by θ, is the expression obtained from E by simultaneously replacing each occurrence of the variable Xi in E by the term ti , where Xi = ti is a binding in the substitution θ.
Example 11 – Another Substitution Suppose θ is the substitution {X = b, Y = a}, γ is the substitution {X = Y, Y = a}, and σ is the substitution {X = Y, Y = a, W = b}. Let E be the atom p(X, Y, Z). Then 1. Eθ = p(b, a, Z). 2. Eγ = p(Y, a, Z). 3. Eσ = p(Y, a, Z). In the first case, the variables X and Y in E are replaced by b and a respectively. Note that the variable Z is not affected by the substitution θ since there is no binding of the form Z = t. In the second case, it is important to observe that the replacement of variables by terms take place simultaneously. Thus the variable X in E is replaced by Y at the same time that Y is replaced by a. We do not further replace Y in the resulting expression by a to produce p(a, a, Z). The last case illustrates that there may exist bindings in the substitution that do not have any effect on the expression. In this since E does not contain the variable W , the binding W = b in σ is superfluous.
Definition 6 CSCI 208 36 Prolog Tutorial
Suppose A and B are two expressions. A substitution θ is called a unifier of A and B if the Aθ is syntactically identical to Bθ. We say A and B are unifiable whenever a unifier of A and B exists. If, in addition, θ is the smallest possible substitution which unifies two atoms, we say that θ is the most general unifier, usually written mgu.
simple queries Let’s see how these definitions apply to our example. When we issue the query ?- edge(a,X). Prolog searches all edge related facts to find the first fact that unifies with the query. It turns out that in our program, the very first fact edge(a,b) is unifiable with the query since the substitution {X = b} is a unifier of the two atoms edge(a,X) and edge(a,b). The substitution corresponds to the answer returned by Prolog. Previously we noted that for the query ?- edge(a,X). either node b or node e may serve as a witness. Prolog returns b simply because the fact edge(a,b) appears before edge(a,e) in our program. So what good is e if we always get b as the answer? This is where the backtracking mechanism of Prolog comes in. When Prolog returns the answer X = b, the user has the option of commanding Prolog to search for other answers by typing a semicolon. The interaction between the user and Prolog is as follows. ?- edge(a,X). %%% User poses a query
Prolog responds by the answer X = b; %%% The user types a semicolon after the answer
Prolog retries the query and returns another answer X = e If the user continues to type semicolon after each answer returned by Prolog, all possible answers will eventually be found. conjunctive queries Let us next examine how conjunctive queries are handled. These are queries that contain multiple atoms. In the case of ground queries, we have already discussed how Prolog answers. Let us then consider the non-ground conjunctive query ?- edge(a,X),edge(b,Y). Since no variable is shared between atoms in the query, Prolog simply attempts to solve each atom independently. The only important part is that atoms are answered from left to right. In this case, Prolog first tries solving edge(a,X). As we have seen already, this unifies with the fact edge(a,b) with the unifier {X = b}. Next the atom edge(b,Y) is tried. Searching through the set of facts related to edge, we find that the first unifying fact is edge(b,d) and the unifier is {Y = d}. Combining the two unifiers yields the substitution {X = b, Y = d}. This is the answer returned by Prolog. ?- edge(a,X), edge(b,Y). Prolog returns the answers
CSCI 208
37
Prolog Tutorial
X = b, Y = d An interesting question is what happens if the user requests for additional answers by typing a semicolon. This causes backtracking to take place, and the order in which atoms in the query are retried is based on the idea of “first tried, last re-tried”. Equivalently we may think of this as “last tried, first re-tried”. The essential idea is that upon backtracking, Prolog retries the last atom (or right most atom) in the query with which an alternative solution exists. In the above example, since edge(b,Y) is the solved last, it is retried first upon backtracking. Looking at our program, we see that in addition to the fact edge(b,d), the fact edge(b,c) also unifies with the atom edge(b,Y) in the query with the unifier {Y = c}. Thus Prolog presents the answers X = b, Y = c as the second solution. Note that in this case the first atom edge(a,X) is NOT retried. Next suppose we type yet another semicolon, prompting another backtracking to take place. Again, this causes edge(b,Y) to be retried. However, this time no more answer exists (i.e. we have exhausted all possible solutions for edge(b,Y)). This causes Prolog to trace back one more atom and retry edge(a,X). This results in the new binding {X = e}. At this point, Prolog is not done. It now proceeds forward in the query to again solve edge(b,Y), producing the answer X = e, Y = d Finally, one last request for additional answers results in the X = e, Y = c non-ground queries In case a conjunctive query is non-ground, and contains variables that are shared among the atoms in the query, we need to modify the above description of how Prolog works slightly. Suppose the query is of the form ?- Atom1, Atom2, ..., Atomn. The order in which the atoms are tried is still left to right, as was the case before. However, each time an atom is unified with a fact in the program, the unifier used must be applied to the remaining atoms in the query before proceeding. For example, if the query in question is ?- edge(a,X),edge(X,b). then solving the first atom edge(a,X) causes a unification with the fact edge(a,b) using the unifier is θ = {X = b}. Before trying the next atom edge(X,b) in the query, we must first apply the substitution θ to it. Computing edge(X,b)θ results in the atom edge(b,b). This is the query that Prolog tries to solve next. Since edge(b,b) does not unify with any fact in the program, the query fails and backtracking takes place. As the last atom in the query with which an alternative solution exists is edge(a,X), it is retried, causing this time a unification with the fact edge(a,e). The new unifier is θ = {X = e}. Again this is applied to the atom edge(X,b). We have edge(X,b)θ = edge(e,b). This is a ground atom that now matches with the fact edge(e,b) in the program. It follows that the query succeed and the answer returned by Prolog is X = e Programming in Prolog provides more flexibility than Scheme or Pascal/C for dealing with computations which may produce multiple (possibly infinitely many) possible results due to its backtracking capability. This allows multiple answers to be returned for a given input, as opposed to a single answer. However, this means that whatever we can do in the other languages, we should be able to do in Prolog. The exercise below involves writing a program to solve a problem that is not functional: For a given input, there may exist several outputs. This type of problem is generally called relational. [Can you figure out how to implement a function in Prolog? Try the standard factorial.] CSCI 208 38 Prolog Tutorial | https://www.scribd.com/document/18319237/Prolog-Intro | CC-MAIN-2018-13 | refinedweb | 16,523 | 64 |
This preview shows
page 1. Sign up
to
view the full content.
Discussion Question(s) #2 Please reply to this thread by or before Friday, day 4 with your answers! • What is capital planning? Why is the internal rate of return important to an organization? Why is net present value important to a project? How would you select from multiple projects presented to your organization? What is capital planning? Capital planning means corporate evaluation of long-term investment proposals, generally by means of discounting estimated future cash flows. Why is the internal rate of return important to an organization? Internal rate of return (IRR) is a measure of the present value of the investment's cash outflows with the present value of the investment's cash inflows, or more specifically, where the two break even. IRR is a critical measurement for an organization's investments because it shows how efficiently or effectively the various investments perform. IRR allows a company - and, by extension, the company's investors - to quickly determine when an investment adds value. IRR is
This note was uploaded on 02/21/2011 for the course FIN 370 taught by Professor Unknown during the Spring '08 term at University of Phoenix.
- Spring '08
- unknown
- Net Present Value
Click to edit the document details | https://www.coursehero.com/file/6147632/FIN-370-Week-3-DQ-2/ | CC-MAIN-2017-09 | refinedweb | 215 | 57.47 |
I have this data
{Wednesday : {22 : {Type = x,
Temp = x,
Speed = x,
Direction = x}
{23 : {Type = x,
Temp = x,
Speed = x,
Direction = x}
class Weather(object):
def __init__(self, wtype, wtemp, wspeed, wdirection):
self.type = wtype
self.temp = wtemp
self.speed = wspeed
self.direction = wdirection
Wednesday.Temp
>>> 22
"Wednesday.22.Type"
Although numbers are not considered to be valid identifiers in Python (but that could be funny for trolling:
0 = 1 = 2 = 3 = 42), things like
_3 are, but are generally considered to be "private" attributes by the python community (myself included), so i use
at followed by the number instead. And I think it would be better to access it like you access a dictionary.
Here is my take on it. Remove the methods if you don't want the associated feature.
class SpecificWeather(object): def __init__(self, data): self.data = data @property def type(self): return self.data["Type"] @property def temperature(self): return self.data["Temp"] @property def speed(self): return self.data["Speed"] @property def direction(self): return self.data["Direction"] class Weather(object): def __init__(self, data): # data is the dictionary self.data = data def __getitem___(self, item): # for wednesday[22].type return SpecificWeather(self.data[item]) def __getattr__(self, name): # for wednesday.at22.type if name.startswith("at"): return SpecificWeather(self.data[int(name[2:])]) raise AttributeError() @property def type(self): # TODO: Return the average type or something like that @property def temperature(self): # TODO: Return the average temperature or something like that @property def speed(self): # TODO: Return the average speed or something like that @property def direction(self): # TODO: Return the average direction or something like that
This solution uses
property a lot, this has a big advantage: If you change the temperate for 22,
wednesday[22].temperature will now give you the new value. If you care for performance however, and you use only half of them, then this one can be faster than storing the results, if you access them even multiple times though, this will be a lot slower.
How to use it:
wednesday = Weather({ 22: { 'Type': ..., 'Temp': 30, 'Speed': ..., 'Direction': ... }, 23: { 'Type': ..., 'Temp': 28, 'Speed': ..., 'Direction': ... } }) print(wednesday.at22.temperature) # gives 30 print(wednesday[23].temperature) # gives 28 | https://codedump.io/share/3YSUpSoIRe0F/1/python---nested-classes-parent-child-new-to-classes | CC-MAIN-2017-30 | refinedweb | 370 | 52.05 |
Convert
Java BMI code
Java BMI code could someone help me with this
heightInInches... in pounds and returns the BMI using the formula: weight * 703 / height2
The main..., stone and pounds which represents someone?s weight and returns that weight in pounds "
finding java code on internet
finding java code on internet Is there anybody to help me?
i want to some java coding web sites.it is prerequest for me Conversion
Java Conversion
... illustrate the conversion from char to Byte. Here, we are going
to convert a char type... you the conversion of double into string.
Convert
ArrayList to Array
Reports to pdf conversion
Reports to pdf conversion I need to convert reports into pdf format using java.. Will i get any sample code
hi.. please give me a java coding for the following question
and display the BMI. Note that one pound is 0.45359237 kilograms and one inch is 0.0254...hi.. please give me a java coding for the following question Body Mass Index(BMI) is a measure of health on weight. It can be calculated by taking...://
finding the prime numbers
finding the prime numbers Hi, I am a beginner to java and I have problem with the code in finding the prime numbers, can someone tell me about... about your problem.
Java programming 1 - Java Beginners
)computeBMI(kilograms, meters);
m_bmiField.setText("" + bmi...Java programming 1 thx sir for reply me..but sir can u pls simplify it? cos the answer is not up to my requirement regarding the BMI index
Finding shapes in digital photos - java
Finding shapes in digital photos - java Hello,
I need some hints/tips regarding some project I'm doing. The project is about finding shapes... class in Java, but any other ideas are more than welcomed.
Thank you very much
hexadecimal conversion java compilation - UML
hexadecimal conversion java compilation write a simple program...,
Please visit the following links: Date Conversion
Java Date Conversion
In java date conversion, two packages are used...
Java Converts String into Date
In this example we are going to convert...; used to convert between dates and time fields and the DateFormat class
Convert One Unit to Another
C:\unique>java UnitConverter1
Conversion Table...
Convert One Unit to Another
Again in this section, you will learn to convert One
Unit to Another
Casting (Type Conversion)
are there in java. Some circumstances requires automatic type
conversion, while in other cases...
Java performs automatic type conversion when the type
of the expression...
Casting (Type Conversion)
Convert InputStream to ByteArray
Convert InputStream to
ByteArray
Here we will learn the conversion of an input
stream into a byte array.
To convert the InputStream
Finding the longest word in a user given string
Finding the longest word in a user given string In java, accept a string from the user and find the longest word in it.
The given code finds the longest word from the string.
import java.util.*;
class LongestWord Double To String
Convert Double To String
...;
This section learns you the conversion of double into string. The following program... a
variable of double type and convert it into the string form by using toString
Convert Inputstream to ByteArrayInputStream
Convert Inputstream to
ByteArrayInputStream
In this example we are going to convert.... Then convert this input stream
into string and then string into byte by using
How to convert string to byte in Java
How to convert string to byte in Java How to convert string to byte in Java
Convert Inputstream to OutputStream
Convert Inputstream to
OutputStream
... to convert an InputStream to OutputStream.
Here we are trying to make understand the conversion of an input stream
into an output stream
Mysql Date Format Convert
and time. Now, we
help you to convert the Mysql Date Format Conversion into other... Mysql Date Format Convert
... 'Mysql Date Format Convert'. To grasp this
concept we use Date now ( ) Query
Convert To Java Program - Java Beginners
Convert To Java Program Can anyone convert this C program codes to Java codes,please...thanks!
#include
int array[20];
int dcn;
int cntr=0;
void add();
void del();
void insert();
void display();
void exit();
void an pdf file to html in Java
convert an pdf file to html in Java Hi all, How to convert an pdf file to html in Java?
Currently all my data is generated into a report in pdf... implementing this, is there any source code in java? Thanks convert file to byte array
Java convert file to byte array How to convert file to byte array in Java?
Thanks
Hi,
To convert file to byte array in Java you have to follow the following steps:
a) Create the object of InputStream class
b
convert java Application to Java Applet
convert java Application to Java Applet hi every Java Master or Java Professional , my Name Is Vincent i'm java beginner can i ask a question regarding for Java application convert to Java Applet. below her is my sample
java Application Convert to java Applet
java Application Convert to java Applet Hi every Java Masters i'm Java beginner ,and i want below this figures source code convert to Java Applet hope every Masters can helping thank .
import java.util.*;
import java.text.
Convert String to Date
Convert String to Date
In this example we are going to convert String into
date.
In java date conversion, two packages are used .They
are java.util.
String conversion
String conversion I want to convert a string of mix cases(lower and upper case) to vice versa.
ex.
HellO should be printed to hELLo.
the string comes from user using datainputstream. Also sending individual chars of string
Java code to convert pdf file to word file
Java code to convert pdf file to word file How to convert pdf file to word file using Java
how to convert Visual c++ to java - Java Beginners
how to convert Visual c++ to java Hi Sakthi here..
How to convert Visual c++ codings to Java codings..
Does both have any similarity in library files
convert Html to Xhtml - Java Beginners
convert Html to Xhtml Hi All,
I am trying to convert html to xhtml in java. to do this i am using htmlcleaner api. i am not able to do with it.i ve not even got basic example on that so please can u send some example
Convert Object To XML
ObjectToXML.java
C:\convert\completed>java ObjectToXML
Enter 10...
Convert Object To XML
Here we are discussing the conversion of an object
into xml
Java code for conversion between .xls and .xlsx or vice versa - Development process
Java code for conversion between .xls and .xlsx or vice versa I've some problems in my Project. I'm working on a web based application which... or tool in Java for converting between .xls to .xlsx or Vice versa
Convert a file name path to url and vice versa in java
():
The toURL()
method of the
File
class is used to convert the file name... with the toURL() method of the File
class.
Here is the code of Convert the Filename
Convert Text to HTML
Convert Text to HTML
In this section, We are discussing the conversion of
text into html file... prompt Output of this program.
C:\corejava>java TextToHTML | http://www.roseindia.net/tutorialhelp/comment/64135 | CC-MAIN-2014-42 | refinedweb | 1,213 | 63.49 |
Converting old App Engine code to Python 2.7/Django 1.2/webapp2
I'm borrowing the code for this blog for another project I'm working on, and it seemed to make sense to take the opportunity to bring it up to speed with the latest-and-greatest in the world of App Engine, which is:
- Python 2.7 (the main benefit for me; I don't like having to dick around with 2.6 or 2.5 installations)
- multithreading (not really needed for the negligible traffic I get, but worth having, especially given that the new billing scheme seems to assume you'll have this enabled if you don't want to be ripped off)
- webapp2 (which seems to the recommended serving mechanism if you're not going to a "proper" Django infrastructure)
- Django 1.2 templating (I'd used this on a work project a few months ago, but the blog was still using 0.96
Of course, having so many changed elements in the mix in a single hit is a recipe for disaster; with things breaking left, right and centre, trying to work out what the cause was was a bit needle-in-a-haystackish. It didn't help that the Py2.7 docs on the official site are still very sketchy, so I ended up digging through the library code quite a bit to suss out what was happening.
As far as I can tell, I've now got everything fixed and working - although this site is still running the old code, as the Python 2.7 runtime has a dependency on the HR datastore, and this app is still using Master/Slave.
I ended up writing a mini-app, in order to develop and test the fixes without all the cruft from my blog code, which I'll see about uploading to my GitHub account at some point. In the mean-time, here are my notes about the stuff I changed. I'm sure there are things which are sub-optimal or incomplete, but hopefully they might save someone else time...
app.yaml
- Change runtime from python to python27
- Add threadsafe: true
- Add a libraries section:
libraries: - name: django version: "1.2"
- Change handler script references from foo.py to foo.app
- Only scripts in the top-level directory work as handlers, so if you have any in subdirectories, they'll need to be moved, and the script reference changed accordingly:
- url: /whatever # This doesn't work ... # script: lib/some_library/handler.app # ... this does work script: handler.app
Templates
- In Django 1.2 escaping is enabled by default. If you need HTML to be passed through unmolested, use something like:
{% autoescape off %} {{ myHTMLString }} {% endautoescape %}
- If you're using {% extends %}, paths are referenced relative to the template base directory, not to that file. Here's an table showing examples of the old and new values:
- If you have custom tags or filters, you need to {% load %} them in the template, rather than using webapp.template.register_template_library() in your main Python code.
e.g.
Old code (in your Python file):
webapp.template.register_template_library('django_custom_tags')New code (in your template):
{% load django_custom_tags %}(There's more that has to be done in this area; see below.)
Custom tag/filter code
- Previously you could just have these in a standalone .py file which would be pulled in via webapp.template.register_template_library(). Instead now you'll have to create an Django app to hold them:
- In a Django settings.py file, add the new app to INSTALLED_APPS e.g.:
INSTALLED_APPS = ('customtags')
- Create an app directory structure along the following lines:
customtags/ customtags/__init__.py customtags/templatetags/ customtags/templatetags/__init__.py customtags/templatetags/django_custom_tags.pyBoth the __init__.py files can be zero-length. Replace customtags and django_custom_tags with whatever you want - the former is what should be referenced in INSTALLED_APPS, the latter is what you {% load "whatever" %} in your templates.
- In your file(s) in the templatetags/ directory, you need to change the way the new tags/filters are registered at the top of the file.
Old code:
from google.appengine.ext.webapp import template register = template.create_template_register()New code:
from django.template import Library register = Library()The register.tag() and register.filter() calls will then work the same as previously.
Handlers
- Change
from google.appengine.ext import webappto
import webapp2and change your RequestHandler classes and WSGIApplication accordingly
- If your WSIApplication ran from within a main() function, move it out.
e.g.
Old code:
def main(): application = webapp.WSGIApplication(...) wsgiref.handlers.CGIHandler().run(application) if __name__ == '__main__': main()New code:
app = webapp2.WSGIApplication(...)Note in the new code:
- The lack of a run() call
- That the WSGIApplication must be called app - if it isn't, you'll get an error like:
ERROR 2012-01-29 22:17:37,607 wsgi.py:170] Traceback (most recent call last): File "/proj/3rdparty/appengine/google_appengine_161/google/appengine/runtime/wsgi.py", line 168, in Handle handler = _config_handle.add_wsgi_middleware(self._LoadHandler()) File "/proj/3rdparty/appengine/google_appengine_161/google/appengine/runtime/wsgi.py", line 220, in _LoadHandler raise ImportError('%s has no attribute %s' % (handler, name)) ImportError:
has no attribute app
- Any 'global' changes you might make at the main level won't be applied across every invocation of the RequestHandlers - I'm thinking of things like setting a different logging level, or setting the DJANGO_SETTINGS_MODULE. These have to be done within the methods of your handlers instead. As this is obviously painful to do for every handler, you might consider using custom handler classes to handle the burden - see below.
Rendering Django templates
The imports and calls to render a template from a file need changing.
Old code:
from google.appengine.ext.webapp import template
...
rendered_content = template.render(template_path, {...})
New code:
from django.template.loaders.filesystem import Loader
from django.template.loader import render_to_string
...
rendered_content = render_to_string(template_file, {...})
As render_to_string() doesn't explicitly get told where your templates
live, you need to do this in settings.py:
import os
PROJECT_ROOT = os.path.dirname(__file__)
TEMPLATE_DIRS = (os.path.join(PROJECT_ROOT, "templates"),)
Custom request handlers
As previously mentioned, where previously you could easily set global environment stuff, these now have to be done in each handler. As this is painful, one nicer solution is to create a special class to set all that stuff up, and then have your handlers inherit from that rather than webapp2.RequestHandler.
Here's a handler to be more talkative in the logs, and which also
sets up the
DJANGO_SETTINGS_MODULE environment variable.
class LoggingHandler(webapp2.RequestHandler):
def __init__(self, request, response):
self.initialize(request, response)
logging.getLogger().setLevel(logging.DEBUG)
self.init_time = time.time()
os.environ["DJANGO_SETTINGS_MODULE"] = "settings"
def __del__(self):
logging.debug("Handler for %s took %.2f seconds" %
(self.request.url, time.time() - self.init_time))
A couple of things to note:
- the webapp2.RequestHandler constructor takes request and response parameters, whereas webapp.RequestHandler just took a single self parameter
- Use the .initialize() method to set up the object before doing your custom stuff, rather than __init__(self) | http://www.john-smith.me/Tag/webapp2 | CC-MAIN-2014-52 | refinedweb | 1,164 | 57.77 |
Contents
Fedora Packaging Committee Meeting of {2008-04-08})
Writeups
The following drafts have been accepted by FESCO and are to be written into the guidelines:
- SysV-style initscript guidelines:
- Java packaging guidelines:
- Eclipse plugin guidelines:
- GCJGuidelines:
Votes
The following proposals were considered:
- No packages may own files or dirs in /srv
-
- This is a new draft this week
- Target release: F10 (including fixing noncompliant packages by then)
- Accepted (6 - 0)
- Voting for: tibbs spot Rathann abadger1999 racor hansg rdieter
- Naming all packages in lowercase
-
- This is a new draft.
- Not Accepted (1 - 4)
- Voting for: agadger1999
- Voting against: tibbs spot hansg racor
- Abstaining: Rathann rdieter
- Revisiting the jpackagage naming exception
- The original exception is at; the committee is revisiting the exception.
- The committee requests from the Java group "a list of information as to why they need the jpp tag, specifically, how they're using it, by May 8th." The committee will revisit the issue then.
- Accepted (5 - 0)
- Voting for: tibbs abadger1999 spot rdieter hansg
- Sugar Activity Guidelines
-
- A new draft this week
- Some issues were identified:
- arch-specific activities should not install under /usr/share
- /usr/share/activities is rather generic
- The draft is tabled until the next meeting.
- Update the GCJ guidelines to require that it be called conditionally
-
- A modification to the existing GCJ guidelines, new this week.
- Accepted (6 - 0)
- Voting for: abadger1999 spot tibbs rdieter Rathann hansg
Other Discussions
The meeting ended with a long discussion of the packaging of static libraries and the conditions under which static libraries are allowable in the -devel pacuage. This was triggered by the discussion in. There was no written proposal.
Next meeting 2008-04-22.
IRC Logs
[12:06] *** rdieter sets the channel topic to "Channel is used by various Fedora groups and committees for their regular meetings | Note that meetings often get logged | For questions about using Fedora please ask in #fedora | See for meeting schedule". [12:06] <spot> abadger1999, racor, hansg, tibbs? [12:06] * hansg is present and ready [12:07] <abadger1999> I'm here [12:07] * tibbs here [12:07] --> Rathann has joined this channel (n=rathann@onizuka.greysector.net). [12:07] * Rathann present [12:07] <spot> ok, thats 6 of us. [12:08] --> caillon has joined this channel (n=caillon@75.147.7.113). [12:08] <spot> first item is about the FPC seats [12:08] <spot> right now, we have two open seats [12:08] <spot> we had an election to determine the first open seat [12:08] <spot> but two candidates came out in a tie for first [12:08] <tibbs> How convenient. [12:08] <spot> thus, it seems reasonable to offer both of them a seat. :) [12:09] <tibbs> +1 to that. [12:09] <abadger1999> +1 [12:09] <Rathann> +1 [12:09] <hansg> +1 [12:09] <spot> +1 [12:09] <rdieter> +1 [12:09] <spot> ok, i will send them email today to invite them to join [12:10] <spot> now, lets get to the fun stuff [12:10] <tibbs> Well, first, who are the two new folks? [12:10] <tibbs> Or is it a secret until they accept? [12:10] <spot> well, i'd rather make sure they are still willing [12:11] <racor> sorry, for being late, and sorry in advance, I'll also have to quit early, today :/ [12:11] <spot> first item of business: [12:11] <tibbs> I wish we could handle this better. [12:12] <spot> tibbs: i wish the FHS wasn't such a trainwreck here. [12:13] <abadger1999> I like the quote. Self-contradictions are always good for proving a point. [12:13] <spot> if the FHS ever gets its head out of its ass here, we'll draft proper usage guidelines for /srv [12:13] <tibbs> Well, yeah. I guess in the absense of useful guidance we just have to stay clear of it. [12:14] <tibbs> +1 to the draft, although I've no idea how to go about fixing things. [12:14] <abadger1999> So what's the plan for migration from F-9 w/ /srv usage to F-10 without? [12:14] <spot> abadger1999: i'll file bugs and work with the packagers on a case-by-case [12:14] <tibbs> The thing that really bothers me is that if we could just fix a structure for /srv, we could have working selinux rules for that content. [12:15] <tibbs> Right now you have to know too much about selinux in order to move your web sites out of /var, for example. [12:15] <Rathann> tibbs: wouldn't mount --bind work around that? [12:16] * spot is +1 on this draft (since it is one of mine) [12:16] <Rathann> +1 from me too [12:16] <abadger1999> +1 [12:16] <racor> +1 [12:16] <abadger1999> If we run into problems porting I'm sure you'll let us know. [12:16] <Rathann> tibbs: it says "at this time", we can revisit it later [12:17] <tibbs> Rathann: Yes, it is always the case that we can revisit guidelines. [12:17] <spot> ok, thats a +5... hansg, if you'd like a vote on the record, feel free to chime in. [12:17] <hansg> +1 [12:18] <spot> next item: [12:18] <rdieter> +1 nobitsinsrv (too) [12:18] <tibbs> -1 [12:18] * spot notes that "Even historic mixed-case packages like X have been converted to lowercase over time." is pretty much false. [12:18] <racor> -10 [12:18] <spot> -1 [12:19] <spot> well, if others would like to vote here, they can go on the record [12:19] <Rathann> 0 [12:19] <hansg> -1 [12:19] <spot> but this one is pretty much dead. [12:20] <abadger1999> +1 [12:20] <rdieter> while I tend to agree with the sentiment of this proposal, it's implementation, wording isn't acceptable. [12:20] <abadger1999> :-) [12:20] <abadger1999> rdieter: Agreed [12:20] <rdieter> 0 [12:20] <spot> OK, lets move on. Next item: Revoke JPackage Naming Exception [12:20] <spot> Specifically, I propose that we revoke: [12:20] <hansg> I could live with a rule saying that mixed case package names should have an all lowercase provides for easy yum install foo instead of yum install fOo [12:21] <spot> the arguments in that exception policy were ... tenuous at best. [12:21] <tibbs> hansg: I agree; I would also be happy with a rule about whether you can have two packages whose names differ only in case. [12:22] <hansg> -1 (to revoking it) seing the discussion on the devel-list, there doesn't seem to be a consensus on this in our community [12:22] <spot> no progress has been made by anyone to work towards improving the areas of concern, but there has also been no serious loss to anyone as a result of their absense. [12:22] <tibbs> spot: I agree about the jpackage naming policy, but as far as I know we still haven't received that information about why it's actually needed. [12:22] <spot> tibbs: indeed. I don't think we're ever going to get any. [12:22] <tibbs> Well, I don't want to go revoking it without understanding why it's actually needed. [12:22] <hansg> I agree it isn't completely pretty, but revoking it nw can only result in bad blood between Fedora and jpackage, which is not something I want [12:22] <tibbs> But then again, they can just not submit the requested information. [12:23] <spot> other than to perform "group exclusions", which no one seems to actually use. [12:23] <tibbs> So what we need is a deadline, I think. [12:23] <rdieter> tibbs: nod, put the onus on justifying the exception... or else. :) [12:24] * spot proposes April 30th, 2008 [12:24] <tibbs> "The exception will expire automatically on <date> unless we're presented with sufficient information to consider extending it." [12:24] <spot> that should be plenty of time. [12:25] <spot> +1 to the deadline for requested information [12:25] <tibbs> We should be meeting on May 6th; how about that as a deadline? [12:25] <spot> ok. [12:25] <abadger1999> How would reasons differ from what's already there? [12:25] <tibbs> It also gives them four full weeks. [12:26] <tibbs> abadger1999: There was a conference call wherein this was discussed. Several reasons were mentioned which I had not heard of before. [12:26] <abadger1999> Okay. [12:26] <spot> abadger1999: well, the reasons already there... they're... umm... not terribly believable. [12:26] <tibbs> One of the action items from that call was that Fernando Nasser would write up something indicating why this is necessary. [12:26] <-- Kevin_Kofler has left this channel ("Bye!"). [12:26] <abadger1999> spot: Very true but we accepted them when we passed it the first time. [12:26] <tibbs> That call was about a month ago. [12:26] <tibbs> abadger1999: Well, we accepted them temporarily. [12:27] <abadger1999> We accepted the exception emporarily. [12:27] <spot> abadger1999: yes, but we accepted it on the grounds that they would work on workarounds. [12:27] <abadger1999> But we accepted the rationale as true. [12:27] <spot> no work whatsoever has been done. [12:27] <spot> this either means that A) they have no intentions of using proper workarounds [12:27] <spot> or B) these concerns are not realistic. [12:28] <racor> spot: who is they? jpp or the Fedora folks integrating java? [12:28] <spot> racor: the Fedora folks integrating java [12:28] <abadger1999> spot: Okay. Then deadline is a good thing. Should it be a deadline for new information or a deadline for work to be done on existing information? [12:29] * hansg would like to see more cross (rpm based) distro collaboration not less [12:29] <spot> abadger1999: i think a list of information as to why they need the jpp tag, specifically, how they're using it. [12:29] <abadger1999> +1 [12:29] <racor> spot: OK, IMO, then we should not set them a deadline, but change the rules. [12:29] * Rathann wonders what those "grouped operations on all the Java packages" are... [12:29] <racor> rationale: jpp is an external repo, not of any busines with fedora [12:29] <hansg> I think in the sense of cross distro collaboration we should see jpackage as upstream, and see our own mods as bugfixes to that upstream, which we then merge back upstream [12:30] <spot> racor: i'd like to see the JPackage folks drop the tag, but thats their business. [12:30] <spot> hansg: except that we're acting more like a weird fork of jpp [12:30] <hansg> The current scheme with a fedora specific version after the jpp tag nicely reflects this upstream <-> downstream release, and gives clear info on which upstream release our release is based on [12:31] <racor> spot: jpp is not our business, Fedora is our business and concern. [12:31] <spot> racor: indeed. [12:31] <Rathann> hansg: I think URL: is enough of an upstream indicator [12:31] <hansg> racor: thats a rather narrow view [12:31] <Rathann> we don't need to put it in %{release}, too [12:31] <spot> hansg: perhaps we should tag "gnome" on everything from GNOME? [12:31] <hansg> Rathann ?? URL should point to the _real_ upstream, not to jpackage [12:31] <Rathann> exactly [12:32] <Rathann> oh [12:32] <Rathann> right [12:32] <hansg> Spot: No, but we don't remove part of their versioning either because we find it ugly [12:33] <spot> hansg: its not in their versioning [12:33] <racor> sorry guys, dinner is waiting, I got to quit .. (DST hits) [12:33] <spot> jpackage is no more of an upstream than Fedora is. [12:33] <caillon> we don't use gnome specfiles which sometimes have different release versions, e.g. .jh [12:33] <spot> and when these packages go into Fedora, they're Fedora packages. [12:34] <hansg> "and when these packages go into Fedora, they're Fedora packages", that doesn't sound like a cross fistro collaboration view of things, not _at all_ [12:34] <tibbs> Also, keep in mind that the reasons I heard about in the conference call didn't have anything to do with upstreams or interlacing jpackage versioning with Fedora versioning. [12:34] <Rathann> hansg: well, how does suse or mandriva handle this? [12:34] <hansg> Why should every tpm based distro do its own fork of java packages? [12:34] <hansg> s/tpm/rpm/ [12:34] <spot> or kernel, or glibc, or X [12:34] <hansg> if we can avoid that, that would be a big win! [12:35] <spot> the simple fact is that all distributions package differently [12:35] <hansg> Rathann, I have no idea [12:35] <abadger1999> hansg: The one thing I don't like about the jpackage naming is that it is built around making the Fedora package interleave with the JPackage packages. That means that local changes to make a particular package work in Fedora will be reverted when JPackage releases a new version. [12:35] <spot> i doubt strongly that OpenSUSE would take packages where a "fedora" tag was forced on them. [12:36] <hansg> Yes, but java code depends on a jre, not an OS, so it should be possible (and this has been show) todo pretty distro agnostic packages [12:36] <spot> hansg: so, if they're distribution agnostic, why the jpp tag? [12:36] <spot> why do we care where they came from? [12:36] <spot> they should be properly maintained inside the Fedora repo. [12:36] <tibbs> Also, if they're distro-agnostic, then fine, they're not something to be considered by this committee. [12:37] <tibbs> But if they'\re in Fedora, then they should be regular Fedora packages. [12:37] <abadger1999> hansg: Not entirely true. For instance filesystem placement, gcj compilation.... [12:37] <Rathann> suse doesn't seem to have any packages with jpp in the release [12:37] <Rathann> at least in the official repos [12:38] <hansg> About the interleaving, don't think of it as interleaving. Think of it as version versus release, version should always win, anyways I'm clearly in the minority here, so I'll shut up now [12:38] * spot feels like we're going in circles here [12:38] <Rathann> +1 to the jpp draft from me [12:38] <abadger1999> hansg: version doesn't always win. [12:39] <abadger1999> hansg: version wins when there's another Fedora package with a higher version. [12:39] <hansg> abadger1999, it does over release [12:39] <abadger1999> hansg: It doesn't win when there's an upstream version with a higher version than the Fedora Package. [12:39] <spot> I propose that we ask specifically for a list of information as to why they need the jpp tag, specifically, how they're using it, by May 8th. [12:39] <abadger1999> amend that to: We don't support or encourage it to win. [12:39] <tibbs> spot +1 [12:39] <hansg> unless a 3th party repo which has this version is activated, which is the exact scenario which can be the case with jpackage [12:40] <spot> We'll revisit this at that point, with that data in hand (or not). [12:40] <abadger1999> (As rpm will happily upgrade foo-1.0-fedora.rpm with random.sf.net/foo-1.1.rpm but we are very much against supporting the pieces in that case.) [12:41] <abadger1999> +1 [12:41] <spot> +1 [12:41] <rdieter> +1 [12:41] <hansg> 0 [12:41] <tibbs> hansg: So you don't support asking for more information? [12:42] <hansg> Not with a gun to their head added to it, no [12:42] <f13> hansg: we've been waiting 2~ years now fo this information [12:42] <f13> hansg: without some sort of motivation, I don't believe we'll ever get it [12:42] <tibbs> Simply talking about it again in a month is holding a gun to their head? [12:42] <tibbs> Wow. [12:43] <Rathann> according to rpmdev-vercmp foo-1.0-1jpp is older than foo-1.0-1.1 and foo-1.0-2jpp is newer than foo-1.0-1.1 [12:43] <rdieter> dropping the exception without receiving new information, *is* a gun, of sorts. [12:43] <spot> Rathann: this is why you shouldn't put alpha characters randomly into release. :P [12:43] <Rathann> so for all intents and purposes, we can drop jpp from our release but keep the number that precedes it [12:43] <tibbs> rdieter: Where was that in spot's proposal? [12:43] <hansg> tibbs, quoting you from this irc meeting: "The exception will expire automatically on <date> unless we're presented with sufficient information to consider extending it." [12:43] <hansg> So yes thats a gun to their head [12:43] <tibbs> That was me. [12:43] <f13> Rathann: that was the proposal I came up with over a year ago, which has fallen on deaf jpackage ears. [12:43] <spot> all i am proposing is: [12:43] <tibbs> That wasn't spot's proposal. [12:44] <spot> I propose that we ask specifically for a list of information as to why they need the jpp tag, specifically, how they're using it, by May 8th. [12:44] <rdieter> ok [12:44] <spot> We'll revisit this at that point, with that data in hand (or not). [12:44] <hansg> In that case, spot +1 [12:44] <spot> ok, thats a +5. [12:44] <Rathann> f13: it was a good proposal :) [12:44] <spot> abadger1999: javascript isn't ready, i assume? [12:45] <abadger1999> spot: No. Not enough feedback. [12:45] <spot> Fair enough. Next item: [12:45] <abadger1999> Unless someone here has ideas,I'll draft something, send it to the list, and see if I can get someone to at least flame it. [12:46] <tibbs> Are these sugar activities always noarch? [12:47] <Rathann> hm, python-only -> noarch? can't it contain some binary bits? [12:47] <abadger1999> Lokspretty good. [12:47] <abadger1999> tibbs: "Architecture-specific Activities" [...] [12:47] <hansg> Hmm, I don like: "%define sugaractivitydir /usr/share/activities/" [12:47] <tibbs> Yeah, but above says they always go in /usr/share/activities [12:47] <tibbs> If arch-specific, that would be bad. [12:48] <Rathann> indeed [12:48] <spot> dgilmore: ping [12:48] <abadger1999> Rathann: Maybe we should clarify that. I took it to mean, no C extensions for the python module. [12:48] <hansg> Hmm, I hadn't even looked at that (arch specific under /usr/share) [12:48] <Rathann> abadger1999: ok, but are they always noarch? [12:49] <hansg> I find /usr/share/activities a bit to generic, why not /usr/share/sugar/activities [12:49] <tibbs> Well, it says that they don't have to be. [12:49] <Rathann> if yes, then why python-only should be noarch? [12:49] <abadger1999> Good catch, tibbs [12:49] <hansg> What if another framework comes around which also has activities, why this claim on the global %{_datadir} namespace? [12:49] <caillon> spot, btw, i'd like to ask for clarification on one item with f9 impact if there's time today [12:50] *** knurd is now known as knurd_afk. [12:50] <spot> caillon: ok... [12:50] <tibbs> I agree that /usr/share/activities is a bit generic. [12:50] <spot> since dennis isn't around, i'll ask him for clarification here [12:50] <spot> and we'll revisit it in two weeks [12:50] <hansg> We also have all these too generic kde stuff directly under %{_datadir} while they really belong under %{_datadir}/kde [12:51] <spot> Next item: [12:51] <abadger1999> I wonder if that's changable on OLPC. I wonder if we can have a different value for the macro on OLPC builds vs Fedora builds if it isn't/ [12:51] <spot> basically, this draft argues that whenever gcj is used, it should be conditionalized. [12:51] <hansg> abadger1999, I wonder the same, if it isn't changeable I guess we will have to live with it, grumble [12:52] <Rathann> it's another copy&paste bit to put into specfiles [12:52] <spot> this means that you can't have a package with gcj and noarch bits together. [12:52] <Rathann> I don't like it very much, but I'm not opposed [12:52] <Rathann> I wish it could be handled with an rpm macro [12:53] <tibbs> This is certainly simpler than the conditionals I've seen from some java packages. [12:53] <spot> well, i take it back, i suppose it just enables the gcj bits with the conditional [12:53] <abadger1999> spot: Actually, that was already the case, righyT? [12:53] <rdieter> spot: why not? (or maybe we don't want to encourage the koji can build pkgs as both arch and noarch hack) [12:53] <abadger1999> rigt. [12:53] <tibbs> But isn't there a bcond macro that does this? [12:53] <dgilmore> spot: pong [12:54] <spot> dgilmore: we had a few concerns about the sugaractivities draft [12:54] <dgilmore> spot: shoot [12:54] <spot> dgilmore: 1. /usr/share/activities is very generic [12:54] <spot> dgilmore: is that something OLPC depends on, or could it be /usr/share/sugar/activities ? [12:54] <dgilmore> spot: thats where sugar looks for activities there and ~/Activities [12:55] <dgilmore> spot: it could be changed but will take time [12:55] <spot> ok, 2. What about architecture specific activities? [12:55] <spot> they shouldn't go in /usr/share [12:56] <dgilmore> an example of an architecture specific activity is simcity [12:56] <spot> where does it live currently? [12:56] <dgilmore> /usr/share/activities/SimCity.activity/ [12:56] <spot> hrm. that seems like it really isn't right. [12:57] <spot> i think we'd want a %{_libdir}/activities (at a minimum) [12:57] <spot> although, i'm not sure if OLPC will buy off on that [12:58] <spot> since OLPC has no multilib concerns [12:58] <Rathann> well, Fedora does have them [12:58] <dgilmore> there is a python wrapper for all activities [12:59] <dgilmore> even arch specific ones [12:59] <spot> dgilmore: yes, but the arch specific bits really don't belong under /usr/share [12:59] <spot> the FHS says no. :/ [13:00] <spot> dgilmore: let's think about this some more and table it for now [13:00] <dgilmore> all the examples i can think of that are arch specific should run ok outside of sugar [13:00] <spot> ok FPC folks, can we vote on the ? [13:00] <abadger1999> +1 [13:00] <spot> +1 [13:00] <tibbs> +1 [13:00] <rdieter> +1 [13:01] <hansg> Why _must_ the use of gcj be made conditional? [13:01] <spot> hansg: so that it can be disabled for local builds. [13:01] <tibbs> Although if anyone understands the bcond macros, I'd like to know why they aren't used here. [13:01] <f13> hansg: one reason, enables spec sharing between Fedora and jpp [13:01] <Rathann> +1, with comments above :) [13:01] <hansg> I don't like conditionals, esp not these style, weren't we supposed to have something better then this now? [13:01] <Rathann> tibbs: are they present in EL-4? [13:02] <tibbs> This draft basically eliminates one difference between Fedora and jpackage guidelines. [13:02] <spot> well, thats a +5, so this passes. [13:02] <hansg> Ok, I understand the why now, and I see that this is good to have [13:03] <spot> caillon: you had something for today? go ahead. [13:03] <tibbs> Rathann: I cannot answer that question. [13:03] <Rathann> one more question, why >= 1.0.31? [13:03] <caillon> spot, wanted clarification on [13:03] <Rathann> or is that taken from jpackage as well? [13:03] <hansg> +1 [13:03] <caillon> spot, the static issue there in the last few comments [13:04] <tibbs> Rathann: I imagine there is some version specific dependency; I guess you'd have to see what changed in that version to enable this kind of thing. [13:05] <spot> caillon: so, does SDL depend on that static library? [13:05] <tibbs> caillon: That's an interesting issue we didn't consider. [13:05] <Rathann> the solution in comment #11 isn't good [13:05] <Rathann> it violates packaging guidelines [13:05] <f13> I don't get the issue. Why can't the -static subpackage require the -devel subpackage? [13:06] <Rathann> f13: it should require it, I think [13:06] <hansg> AFAIK, SDLmain shouldn't be used on Unix at all, its a windows thing which does the necessary dll loading (windows dynamic linking stinks?) [13:06] <Rathann> as with any -static package [13:06] <caillon> spot, i'm not the SDL guy, just someone trying to rebuild things against GCC 4.3... but AIUI SDL doesn't require it, but pretty much anything that BR SDL does [13:06] <spot> i think the solution is for packages to properly BuildRequire: SDL-static if they really need it. [13:06] <Rathann> the question is, does every sdl app need that libSDLmain.a to build? [13:06] <Rathann> if not, what spot just said is my proposal as well [13:07] <spot> hansg: you do more SDL than I do... [13:07] <spot> caillon: wouldn't lots of other stuff be breaking here if that was the case? [13:07] <rdieter> since libSDLmain.a is static only, including it in -devel is (should be!) ok. [13:08] <caillon> spot, no idea :) [13:08] <Rathann> rdieter: I disagree (if it isn't needed to build ALL SDL apps) [13:08] <f13> rdieter: that's now how I read the guidelines [13:08] <spot> rdieter: no, i'm pretty sure it needs to be in a -static [13:08] <f13> rdieter: if sdl-devel were entirely made up of just static libraries, thenit could be -devel. [13:08] <hansg> I maintain tons of SDL packages and non require SDLmain, using that under unix is in general ill advised, it isn't needed. It does some magic to hide main vs winmain for windows compatibility and more ugliness like that [13:09] <f13> but since there is both shared /and/ static libraries (not all the same) there needs to be a -static subpackage. [13:09] <rdieter> shrug, that's just my interpretation and intent of those guidelines. [13:09] <hansg> [hans@localhost ~] $ sdl-config --libs [13:09] <Rathann> so, IOW, whatever uses libSDLmain.a should be fixed not to use it? [13:09] <spot> caillon: well, it seems like packages that need that package should properly BR and R it. [13:09] <hansg> -lSDL -lpthread [13:09] <abadger1999> If it's necesssary then I think we want a subpackage [13:09] <hansg> Notice how there is no -lSDLmain there [13:09] <f13> hrm. [13:09] <Rathann> hansg: well, it IS static only [13:09] <f13> sounds like it should be dropped all together, and the offending packages built. [13:09] <abadger1999> subpackage for SDLmain that is. [13:09] <f13> s/built/fixed/ [13:09] <Rathann> hansg: no reason for it to show up there [13:09] <rdieter> there's qt4 as well as a few kde packages are in violation then. [13:09] <hansg> Erm [13:10] <hansg> allegro-config --libs [13:10] <abadger1999> Then it can have a -static or -devel independent of SDL. [13:10] <hansg> -Wl,--export-dynamic -lalleg-4.2.2 -lalleg_unsharable [13:10] <tibbs> We should first consider the intent of the static guideline, and then apply that intent to the package in question. [13:10] <hansg> alleg_unsharable is static too [13:11] <f13> tibbs: I do believe the intent was to isolate the static libs and campaign to remove them all together [13:11] <tibbs> The point was that any application which uses a static library should have a dependency on the -static package so we can find them and rebuild them if necessary. [13:11] <hansg> f13: I think that would be a good solution yes [13:11] <f13> tibbs: and also to be able to find when things require static libs, so when we update a static lib, the other things get rebuilt so that they aren't continually vulnerable in their static copy. [13:11] <hansg> But since F-9 is close, I guess we can just move SDLmain.a to -devel [13:11] <tibbs> The exception about putting them in -devel was to avoid having a pointless -devel package with no libraries. [13:11] * f13 agrees with tibbs [13:11] --> Kevin_Kofler has joined this channel (n=Kevin_Ko@chello213047068123.17.14.vie.surfer.at). [13:12] <tibbs> So, how does that apply to this case? [13:12] * spot remains unsure as to why this package which needs this SDL-static lib can't just use BuildRequires: SDL-static, SDL-devel [13:12] <tibbs> Does the package in question need the static library? [13:12] <hansg> tibbs, AFAIK yes [13:12] <Kevin_Kofler> libSDLmain.a contains the main() function. [13:12] <Kevin_Kofler> A program without a main() function won't run... [13:12] <tibbs> Then it should depend on the -static package at build time. [13:12] <tibbs> So what issue remains? [13:13] <Kevin_Kofler> The guidelines say: [13:13] <Kevin_Kofler> > If a library you depend on _only_ provides a static version your package can [13:13] <Kevin_Kofler> > link against it provided that you BuildRequire the *-devel subpackage. [13:13] <Kevin_Kofler> not the *-static one. [13:13] <f13> Kevin_Kofler: that seems counter to what hansg has just been saying. [13:13] <hansg> No, Kevin is right. [13:13] <f13> hansg: you were just saying it wasn't needed! [13:14] <spot> so, if we fix that to say "If a library you depend on _only_ provides a static version your package can link against it provided that you BuildRequire both the *-devel and the *-static subpackage." [13:14] <f13> Kevin_Kofler: ah, I think that's poorly worded. [13:14] <abadger1999> spot: No [13:14] <hansg> Here is how it _normally_ works, an SDL app has a normal main(), and on windows that gets #defined to SDLmain with SDLmain.a providing the real main [13:14] <abadger1999> I think that defeats the intention of that wording. [13:15] <abadger1999> The intention was, when/if a dynamic version appears, the next rebuild will do the right thing and link dynamically. [13:15] <rdieter> abadger1999: +1! [13:15] <f13> spot: I think it should be: "If a library package you depend on _only_ provides static libraries, your package can link against it provided that you BuildRequire the -devel suppackage" [13:15] <hansg> However some applications have trouble with the #define because of the way they prototype their main, this can be solved by doing the renaming in the source instead of letting the preprocessor do it [13:15] <tibbs> Kevin_Kofler: The quote from the guidelines above do not seem to be correct. [13:15] <Rathann> hm, right, but in this case there won't be a next version with dynamic lib [13:15] <hansg> in this case the app will need SDLmain.a on other platforms too [13:15] <tibbs> At least, I can't see where you pasted that from. [13:16] <Kevin_Kofler> From the page which says that FESCo approval is needed for BRing *-static. [13:16] <f13> Kevin_Kofler: I think that snippit only applies when the library package in question only has static, there are no shared libraries whatsoever, which isn't hte case with SDL [13:16] <tibbs> The guidelines themselves seem quite clear on this to me. [13:16] <caillon> Kevin_Kofler, btw, not sure why i didn't think of pinging you about this, but thanks for joining anyway. you know more about this than i do. :) [13:16] <tibbs> I'm not really sure that there's a question here that isn't answered by the guidelines themselves. [13:16] <hansg> To me the solution is quite simple, since there is no dynamic SDLmain, the static one may and should go in the normal -devel [13:17] <spot> tibbs: yeah, i agree. i'm not sure where that wording came from. [13:17] <Kevin_Kofler> Here's the source: [13:17] <spot> hansg: no, thats really not right. [13:17] <Rathann> obviously libSDLmain.a is a special case [13:17] <f13> so, what I'm really missing, is what is the complaint? If SDL is following the guidelines, and it seems it is by havinging -devel for shared, and -static for the statics, what is the problem? [13:17] <hansg> spot, why not? [13:17] <Rathann> hansg: that's the simple solution [13:17] <Kevin_Kofler> spot: It comes from a page you maintain. ;-) [13:17] <spot> Kevin_Kofler: i probably even wrote it. [13:17] <tibbs> Kevin_Kofler: The text that you quoted above is not present at the url you just gave. [13:18] <spot> tibbs: "If a library you depend on only provides a static version your package can link against it provided that you BuildRequire the *-devel subpackage. BuildRequiring *-devel causes your package to link against the dynamic version once the library starts providing one and your package is rebuilt." [13:18] <hansg> f13, " havinging -devel for shared, and -static for the statics" only applies when there are both versions of a lib, in the libSDLmain case there only is a static version [13:18] <spot> tibbs: its there [13:18] <Kevin_Kofler> The "not the *-static one" text isn't there, but that wasn't a quote. [13:18] <tibbs> That means that you buildrequire both the -static and the -devel packages. [13:19] <Rathann> I propose a separate SDL-devel-SDLmain package with the problematic library only [13:19] <f13> hansg: no, you're talking about versions of individual library files, whereas the guidelines are talking about /any/ shared, vs /any/ static. [13:19] <spot> tibbs: which does defeat the point, but its the best solution i see [13:19] <tibbs> Crap, or am I confused now? [13:19] <hansg> f13 are they? [13:19] <abadger1999> Rathann: +1 [13:19] <f13> hansg: that was my understanding. [13:19] <rdieter> f13: I'd rather clarify the guidelines to say something like "in the case of *both* shared and static versions of a library are provided, the static one should go in -static" [13:19] <abadger1999> Rathann: Maybe SDL-SDLmain-devel, though [13:19] <hansg> But that it is not why they literary say! [13:20] <Kevin_Kofler> FWIW, rdieter's proposal is what I've been arguing for in the bug report. [13:20] <f13> hansg: which is why we have humans to parse them and adjust them for clarity. [13:20] <Rathann> abadger1999: I wasn't sure about the name :) [13:20] <hansg> And the logical thing would be to put SDLmain.a in -devel, as when there are only static libs, we put them in -devel [13:20] <spot> So, there are two use cases: [13:20] <f13> hansg: the intent may be different than the literal translation. [13:20] <tibbs> Unfortunately IRC really isn't the place for this. [13:20] <spot> 1. static libs and dynamic libs [13:20] <rdieter> hansg: +1 [13:20] <spot> 2. static libs only [13:20] <f13> spot: 3. [13:20] <tibbs> In the past we've said that we'd only address written drafts here, and I guess this is what happens when we go off-script. [13:20] <f13> static libs of one library only, dynamic libs of different libraries in the same package. [13:21] *** gregdek is now known as gregdek_gone. [13:21] <rdieter> f13: foreach lib in *.so *.a ; case 1 2 ; done [13:21] <thm> problem is the guidelines think of a single library (static or dynamic) per package [13:21] <Rathann> yeah, we should continue this on fedora-packaging [13:21] <abadger1999> What about subpackage? Both Rathann and I have suggested it. [13:22] <spot> abadger1999: would violate the guidelines as written. [13:22] <rdieter> abadger1999: -1 needless complication (and I'd rather sort out the guidelines intention first) [13:22] <f13> rdieter: so again, I feel you're trying to apply the 'package' guidelines to individual 'files'. I don't believe that was the original intent of the guidelines [13:22] <f13> rdieter: as now, if you just BR the -devel package, we have no way of knowing that you actually used static libraries. [13:22] <rdieter> f13: ok, I guess we just disagree then. :) [13:22] <abadger1999> spot: Depends on your definition of "package" I guess. [13:22] <spot> this is almost getting Clintonesque. [13:22] <abadger1999> (I've gotten in trouble for that before as hans canattest :-/) [13:23] <spot> the idea behind the -static package was this [13:23] <spot> we could track packages that used static libraries by looking at BuildRequires [13:23] <rdieter> f13: right, my intention was -static let's you know if static libs were used, but shlibs were available. [13:23] <spot> if SDL packages need this static library, great, let them BR it. [13:24] <spot> lots of SDL packages don't need it. [13:24] * hansg isholding a crying baby now so don't exprvt much input from me atm [13:24] <rdieter> that's it! we made the baby cry. stop now. :) [13:24] <f13> I have no voting power, but I agree with spot [13:25] <rdieter> I just think forcing -static pkgs for which there are no shlib equivalents is a little silly. [13:25] <f13> caillon: question, what is the F9 impact here? [13:25] <spot> i agree that the static section could use some clarification (and possibly simplification), but the spirit of putting static bits in -static whenever any dynamic libs (whether they are a whole set replacement or not) are present. [13:26] <caillon> f13, several gcc rebuild failures depend on SDLmain.a [13:26] <f13> rdieter: if you brought the static into -devel, -devel would have to provide -static, and then /every/ SDL app would pop as having "static" requirements. [13:26] * hansg just realizes this applies to allegro too [13:26] <f13> rdieter: it would ruin our ability to track the things that really do require static libraries. [13:26] <Rathann> the way I see it, puting it in -devel defeats the intent of keeping static libs separate and putting it in -static may make a package linking against it link static versions of other SDL shared libs [13:27] <Rathann> hence my and abadger1999's proposal seems sane [13:27] <rdieter> f13: sorry, being selfish thinking as packager only here. it's an increased burden by changing what I thought the intention was. [13:27] <rdieter> I thought the intention was to simplify things for packagers (mostly) [13:27] <f13> rdieter: this is. [13:27] <hansg> allegro has a liballeg_unsharable which contains non pic asm code liballeg.so needs [13:27] <rdieter> not primarily be a means of tracking where static libs were being used. [13:28] <f13> rdieter: it helps the maintianer realize with a static library they require changes. [13:28] * spot thinks about Rathann's point [13:28] <f13> rdieter: if we just chuck the static library in the same package with all the other shared libraries, it increases the difficulty to track just static changes. [13:28] <rdieter> f13: but if they BR: foo-devel foo-static, they'll never notice. [13:29] <f13> rdieter: yes they will, because of the -static, and because they'll have to be on the initialcc of the package. [13:29] <Rathann> make it SDL-SDLmain-static if you want to have -static in the name [13:29] <spot> i would rather have a package linking against 99% shared and 1% static than 100 static [13:29] <hansg> -1 to a seperate subpackage [13:29] <f13> hansg: is there a way to prevent it from static linking to the rest of the static libs? [13:29] <hansg> SDLmain.a belongs in -devel, as there is no shared equivalent [13:30] <rdieter> hansg: seems we're in the minority on that viewpoint. [13:30] <hansg> f13, I've lost you here, need more context [13:30] <spot> well, if we make the case that static libraries with no shared library equivalent stay in -devel... [13:31] <spot> if they ever grew a shared library equivalent, they'd need to move into -static [13:31] <hansg> spot +1 [13:31] <f13> hansg: if we were to put main.a in -devel, the -devel subpackage would have to grow a Provides: -static. Then everybody BRing -devel would suddenly trigger as requiring "static" libraries [13:31] <rdieter> yes [13:31] <spot> but we wouldn't need a -static Requires in -devel [13:31] <Rathann> if a bug is found in libSDLmain, you need to rebuild all packages which BRequire it anyway [13:31] <hansg> f13 why? [13:31] <f13> spot: which would then trigger false positives on repo searches [13:31] <abadger1999> hansg: Yes it belongs in a -devel. No it does not belong in SDL-devel. [13:31] <spot> f13: i'm not sure I understand this [13:31] <f13> hansg: there is now way to tell "I BR foo-devel for the shared, not for the static in there" vs "I BR foo-devel for the static" [13:32] <Rathann> how do you know which packages are linked against libSDLmain.a? [13:32] <spot> we're way overtime here. [13:32] <spot> i'll try to come up with a draft here. [13:32] <spot> and i'll send it to the list. [13:32] <rdieter> spot: thx, you're a saint. [13:32] <f13> I seriously don't understand what's so difficult about changing a couple packages to grow a BR on -static. [13:32] <spot> f13: i'll come talk to you [13:32] <hansg> Rathann, you don't know which packages are linked against libSDLmain.a [13:33] <Rathann> hansg: exactly [13:33] <spot> ok guys, we're done for the day. [13:33] <spot> thanks all. [13:33] <Rathann> hence it shouldn't be in -devel [13:33] <Kevin_Kofler> Easy: they failed to rebuild in the GCC 4.3 mass rebuild. ;-) [13:33] <caillon> f13, fwiw, many maintainers don't notice that their package failed rebuild. i doubt they'd notice a static lib changed and needs rebuild either. not that it's an argument one way or another. [13:33] <hansg> Rathann, I see your point [13:33] <abadger1999> We could set the virtual provide to SDLmain-static instead of SDL-static but then we should also have a virtual provide for SDLmain-devel.... which is basically a subpackage [13:33] <Rathann> yeah, let's continue this in the mailing list [13:34] <f13> caillon: sometimes it's not about the packagers noticing, but about the security team seeking out and fixing things. [13:34] <Rathann> Kevin_Kofler: that's only because libSDLmain was moved to -static, isn't it? [13:34] <caillon> fair enough [13:35] <Rathann> hansg: and with BR: SDL-SDLmain-static (or something similar), you can track those packages [13:35] <hansg> bye all (baby is becoming heavy) [13:35] <Rathann> :) [13:35] <-- hansg has left this server ("Leaving"). [13:35] <Rathann> ok, thanks everyone, see you [13:36] <abadger1999> Later [13:36] <-- Rathann has left this channel ("Leaving."). | http://fedoraproject.org/wiki/Packaging:Minutes20080408 | CC-MAIN-2018-17 | refinedweb | 7,251 | 68.3 |
Time routines
These functions are declared in the main Allegro header file:
#include <allegro5/allegro.h>
ALLEGRO_TIMEOUT
typedef struct ALLEGRO_TIMEOUT ALLEGRO_TIMEOUT;
Represent a timeout value. The size of the structure is known so it can be statically allocated. The contents are private.
See also: al_init_timeout
al_get_time
double al_get_time(void)
Return the number of seconds since the Allegro library was initialised. The return value is undefined if Allegro is uninitialised. The resolution depends on the used driver, but typically can be in the order of microseconds.
al_init_timeout
void al_init_timeout(ALLEGRO_TIMEOUT *timeout, double seconds)
Set timeout value of some number of seconds after the function call.
For compatibility with all platforms,
seconds must be 2,147,483.647 seconds or less.
See also: ALLEGRO_TIMEOUT, al_wait_for_event_until
al_rest
void al_rest(double seconds)
Waits for the specified number of seconds. This tells the system to pause the current thread for the given amount of time. With some operating systems, the accuracy can be in the order of 10ms. That is, even
al_rest(0.000001)
might pause for something like 10ms. Also see the section on Timer routines for easier ways to time your program without using up all CPU. | http://liballeg.org/a5docs/5.2.1/time.html | CC-MAIN-2017-39 | refinedweb | 194 | 51.34 |
This article will help you get started with concurrency and will also introduce you to the features C++ offers in order to support concurrent programming. In this series of articles, I will not only talk about what concurrent programming is but we’ll also be looking into the features that C++ standards 11, 14 and 17 have brought to support concurrent programming.. Yet, that’s Stone Age talk.
Note This article assumes your basic knowledge, familiarity, and comfort with C++.
Concurrency and Concurrent Programming
Concurrency refers to the idea of executing several tasks at the same time. This can be achieved in a time-shared manner on a single CPU core (implying ‘Multitasking’) or in parallel in case of multiple CPU Cores (Parallel Processing).
Concurrent program is a program that offers more than one execution paths that run in parallel or simply a program that implements the concurrency. These execution paths are managed by means of threads that execute concurrently and work together to perform some task.
Thread describes the execution path through the code. Each thread belongs to a process (the instance of an executing program that owns resources like memory, file handle etc.) as it is executing the code of the process, uses its resources, and there can be multiple threads being executed at the same time inside a process. Each process must have at least one thread that shows the main execution path.
Concurrency and Parallelization
When talking about computations and processing, concurrency and parallelism seem pretty similar. They are closely related as they can use the same software and hardware resource but yet different concepts so I feel the need to highlight the difference here.
Concurrency structures the program by allocating multiple control flows in it. Conceptually, these flows are executed parallel, although, in fact, they can be executed on a set of processors (cores) or on one processor with context switching (switching the CPU from one process or thread to another). This approach is otherwise known as multi-threading. Now the true parallelism is achieved through Parallel programming that aims at speeding the execution of a certain task up by means of using multiple equipment items (processors, cores, or computers in a distributed system). The task is divided into several subtasks that can execute independently and uses their own resources. Once all subtasks are complete, their results are merged. In practice, these two approaches can be combined to complement each other. For example, allocation of independent concurrent subtasks can help both, structure a program and improve its performance.
Why Concurrency?
Now that we have developed a basic understanding of what concurrency is and why we should be considering it, let’s move to some C++ specifics.
The Threading Library
As I mentioned earlier, C++ did not have any standard support for concurrent programming before C++ 11. You had to rely on libraries that were OS-dependent like pthread for Linux or Windows API on Windows. Though the concepts were same, there was a significant difference in how you implement them. The need for a portable concurrent code was met by introducing the multithreading capabilities in standard C++11 that consists of two parts.
Standard Threading API provides you a portable way to work with threads using the <thread> header while memory model sets the rule that threads will follow when sharing data in memory.
C++14 did not bring a lot to the table but introduced Reader-Writer Locks to minimize the bottleneck. C++17 added more to the recipe and made most of the algorithms of the Standard Template Library available in a parallel version. Though, this was a brief overview of what C++ offers to support concurrent programming and let’s not forget synchronization, Atomic variable and high-level asynchronous programming that we’ll be exploring later in the article. Let’s start seeing things in action beginning with multi-threading.
Multithreading
Thread is basically a lightweight sub-process. It is an independent task running inside a program that can be started, interrupted, and stopped. The following figure explains the lifecycle of a thread.
More than one thread can be executed concurrently within one process (which refers to the idea of Multi-threading) and share the data, code, resources such as memory, address space, and per-process state information. Each C++ application has one main thread, i.e., main() while additional can be created by creating the objects of std::thread class.
Let’s break things down here. We created a simple function "func" that simply prints a line to the screen; nothing fancy. std::thread t1(func) is going to launch a thread that will execute our function while join() will make sure of waiting until t1 terminates. Let’s make a few changes to the above program to examine the workflow.
That’s what the output of the above function looks like. Yours could be a little different. The main function thread execution could be in the beginning or anywhere. The reason is that there is no strict ‘sequence’ of execution rather both threads execute at the same time (That’s what concurrency is about right!) but the main function will always exit at the very end. Here, join() makes sure that t1 terminates before main function exits.
Joining and detaching threads
When you create a thread, you need to tell the compiler what your relationship with it is going to be. Destructor for std::thread class checks whether it still has any OS thread attached to it and will abort the program if it has. Try experimenting with the above code by removing join() and though it will compile fine but will abort when run. To avoid abortion, you must join a thread or detach from it.
You can check if a thread is joinable or not by simply calling joinable() member function. This function returns true if the thread is joinable or false otherwise (a thread cannot be joined more than once or already detached). A simple check can be applied before joining the thread. Observe the following:
But why bother applying checks when you have another option available to make execution happen? Surely our examples would work fine if you replace join() with detach() . But here’s the catch. detach() make a thread to run in the background which can result in daemon thread (Linux terminology). You don’t know when a detached thread is going to finish so extra care is needed when using references or pointer (as things can go out of scope when a thread finishes executing). That’s the reason why join() is preferable in most conditions.
Other ways of creating threads
Using functions is just one way to creating and initializing thread. You can also use functor (function object of the class that overloads operator ()). This can be done as below.
Now, all we need is to initialize a thread by passing an object of our above defined class to the thread constructor.
You can also use a lambda expression (functional way) to achieve the same functionality.
Identifying Threads
Now that we are working with multiple threads, we need a way to distinguish between different threads for the reasons of locking and debugging. Each std::thread object has a unique identifier that can be fetched using a member function of std::thread class.
It is to be noted that if there’s no associated thread, then get_id() will return a default constructed std::thread::id object and not of any thread. Let’s see an example that will clarify the idea.
Let’s stop here for a while and talk about std::this_thread. It is not a member function rather a namespace that contains global functions related to threading. Here are some functions that belong to this namespace.
We’ve seen get_id() already in action. You can read more about the namespace here or else Feel free to explore the namespace and work around other functions.
Passing arguments to the thread
So far, we’ve just created threads using functions and objects but without passing any arguments. Is it possible to pass arguments to the threads? Let’s see.
We just created a function passing an integer as arguments to the function. Let’s try to call the function by invoking thread as we did before.
And it works. To pass arguments to the thread’s callable; you just need to pass additional arguments to the thread constructor. By default, all arguments are copied into the internal storage of the new thread so that it can be accessed without any problem. But what if we are to pass it by reference? C++ provides std::ref() wrapper to pass arguments by reference to the thread. Let me explain it with an example.
Now it should be clear that if we don’t pass the argument by reference in the above case, the number would still be 15 even after the external thread execution. You can go ahead, try it and see for yourself.
Move Semantics (std::move())
Time for something extra sweet. Let’s compare the functions from our last examples.
Note that we passed our string literal in the first function by reference but we didn’t have to use std::ref() in order to access it while our approach with an integer is different. The reason behind is that the string literal would be used to create a temporary string object which satisfies the needs for const reference while integer needs to be wrapped in std::ref() to be passed by reference.
Although it seems nice at first glance that we don’t need to use any kind of wrapper, the creation of temporary objects is like an obstinate wart which tends to slow down the programs. C++ introduced move semantics to be used instead of coping the expensive objects with rvalue references (An expression is an rvalue if it results in a temporary object) and passing temporaries. For example, here’s a function that expects an rvalue reference to be passed.
And I can use it as follows:
Now the call to move() is going to move the string str to the function rather than copying it. Here’s another interesting thing, std::thread itself is movable but not copy-able. It means that you can pass the ownership of OS thread between the std::thread objects but only one instance will own the thread at any one time.
t1 is executing our function func so now if I want to create another thread t2, the move() will move the ownership of thread t1 to t2 (t2 is now managing the OS thread). If you try assigning a thread that is already managing some OS thread, you’ll get an exception.
But how many threads can we create? (hardware_concurrency())
We’ve been talking about creating and manipulating threads but how many of them can be created specifically? That’s something known as hardware concurrency. You can get the numbers on your machine as follow:
The number displayed could be the cores on your machine, as for me, it is 4. But that’s wrong to ask. Hypothetically, you can create as many threads as an amount of memory on your machine but then the scenarios arise where your concurrent code would execute much slower than sequential so the right question is how many threads should you create. To answer this question, there are a number of factors to be considered. Bear with me for a little theory.
Computation intensive program
If your code is number crunching and involves a lot of computations and processing huge amounts of data then the suggested number of threads should be less than or can be equal to the number of cores on your machine.
IO intensive program
On the other hand, if your code is IO intensive -- reading or writing a large amount of data -- then the suggested number of threads are given as follow.
No. of threads <= No. of cores / 1- blocking factor
While the blocking factor is the time a task will be spending before being blocked, the reason I’m emphasizing this number is that if you exceed this limit, there is a greater chance that the performance of your program will go down. Just because you can create as many threads as you want does not mean you should.
What’s next?
So far, we’ve only seen how we can create and manipulate threads. But we haven’t talked about the part “Data is shared between the threads”. Simultaneous access to the same resource can give birth to a numbers of errors and thus create chaos. Consider a simple scenario where you want to increment a number and also output the result.
Now when executing the above function concurrently, the threads will access the same memory location and one or more thread might modify the data in that memory location which leads to unexpected results and the output becomes un-deterministic. This is called a race condition. Now, the question arises of how to avoid, find, and reproduce the above condition if already occurred. It’ll be picking up the things right from here in my next article of the series. Until then, feel free to explore and learn on your own.
View All | https://www.c-sharpcorner.com/article/programming-concurrency-in-cpp-part-1/ | CC-MAIN-2021-21 | refinedweb | 2,214 | 61.87 |
Odoo Help
Odoo is the world's easiest all-in-one management software. It includes hundreds of business apps:
CRM | e-Commerce | Accounting | Inventory | PoS | Project management | MRP | etc.
How can I display data from database in form view
def _sel_func(self, cr, uid, context=None): obj = self.pool.get('stock.location') ids = obj.search(cr, uid, []) res = obj.read(cr, uid, ids, ['id','name'], context) res = [(r['id'],r['name']) for r in res] return res
Currently I'm using this code but what if two or more tables are needed to get the desired field. How can I do that using a sql query or any other approach?
About This Community
Odoo Training Center
Access to our E-learning platform and experience all Odoo Apps through learning videos, exercises and Quizz.Test it now | https://www.odoo.com/forum/help-1/question/how-can-i-display-data-from-database-in-form-view-32584 | CC-MAIN-2017-26 | refinedweb | 136 | 66.94 |
Today's blog post is by a guest community contributor, Rizwan Reza. Rizwan is an active member of the Rails community, and as of late, has been working to clean up the overgrown Lighthouse queue. We're happy to have him write for those seeking advice on deploying on a Platform as a Service.
Stop! I'd like to tell you something important, but it may be a bit shocking, so you should probably have a seat. Here goes: everything you knew about working with routes in Rails 2... is history! With Rails 3, you've got to roll up your sleeves, unlearn what you learned, and route the new way around. And this time, it's faster, cleaner and a lot more Ruby-like.
In this post, we'll walk through the underpinnings of Routes in Rails 3. They've been rewritten—for good reason—and after we get through the explanation, I'm confident you'll agree.
Let's start by looking at some code; here's the new DSL, in its full glory:
resources :products do resource :category member do post :short end collection do get :long end end match "/posts/github" => redirect("")
Now check out the old way of doing it:
map.resources :products, :member => {:short => :post}, :collection => {:long => :get} do |products| products.resource :category end
As you can see, the example from Rails 3 is much cleaner and more Rubyish. So let's jump right in and walk through a quick overview of how you'd define different types of routes in Rails 3.
Default Route
The default route in Rails 3,
match '/:controller(/:action(/:id))', is much more explicit, as the parenthesis denote optional parameters.
Regular Routes
Rather than defining different keys for controller and action, you just have
catalog#view, which is pretty awesome.
match 'products/:id', :to => 'catalog#view'
In Rails 2, you would've done:
map.connect 'products/:id', :controller => 'products', :action => 'view'
Named Routes
Named Routes generate helpers like
posts_url and
posts_path, rather than manually defining the hash to action and controller in helper methods like
link_to:
match 'logout', :to => 'sessions#destroy', :as => "logout"
The key
:as specifies a name to generate helpers. In Rails 2, you would have done:
map.logout '/logout', :controller => 'sessions', :action => 'destroy'
Empty Route
The root of the web site is the empty route. Whereas Rails 2 added a nice shortcut to it, Rails 3 simplifies things even further:
# Rails 3 root :to => 'welcome#show' # Rails 2 map.root :controller => "welcome", :action => 'show'
Shorthands
The revamped routes in Rails 3 sport some nice shortcuts to commonly used routes. There are two types of shorthands. First, the
:to shorthand allows you to skip the
:to key and directly designate the route to the matcher:
match "/account" => "account#index" match "/info" => "projects#info", :as => "info"
Second, the
match shorthand allows you to define a path and controller with its action at the same time:
match "account/overview" # identical to match "account/overview", :to => "account#overview"
Verb Routes
While you can limit a route to an HTTP request through
:via, it's a nice added convenience to have Verb routes. Adding sugar on top, you can even use shorthands with them:
get "account/overview" # identical to match "account/overview", :to => "account#overview", :via => "get"
Keys
The match method (as well as the verb shorthands) take a number of optional keys.
:as
The
:as key names the route. You can then use named route helpers wherever
url_for is available (such as controllers, tests, and mailers). Resource routes (using the
resources helper) automatically create named routes, as in Rails 2.3.
match "account/overview/:id", :as => "overview" # in your controller overview_path(12) #=> "/account/overview/12"
:via
Allows you to specify a set of verbs, so only those HTTP requests are accepted for a route.
match "account/setup", :via => [:get, :post]
Rack
Rack is a sweet interface to web servers that provides unified API to Ruby frameworks. Most if not all Ruby frameworks are built on top of Rack these days. The recent built-in support for Rack means your application is not bound to being Rails specific. You can have parts of your application handled by any Rack supported framework, be it Sinatra, Cramp or something else. You can skip the Rails stack altogether and pass on the request to a Rack app.
Here's an example of a Sinatra app:
class HomeApp < Sinatra::Base get "/" do "Hello World!" end end Rizwan::Application.routes do match "/home", :to => HomeApp end
And here's an example of a Rack app:
match "/foo", :to => proc {|env| [200, {}, ["Hello world"]] }
match 'rocketeer.js' => ::TestRoutingMapper::RocketeerApp
RocketeerApp = lambda { |env| [200, {"Content-Type" => "text/html"}, ["javascripts"]] }
Resourceful Routes
Since Rails 1.2, resourceful routes have been the preferred way to use the router. Recognizing this fact, the Rails core team has added some nice improvements. Take a look at this typical RESTful route in Rails 3:
resources :products
This would generate all the neat helpers we have come to love and would also route the URLs accordingly. Just like before, you can also add multiple resources in a single line:
resources :products, :posts, :categories
More RESTful Actions
As you know, you're not limited to the seven actions that RESTful architecture provides, but can also define more actions in a resource. Having said that, you might want to keep an eye open if you're defining lots of actions in a single resource, as they can be turned into separate resources.
We can add RESTful actions to this resource in a couple of ways. Here's a few
collection RESTful actions inside a block:
resources :products do collection do get :sold post :on_offer end end
And take a look at this inline member RESTful action:
resources :products do get :sold, :on => :member end
Not only that, but you can also redefine to extend the scope of the default seven RESTful actions:
resources :session do collection do get :create end end
create actions, which usually only accepts POST requests, can now accept GET requests as well:
resource :session do get :create end
Nested Resources
In Rails 2, nested resources were defined by a block or by using a
:has_many or
:has_one key. Both of these have been superseded by a block, giving them a more Rubyish interface to defining associated resources.
Here's a route for a project that has many tasks and people:
resources :projects do resources :tasks, :people end
Namespaced Resources
These are especially useful when defining resources in a folder; it doesn't get much cleaner than this:
namespace :admin do resources :projects end
Renaming Resources
You can also rename resources through the
:as key. This code uses
:as in resourceful routes to change the products path to devices:
namespace :forum do resources :products, :as => 'devices' do resources :questions end end
Restricting Resources
Resources can be restricted to only specified actions.
resources :posts, :except => [:index] resources :posts, :only => [:new, :create]
Altering Path Names
You can define a different path name for a particular REST action. This helps you customize your RESTful routes. This code will route /projects/1/cambiar to the edit action.
resources :projects, :path_names => { :edit => 'cambiar' }
The Redirect Method
The newly added redirect method in Rails 3 provides a level of convenience not present before. For example, it can redirect to any path given and eventually, can also pass on to a full-blown URI, something previously accomplished by Rails plugins like redirect_routing.
Moreover, the redirect method also introduces generic actions. Unique to Rails 3, generic actions are a simple way to provide the same action to complex paths, depending on what's passed to redirect.
This code will redirect
/foo/1 to
/bar/1s:
match "/foo/:id", :to => redirect("/bar/%{id}s")
This code will redirect
/account/proc/john to
/johns.
match 'account/proc/:name', :to => redirect {|params| "/#{params[:name].pluralize}" }
Note that
redirect cannot be used in a block as opposed to other constraints and scopes.
The Constraints Method
Constraints allow you to specify requirements for path segments in routes. Besides that, they also allow you to use a handful of methods to verify whether or not something matches a given criteria. Like a route that checks if the request is AJAX or not, for example.
In this code, we're using a regular expression, and the route has been restricted to only allow one digit IDs to pass through:
match "/posts/show/:id", :to => "posts#index", :constraints => {:id => /\d/}
Scope
When the scope method is passed along a symbol, it assumes the symbol is a controller. When the argument is a string, the scope method prepends that string to the beginning of the path.
Scope can also have
path_segments, which can be constrained, giving us greater flexibility in routes.
controller :articles do scope '/articles', :name_prefix => 'article' do scope :path => '/:title', :title => /[a-z]+/, :as => :with_title do match '/:id', :to => :with_id end end end scope :posts, :name_prefix => "posts" do match "/:action", :as => "action" end scope ':access_token', :constraints => { :access_token => /\w{5,5}/ } do # See constraint here resources :rooms end
As you can see, when scope is given a string as its argument, it prepends to the path, something that was accomplished through
path_prefix in Rails 2.
name_prefix is essentially the same as before.
Optional Segments
Unlike all the previous versions of Rails, path segments can now be optional in routes. Optional segments don't necessarily have to be path segments, which are passed as parameters to the action. The default route is a good example of optional segments in use. Here, both
/posts/new and
/posts will be redirected to the create action in posts controller, but
/posts/edit will not work:
match 'posts(/new)', :to => 'posts#create'
This is an optional path scope that allows to have a prepended path before a resource:
scope '(:locale)', :locale => /en|pl/ do resources :descriptions end
Pervasive Blocks
As evident from the examples, routes in Rails 3 exhibit pervasive blocks for almost all the methods you'd normally want to pass a block to, helping you achieve DRY in
routes.rb.
controller :posts do match 'export', :to => :new, :as => :export_request match '/:action' end
Right now, most Rails developers (and those doing Rails deployment with Engine Yard) wouldn't use all of these methods, but when the need arises—when you need to define more complex routes—you might appreciate having the above information handy. You don't need to use a plugin or a hack when you know it's built right in. With Rails 3 and Rails hosting on Engine Yard, Routes rock at a whole new level.
Questions and comments welcome! | https://blog.engineyard.com/2010/the-lowdown-on-routes-in-rails-3/?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+engineyard+%28Engine+Yard%29 | CC-MAIN-2014-23 | refinedweb | 1,770 | 56.69 |
Think about how web pages have been built over the years. If you were around for the early days (c. 1995), you probably built a web as pure HTML using either a text editor or some early HTML editor. Within a few years, there were scripting language technologies such as classic ASP with VBScript. Programmers began building web pages as mostly static HTML, with some VBScript thrown in to build out dynamic or data-driven areas — but the page was still mostly static HTML. Then ASP.NET came along and introduced the code-behind concept. C# and VB.NET in the Visual Studio environment made writing bug-free code much easier. Now, your entire page could be built out programmatically from code. So what did you do? You probably just brought your class ASP programming style to ASP.NET and continued to build pages as a mix of static text and code. This technique was even simplified by the "toolbox" concept in Visual Studio which provided some pretty impressive support for dropping controls on pages and setting their properties — about as good as you can get to build an entire web site by drag-and-drop.
These methods for building web pages exist along a spectrum. At one end is the purely static HTML page. At the other end, you can build a web page entirely from code creating all of your HTML elements in the code-behind. Then there is the mushy ground in between where pages are a mix of static HTML intermingled with sections of script to build out any data-driven portions of the page. I am sure you have seen some classic ASP pages a lot of static text, interspersed with five, ten, or even more snippets of VBScript. Not a great design, but perhaps the best one could do with the technology available at the time.
Actually, my the first data-driven web site I ever built was a project for a web-programming class in 1995. This predated Java and VBScript. At that time you really had only the two end points of the spectrum. You could built pages as purely static HTML. But if you wanted any data driven component to the web page at all, you had to build the entire web page programmatically using cgi-bin programming (Perl was also an option). Unfortunately, programming cgi-bin was very cumbersome and a nightmare to debug.
My first commercial data-driven web project was written in classic ASP with VBScript using Microsoft's old Visual InterDev. Frankly, the result was a mess and barely worked. It was then ported to ASP.NET in C#. Being new to ASP.NET, the first iteration of the port was pretty much just recoding the script elements in C# without much change to the architecture. I am sure many of you have seen such ports, as I have on other projects written by other programmers. In the processing of the second iteration in ASP.NET, I found myself moving more and more code into the code-behind. I began building out my own library of ASP.NET classes and adopting more object-oriented techniques. For years, most of the work I did was Windows desktop applications in C++ and MFC so I was comfortable with object-oriented design and rich class libraries. On this and several other projects, I found that the more complicated the page logic, the better off it was in the code-behind. Finally, after working on this and several other projects, I decided to completely move all code to the code-behind for a new project. In other words, I moved my web page programming entirely to the end of the spectrum. As a result, I can build more robust data-driven web applications much faster than when I try to write HTML.
If all or even part of this story sounds familiar, you may want to consider this technique.
We have come a long way since cgi-bin. Using C# or VB.NET, it is now very easy to build your web pages entirely dynamically in the code behind. However, if your web programming skills evolved over the period of classic ASP, then you probably haven't thought much about this method of building web pages. Once you learn it, it is in fact a very easy technique and has some great benefits, but it requires a change in the way you think about web page programming.
The purpose of this article is to introduce you to the idea of building your data-driven web pages dynamically in the code behind. I will get you started on building a class library of your own to make this technique more efficient. I will show you how to build out pages dynamically. Finally, I will explain both the benefits and disadvantages.
You should read this article if:
Building out your web pages dynamically in the code behind will not greatly simplify your web site development unless you have a rich library of code classes. The basic ASP.NET classes are impressive, but they are not enough. You will need to enhance them in your own library. If just try to do build your pages with the standard ASP.NET classes, you will never see the advantage of the method.
Building your own code library means:
The project includes some example classes to get you started.
We are building our web pages from code. That means no more typing HTML. In fact, we want to avoid typing HTML tags at all (or at least minimize it). Any HTML tags that you actually write should be in a class specifically designed to write HTML tags. This allows us to take advantage of the Visual Studio features such as auto-complete/intellisense and dynamic syntax checking. One such class is the
TextWriter class.
Here is a portion of the class:
public class TextWriter { public TextWriter() { } static public string MakeParagraph(string s) { return "<p>" + s + "</p>"; } static public string MakeLine(string s) { return s + "<br />"; } static public string MakeH1Text(string s) { return "<h1>" + s + "</h1>"; } }
The purpose of the class is simply to write HTML formatted text. Note that all of the members are static. This is just a small sample of the types of functions that could be included in the text writer class. Anytime you find yourself writing an HTML tag outside of this class, perhaps it is time to add another function to the class.
In a code sample below, we will see this class in action.
A
Literal control is simply a control that contains literal HTML markup. When the HTML for the page is generated, any text for the control is simply written out to the page — literally. When you build pages dynamically, you will use a lot of Literals. So it makes sense to derive your own
Literal class as shown below. Note the use of a constructor to set the text value making programming the control more efficient. Also note the use of the
TextWriter class.
public class MyLiteral : Literal { public MyLiteral(string strText) { Text = strText; } public void AddParagraph(string strText) { Text += TextWriter.MakeParagraph(strText); } }
Admittedly, there is not much to this extended
Literal class, although even this small class enhancement will save you a couple of lines of code for each use of the
Literal. You will find yourself adding a lot of custom functionality to more complex web controls.
In ASP.NET,
Label controls produce text enclosed in <span> tags.
Panel controls produce text enclosed in <div> tags. To make it easier to work with these controls and set their CSS styles, you should derive your own classes from these controls. Here is an example of your own custom
Panel class.
public class MyPanel : Panel { public MyPanel(string strClass) { this.CssClass = strClass; } // Add a child panel to this panel public MyPanel AddDiv(string strClass) { MyPanel panel = new MyPanel(strClass); Controls.Add(panel); return panel; } // add a child panel to this panel public MyPanel AddDiv(string strClass, string strText) { MyPanel panel = AddDiv(strClass); panel.AddLiteral(strText); return panel; } // Add a literal control with text to this panel public Literal AddLiteral(string strText) { Literal lit = new Literal(); lit.Text = strText; Controls.Add(lit); return lit; } // Add a label control with text to this panel public Label AddLabel(string strClass, string strText) { Label label = new Label(); label.Text = strText; label.CssClass = strClass; Controls.Add(label); return label; } public void AddParagraph(string strText) { AddLiteral(TextWriter.MakeParagraph(strText)); } } // end of class declaration
To make this even more efficient, you may want to further subclass
MyPanel. Perhaps you have a panel that displays a menu bar. You can create a class
MenuPanel and add it to your pages wherever it is needed.
As a general rule, consider deriving your own subclasses from any of the
System.Web.UI controls including tables, text boxes, check boxes, buttons, etc. For example, building a table programmatically can be tedious when you have to do it over and over because you must repeatedly set properties for each cell and row. Creating your own table class can make using tables much easier.
Good object-oriented design means you are not writing the same code-snippets over and over. If you are, then that is a sign that there is something wrong with your class design. In any professional, large, data-driven web site, there is going to be some code that will be accessed by many pages. For example, error handling code is a commonly shared by many pages. Therefore, it is a good idea to create a
BasePage class derived from
System.Web.UI.Page. Then derive all of your web pages from
BasePage.
You can do the same with master pages and user controls. This project includes
BaseMasterPage for master pages and
BaseUserControl for user controls.
Even if you do not know what to put in the base classes at the beginning of your project, you should follow this technique. By the end of your project, you may be surprised just how much code can be shared by each page.
So what do the pages look like with this programming technique? The have as little markup as possible. A simple page is shown below. The most important element — in fact the only control — is the
PlaceHolder control. Every page has a single placeholder.
<%@ Page <html xmlns="" > <head runat="server"> <title>This is a simple page example</title> <link rel="stylesheet" type="text/css" href="Css/StyleSharePoint.css"> </head> <body> <form id="form1" runat="server"> <div> <asp:PlaceHolder</asp:PlaceHolder> </div> </form> </body> </html>
All of the code in this file, with the exception of the placeholder, was generated automatically by Visual Studio.
In the code behind, the page is built out as controls added to the placeholder as shown below (note that the page is derived from
BasePage):
public partial class _Default : BasePage { protected void Page_Load(object sender, EventArgs e) { Literal lit = new Literal(); lit.Text = TextWriter.MakeH1Text("This is a sample page without a master page."); LocalPlaceHolder.Controls.Add(lit); lit = new Literal(); lit.Text = TextWriter.MakeParagraph( "This sample project shows how to build out pages dynamically in the code behind."); LocalPlaceHolder.Controls.Add(lit); // in this case, "blockstyle" is the css style for my panel MyPanel panel = new MyPanel("blockstyle"); panel.AddLiteral("This block of text shows how to build a panel."); LocalPlaceHolder.Controls.Add(panel); MyLabel label = new MyLabel("inlinestyle"); label.AddParagraph("This is a label."); } }
Note how we create each page element dynamically as a control and add it to the placeholder. The project includes samples to show how to do this with master pages and user controls as well.
Great Support for Object Oriented Programming and Class Reuse — This is one of the strongest arguments for this method of web programming. Using classic ASP techniques, even with ASP.NET can result in a lot of repetition of the same code on multiple pages. As you move more and more of your page logic into classes called from the code-behind, you eliminate a lot of this redundant code. This reduces errors and makes large projects more manageable and robust.
Intellisense and real-time syntax checking make coding a snap — These Visual Studio features make writing code very easy, fast, and efficient. It really makes the difference for this style of programming. Without these technologies, the argument for this type of development would be much less compelling.
Best for data-driven web sites, such as catalogs pages that read from a database — This system works best for highly data-driven web projects where pages get much of their content from a database or other data source. Simply derive control classes for each type of data display — lists, forms, etc. Then build your page from these controls dynamically in the code-behind.
Best for pages where page design changes rapidly, such as from designers and management that can't decide what they want. — I worked on one project where top management could never decide on the final design for pages. They kept changing their minds. Single pages would be reworked five times or more. I found that building pages this way made it very easy to alter the appearance of each page with just a little code tweaking.
Easily Supports Cascading Style Sheets (CSS) — You may not think so at first, but once you get up and running with this method, you will find that it works very easily with CSS. As with the
MyPanel class, simply requiring a CSS class style name as a constructor for your derived classes can simplify applying styles to your controls. Nested panel controls make it easy to cascade styles.
Management of Cookie and Session Variables — Well designed web applications have classes for handling cookies and session variables. This design makes it easier to access those classes from your controls.
Best for Pages with Highly Complex Logic — I found that this technique works best on pages with very complex logic — for example, a shopping cart, or a login page that must handle session variables or cookies. One some projects, I have been able to take pages that never worked quite right and fix them by adopting this programming technique. If your project has complex pages where you just can't seem to get rid of all of the bugs, try adopting this technique and see if it doesn't fix the problems.
You Lose the Toolbox — Those of you who like dragging and dropping controls from the Visual Studio toolbox onto their web pages may not like this method of web development. However, you can still use the technique with user controls as shown in the example project.
Sparse Documentation — Much of the MSDN documentation for ASP.NET assumes that you will be dropping controls onto page files and setting their properties in the tags. It can be difficult to look at those examples and figure out how to do the same thing programmatically. This is also true for many code snippets that you find on web sites like this one and others popular for ASP.NET development. This was particularly a problem with AJAX controls. It took me awhile to get AJAX controls working using this method because I couldn't find examples that illustrated AJAX controls built programmatically. But once I figured out the basic principles, I was off and running.
Worst for "brochure" style web pages with lots of content that does not change — Just as this technique works best for highly data-driven web pages that feed from a database, it is least suitable for highly static web pages such as brochure-type web sites or simple data web sites where simply plopping a data grid on the page and connecting to a data source is sufficient. However, if I was to start a new project of that type, I would still consider using this technique.
Less efficient for small, one-off projects — As discussed, this technique becomes more efficient as your project gets larger. This is because building your own class library is important to the efficiency of the method. But remember that small projects often turn into large ones.
The included project shows how to use this technique to build out some simple pages. It shows with technique both with and without master pages, and also how you can use the technique with user controls. The project is in C# for Visual Studio 2005. However, the same principles can be applied in VB.NET.
The transition of web development from static HTML, to classic ASP, to ASP.NET has made it easier to move more and more of your page display logic into the code-behind and well-designed class objects. This article takes a look at the extreme end of the spectrum — moving all coding logic into the code-behind for all pages.
As with any extreme method of programming, I expect that there will be resistance to adopting it in its entirety for your next project. However, you can take these techniques and incorporate them gradually into your projects — especially page rewrites. Central to the technique is building up a library of classes which you can reuse. I think you will find that as your class library grows, you will find it easier to adopt the technique and quickly build complex and robust web projects. I have used this technique very successfully in several projects, with almost all page presentation logic in the code-behind.
If you are working on a web project that is a "web" of messy classic ASP pages that you are trying to port to ASP.NET, I strongly recommend that you consider moving your project to this development method. It isn't something you would do in one iteration, but rather, with each iteration, move more and more of the code to code behind Use object-oriented techniques to build out a class library. Within several iterations, you will have a robust, well-designed, and very manageable project.
For me, adopting this technique required a change in mindset, undoing years of conditioning about web development. It is impossible to convey all aspects of the technique in a single article. I could fill a book on the technique. But check out the project and give the method some consideration. When you come across a web programming challenge, think about how you would solve it using this technique instead of the way you typically approach web programming. Over time, you may too find yourself programming more robust sites in less time.
General
News
Question
Answer
Joke
Rant
Admin | http://www.codeproject.com/KB/aspnet/dynamic_page_building.aspx | crawl-002 | refinedweb | 3,101 | 63.7 |
Georgios Gkoutos,
/
/This email is being sent at the request of the OBO Foundry coordinators
Barry Smith, Suzi Lewis, Chris Mungall and Michael Ashburner.
I am approaching you regarding your role as an editor of the Unit
ontology and would appreciate your input to our survey on your current
practice in naming (labeling) entities within your ontology or
controlled vocabulary.
The questionnaire is copied below and it is also available at the OBO
Foundry wiki
Please, fill it out and send it back to me, or alternatively let me know
if you are available for a phone or skype interview and your contact
details.
Thanks in advance for your reply!
Best regards,
Daniel Schober
_ PS:
_Note that the survey will be closed by September 7th and result posted
at the wiki page.
If you have any question, please don't hesitate to contact me
(schober@...).
---
_naming conventions - SURVEY_
Scope
The overall goals of this survey are twofold:
1. to evaluate the current practice in naming entities within the
OBO ontology working groups
2. to move towards a common set of naming convention for the OBO Foundy
Further details on the rationale for this survey can be found in Schober
/et al/. 2007, "Towards naming conventions for use in controlled
vocabulary and ontology engineering",
_, pages 29-32.
Results
Any questions as well as the completed questionnaires should be sent to
Daniel Schober (schober@...). The outcome will be posted on the
OBO Foundry wiki pages () and
all participants will get notified accordingly.
//
Questionnaire
_1. Questions on your ontology and its engineering and maintenance
process_
*1.1 *Are you and your co-workers familiar with the OBO Foundry
principles ()?
*1.2* If yours in an OBO Foundry ontology, have you started implementing
these pronciples and aligned your development process accordingly?
*1.3* Is work on your ontology closely associated with the need to
manage and formulate queries about a specific body of data? If so, can
you specify the type of data?
This question refers to the instance level and annotated data bodies. Is
the ontology developed in collaboration with the maintenance of a
database or collection of databases (as the GO is developed in
collaboration with UniProt and with various MOD databases)?
*1.4* Which ontology editor tool(s) do you use to build and manage your
ontology?
*1.5 *Please illustrate the editing process, i.e. is your ontology
developed in a centralised or distributed manner? In both cases, please,
state the number of people directly handling and editing the ontology
file and if they are physically distributed or if they are located in
one spot.
*1.6* Do you introduce special /helper classes/ or /bins/, that refer to
metadata to facilitate the engineering process? If yes, please describe
them and explain how do you indicate their special status?
Examples are 'obsolete classes', 'imported classes', 'deleted classes'.
_2. General questions on your current practice in naming entities
and their documentation_
*2.1* Have you developed naming conventions within your ontology
community? If yes, please specify how these are formulated, e.g. as a
specific, standalone document or as part of other documentation and
where these are available, e.g. provide URL.
*2.2 *(If your answer to 2.1 is positive) Which entities are tackled by
your naming conventions?
Some examples are provided below, add if required:
* class names
* relation names, e.g. colour vs has_colour vs colour_of
* instance names
* the name of the ontology, its versions, namespaces and term IDs
*2.3* (If your answer to 2.1 is negative) Have you re-used existing
naming conventions from other ontology groups?
For example have you applied the GO editor style guide or conventions
from other sources, e.g. ontology tutorials or guidelines from
standardisation bodies such as ISO?
_3. Questions on the implementation of names_
*3.1 *Which of the following categories of names (or name types) do you
record in your ontology and which one do you anticipate such common
naming conventions are useful for?//
Some examples are provided below, add if required://
· preferred name
· short name or display name
· formal name
· synonym
· foreign language translations
· broader or narrower term
*3.2* (If applicable) Which ontology language idioms do you use to
capture the categories of names, listed in question 3.1? Please, provide
examples.
In OWL the preferred class name are probably captured using the
rdfs:label idiom and foreign language translation via another rdfs:label
idiom with the lang attribute set. Synonyms are probably captured by
some self-created OWL annotation properties or in OBO by the
'exact_synonym' idiom.
*3.3 *Do you think there is a need to expand the expressivity of the
ontology representation languages in order to provide more naming
flexibility? What elements are missing?
*3.4* Did you use any features/functions of your ontology editor to
check for consistency within the names?
In Protégé these features would be the browser key, PROMPT or
StringSearchTab, and the redundancy check functionality in OBO Edit.
Specialized software tools also exist to check naming conventions, e.g.
Validator ()
_4. In depth questions on specific naming conventions_
*4.1 Explicit and concise names and context independence*
*4.1.1* Do you put any constraints on the use of natural language?
For example, do you omit nouns, articles or other words to ensure
shorter names, e.g. /'two dimensional J-resolved', /in place of /'the
two dimensional J-resolved pulse sequence'? /If yes, please describe.
*4.1.2* Do you make sure all the names are understandable on their own,
even when viewed outside of the immediate context?
*4.2 Compound names*
*4.2.1* Do you apply any conventions that help string matching? For
example, when creating compound names do you try to build the names out
of already defined building blocks, re-using the same words or
word-parts (affixes) present in other names and other representational
units?
For example, use 'x_part_of_process', 'y_part_of_process' and
'z_part_of_process' using consistently the string 'part of' (used and
defined elsewhere) instead of using also a synonymous strings e.g.
'x_component_of_process', 'y_part_of_process', 'z_portion_of_process',
introducing heterogeneity. GO for example re-uses the string
'development' in such a defined way all over in its class names.
*4.2.2* Do your names contain defined strings that have a special
defined meaning in each occurrence?
Defined strings could indicate administrative metadata, e.g. as in the
names '?device' or 'device refine' or 'obsolete' as in '/hydrolase
activity, acting on carbon-nitrogen (but not peptide) bonds, in other
compounds (Obsolete)'/ (GO:0016816). GO also used the 'sensu' string to
constrain validity, e.g. species specificity as in 'fruiting body
development (sensu Bacteria)' (GO:0030583, Note that the 'sensu'
practice is now discouraged in GO in favour of stating appropriate
differentia explicitly and avoiding the taxon in names and definitions,
e.g. 'cell wall (sensu bacteria)' becomes 'peptidoglycan-based cell
wall' ).
*4.2.3 *Have you developed any guidelines to create compound names?
For example conventions that demand a specific order of types of words
within the name.
*4.3 Homonyms*
*4.3.1 *How do you cope with homonyms and highly ambiguous names?
For example, one can try to avoid or disambiguate homonyms like 'set',
which can indicate a plurality as in 'protocol set', as well as an
action as in 'parameter set'. OpenCyc uses qualifiers as name suffixes
to disambiguate homonyms, e.g. 'Plant-the factory' vs. 'Plant-the organism'.
*4.4 Consistency of language*
*4.4.1* Do you consistently apply British or US English word forms?
For example using 'polymerising' vs. 'polymerizing' throughout.
*4.4.2* Do you encounter cases where inconsistency arises from including
words from different languages? If yes, please explain how you tackle
these inconsistencies.
For example, 'gut' is the English word for the Latin 'intestine'
*4.5 Noun and verb forms*
*4.5.1* Do you encode word forms consciously and in a consistent way
within your names and do you have any guidelines regarding word forms?
For example, using 'to be measured' (future) and 'measured' (past) or
the time-neutral noun form 'measurement' in certain circumstances only.
*4.6 Abbreviations and acronyms*
*4.6.1 *How do you handle acronyms and abbreviations and how do you deal
with widely used acronyms, .e.g. 'NMR' that would result in very long
name when resolved? Could a /cut-off/ be defined when an acronym can be
used in a name and still be intuitive and understandable throughout the
domain?
*4.7 Singularity*
*4.7.1* Do you capture plural or singular word forms throughout your
ontology? When capturing pluralities, do you use a consistent naming
convention?
For example one could restrict the usage of plurality indicators, e.g.
either 'Xs' 'X collection', 'X set', or 'aggregate of X' throughout.
*4.8 Positive names*
*4.8.1 *Do you apply negative names such as 'non-separation device'?
*4.8.2 *Do you explicitly exclude things within your names?
For example in gene ontology one can find 'hydrolase activity, acting on
carbon-nitrogen (but not peptide) bonds, in cyclic amides
<>'; (GO:0016812
<>).
*4.9 Conjunctions*
*4.9.1* Do the names in your ontology contain logical connectives and
Boolean operators such as 'or' or 'and', e.g. as in 'strain or line' or
' antigen processing and presentation of peptide or polysaccharide
antigen via MHC class II
<>'; (GO:0002504
<>)?
*4.9.2* Do the names in your ontology contain hyphens, slashes,
parenthesis or other symbols and if so, do you use them consistently? If
yes, please explain their meaning and use.
In many ontologies currently the hyphen and slashes are used with
different underlying meanings. Hyphens can indicate omissions in names
(ellipse or apocope), e.g. 'gene-technology' for 'gene modification
technology', indicate logical connectives, e.g. 'black-white', or
ranges, e.g. '10-100'.
*4.10 Taboo words*
*4.10.1* Do names in your ontology contain words that refer to the
representational units (e.g. class or relation) they are encoded in,
rather than to what is represented
For example as in 'protocol class', 'animal type', 'color attribute',
'ligand relation'.
*4.11 Typography*
*4.11.1* Which typographical convention, e.g. lower case, UPPERCASE,
mixed Case or CamelCase do you use for the categories of names (listed
in question 3.1)?
Under the OBO umbrella one can find 'MyClass' 'My Class', 'My-Class',
'My_Class', 'My_class' and 'my class' conventions, even within one
ontology and throughout different representational idioms. In the AI
community the convention to have classes starting upper-case and
relations and instances starting lower-case is common.
*4.11.2* Do you use sub- or superscripts or other text formatting to
encode additional information?
*4.11.3* Do you use any character as a word separator (such as '_', '-',
' ', etc. ) within compound names? If yes, please, explain the reason of
your choice.
For example, XML based languages, such as OWL, cannot have the space
separator, because they need to be a valid when part of URIs, where
space is not allowed. CamelCase is problematic for text mining since
indicators for word-borders are lost in CamelCase.
*4.11.4* How do you handle chemical element symbols, Greek symbols like
*a**,** *and other special characters like *° C** *?
*4.11.5* Do you have to handle product names or registered brand names?
If yes, how do you render their names intuitive (or do you capture them
as they are) ?
A brand name 'US 2', describing an NMR magnet, could be renamed by using
the company name as prefix, the product brand name as infix and the
product type (superclass) as headword/suffix, e.g. use 'Bruker US 2 NMR
magnet'.
*Lastly, is there any final comment you want to make, including
additional questions that should have been in this questionnaire? Has
every naming issue you came across been covered?*
*THANKS*
--
__________________________________________________________________________________________
Dr. Daniel Schober
NET Project - Ontologist
The European Bioinformatics Institute email: schober@...
EMBL Outstation - Hinxton direct: +44 (0)1223 494410
Wellcome Trust Genome Campus fax: +44 (0)1223 494 468
Cambridge CB10 1SD, UK Room: A3-141 (extension building)
Project page:
Personal page:
Former home page:
I agree to receive quotes, newsletters and other information from sourceforge.net and its partners regarding IT services and products. I understand that I can withdraw my consent at any time. Please refer to our Privacy Policy or Contact Us for more details | https://sourceforge.net/p/obo/mailman/obo-unit/?viewmonth=200708 | CC-MAIN-2016-40 | refinedweb | 2,061 | 56.96 |
The Kestrel web server is a new web server as part of ASP.NET Core. It is now the preferred web server for all new ASP.NET applications. In this article, we will review what it is, how to use it, and the differences between Kestrel vs IIS.
Why Do We Need the New Kestrel Web Server? What about IIS?
If you have been developing ASP.NET applications for a while, you are probably familiar with Internet Information Services (IIS). It does literally anything and everything as a web server. It is infinitely configurable with ASP.NET handlers & modules via the ASP.NET integrated pipeline. It has robust management APIs for configuration and deployment. It is even an FTP server.
The same codebase that has to support the original “.asp” pages from 15+ years ago now also handles new technologies like async ASP.NET. Like most software, as it ages it gets modified over time, they carry a lot of weight and bloat. IIS does everything, but it is not the fastest web server around. Lightweight web servers like Node.js and Netty make IIS look old and slow.
A Chance to Start Over
By creating the Kestrel web server, the .NET community was able to start over from scratch. They no longer had to worry about backward compatibility for technologies that were 15+ years old. They could take all of their past knowledge to build the simplest and fastest web server possible. That is exactly what they did. Kestrel and ASP.NET Core were built for speed.
Kestrel is more than just a new web server. ASP.NET Core & Kestrel combined are a whole new request pipeline for how ASP.NET requests work. Things like HTTP modules & handlers have been replaced with simple middleware. The entire System.Web namespace is gone. Another big advantage is designing a web server to take advantage of async from the ground up. Performance is now a feature of ASP.NET.
Built for Speed
One of the big problems with IIS and the existing ASP.NET pipeline was the performance of it. For most real world applications, the performance is perfectly fine. However, it lagged way behind in benchmarks. The combination of Kestrel & ASP.NET Core has been shown to be many times faster. It is great to see the team putting performance as a top priority.
Granted, benchmarking an ASP.NET request that says “hello world” is not comparable to most real applications that do multiple SQL queries, cache calls, and web service calls in a single request. ASP.NET makes it easy to do most I/O operations asynchronously. ASP.NET Core & Kestrel have been designed from the ground up to take advantage of async. Most real world apps should perform better if the developers follow good best practices around using async.
Cross Platform
If the goal was to get ASP.NET running on Linux, that meant porting IIS to Linux or making ASP.NET work without IIS. Kestrel solved this problem. As a developer, I can write my ASP.NET application and deploy it to Windows or Linux either one. Kestrel works as my web server on both. However, it is still recommended to use IIS, Apache, or NGINX as a reverse proxy in front of it. Next, we will discuss why that is.
Comparing Kestrel Web Server vs IIS
IIS does almost everything. Kestrel does as little as possible. Because of this, Kestrel is much faster but also lacks a lot of functionality. I would think of Kestrel as really more of an application server. It is recommended to use another web server in front of it for public web applications. Kestrel is designed to run ASP.NET as fast as possible. It relies on a full fledged web server to do deal with things like security, management, etc.
Microsoft suggests always using another web server in front of Kestrel for public websites.
Feature Comparison for Kestrel vs IIS
Here is an IIS vs Kestrel comparison of some key features. This should help you better understand the limitations of Kestrel. You can overcome these limitations by pairing it up with IIS or NGINX.
* Port Sharing is a big limitation! This means you can’t host “site1.stackify.com” and “site2.stackify.com” both on port 80 on the same server, running different ASP.NET applications.
** Only works with internal SSL traffic between the reverse proxy web server and ASP.NET.
To learn more about ASP.NET server hosting technology, check out the Microsoft docs: Web server implementations in ASP.NET Core
Need help monitoring your ASP.NET Core applications?
Stackify Retrace’s APM solution works perfectly with ASP.NET Core!
- | https://stackify.com/kestrel-web-server-asp-net-core-kestrel-vs-iis/ | CC-MAIN-2022-40 | refinedweb | 780 | 70.09 |
Wednesday Mar 16, 2011
Monday Mar 30, 2009
Stopping.
Tuesday Nov 11, 2008
dmidecode for Solaris
By user12614486 on Nov 11, 2008
dmidecode can be ported to run on Solaris, but Solaris now comes with a builtin command called smbios that performs the same function (and is supported). If you're looking for dmidecode, use smbios instead.
Tuesday Nov 04, 2008
Oh, thank God.
By user12614486 on Nov 04, 2008
Monday Sep 24, 2007
Finding.
Thursday Jun 21, 2007
UDP process finder
By user12614486 on Jun 21, 2007
Ever had your system constantly transmitting network packets, and had a hard time finding out who or why?
Recently my system was sending loads and loads of DNS requests for a system I knew not to be on the network (an old system of mine that had been decommissioned). I saw the DNS requests with snoop(1m), but had no idea which process was doing the job.
Enter dtrace. 15 seconds of experimentation: first, look to see if there are functions being called with "udp" in their name:
dtrace -n 'fbt::\*udp\*:entry'
Yes, there certainly are. OK, modify the above to suppress the default print with -q, and add what I'm interested in, straight out of built-in variables:
dtrace -q -n 'fbt::\*udp\*:entry{printf("%s from %s(%d)\\n", probefunc, execname, pid);}'
(Turns out it was automountd. A quick service disable/enable, and it stopped.) Another mysterious system behavior immediately found with dtrace.
Friday Oct 20, 2006
Making backspace be your default delete character
By user12614486 on Oct 20, 2006
One consistently-annoying thing about Solaris is the default terminal control-character settings, which cause Backspace \*not\* to erase a character in most shells (without someone somewhere executing an "stty erase \^H" to fix it up). I'm not going to claim that the default is rational, or try to speculate about where it arises, although I will say that it's being looked at.
However, today, we discovered that it's relatively easy to change; the initial control-character settings are set up by the ldterm module (the "line-discipline" is the one that establishes all the normal character-editing modes that many shells use when using "cooked-mode" terminal I/O). ldterm, it turns out, reads them from a property in the
/kernel/drv/options.conf file, called
ttymodes. It's encoded, but it represents the full termio settings, as
stty -g would output them. The default looks like this:
ttymodes="2502:1805:bd:8a3b:3:1c:7f:15:4:0:0:0:11:13:1a:19:12:f:17:16";
If you change that 7f (the ASCII code for Del) to 8 (the ASCII code for Backspace), and reboot, then Backspace works as you expect, as soon as you log in, in all shells, thank you very much, the way God intended.
Friday Jun 30, 2006
Dell USB keyboard volume keys hack
By user12614486 on Jun 30, 2006
If you have a Dell SK-8125 keyboard (101-key, black, built in 2-port hub, with a silver band at the top and 8 silver application keys, the right three of which are Volume Up/Down/Mute), this hack might interest you.
It turns out Solaris attaches a
hid driver instance to the special "consumer control" device that makes up the 8 multimedia keys, but there's no client driver module that interprets the data, and in fact if no one opens that
hid device, the data isn't ever generated.
But if you \*do\* open it, it turns out reading the keys is easy...and since
/dev/audioctl is also an easy way to do volume, the following silly userland program has me using volume keys, when I run it as
dellusb /dev/usb/hid2.
Maybe if you have a similar keyboard, you can hack it, so I've left the debug dump. This Dell sends 4 bytes for make and break, and doesn't seem to change anything but the second byte, which is a bitmask of keys pressed... pretty easy.
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <sys/audio.h> #define VOLDOWN 128 #define VOLUP 64 #define MUTE 32 #define HOME 16 #define RELOAD 8 #define CANCEL 4 #define FORWARD 2 #define BACK 1 void volevent(unsigned char mask); void dump_event(unsigned char mask); int main(int argc, char \*\*argv) { int fd; char errmsg[80]; unsigned char kbuf[4]; unsigned char mask; if (argc < 2) { fprintf(stderr, "usage: dellusb <hid-device>\\n"); exit(1); } if ((fd = open(argv[1], O_RDONLY)) < 0) { sprintf(errmsg, "open %s", argv[1]); perror(errmsg); exit(1); } while (1) { read(fd, kbuf, sizeof(kbuf)); mask = kbuf[1]; if (!mask) continue; #if 0 dump_event(mask); #else if (mask & (VOLUP | VOLDOWN | MUTE)) volevent(mask); #endif } } void volevent(unsigned char mask) { struct audio_info i; static uint_t gain_at_mute = 0; int fd; /\* get audio info, no matter what we have to do \*/ if ((fd = open("/dev/audioctl", O_RDWR)) < 0) { perror("open /dev/audioctl"); return; } ioctl(fd, AUDIO_GETINFO, &i); switch (mask & (VOLUP | VOLDOWN | MUTE)) { case VOLUP: i.play.gain += 5; if (i.play.gain > AUDIO_MAX_GAIN) i.play.gain = AUDIO_MAX_GAIN; break; case VOLDOWN: /\* gain is a uint_t, requiring this silly dance \*/ if (i.play.gain <= 5) i.play.gain = 0; else i.play.gain -= 5; break; case MUTE: if (gain_at_mute) { i.play.gain = gain_at_mute; gain_at_mute = 0; } else { gain_at_mute = i.play.gain; i.play.gain = 0; } break; default: goto out; } ioctl(fd, AUDIO_SETINFO, &i); out: close(fd); return; } void dump_event(unsigned char mask) { if (mask & VOLDOWN) printf("VOLDOWN "); if (mask & VOLUP) printf("VOLUP "); if (mask & MUTE) printf("MUTE "); if (mask & HOME) printf("HOME "); if (mask & RELOAD) printf("RELOAD "); if (mask & CANCEL) printf("CANCEL "); if (mask & FORWARD) printf("FORWARD "); if (mask & BACK) printf("BACK "); if (mask) printf("\\n"); return; }
Wednesday Jun 15, 2005
Diagnosing kernel hangs/panics with kmdb and moddebug
By user12614486 on Jun 15, 2005
If you experience hangs or panics during Solaris boot, whether it's during installation or after you've already installed, using the kernel debugger can be a big help in collecting the first set of "what happened" information.
The kernel debugger is named "kmdb" in Solaris 10 and later, and is invoked by supplying the '-k' switch in the kernel boot arguments. So a common request from a kernel engineer starting to examine a problem is often "try booting with kmdb".
Sometimes it's useful to either set a breakpoint to pause the kernel startup and examine something, or to just set a kernel variable to enable or disable a feature, or enable debugging output. If you use -k to invoke kmdb, but also supply the '-d' switch, the debugger will be entered before the kernel really starts to do anything of consequence, so that you can set kernel variables or breakpoints.
So "booting with the -kd flags" is the key to "booting under the kernel debugger". Now, how do we do that?
Kernel debugging with GRUB-boot systems
On modern Solaris and OpenSolaris systems, GRUB is used to boot; to enable the kernel debugger, you add -kd arguments to the "kernel" (or "kernel$") line in the GRUB menu entry. When presented with the GRUB menu, hit 'e' to edit the entry, highlight the kernel line, and hit 'e' again to edit it; add the -kd arguments just after the /platform/i86pc/kernel/$ISADIR/unix argument, so that it says
kernel$ /platform/i86pc/kernel/$ISADIR/unix -kdand then hit 'b' to boot that edited menu entry. '-k' means "start the debugger"; '-d' means "immediately enter the debugger after loading the kernel". After some booting status, you'll see the kernel debugger announce itself like this:
[0]>
(The number in square brackets is the CPU that is running the kernel debugger; that number might change for later entries into the debugger.):
[0]> moddebug/W 80000000 [0]> :cThat will give you debug output for each kernel module that loads. (see /usr/include/sys/modctl.h, near the bottom, for moddebug flag information. I find 0x80000000 is the only one I really ever use.)
-
[1]> 0::switch
There's obviously a lot more you can do with the kernel debugger, but these small tips will
sometimes help get from a "I have no idea what to do" to "I have a few ideas to try that might
let me continue to boot or install", which can make all the difference.
Technorati Tag: opensolaris solaris
Tuesday Jun 14, 2005
PCI device identification and driver binding in Solaris
By user12614486 on Jun 14, 2005
PCI device identification and driver binding in Solaris
A PCI device has a bunch of device identification numbers associated
with it, which generic code can retrieve. I've listed them here in
most-specific to least-specific order, by their Solaris property name
(shown in the
prtconf -pv output, which is why we always always always
ask for that when diagnosing driver-binding problems):
- revision (not useful on its own)
- vendor-id, device-id (the usual lone source of driver binding)
- subsystem-vendor-id, subsystem-id (the usual source of the "name" property, and hence the usual source of the /devices node name)
- class-code
The revision number is only useful in conjunction with vendor-id, device-id.
Entry 3, the subsystem, is nearly useless for every purpose, as many machines now use the same subsystem ID for every motherboard device, and if not, at least the same subsystem-vendor-id. Sun had originally interpreted subsystem to be more specific than vendor-id, device-id, but that's not how the industry ended up adopting it. (as usual, the spec was unclear as to its intent).
The only things Solaris normally uses for binding device drivers are 2 and 4.
The way Solaris driver binding works is: for every element in the compatible property, in order, a) look for a same-named driver; if it's there, use it; if not, b) look for a same-named device alias, and get the driver field out of it; if it's there, use it. That's it. (Note that I'm specifically talking about Solaris, nothing to do with bootconf or the DCA.)
So most devices are bound through the vendor-id, device-id pair. Some devices and drivers are generic enough so that one driver is able to run an entire class of devices (say, for instance, pci-ide); in that case, the class-code can be used. But for the most part, vendor-id,device-id is what you want in /etc/driver_aliases, and it's always the right thing to talk about when you're trying to describe which device you have to someone else.
The Broadcom device aliases were added with both vendor-id, device-id and subsystem-vendor-id, subsystem-id, the intent being to try to bind the bge device driver only to particular boards and motherboards we had tested explicitly. (Opinions differed as to whether this was a good idea.) Since then, I believe the motion is back to just vendor-id,device-id, but if you see device aliases for bge with four numbers, that's why. They'll still work with two numbers, just not as pickily.
Now obviously this opens up the possibility that more than one alias might match for a particular set of numbers in the PCI device...but that's why we specify what's in the compatible property, not what's in the device. The compatible property is always constructed in a specific order, and as of s10_37, contains the following (intentionally-redundant) elements for PCI devices:
\* (possibly) node-name (0) \* pciVVVV,DDDD.SSSS.ssss.RR (1) \* pciVVVV,DDDD.SSSS.ssss (2) \* pciSSSS,ssss (3) \* pciVVVV,DDDD.RR (4) \* pciVVVV,DDDD (5) \* pciclass,CCSSPP (6) \* pciclass,CCSS (7)
(VVVV is vendor-id, DDDD is device-id, SSSS is subsystem-vendor-id, ssss is subsystem-id, RR revision, CC major class number, SS subclass number, PP programming-interface-byte)
Form 0 is there for certain special devices, to "override" the normal matching, mostly older devices. Then, as you can see, we sorta go from most-specific to least-specific, which is the intent of the compatible property on any bus, PCI being no exception. The exception to that order is number 3, which had to be where it is because of the original definition of the compatible property in the original IEEE1275 spec, which all this is based on. But it's OK, because we (as noted above) virtually never use it for binding drivers anyway; we almost-always use 5 or 6/7, and sometimes 2.
OpenSolaris Technorati Tag: OpenSolaris Technorati Tag: Solaris
Wednesday Jun 08, 2005
Removing.)
Thursday Mar 31, 2005
Disabling:
Watching system events
By user12614486 on Mar 31, 2005
System events comprise a mechanism for kernel code to signal up the tree to anyone who might be listening: other kernel agents, userland code, etc. Here's a very stupid demo program (Solaris-10-or-later only), just to save you some typing, that demonstrates what an event looks like. Try running this and then plugging/unplugging a USB device.
See libsysevent(3LIB) for a description of the userland interface used in this demo program, and syseventd(1M) for a description of the userland daemon.
If this little sample piques your interest, check out what you could do with syseventadm(1m) and some shell scripts, perhaps involving zenity(1)...
Compile with
cc evprint.c -o evprint -lsysevent -lnvpair
#include <unistd.h> #include <libsysevent.h> #include <libnvpair.h> typedef void (sehfn)(sysevent_t \*ev); sehfn handler; int main(int argc, char \*\*argv) { sysevent_handle_t \*seh; const char \*subclass_list[] = {"EC_SUB_ALL"}; seh = sysevent_bind_handle(handler); if (seh == NULL) { perror("sysevent_bind_handle"); exit(1); } if (sysevent_subscribe_event(seh, EC_ALL, subclass_list, 1) != 0) { perror("sysevent_subscribe_event"); exit(1); } while (1) pause(); } void handler(sysevent_t \*ev) { nvlist_t \*nvlist; nvpair_t \*nvpp; char \*class, \*subclass; unsigned int n, i; boolean_t bv, \*ba; int8_t i8v, \*i8a; int16_t i16v, \*i16a; int32_t i32v, \*i32a; int64_t i64v, \*i64a; uint8_t ui8v, \*ui8a; uint16_t ui16v, \*ui16a; uint32_t ui32v, \*ui32a; uint64_t ui64v, \*ui64a; char \*str, \*\*sa; str = (char \*)malloc(100); class = sysevent_get_class_name(ev); subclass = sysevent_get_subclass_name(ev); printf("\\n\*\*\* event: class '%s', subclass '%s'\\n", class, subclass); if (sysevent_get_attr_list(ev, &nvlist) != 0) { printf("no nvlist\\n"); return; } nvpp = NULL; while ((nvpp = nvlist_next_nvpair(nvlist, nvpp)) != NULL) { printf("%s: ", nvpair_name(nvpp)); switch (nvpair_type(nvpp)) { case DATA_TYPE_BOOLEAN: printf("true\\n"); break; case DATA_TYPE_BOOLEAN_VALUE: nvpair_value_boolean_value(nvpp, &bv); printf("boolean %s\\n", bv ? "false" : "true"); break; case DATA_TYPE_INT8: nvpair_value_int8(nvpp, &i8v); printf("int8 %d\\n", i8v); break; case DATA_TYPE_BYTE: case DATA_TYPE_UINT8: nvpair_value_uint8(nvpp, &ui8v); printf("uint8 %d\\n", ui8v); break; case DATA_TYPE_INT16: nvpair_value_int16(nvpp, &i16v); printf("int16 %d\\n", i16v); break; case DATA_TYPE_UINT16: nvpair_value_uint16(nvpp, &ui16v); printf("uint16 %d\\n", ui16v); break; case DATA_TYPE_INT32: nvpair_value_int32(nvpp, &i32v); printf("int32 %d\\n", i32v); break; case DATA_TYPE_UINT32: nvpair_value_uint32(nvpp, &ui32v); printf("uint32 %d\\n", ui32v); break; case DATA_TYPE_INT64: nvpair_value_int64(nvpp, &i64v); printf("int64 %d\\n", i64v); break; case DATA_TYPE_UINT64: nvpair_value_uint64(nvpp, &ui64v); printf("uint64 %d\\n", ui64v); break; case DATA_TYPE_STRING: nvpair_value_string(nvpp, &str); printf("string '%s'\\n", str); break; case DATA_TYPE_NVLIST: printf("nvlist\\n"); break; case DATA_TYPE_BOOLEAN_ARRAY: printf("boolean array: {"); nvpair_value_boolean_array(nvpp, &ba, &n); for (i = 0; i < n; i++) printf("%s ", ba[i] ? "true" : "false"); printf("\\n"); break; case DATA_TYPE_BYTE_ARRAY: printf("byte array: {"); nvpair_value_byte_array(nvpp, &ui8a, &n); for (i = 0; i < n; i++) printf("0x%x ", ui8a[i]); printf("}\\n"); break; case DATA_TYPE_INT8_ARRAY: printf("int8 array: {"); nvpair_value_int8_array(nvpp, &i8a, &n); for (i = 0; i < n; i++) printf("%d ", i8a[i]); printf("}\\n"); break; case DATA_TYPE_UINT8_ARRAY: printf("uint8 array: {"); nvpair_value_uint8_array(nvpp, &ui8a, &n); for (i = 0; i < n; i++) printf("0x%x ", ui8a[i]); printf("}\\n"); break; case DATA_TYPE_INT16_ARRAY: printf("int16 array: {"); nvpair_value_int16_array(nvpp, &i16a, &n); for (i = 0; i < n; i++) printf("%d ", i16a[i]); printf("}\\n"); break; case DATA_TYPE_UINT16_ARRAY: printf("uint16 array: {"); nvpair_value_uint16_array(nvpp, &ui16a, &n); for (i = 0; i < n; i++) printf("%d ", ui16a[i]); printf("}\\n"); break; case DATA_TYPE_INT32_ARRAY: printf("int32 array: {"); nvpair_value_int32_array(nvpp, &i32a, &n); for (i = 0; i < n; i++) printf("%d, ", i32a[i]); printf("}\\n"); break; case DATA_TYPE_UINT32_ARRAY: printf("uint32 array: {"); nvpair_value_uint32_array(nvpp, &ui32a, &n); for (i = 0; i < n; i++) printf("%d, ", ui32a[i]); printf("}\\n"); break; case DATA_TYPE_INT64_ARRAY: printf("int64 array: {"); nvpair_value_int64_array(nvpp, &iamp;64a, &n); for (i = 0; i < n; i++) printf("%lld, ", i64a[i]); printf("}\\n"); break; case DATA_TYPE_UINT64_ARRAY: printf("uint64 array: {"); nvpair_value_uint64_array(nvpp, &ui64a, &n); for (i = 0; i < n; i++) printf("%lld, ", ui64a[i]); printf("}\\n"); break; case DATA_TYPE_STRING_ARRAY: printf("string array: {"); nvpair_value_string_array(nvpp, &sa, &n); for (i = 0; i < n; i++) printf("'%s', ", sa[i]); printf("}\\n"); break; case DATA_TYPE_NVLIST_ARRAY: printf("nvlist_array\\n"); break; default: printf("type unknown\\n"); break; } } }
Thursday Mar 17, 2005
prtpci: digest and display prtconf -pv output
By user12614486 on Mar 17, 2005
Here's a tool (prtpci.tar.Z) for digesting PCI information from prtconf -pv output.
There are several tools around that will show you a PCI manifest; this one
- is safe, doesn't poke at machine ports to do its job
- can be run offline with a captured prtconf -pv file
- makes use of the common "pci.ids" database from Sourceforge, and includes a script to update that database periodically
- decodes the Base Address Registers (BARs) and slot-names properties
- is written in Perl for easy hackability
It's useful to me, and I hope it is useful to you. Here's a little sample output:
3/0xb/0 1095,3114 (1095,3114)
Silicon Image, Inc. (formerly CMD Technology Inc) SiI 3114 [SATALink/SATARaid] Serial ATA Controller
class 1/80/0: Mass storage controller/Unknown mass storage controller
BAR[0]: I/O 0xbc00 0x8
BAR[1]: I/O 0xb802 0x1
BAR[2]: I/O 0xb400 0x8
BAR[3]: I/O 0xb002 0x1
BAR[4]: I/O 0xac00 0x10
BAR[5]: I/O 0xfc8ffc00 0x400
ROM: 32-bit memory 0xfc800000 0x80000
3/0xc/0 104c,8023 (10f1,2885)
Texas Instruments TSB43AB22/A IEEE-1394a-2000 Controller (PHY/Link)
class c/0/10: Serial bus controller/FireWire (IEEE 1394)
BAR[0]: 32-bit memory 0xfc8ff000 0x800
BAR[1]: 32-bit memory 0xfc8f8000 0x4000
About
Categories
- General | https://blogs.oracle.com/dmick/category/General | CC-MAIN-2016-50 | refinedweb | 3,015 | 52.73 |
Exam Questions for Chapters 5 and 6¶
The following questions test what you have learned in chapters 5 and.
- value
- When you print a variable it will print the value of the variable.
- Second
- When you call myFunction("Second") the value of parameter is set to "Second". This code prints the value of the variable called "value" which is set to the value of parameter.
- parameter
- When value = parameter is executed the value of parameter is copied into the space called value.
- First
- While value was first set to "First" it was changed to a copy of the value of parameter.
- This would be true if the alice.pencolor("red") was after the first forward.
- This would be true if the alice.pencolor("red") was before the first forward.
- Since the alice.pencolor("red") is after the second forward the first two lines will be black and the last two will be red.
- This would be true if the alice.pencolor("red") was after the third forward.
- bob.move(50)
- Turtles don't understand move.
- bob.left(50)
- The left procedure turns the turtle left by the specified amount.
- bob.forward(50)
- Turtles have a forward procedure which moves the turtle in the direction it is facing by the specified amount.
- bob.right(50)
- The right procedure turns the turtle right by the specified amount.
- definition
- You use the def keyword to define a procedure or function.
- procedure
- A procedure doesn't return anything.
- turtle
- Turtles have procedures and functions.
- function
- A function returns a result.
- This would be true if it was right first and then left.
- This would be true if it was right first and then left and if the first forward was 150 and the last was 75.
- This would be true if it was the shorter line to the north and the longer to the east.
- This will draw the shorter line to the north and then the longer one to the east.
- Two squares connected with a straight line
- This would be true if the right turns were 90 and there were four forwards
- Two triangles connected with a straight line
- This procedure will draw a triangle and it is called twice so it draws two triangles
- Two rectangles connected with a straight line
- This would be true if the right turns were 90 and there were four forwards with two different forward amounts
- Nothing
- This would be true if we only defined the procedure and didn't execute it.
6-10-1: What value is printed when the following code is executed?
name = "John Smith" def myFunction(parameter): value = "First" value = parameter print (value) myFunction("Second")
6-10-2: Which picture would the following code produce?
from turtle import * screen = Screen() alice = Turtle() alice.forward(50) alice.left(90) alice.forward(50) alice.left(90) alice.pencolor("red") alice.forward(50) alice.left(90) alice.forward(50)
6-10-3: Given the following lines of code, which will move the turtle bob 50 units forward?
from turtle import * space = Screen() bob = Turtle()
6-10-5: Which picture would the following code produce?
from turtle import * space = Screen() sue = Turtle() sue.left(90) sue.forward(75) sue.right(90) sue.forward(150)
6-10-6: What will the following code draw?
def shape(turtle): turtle.left(60) turtle.forward(100) turtle.right(120) turtle.forward(100) turtle.right(120) turtle.forward(100) turtle.right(120) from turtle import * space = Screen() luis = Turtle() shape(luis) luis.forward(200) shape(luis) | http://interactivepython.org/runestone/static/StudentCSP/CSPNameNames/exam5a6.html | CC-MAIN-2017-51 | refinedweb | 585 | 65.52 |
The Service Container is an extremely powerful feature of Masonite and should be used to the fullest extent possible. It's important to understand the concepts of the Service Container. It's a simple concept but is a bit magical if you don't understand what's going on under the hood.
The Service Container is just a dictionary where classes are loaded into it by key-value pairs, and then can be retrieved by either the key or value through resolving objects. That's it.
Think of "resolving objects" as Masonite saying "what does your object need? Ok, I have them in this dictionary, let me get them for you."
The container holds all of the frameworks classes and features so adding features to Masonite only entails adding classes into the container to be used by the developer later on. This typically means "registering" these classes into the container (more about this later on).
This allows Masonite to be extremely modular.
There are a few objects that are resolved by the container by default. These include your controller methods (which are the most common and you have probably used them so far) driver and middleware constructors and any other classes that are specified in the documentation.
There are four methods that are important in interacting with the container:
bind,
make and
resolve
In order to bind classes into the container, we will just need to use a simple
bind method on our
app container. In a service provider, that will look like:
from masonite.provider import ServiceProviderfrom app.User import Userclass UserModelProvider(ServiceProvider):def register(self):self.app.bind('User', User)def boot(self):pass
This will load the key value pair in the
providers dictionary in the container. The dictionary after this call will look like:
>>> app.providers{'User': <class app.User.User>}
The service container is available in the
Request object and can be retrieved by:
def show(self, request: Request):request.app() # will return the service container
Sometimes you really don't care what the key is for the object you are binding. For example you may be binding a
Markdown class into the container but really don't care what the key binding is called. This is a great reason to use simple binding which will set the key as the object class:
from masonite.provider import ServiceProviderfrom app.User import Userclass UserModelProvider(ServiceProvider):def register(self):self.app.simple(User)def boot(self):pass
In order to retrieve a class from the service container, we can simply use the
make method.
>>> from app.User import User>>> app.bind('User', User)>>> app.make('User')<class app.User.User>
That's it! This is useful as an IOC container which you can load a single class into the container and use that class everywhere throughout your project.
You can bind singletons into the container. This will resolve the object at the time of binding. This will allow the same object to be used throughout the lifetime of the server.
from masonite.provider import ServiceProviderfrom app.helpers import SomeClassclass UserModelProvider(ServiceProvider):def register(self):self.app.singleton('SomeClass', SomeClass)def boot(self):pass
You can also check if a key exists in the container by using the
has method:
app.has('Request')
You can also check if a key exists in the container by using the
in keyword.
'Request' in app
You may want to collect specific kinds of objects from the container based on the key. For example we may want all objects that start with "Exception" and end with "Hook" or want all keys that end with "ExceptionHook" if we are building an exception handler.
We can easily collect all objects based on a key:
app.collect('*ExceptionHook')
This will return a dictionary of all objects that are binded to the container that start with anything and end with "ExceptionHook" such as "SentryExceptionHook" or "AwesomeExceptionHook".
We can also do the opposite and collect everything that starts with a specific key:
app.collect('Sentry*')
This will collect all keys that start with "Sentry" such as "SentryWebhook" or "SentryExceptionHandler."
Lastly, we may want to collect things that start with "Sentry" and end with "Hook"
app.collect('Sentry*Hook')
This will get keys like "SentryExceptionHook" and "SentryHandlerHook"
You can also collect all subclasses of an object. You may use this if you want to collect all instances of a specific class from the container:
from cleo import Command...app.collect(Command)# Returns {'FirstCommand': <class ...>, 'AnotherCommand': ...}
This is the most useful part of the container. It is possible to retrieve objects from the container by simply passing them into the parameter list of any object. Certain aspects of Masonite are resolved such as controller methods, middleware and drivers.
For example, we can type hint that we want to get the
Request class and put it into our controller. All controller methods are resolved by the container. Masonite 2.1 only supports annotations resolving by default:
def show(self, request: Request):request.user()
In this example, before the show method is called, Masonite will look at the parameters and look inside the container for the Request object.
Masonite will know that you are trying to get the
Request class and will actually retrieve that class from the container. Masonite will search the container for a
Request class regardless of what the key is in the container, retrieve it, and inject it into the controller method. Effectively creating an IOC container with dependency injection. capabilities Think of this as a get by value instead of a get by key like the earlier example.
Pretty powerful stuff, eh?
Another powerful feature of the container is it can actually return instances of classes you annotate. For example, all
Upload drivers inherit from the
UploadContract which simply acts as an interface for all
Upload drivers. Many programming paradigms say that developers should code to an interface instead of an implementation so Masonite allows instances of classes to be returned for this specific use case.
Take this example:
from masonite.contracts import UploadContractdef show(self, upload: UploadContract)upload # <class masonite.drivers.UploadDiskDriver>
Notice that we passed in a contract instead of the upload class. Masonite went into the container and fetched a class with the instance of the contract.
This feature should not be used and you should instead use the more explicit form of resolving in the section above.
You can technically still resolve parameters with your container like you could in previous versions of Masonite. Resolving a parameter looked like this:
from masonite.request import Requestdef show(self, request: Request):request.user()
Although this was removed in 2.1+, you may still enable it on a per project basis. To enable it, go to your
wsgi.py file and add this to the constructor of your App class towards the top of the file:
container = App(resolve_parameters=True)
Your project will now resolve parameters as well. Resolving parameters looks for the key in the container instead of the class.
The service container can also be used outside of the flow of Masonite. Masonite takes in a function or class method, and resolves it's dependencies by finding them in the service container and injecting them for you.
Because of this, you can resolve any of your own classes or functions.
from masonite.request import Requestfrom masonite.view import Viewdef randomFunction(view: View):print(view)def show(self, request: Request):request.app().resolve(randomFunction) # Will print the View object
Remember not to call it and only reference the function. The Service Container needs to inject dependencies into the object so it requires a reference and not a callable.
This will fetch all of the parameters of
randomFunction and retrieve them from the service container. There probably won't be many times you'll have to resolve your own code but the option is there.
Sometimes you may wish to resolve your code in addition to passing in variables within the same parameter list. For example you may want to have 3 parameters like this:
from masonite.request import Requestfrom masonite import Maildef send_email(request: Request, mail: Mail, email):pass
You can resolve and pass parameter at the same time by adding them to the
resolve() method:
app.resolve(send_email, '[email protected]')
Masonite will go through each parameter list and resolve them, if it does not find the parameter it will pull it from the other parameters specified. These parameters can be in any order.
If you need to utilize a container outside the normal flow of Masonite like inside a command then you can import the container directly.
This would look something like:
from wsgi import containerfrom masonite import Queueclass SomeCommand:def handle(self):queue = container.make(Queue)queue.push(..)
Sometimes when you resolve an object or class, you want a different value to be returned.
We can pass a simple value as the second parameter to the
swap method which will be returned instead of the object being resolved. For example this is used currently when resolving the
from masonite import Maildef show(self, mail: Mail):mail #== <masonite.drivers.MailSmtpDriver>
but the class definition for the
class Mail:pass
How does it know to resolve the smtp driver instead? It's because we added a container swap. Container swaps are simple, they take the object as the first parameter and either a value or a callable as the second.
For example we may want to mock the functionality above by doing something like this in the boot method of a Service Provider:
from masonite import Maildef boot(self, mail: MailManager):self.app.swap(Mail, manager.driver(self.app.make('MailConfig').DRIVER))
Notice that we specified which class should be returned whenever we resolve the
Instead of directly passing in a value as the second parameter we can pass in a callable instead. The callable MUST take 2 parameters. The first parameter will be the annotation we are trying to resolve and the second will be the container itself. Here is an example of how the above would work with a callable:
from masonite import Mailfrom somewhere import NewObject...def mail_callback(obj, container):return NewObject...def boot(self):self.app.swap(Mail, mail_callback)
Notice that the second parameter is a callable object. This means that it will be called whenever we try to resolve the
Remember: If the second parameter is a callable, it will be called. If it is a value, it will simply be returned instead of the resolving object.
Sometimes we might want to run some code when things happen inside our container. For example we might want to run some arbitrary function about we resolve the Request object from the container or we might want to bind some values to a View class anytime we bind a Response to the container. This is excellent for testing purposes if we want to bind a user object to the request whenever it is resolved.
We have three options:
on_bind,
on_make,
on_resolve. All we need for the first option is the key or object we want to bind the hook to, and the second option will be a function that takes two arguments. The first argument is the object in question and the second argument is the whole container.
The code might look something like this:
from masonite.request import Requestdef attribute_on_make(request_obj, container):request_obj.attribute = 'some value'...container = App()# sets the hookcontainer.on_make('Request', attribute_on_make)container.bind('Request', Request)# runs the attribute_on_make functionrequest = container.make('Request')request.attribute # 'some value'
Notice that we create a function that accepts two values, the object we are dealing with and the container. Then whenever we run
on_make, the function is ran.
We can also bind to specific objects instead of keys:
from masonite.request import Request...# sets the hookcontainer.on_make(Request, attribute_on_make)container.bind('Request', Request)# runs the attribute_on_make functionrequest = container.make('Request')request.attribute # 'some value'
This then calls the same attribute but anytime the
Request object itself is made from the container. Notice everything is the same except line 6 where we are using an object instead of a string.
We can do the same thing with the other options:
container.on_bind(Request, attribute_on_make)container.on_make(Request, attribute_on_make)container.on_resolve(Request, attribute_on_make)
By default, Masonite will not care if you override objects from the container. In other words you can do this:
app.bind('number', 1)app.bind('number', 2)
Without issue. Notice we are binding twice to the same key. You can change this behavior by specifying 2 values in the constructor of the
App class:
container = App(strict=True, override=False)
If override is
False, it will not override values in the container. It will simply ignore them if you are trying to bind twice to the same key. If override is
True, which it is by default, you will be allowed to override keys in the container with new values by binding them.
Strict will throw an exception if you try binding a key to the container. So with override being
False it simply ignored binding a key to the container that already exists, setting strict to
True will actually throw an exception.
Container remembering is an awesome feature where the container will remember the objects you passed in and instead of resolving the object over and over again which could possibly be expensive, it will pass in the previous objects that were passed in by storing and retrieving them from a separate remembering list the container builds.
Once an object is resolved for the first time, a new dictionary is built containing that object and it's dependencies. The second time that object is resolved, instead of inspecting the object to see which dependencies it should pass in, Masonite will inject the ones from the remembering dictionary.
This can speed up resolving your code by 10 - 15x. A significant speed improvement.
You can enable this on a per application basis by setting the
remembering parameter to
True on your container class. This can be found in your
wsgi.py file:
container = App(remembering = True) | https://docs.masoniteproject.com/architectural-concepts/service-container | CC-MAIN-2020-34 | refinedweb | 2,345 | 56.05 |
THE ARKANSAS APRIL
1985
** **
GUEST ARTICLES BY DR. ROBERT A. LEFLAR BILL W. BRISTOW VINCENT W. FOSTER, JR. ROBERT D. CABE G. ROSS SMITH PHILLIP CARROLL PROFESSOR ALBERT M. WITTE ROBERT M. CEARLEY, JR. J. W. DICKEY, JR. CELEBRATING LAW DAY - MAY 1ST
*
**
*
*
CJhe Pirste5'lmericall
搂~llrnl11
Serving the Legal Profession SINCE 1889 . '
..
.
~.
"
T
",
. ":,,:
he firm known today as First American Title Insurance Company was already over a decade old when the doors opened on the big, red sandstone Orange County Courthouse in
-: !.;
. ':
Santa Ana, California, back in the 1900路s. Today we are the nation's third largest title insurer, working nation-wide with the legal profession and serving with a special
dedication and attitude that sets this independent title company apart from all the others.
e have the First American Spirit and we.'re ready to assist you!
W
7he First American
First American Title Insurance Company of Mid-America REGIONAL OFFICE: 100 North Main BUilding, Memphis. Tennessee 38173-0073' (901) 525路4343 ARKANSAS TOLL-FREE NUMBER: (BOO) 238路6321
SERVING TITLE INSURANCE NEEDS THROUGHOUT MID-AMERICA AfJiliatrd It'ith The First American Financial Corpomtion
ARKANSAS
LCx
April 1985 Vol. 19. No. 2
THE PUBLlCATtON OF THE ARKANSAS BAR ASSOCIATtON
SPECIAL FEATURES
OFFICERS
REGULAR FEATURES
William R. Wilson. Jr.. President Don M, Schnipper, President-Elect Annabelle D. Clinton. Sec-Treasurer David M. "Mac" Glover. Council Chair
55 57
The President's Report Law. Literature & Laughter
Coming of Age: Women
Wm. A. Martin. Executive Director Judith Gray, Assistant Executive Director
Lawyers in Arkansas
1960-1984, by Annabelle Davis Cli~ton
EXECUTIVE COUNCIL Jack A. McNulty W. Kelvin Wyrick Gary Nutter William Russ Meeks III Kaye S. Oberlag Tom Overbey Robert S. Hargraves Robert Hornberger Joe Reed David Solomon Stephen M. Reasoner James A. Mclarty
58 64 66
Historic Surroundings: An Infinite Variety 01 Law Ollices' Styles and Qualities by Jacalyn Carfagno Some Arkansas Cases. by Frances Mitchell Ross Toward the Bicentennial, Part I by Dr. Robert A. Leflar, Bill W. Bristow and Vincent W. Foster. Ir. The Tax Relorm Act of 1984: Real Estate Transactions. by Michael O. Parker
EX-OFFICIO William R. Wilson, Jr. Don M. Schnipper Dennis L. Shackleford Annabelle D. Clinton Martha M. Miller David M. "Mac" Glover EDITOR Ruth M. Williams
In Memoriam Generations in the Law: William Starr Mitchell and John Thorpe Williams, by Robert L. Brown
71
75
78 89 96 98 99 100 101
Bulletin Executive Director's Report Young Lawyers' Update
Arkansas Bar Foundation
_============================---j
The Arkansas Lawyerby (USPS is lI published quarterly the 546-040) Arkansas Bar Association, 400 West Markham, Little Rock, Arkansas 72201. Second class postage poid at Little Rock, Arkansas. Subscription price to nonmembers of the Arkansas Bar Association S.
La\iJYer ~ TOWARD THE
BICENTENNIAL
• CONSTITUTION GUEST ART1Cl..ES BY DR. ROBERT A. u:rt.AR ..
All inquiries regarding advertising should be sent to The Arkansas Lawyer at the above address.
BIll. W BRlSIOW .. VINCDIT W fOS'lm. JR. .. ROBER\' D. CAN: .. G ROSS SMITH .. PHlllJP
CAFlROI.l. .. PROfESSOR AImU M. WI'Tn: ..
ROBERT M. CEARlEY. IR... r, W DICI<I:Y.!R .. C11£BRAnNG LAW DAY MAY 1ST'
In-House News
ON THE COVER:
The bicentennial observance in 1987 of the United Slates Constitution is being launched in The Arkansas Lawyer with "Toward the Bicentennial of the Constitution" - a series of articles on First Amend-
ment issues pertaining to newspapers, educational materials and cable television programming, Dr. Robert A. Leflar,
in an introduction to the series. reviews the 250th anniversary ofthe John Peter Zenger trial. called the "momingstar of the liberty which revolutionized America." The first articles in the four-part series, by Bill W. Bristow and Vincent W. Foster, Jr., will examine a newspaper's negilgence li-
ability in reporting inaccurate information. April 1985/Arkansas Lawyer/53
It's Open Season On La ers!
In fact, there's no telling when you'll be hit with a law uit by a dissatisfied client. Even the mo t competent attorney cannot always avoid a suit, and often the wealthiest attorney cannot afford one. Right or wrong. the number of claims is growing and the total dollar amount paid out in settlements is growing even faster. But we can help. CNA and the Arkansas Bar Association have worked together to come up with a comprehensive program of professional liability insurance for its members that can help protect both your financial and proessional future. First, it helps to minimize the causes of liability suits through loss prevention programs. Then, it provides financial protection to help guard you against professional and business liability with a maximum of $100,000 per claim ($300,000 annually) after a deductible. Think you need more? Higher Limits-Up to $5 million-are available for an extra measure of security against large liability lawsuits. Any case you handle could leave you wide open to a lawsuit. So, let your Arkansas Bar Association sponsored Comprehensive Lawyers Professional and Business Liability Plan help protect you from financial danger. To find out 54/Arkansas Lawye,/Ap,il 1985
all the important details, including the exclusions, any reductions or limitations and the terms under which the policy may be continued in force, send the coupon below to the administrator: Rather, Beyer & Harper. 362 Prospect Building, Little Rock, Arkansas 72207. Or call (50l) 664-8791.
,---------------------1 I I I I
Please send me information for the Arkansas Bar Association sponsored Lawyers Professional and Business Liability Insurance. Send to:
I
I
i
I I
I
I I I
I~_
'Zip
I
I
Arkansas Bar Association Adminislr:ltor Rather. Beyer & Harper 362 Prospect Building Lillie Rock. Arkansas 72207
I I ~,m I~~ I IC~ I State
I I
Sponsored ...... ~~s~路 by: ~-'A~" .... <;...;.~,JO> ~
,,( \
~ /.0.\'-
I I I I I II I
I
_______________________ J
THE PRESIDENT'S REPORT
courts will correct fortunate situation.
this
un-
In fact, your President has just lost a case in the Eighth Circuit on this precise point. In the District Court I called a forensic psychologist and submitted the affidavits of several leading trial lawyers, to the effect that it is impossible to obtain a fair and impartial jury unless the lawyer for a party can participate. to a reason-
able extent in the voir dire process. A petition for a Rehearing En Blac is pending. Both Arkansas senators are cosponsors and vigorous supporters
'85 Congress of Interest By William R. Wilson, Jr.
of the lawyer voir dire legislation. By the time you read this, the federal product liability legislation will again be pending before Congress. While the Association has not taken a posi tion on this legislative proposal. I can assure you that its passage would be most
Undoubtedly the legal profession will be interested in many issues which will come before the Federal Congress in 1985. The FTC Reauthorization Legislation will undoubtedly be back again, and the organized bar will again attempt to insure that this agency is not given authority to make unwarranted intrusions into
the disci plining of lawyers - a subject that can be best handled by
unfortunate
for
in advance of the 1987 session of the General Assembly to remind all members of the Association that we have a legislative timetable which requires that proposals be submitted to the appropriate committee and House of Delegates several months in advance of a session. I do not know what the exact timetable will be in 1986, but there is no reason to believe that it will not be similar to the 1984 schedule. While it is true that we may miss some worth-
while legislation by requiring advance submissions. the House of Delegates is the policy making aIm of the Association, and it must have time to get recom-
mendations from the appropriate committee before taking a stand. f continue to be amazed that active.
knowledgeable members of the Association submit proposals in November' or December before the
future
General Assembly convenes in
victims of unsafe products. I am happy to report that both sen-
January. So, again, I urge you to file this information in the back of
ators, and most of our congressmen, are on record in opposition
your mind for future reference.
to this legislation. On the home front, Martha Miller, our lobbyist. is working at the Legislature and is doing a topflight job. As the session pro-
gram for our annual meeting in
gesses you will be receiving re-
ports from us. Let me take this opportunity far
Keep your eye open for the proJune - I promise you it will be a lalapalooza. The dates are June 58 - please mark your calendar now. And the members of the House of Delegates are reminded that it will meet Saturday morning, June 8th. 0
the various state supreme courts.
The Arkansas Bar Association is on record on this issue, and your officers will continue to maintain contact with our senators and congressmen.
An attempt will be made to enact legislation which would insure the right of a lawyer for a party to conduct reasonable voir dire examination in cases in Federal District Court. Unfortunately, too many Federal District judges categorically deny this basic due process right. And there is little possibility that the appellate FORENSIC OOCUMENT EXAMINER 1109 N. 4TH STREET MONROE. LOUISIANA 71201 318-322-0661
Qualified and Experienced Expert Witness in Federal, State. Municipal and Militarv Courts.
April t98S/Arkansas Lawyer/55
Consider the evidence. You be the judge: What better location for an attorney in Little Rock is there? The Rogers Building stands within a block of the Pulaski County Courthouse, VALR lAw School • !iui/lg like never hefore. For lea$il/g il/formatioll. Clmlad til(' Doyle Rogl'rs Compally, 221 West Secolld Street, Suite 800, lillie Rock, Arka"sas 72201, (501) 375-1662.
56/Arkansas Lawyer/April 1985
Law, Literature & Laughter A woman will lose her purse at
Stating rules that are helpful in dealing with life has always been popular. Addressing Old Testament legal concepts, scholars have identified two types of laws: apodictic and casuistic. The former is typified by unconditional
imperative
the most inconvenient time. and it
will always be located in a place where it had no business being in the first place.
statements
without any stipulation of consequences or sanctions. For ex-
ample, "Thou shalt not kill" (Ex. 20:13). The latter is characterized by a conditional statement and differentiation of various and subordinate circumstances and is usually based upon the decision of one in authority as to a specific factual experience. Example: "If you buy a Hebrew slave, he shall serve only six years and be freed in the seventh year, and need pay nothing to regain his freedom" (Ex. 21:2). These two categories remain with us. A quick example of a modem day apodictic law is, "The maximum lawful rate of interest on any contract ... shall not exceed five percent (5%) per annum above the Federal Reserve Discount Rate at the time of the contract" (Ark. Const. amend. 60(a)(O ). Casuistic laws are reminiscent of Socratic law school teaching in which one must ferrett out the rule of the case. Example: Certain good faith mistakes of fact resulting in minimal overcharges will exonerate a creditor in an otherwise usurious transaction. Davidson v. Commercial
Credit Corp.• 255 Ark. 127, 499 S. W.2d 68 (973). In the Murphy's Law genre, many have entertained others with principles of diffuse utilization. My favorite is one I heard Phil Carroll read at a Bar Iuncheon some years back: "The odds on the bread falling butterside down are directly proportionate to the cost of the carpet." Casuistic? Ask Phil. In 1978 Russell Baker listed in a column a number of apodictic "principles for the guidance of life." Among such admonitions as "Don't expect love from a cat" and "Never play poker with a man named 'Doc'," the injunction
"Avoid lawyers" appeared three times.
Inundated by letters from lawyers, who Baker said were "hurt rather than angry," he casuistically commented in a later column said he wouldn't mind his sister marrying a successful lawyer. But if she considered an unsuccessful
one, he would "urge her to consider a dentist before doing anything irreversible." The rules we learn to live by, like the laws of Moses, similarly fall into the same two groupings. Examples of modern apodictic laws of behavior: Never assume, especially when the contents of a suitcase are con-
cerned. Unplug the coffee maker if it is past 5:00 and the secretaries are gone. Think twice before saying what's on your mind to the senior partner.
If your wife wants to sleep late, let her. Corrolary: If your husband wants to sleep late, tell him to forget it. Modern day examples of casuistic behavioral precepts: As a deadline draws nigh, the odds that the one thing needed to meet the deadline will be missing incease
exponentially
toward
1.000 to I. To get a room at the Arlington in which the dumpster trucks cannot be heard collecting garbage at dawn, one must specifically request such and endure the chuckles of the desk clerk. Elevators work better and fewer people ride them when you leave early for an appointment. Corrollary: You are ten times more likely to receive simultaneous urgent calls when you're late for a meeting than at any other time.
No doubt the General Assembly had the spirit of the law of Moses in mind when it passed Act 34 of 1969, which was expressly aimed at glue-sniffing. Apparently our lawmakers deemed it wise. however, to list a number of compounds and forbid all methods of ingestion.
Read the statute and I think you will sleep better at night knowing it is unlawful to drink gasoline for the purpose of inducing intoxication without a doctor's prescription. Also, I would like to hear from anyone in a dry county who gets his prescriptions filled at a Fina station.
Legislatures tread on dangerously humorous ground when they set out to prohibit a number of things with one statute. With roots in Pope's Digest, Ark. Stat. Ann. §41-3261 prohibits the betting of money "or any valuable thing on any game of brag, bluff, poker, seven-up, three-up, twenty-one, vingtun, thirteen cards, the odd trick, forty-five, whist, or at any other game at cards, known by any name now known to the laws. or with any other or new name, or without any name ... ' While the statute is apodictic, it led to a casuistic construction.
In 1884 the conviction of a man who, with others, had "engaged in a game of freeze-out pocre," was upheld. Each player was given "a certain number of grains
of corn to be used in counting the game," and it was agreed that the first one "froze out" (losing all his corn) would treat the others to cigars worth a nickel apiece. Wade v. State. 43 Ark. 77. The court cited a Tennessee case in which, under a similar statute. a
man was convicted of playing ten pins with the understanding that if he lost he was "to treat to a bottle of champagne." Cheers! 0 April 1985/Arkansas Lawyer/57
..
Coming of Age: Women lawyers in Arkansas, 1960-1984 By Annabelle Davis Clinton ver 450 women became licensed to practice law in Arkansas between the years 1960 and 1984.' This figure demonstrates the coming of age for women lawyers in Arkansas.
O
Three times as many women en-
tered the legal profession in the last twenty-five years as compared with the preceding forty year period (1918-1959) when only ISO women were admitted to the practice.' The majority (264) have been admitted in the last five years (1980-1984).' Of the 380 women lawyers presently in the active practice of law in Arkansas. 227 are located in Pulaski County.'. The years 1960-1984 saw a continuation of firsts for Arkansas women in the legal profession: the Honorable Elsijane Trimble Roy was the first woman appointed to the circuit bench (1966); in 1974 the Honorable Bernice Lichty Kizer became Arkansas' first elected
woman judge; the Honorable Elsijane Trimble Roy also became the first woman appointed to serve on the Arkansas Supreme Court (1975) and the first woman appointed United States District Court judge in Arkansas (1977). Perhaps the best way to illustrate the coming of age for women lawyers in Arkansas is to present
the personal stories of a representative sample of women lawyers
whose range of professional experience extends from two to 24 years and from a small town family practice to a large law firm Little Rock practice.
Judith Rogers No women were admitted to the
bar during the years 1957-1961. In 1962. judith Rogers broke the drought and became licensed officially at the swearing-in ceremony for new admittees held at the Little Rock Club. an exclusively male club at the time. job offers
Judith Rogers were not the order of the day even
for a lawyer who graduated second in her class from Indiana University School of Law. Rogers entered into a space sharing agreement with attorney Byron Bogard - 50010 of her gross income each year in return for office space. In the beginning her practice was limited to a poor female clientele with mainly domestic relations problems. Rogers admits that she assumed a tough stance partially as a result of her own perception that the world out there was hostile territory for women lawyers. Her reputation
for being pro-female lingered for several years, even after her prac-
tice broadened into the areas of probate, bankruptcy, collection and
workers'
compensation.
Rogers recalls that the practice of law was "gentlemanly"; that is, that attorneys treated each other courteously in matters such as postponements. scheduling of depositions, and in the sharing of advice and counsel. Eventually Rogers' law practice supported the purchase of abuilding. three full-time secretaries and a Mag Card 11. grossing over $100.000 each year. [n [977. Rogers agreed to temporarily assume the position of juvenile judge for Pulaski County. After about three months of balancing a law practice and juvenile Court. Rogers decided to close down the law practice and devote her energies exclusively to
58/Arkansas Lawyer/April 1985 A
the juvenile system. Her tenure as juvenile judge brought Rogers in contact with more people, more pain and more unsolvable problems. In 1982, Rogers was elected to the Chancery bench in Pulaski County to serve out a remaining two-year term. In 1984 she was reelected without opposition. Judge Rogers finds the chancellorship to be another challenge for further professional growth.
Idalee R. Hawkins Idalee R. Hawkins, a native of Texarkana, went to law school for insurance in case she ever had to be sell-supporting, but not necessarily to pursue a legal career immediately. She was licensed to practice law in 1966 and in 1968 began practicing law part路time with her father and husband in their family-owned law firm of Raffaelli & Hawkins at Texarkana, Texas. Hawkins' law practice in her family's firm was adjusted to coordinate with the raising of three children. Both as a result of her own choice and the prevailing attitude that a woman did not litigate, Hawkins pursued a non-adversarial office practice examining abstracts,
preparing
wills and commercial contracts, probating estates, etc. In 1971. she was appointed United States magistrate for the Eastern District of Texas, which position she still holds. On January I. 1985, she was appointed U.S. magistrate for the Western District of Arkansas. Her real desire is to become a specialist in family law - seeking solutions to the myriad problems encountered by spouses, parents and children in divorce and custody matters.
Josephine Linker Hart
Idalee R. Hawkins Hart enrolled in law school at the University of Arkansas and graduated in 1971. Although she had intended to eventually return to the army as a JAG officer, Hart decided to delay pursuing her legal career in the military and take advantage of an opportunity to clerk for the Honorable Frank Holt, associate justice of the Arkansas Supreme Courl. In 1973, she again postponed returning to the army and accepted an offer of employment by the firm now known as Highsmith, Gregg, Harl. Ferris and Rutledge in Batesville, Arkansas. Hart wanted to be in the courtroom; she accepted appointments to represent indigents in criminal cases in order to get the courtroom experience. In fact. she accepted any type of case to get the trial experience. Alter one year with the law firm, she was made a junior partner
and alter three years, a full partner. Her practice now includes
criminal defense, domestic relation cases (including child custody), insurance defense, workers' compensation. and some
Josephine Linker Hart grew up on a farm outside of Russellville, Arkansas, graduated from Arkansas Tech in 1965, and joined the United States Army for service in the Adjutant General's Corps. After four years in the United States Army doing quasi-legal work. including court martial experience while serving in Japan,
plaintiff's personal injury work. Hart's experience with the bench and bar has been positive. She found the Batesville bar to be extremely supportive. In the final analysis, Hart concluded that her status as a woman lawyer was neither an advantage nor a disadvantage - she was just another new lawyer in town, the basic pre-
Josephine Linker Hart mise being that you can do whatever you want if you are willing to work.
Hillary Rodham Clinton Hillary Radham Clinton's experience may not be typical considering her status as the Governor's wife, but otherwise her professional career is fairly representative of women in the large Little Rock law firms. Before joining the Rose Law Firm in 1977, Clinton taught at the University of
Editor's Note: Annabelle Davis Clinton, of Little Rock, is a member of the Wright. Lindsey and Jennings law firm. She is a former circuit judge of the Fifth Division. Sixth Judicial District and is in her third term as secretary of the Arkansas Bar Association. Clinton attended Bates College of Law and the University of Arkansas. receiving a J.D. in 1977. She is a former member of the Houston Law Review, and served as comments editor for the Arkansas Law Review. "Coming of Age, Women Lawyers in Arkansas 1960-1984" is the final in a series of three articles celebrating the lOOth anniversary of women in the law in Arkansas. Our thanks to Clinton, Frances Ross and Jacqueline S. Wright for their research into the past of Arkansas' women lawyers. April 1985/Arkansas Lawyer/59
Georgia Elrod: No access to good 01' boy network I
Hillary Rodham Clinton Arkansas law school in Fayetteville. As an adjunct to her teaching duties she instituted a legal clinic for the representation of indigents in domestic relations, landlord-tenant and credit matters. One particularly noteworthy case involved criminal charges against members of a religious cult for the "unlawful burial" of a child. As an associate at the Rose Law Firm, she handled a variety of matters ranging from anti-trust. securities and product liability litigation to adoption and custody cases. She was actively involved in overturning the state's rule that barred foster parents from adopting their foster children. Because of the demands that domestic relations cases entail. Clinton has limited that aspect of her practice and concentrated on commercial litigation. According to Clinton, she joined the Rose Law Firm to develop trial practice skills and found among her fellow lawyers support. collegiality and high standards. The firm also placed a premium on independence, allowing its members to pursue their individual interests such as her service as a board member and chair of the National Legal Services Corporation. In 1979, Clinton became the firm's first woman portner and the first in a large Little Rock law firm. Since then her practice has focused on complex matters that demand concentrated periods of work such as takeover challenges and suits for immediate injunctive
60IArkansas Lawyer/April 1985
relief. This work also fits her schedule demands as First Lady. Both as a woman lawyer and as the Governor's wife, Clinton has been the object of curiosi ty by both bench and bar. She also has had to consider whether or not her political affiliation might present any conflicts of interest. As in the case of Josephine Linker Hart, being a woman has not been a
significant factor in Clinton's perception of her professional career.
Georgia Elrod
-
;'
,
~-ir\J J
~
Georgia Elrod not have access to the 'good 01' boy network, such as Rotary Club. The client's respect for her professional opinion is an individual matter, with little or no relation to her being a woman. However. on
For a number of years, Georgia Elrod was the only woman attorney in Benton County. Upon admission to the bar in 1974, Elrod went into practice with her husband and father-in-law in Siloam Springs. Over the years her practice has tended to concentrate in chancery court, in the areas of domestic relations, wills, trusts and real estate. Elrod has little interest in trying cases before a jury and in fact believes that her talents are better used in the per-
one occasion a new client ap路 peared for an appointment and was chagrined to learn that Georgia was not George! Elrod finds her practice fulfilling and feels well-accepted in the community.
son-ta-person communications generic to chancery court prac-
lawyers. After nearly 12 years as a research scientist, Roaf. who is female and black, decided to radically change her professional course. She enrolled at the University of Arkansas School of Law at Little Rock and began to Commute from Pine Bluff, where she resides with her husband and four children. Upon graduation from law school in 1978, Roaf's initial quest for employment focussed on Pine Bluff law firms engaged in commercial law practice - without success.' In 1979 Roaf joined the law firm of Woodson Walker & Associates in Little Rock, becoming the third member of that firm. The understanding was that her practice would be devoted to com-
tice. Elrod perceives the struggle to be one of youth and inexperience rather than gender. She readily admits that the establishment of a small town practice would have been significantly harder had she been without contacts and family in the local community. Elrod has felt no discrimination by either the bench or bar. Sometimes a fellow lawyer will comment that she is the best-looking lawyer in the county, which Elrod merely attributes to a particular style of communication that is not intended to
be demeaning. She does not get as many male clients with business problems because as a woman in a small town she does
Andree Roaf Andree Roof's experience in the legal profession brings into focus
factors which are not present in the experience of most women
mercial matters with some pro-
bate and domestic relations prac-
lice. Since the firm had little commercial practice, Roaf began the task of developing the expertise necessary to handle commercial matlers. Roaf has been impressed with the assistance offered by senior members of the Li ttle Rock bar in response to her requests for advice and counsel. Occasionally a client will express discomfort with the idea of being represented by a woman lawyer. Six years later the goal of establishing a full service law firm is closer to becoming a reality. Roaf devotes 50"10 of her lime to the commercial practice. The effort to attract more corporate clients, as
opposed to individual clients, is proving to be successful. Compared to her experience as a research biologist with limited human contact in the laboratory, Roaf finds the law practice to be more rewarding - offering a greater opportunity to help people solve their problems.
Jo Ann Compton Maxey
Andree Roaf
10 Ann Compton Maxey The most junior member of this representative sample has been
practicing law for less than three years. )0 Ann Compton Maxey directed the funding activities for the Arkansas Community Foundation and clerked for the Little Rock law firm of Kaplan. Brewer &
SAS COURT RULES 1985 Edition Arkansas Court Rules, 1985 Edition contains, in one convenient volume, all Arkansas court rules with annotations. Upto-date through February 1, 1985, it also includes federal circuit and district court rules. Each set of rules is indexed separately and official commentary is carried where applicable. $27.50* Appx. 900 pages, softbound, replaced annually 漏 1985, The Michie Company
THE
MICHIE COMP~ ~
A publishing subsidiary of I
For customer service contact: ALLIN R. JONES P.O. Box 1306 Conway, Arkansas 72032 (501) 327-6526
Or call toll-free 1-800-446-3410. 'plus Shipping, handling and sales tax where applicablt路,
April 1985/Arkansas Lawyer/6l
*1984-85 Arkansas Women Attorneys f~'OfO
5
1
5
1
3
6
2
Total:
380
""'" 3
--
'Statistics
based on 1984-85 Attorney Roster from Arkansas Legal Directory.
""
ARKANSAS
Miller, P.A.. while attending the night division of the University of Arkansas School of Law at Little Rock. The clerkship experience with the Kaplan firm eventually evolved into full-time employment as an attorney after Maxey graduated from law school in 1982. Federal court has been Maxey's turf in the context of civil rights litigation and the hotly contested Little Rock School District consolidation case. She is also beginning to develop a general practice
some
domestic
re-
lations. probate and commercial matters. As with most newlylicensed attorneys. Maxey has followed the maxim: prepare well to balance out lack of experience. 621Arkansas Lawyer/April 1985
She echos other women lawyers in observing that her experience with other members of the bar has been no different from that of any other new attorney. Male clients have been watchful in evaluating Maxey's professional competence. In contrast. Maxey senses
that she has to work harder to convince female clients that she is capable. which may be merely a reflection of the female client's
lack of confidence in herself. Maxey has also noticed that some women lawyers try to be too stalwart. possibly in an effort to present an impression of strength.
In the second year of her practice. Maxey joined the increasing number of women lawyers who are
Female Participation in ABA Sections Economics of Law Practice 10"10 (69m Family Law Section. . . . . . . . . .. 13% (234130) Labor Law Section. . . . . . . . . . . .. 13"10 (69/9) Probate Law Section. . . 6% (l68!IO) Real Estate Law Section. . 5% (153m Savings & Loan Section. . . . . . . . . . . . . . 0 (44/0) Section of Taxation ... 3% (148/4) Workers' Compensation Section. . . . .. 5% (207/10)
Arkansas Supreme Court Licensed Female Attorneys 1960-1984
1960 0
1961 0
1962 1
1963 1
1964 1
1965 4
1966 1
1967 3
1969 2
1970 2
1971 5+1?
1972 6
1973 10
1974 5+1?
1975 20+1?
1976 25+1?
1978 46+3?
1979 63+1?
1980 59+1?
1981 52
1982 29+2?
1983 65+2?
1984 59+2?
1968 1
1977 27+1?
*Totals: 487+ 16?
-
*The 16? total represents those attorneys whose gender cannot be determined. balancmg motherhood with the practice 01 law. Since late night and weekend work can no longer be the rule. Maxey strives lor greater elliciency and productivity during regular working hours. Professional organization work has been deferred for the foreseeable future. With the acceptance that she cannot be the best lawyer. wife and mother. Maxey endeavors to do a good job and is proud of her contribution to the legal system. What conclusions can be drawn about the luture for women lawyers in Arkansas? The groundwork laid by women licensed to practice law between 1918 and 1959 has made it poSSible for those entering the legal profession since 1960 to reap the rewards of unlimited opportunity. Unlimited opportunity brings hard decisions about career. marriage. children a balancing ellort that defies per-
feet answers and necessarily re-
sults in compromise.
There are still more firsts to be achieved in Arkansas: election of a woman to the (I) circuit court bench; (2) Arkansas Supreme Court; (3) Arkansas Court of Ap¡ peals; and (4) presidency of state and local bar associations. just to name a few. But the real task is not in the achievement of firsts but in what women have to oller to the legal prolession in its ellort to resolve disputes without resorting to violence. Women in this society have learned to be supportive. nurturing, and sensitive to the
feelings of other human beings. The challenge to women lawyers is to integrate those interpersonal communication skills into the practice of law. and thereby make the resolution of legal disputes a healing. rather than divisive. process.
o
FOOTNOTES 'Clerk of the Arkansas Supreme Court. Register of Attorneys licensed to practice law in Arkansas. , Clerk of the Arkansas Supreme Court. Register of Attorneys licensed to practice law in Arkansas. , Clerk of the Arkansas Supreme Court. Register of Attorneys licensed to practice law in Arkansas. • The Arkansas Legal Directory. 1984-1985. Women attorneys listed in the Arkansas Legal Directory were designated as being in the "active practice of law." By way of caveat. these statistics may include some errors in the
determination of gender. , According to the Arkansas Legal Directory. 1984-1985. seven women are presently in the active practice of law in Jellerson County. Arkansas. April 1985/Arkansas Lawyer/63
IN
MEMORIAM of Arkansas to study journalism. He later switched from journalism to language and volunteered for the Army in World War II. He was on the first convoy into Normandy after the D-Day invasion and served there as an inter-
Survivors are his wife, Esther
preter until he was wounded in 1944. He received the Purple Heart and three Battle Stars for his mili-
White Putman of Fayetteville; a son, William Putman IV of Champagne, Ill.; and, two hal/brothers. Dr. Robert Dickson of Pueblo, Colorado. and James F. Dickson of Fayetteville.
tary service. He also served as an
interpreter for the chief of the German Civilian Police until December 1945 and, in 1948, went to work for the Stanolind Oil and Gas Company in Columbia, South America. Between his military service and his position as an interpreter
William B. Putnam William B. Putman III, aged 61. of Fayetteville, died Thursday, December 13, 1984. A lecturer at the University of Arkansas at Fayetteville School of Law and a criminal defense lawyer. Putnam was a member of
the W. B. Putnam law firm. He was appointed a special justice to the Arkansas Supreme Court on different occasions in 1968, 1970 and 1971. and had served since 1962 on its Committee on Model Jury Instructions. In September, Putman was inducted as a Fellow in the American College of Trial Law-
for the oil firm, he completed his bachelor's degree in journalism and language at the University. The Arkansas Gazette reported that although he said in 1977 that he
"remained
a
journalist
at
heart," he entered the Fayetteville law school in 1951 and completed his degree in 27 months. Putman served as a United States commissioner from 1954-61. was a Washington County elec-
tion commissioner from 1957-61 and began lecturing at the Fayetteville law school in 1956. He was a member of the Arkansas Board of Law Examiners from 195964. He was considered an expert on
American Western art and had one of the largest collections in the state. A 31-year member of the Arkansas Bar Association, Put-
yers.
man
He graduated with honors in 1953 from the Fayetteville law
legal education, judiciary, unau thorized practice of faw, legal
school. where he served as editor
education and judicial nations committees.
in his senior year of the Arkansas Law Review. A native of Springdale, Putnam was the only child of the late William Benjamin Putman II and Maxine Corbin Putman. He was
graduated from Fayetteville High School and entered the University 64/Arkansas Lawyer/April 1985
He was a fellow of the International Society of Barristers, a member of the American Judicature Society, Phi Alpha Delta, Omicron Delta Kappa and Sigma Alpha Epsilon.
served
on
its
continuing
nomi-
He was a former member of the
Arkansas Bar Foundation Board of Directors and was a former pres-
ident of the University of Arkansas Law School Foundation and Washington County Bar Association.
Edgar A. Woolsey Edgar A. Woolsey Jr.. aged 48, of Clarksville. died Saturday. January 26. 1985. The senior partner in the Clarksville firm of Woolsey and Wilson, he had served as Johnson County deputy prosecuting attorney, as juvenile judge and as Clarksville city attorney. Born north of Ozark, Woolsey graduated from Ozark High School in 1954 and attended Arkansas Polytechnic College on a working scholarship operating an experimental farm. After studying agriculture he transferred to the University of Arkansas at Fayetteville where he received a bachelor of arts degree in 1958. In 1960 he received a bachelor of laws degree which was replaced with a juris doctor degree in 1969, While in law school. Woolsey was elected president of the Arkansas Law Students' Association, marshal of Phi Alpha Delta Legal Fraternity and assistant attorney general for the University. Woolsey was licensed in 1960 to
practice law in the state and federal courts. He practiced law three years in Harrisburg. A 24-year member of the Arkansas Bar Association, Woolsey was also a member of the Johnson County and American Bar Associations.
He was a member of the Board of Directors of the Christian Civic Foundation of Arkansas and the Arkansas Basin Foundation, director of the Ozarka three-state commission, member of the Johnson County Chamber of Commerce
and
a
member
of
Searcy; his parents, Mr. and Mrs. Edgar Woolsey Sr. of Ozark, and a sister, Mona Beth Brown of Ozark.
David Wilson Brandt
the
Mid-Arkansas River Valley Regional Planning Commission. He was president of the Johnson County Bridge Association and cochair of the Johnson County Peach Association. Woolsey was raised to the sublime degree of master mason in
1969 in Franklin Lodge No, 9 where he was master in 1976 and later secretary, He became a certified lecturer in 1973, certified instructor in 1974 and served as deputy district custodian of District 25 for four years, He raised more than 300 candidates to the degree of master mason. He was a dual member of
Ozark Lodge No. 79, a member of Clarksville Royal Arch Chapter No. 49, Orsiris Council No.5 Royal and Select Masters and Jacques Demolay Commandery No. 3 in Fort Smith. Woolsey was an officer of the Trinity Conclave, Red Cross of Constantine in Fort Smith, the Western Arkansas Consistery, a knight commander of the Court of Honor, orator of the Rose Croix Chapter, past-patron of Clarksville Chapter No. 172, Order of the Eastern Star, and served as the grand master of the M,W. Grand Lodge of Free and Accepted Masons of Arkansas. He was a member of the First United Methodist Church m Clarksville and served on its administrative board. He was associate director of Laity for the Fort Smith District of the North American Conference.
Woolsey was a member of the Board of Directors of the Western Arkansas Area Council, Boy Scouts of America, served on the Mt. Magazine District Sub-
David Wilson Brandt. aged 36, of Fayetteville, died Thursday, December 20, 1984. A member of the Bumpass and Brandt law firm in Fayetteville, Brandt was the Washington County coordinator for Governor
Bill Clinton's 1984 re-election campaign. Born in Cape Girardeau, Mo .. Brandt was the son of the late Richard and Edna Brandt. He earned a bachelor's degree in political science and a juris doctorate degree from the University of Arkansas. He received a master
of laws degree in taxation from Southern Methodist University. He was admitted to the bar in 1974. Brandt was formerly a trust officer for First State Bank of Springdale, He was president of C,A.R.E. Inc., a nursing home and health care company. Brandt was a member of the Washington County and American Bar Associations and St. Paul's Episcopal Church of Fayetteville. Survivors are his wife,
Joan
Greene Brandt; a son, Wilson David Brandt, both of Fayetteville; and, a brother, Joe Brandt of Edina, Mo.
ber of Franklin County Farmers Association. Survivors are his wife, Neva
Belcher King; two daughters, Hillary Marie and Haley Noel; his mother, Myrtis King, all of Ozark; and, two sisters, Lucille King Sowell and Reba King Irons, both of Fort Smith.
Wayne Jewell Wayne Jewell. aged 74, of El Dorado, died Wednesday, November 28, 1984. A native of Greene, Iowa, Jewell practiced law in El Dorado for more than 51 years. He was a member of the Arkansas and Union County Bar Associations. He was a life member of Kiwanis International, served as
president of the EI Dorado Kiwanis Club in 1938 and as secretary of the MO-KAN-ARK district of Kiwanis International in 1939. He held a perfect attendance record for a number of years at the local Kiwanis Club. King was one of EI Dorado's first Eagle Scouts. Survivors are his wife, Mrs. Nettie Hunt Jewell of EI Dorado; four daughters, Sylvia Jewell of Juneau, Alaska, Helen Decker of San Leandro, Calif.. Rebecca Hill of Napa, Calif., and Carla Jewell of New Jersey; a son, James Jewell of EI Dorado; and, two grandchildren. 0
A. Jack King A. Jack King, aged 55, of Ozark. died Thursday, November 29, 1984.
HEIRS lOCATED
King was a former Ozark muni-
cipal judge and Franklin County juvenile judge and an Ozark farmer.
Missing and unknown heirs idenlified and lo-
He was a retired lieutenant colonel in the United States Air Force, with 25 and one-half years
cated by licensed invesligator with 15 years of gcneOllogical and search experience. All fees contingent upon successful search.
committee and was a member of
of service.
the Order of the Arrow of the National Brotherhood of Scout Honor Campers. Survivors are his wife, Jacquelene Woolsey of Clarksville; a daughter, Victoria Jane Woolsey of Clarksville; two sons, David Allen Woolsey of North Little Rock and Paul Edward Woolsey of
The son of Andrew J. and Myrtis Yeartha King, he was member of the Arkansas Bar Association since 1976. King was a member and chairman of the board of First United Methodist Church, chairman of the board of trustees of Turner Memorial Hospital and board mem-
Carol Briggs RR#2, Eldridge, Iowa 52748 (319) 285-4509
April t985/Arkansas Lawyer/65
Standing in Iront 01 Chancellors Hall 01 Trinity Episcopal Cathedral in Little Rock are (from lell) Robert D. Ross. Marilyn Mitchell. Frances Mitchell Ross. Virginia Mitchell. John Thorpe Williams and Elizabeth Williams.
William Starr Mitchell John Thorpe Williams By Robert L. Brown 66/Arkansas Lawyer/April 1985
Generations in the Law: A Series William Starr Mitchell. deceased on November 25, 1981. and John Thorpe Williams practiced law in different Little Rock law firms during their heyday (Chowning, Mitchell. Hamilton & Burrow in the case of Mitchell; Smith, Williams, Friday & Bowen in the case of Williams) and were not related or close social friends. Yet the two men typify a generation of successful lawyers and, more importantly, a style of practicing law that has inspired numerous successors to the practice and even
some of their peers. In a profession often perceived as composed of overly zealous desk-pounders or clever finnaglers, the two men's careers are examples of integrity.
Photo by Willie Allen
Their lives intertwined like figure eights
competence, humility, dedication to community, and compassion. William H. Bowen, a former law partner of John Williams and now chairman of the Board of First Commercial Bank of Little Rock, makes the case succinctly: "If more lawyers like Will Mitchell and John Williams predominated, the profession would be viewed much more favorably." Born two years apart. their lives like figure eights intertwined repeatedly. For years their law firms occupied adjoining floors in the Boyle Building in downtown Little Rock. They were both presidents of the Arkansas Bar Foundation during the watershed period when the purchase of the land and construction of the Bar Center and Law School next to the Camelot Hotel were being structured. They served for years on major Little Rock bank boards. Most significantly, both men have given tirelessly of their time and efforts to the Bar, their community, and their church which they shared in common - Trinity Episcopal Cathedral in Little Rock. In recognition of their countless hours of devoted service as chancellors, or chief legal advisors, to the Episcopal Diocese of Arkansas, Trinity Episcopal Parish and the Diocese recently re-
named a building on the Cathedral grounds Chancellors Hall in memory of William Starr Mitchell and in honor of John T. Williams. There
are
other
connecting
points in their lives as well. Law partners and friends of the two men assign them the same work habits and personality traits: gentle, scholarly, meticulous. ethical. low key, slow to anger but quick to defend what's right. and an intense interest in and dedication to the betterment of their fellow man. When contemporaries of Will Mitchell are asked about the man and his legal career. he is often described as "too good to be true." "If the devil walked into this room today, Will Mitchell would have something nice to say about him," former law partner W. P. Hamilton was fond of saying. Others maintain that Will Mitchell missed his true calling - "he would have been a magnificient minister," they say. Born in Little Rock in 1907, Will Mitchell had his origins in both publishing and business. His grandfather, James Mitchell. had been editor of the Arkansas Gazette and an owner of the Arkansas Democrat. He attended Editor's Note: Robert L. Brown is a member of the Little Rock law firm of Harrison and Brown, P.A. He was formerly in general law practice with the Chowning, Mitchell. Hamilton and Burrow law firm, now defunct. Brown is a former administrative assistant to Congressman Jim Guy Tucker, former legislative assistant to Senator Dale Bumpers, and former legal aide to Governor Dale Bumpers. He is a former deputy prosecuting attorney in the 6th Judicial District. He received an LL.B. from the University of Virginia in 1968 and is the author of several previous articles in The Arkansas Lawyer on "Lawyers in the Governor's Office" and "Lawyers As Law-
makers." April 1985/Arkansas Lawyer/67
public schools in Little Rock, Carver Military Academy and graduated from Princeton University, where he was known as Bill, in 1929. His Grand Tour alter college was not limited to Europe but embraced the entire world. He traveled with a friend on a budget of $1,000 and when his money ran out he had to work his way home across the Pacific Ocean in the engine room of a steamer.
Following Princeton and his traveling adventures, he began his legal studies at the University of Arkansas School of Law and then entered Yale University where he received an LL.B. degree in 1933 and roomed with Henry W. Gregory, the prominent Pine Bluff attorney. He then came home and after being admitted to the Arkansas Bar, he practiced with the law firm of Rose, Hemmingway, Cantrell and Loughborough in Little Rock. In 1938, he married Virginia Grobmyer of Forrest City, became an associate in the firm of Moore, Burrow & Chowning which eventually became Chowning, Mitchell, Hamilton & Burrow. There was not much that Will Mitchell did not do for the Bar Association or for his community. Indeed, he was so dedicated and willing to help and so thorough in his work, he was often called on to give more than his fair share. It was commonly accepted that whenever Will Mitchell did something, he gave 1.000 percent whether it be founding the Arkansas Bar Foundation in 1959, president of the Arkansas Bar Association which he was in 196061. president of the Chamber of Commerce for Little Rock which he was in 1963, chancellor of the Diocese of Arkansas which he was from 1955 to 1964, director of Union National Bank, or leader of the former Community Chest. He also headed the Justice Building Commission and worked for an amended judicial article for the State Constitution and for an integrated Bar Association. During his tenure in leadership for the Bar Association and Chamber of Commerce, he was renowned for trying to attend every committee meeting. Unlike some who seek leadership positions to advance their careers. former law
partner Lawrence B. Burrow says Mitchell did just the opposite. "He 68/Arkansas Lawyer/April 1985
studiously avoided any appearance of a conflict of interest and would have been undone if a conflict had been suggested," says Burrow. Burrow adds, "Will Mitchell believed in the notion of avoiding the appearance of conflicts before that notion was popular." "Will Mitchell's priorities can be summed up easily," says W. P. Hamilton. "First, his family, then his church and the Bar in that order." There is no question that Will Mitchell's finest hour was during the volatile school desegregation crisis in 1959 when he was campaign chairman of the Committee to Stop this Outrageous Purge (STOP), a group designed to thwart the firing of Little Rock schoolteachers and principals because of their associations and to recall segregationist members of the Little Rock School Board responsible for those firings. At the time, the Little Rock Public Schools had been closed by legislative act and Little Rock was under the microscope of an international media. The STOP campaign under Mitchell's direction represented a turning point in the desegregation crisis and set the stage for the peaceful integration of the Little Rock Public Schools. There were other high points in Will Mitchell's legal career. One certainly had to be his introduction of Vice President Lyndon Johnson at the annual meeting of the Arkansas Bar Association in Hot Springs in June, 1962. He worked for days on the introduction and it was so detailed and full-blown in its wit and illustrations that Johnson subsequently referred to it in Washington repeatedly and offered Will Mitchell a position on the newly formed United States Civil Rights Commission - a position Mitchell refused to take. When the American Bar Association met in London during Ed Wright's tenure as president in July, 1971, Will Mitchell was chosen to read the Old Testament lesson from the lectern at a ser-
vice at St. Paul's Cathedral. He read from Leviticus. Appropriately enough, the lesson was on loving thy neighbor. And then for some eight years he joined a group of friends including Chancery Judge Bruce Bullion
in editing "Arkansas Bylines" which was a mimeographed bulletin to Arkansans in the armed service and particularly in Viet Nam and which contained a telescoped version of news stories about Arkansas. At the time Mitchell described it as a morale builder: "It was started when there was so much criticism of the war and when
relatives
of
servicemen
were being harassed. We wanted to do something to offset this." Former Bishop of the Episcopal Diocese of Arkansas, Robert R. Brown, worked closely with Mitchell during the school crisis and refers to him as a "perfectionist." Others type him as thorough to a fault and as a man who did tbings in excruciating detail. Often, there was no way he could bill a client for the time and effort he had put into a case. On one occasion his son, Jim. who is a lawyer
and probate judge in Augusta, Maine, recalls him attending a field survey in Scott, Arkansas over a few feet of land. Jim raised the question of how he could charge for the work involved. His father answered simply: "[ can't charge for it." His modesty and humility were perhaps best illustrated by the extremely difficult time he had in billing clients. There is also the story that when Will Mitchell's tum came to be president of the Arkansas Bar Association, he had not prepared someone to place his name in
nomination. Undoubtedly, he was embarrassed by the act, and friends had to scramble to do so at the last minute. He was a man of warm humorunder all circumstances - which made him much in demand as a master of ceremonies. When hos路
pitalized for his first heart attack, the doctor entered his room and advised him that he was going to check his pulse. Will Mitchell responded: "Doctor, I am sure glad you are not a lawyer. A lawyer would have said: 'I'm going to check your pulse, if any.' .. John Thorpe Williams was born on March 8, 1909 in Lonoke, Arkansas where his father was a grocery merchant. His father, Carroll A. Williams, had migrated from Shelbyville, Tennessee; his mother, Mary Thorpe, from Prairie Grove in Washington County,
"
Arkansas. Growing up, Williams had three brothers and four sisters and recalls times as being rough. Despite the economic straits, he attended Lonoke High School and graduated in 1927 as valedictorian of his class. He then came to Little Rock where he worked at the Rock Island Railroad in various capacities while attending Robinson Business College and subsequently the Arkansas Law School. He recalls that during these hard times there was a whole group of attorneys who still practice law who attended the Arkansas Law School. He earned his LL.B. in 1931 and was admitted to the Arkansas Bar in 1933. He didn't begin the practice of law right away because he had a job and they were hard to come by. During the early thirties he shuttled back and forth between work with the Rock Island (traffic manager) and with Standard Oil Company of Louisiana (sales), but in 1936 he broke away from business and joined then Prosecuting Attorney Fred A. Donham's staff where Pat Mehaffy, later chief judge of the Eighth Circuit U.S. Court of Appeals, worked as chief deputy. Williams worked as a deputy prosecuting attorney and as a grand jury reporter for three years and in 1939 joined the staff of United States District Judge Harry J. Lemley as secretary, law clerk and court reporter. At the time, Judge Lemley was a roving judge for the Eastern and Western Districts of Arkansas with his base in Texarkana, which is where Williams moved and lived for ten years. While there, he met Elizabeth Green of Hope and they were married in June of 1941. Following his work with Judge Lemley, John Williams served as chief assistant attorney general in Ike Murry's office in 1949 and in 19SO joined the respected law firm of Daggett & Daggett in Marianna where he practiced until 1952 when he joined Pat Mehaffy and William J. Smith in the formation of a new law firm - Mehaffy, Smith & Williams, the predecessor of what is now Friday, Eldredge & Clark in Little Rock. In that firm, Williams specailized as district attorney and then assistant general counsel for the Missouri Pacific Railroad Company and counsel
for the Little Rock Housing Authority and for the State Highway Department in which capacity he handled land condemnation litigation. Later, the State Highway Department was to develop its own in-house legal staff, a development which John Williams championed and helped to implement.
In addition to his service as president of the Arkansas Bar Foundation and as a member of
the Board of Directors of First National Bank of Little Rock from 1963 to 1982, John Williams headed the State Legislative Committee of the Chamber of Commerce for Little Rock in 1963 and 1964. Perhaps he is proudest of being a moving force behind the building of the Good Shepherd Ecumenical Retirement Center in
Little Rock which can house 280 residents and where he has served in numerous capacities since its inception. He currently serves as the Center's chairman of
the Board. "He is always there and always available with information,
It
says
lawyer
Diane
Mackey, who also serves on the Board. His former law partner, William J. Smith, describes Williams as "one of the finest gentlemen I ever knew." "We were partners for thirty years and never had a cross word," Smith adds. "He is a great Christian and I think he has demonstrated that. He has a high standard of ethics as a lawyer which through his own practice he passed on to younger lawyers who worked with him. Indeed, he was a mentor for a number of
lawyers in the firm." John Williams' religious convictions were "demonstrated in
his daily activities," according to Smith. "He is a man who has a fine command of the English language. He does not resort to profanity to stress a point as many people do." Since 1974 when John Williams became counsel to his law firm, he has kept office hours, but worked three to four hours a day on matters for the Episcopal Diocese of Arkansas. The Bishop of the Episcopal Diocese, Herbert A. Donovan, describes Williams as having
"0
clear cut sense of
what's right legally and morally. But there is something else that al-
ways comes through," Bishop Donovan goes on, "and that is his pastoral concern for people. He has a marvelous ability to care about people." There is not much that John Williams has not done for his church. He has served as president of the Trinity Parish laymen, been delegate to at least four national conventions. served as se-
nior warden for Trinity Cathedral on three occasions, headed fund raisers, and led search committees for the selection of a bishop and dean, just to name a few. Whether it be negotiating longterm financing or giving advice on a personal crisis. Bishop Donovan describes John Williams as an invaluable counselor and rock of support. He is a man who knows how to get things done, quietly and effectively. Dean Joel Pugh at Trinity Cathedral says Williams not only gives advice, "but helps you carry that advice through." And then there is his common sense. "A part of that is knowing the reali ties and not trying to get around them," says Pugh. "John and I were once at a meeting where a discussion was made and someone asked if the discussion was to be kept a se-
cret. John said, 'Don't two people know it? Of course it's not a secret.路 "
Other members of Williams family have had associations with a legal career. His sister, Beulah Williams, worked in Hot Springs as a legal secretary for the law firm of Morris & Barron. But she admits the highlight of her career was her work with then Senator Harry S. Truman in Washington on Truman's War Effort Investigation Committee during World War 11. His brother, Thomas D. Williams, was admitted to the Arkansas Bar in 1935, but subsequently joined the Army and made the Army his career. Another sister, Ethel Williams Carpenter, worked for United States District Judge Thomas C. Trimble when he was in private practice in
Lonoke. William J. Smith, in contemplating both men, sums it up nicely: "When you soya gentlemen has humility, compassion, and integrity, that's about it. and that's what I'd say about both of them."
o
April 1985/Arkansas
Lawyer/69
Leake路lngham Building in Camden. 70/Arkansas Lawyer/April 1985
Photo courtesy 01 Arkansas Historic Preservation Program
Historic Surroundings: An infinite variety of law offices' styles and qualities As long as there have been lawyers there have been law offices. Like lawyers themselves the offices' styles and qualities have had an almost infinite variety and have reflected their surroundings. From the mid-nineteenth century to the present law offices have played a prominent role in defining our downtowns, built as they frequently are near the center of a
Among the earliest buildings constructed for law offices that remain in Arkansas is the Leake-
Ingham building in Camden. Constructed about 1850 this building, which has been moved. stood for over a hundred years at the corner of Washington and Harrison streets in
city with quick access to courts,
the heart of Camden. Mr. William W. Leake, a prominent Camden attorney, built it. He had at least three different part-
libraries and other professional
ners in his practice there. The
concerns.
Classical style of this small building gave it a dignity appropriate to its use and others. By 1866 Leake had rented it to the Federal government as offices for the Freedmen's Bureau and later as a Government Land Office. The cost of construction is not known but records do show Mr. Leake paying a $16.00 premium on a $1.000 fire insurance policy. In 1906 the Camden Library Association purchased the building for $1.100 and it has served since as a library. In addition to carrying the name of Leake the building name recognizes Mr. and Mrs. H. M. Ingham who made substantial con-
In recent years many lawyers have looked to older structures surrounding and in their downtowns as possible office space. In addition to good location these historic structures frequently offered high quality and distinctive space at relatively low cost. The Arkansas Historic Preservation Program (AHPP) has had the pleasure of working with lawyers, architects and developers in planning and executing many of these projects while also working with other groups that have taken what used to be law offices and turned them to new uses.
tributions to the purchase and conversion of the building. A little farther south is the King-Whatley building in Lewisville constructed in 1902 as a bank. Lewisville was thriving as a county seat in cotton-growing
country with the railroad running through. By 1919 the bank had moved and David Latimore King acquired the building. It remained a law office accommodating the practice of King and his son-in-law. George Whatley until about 1960. King was prominent in legal and political affairs of southwest Editor's Note: Jacalyn Carfagno, of Little Rock, is a planning specialist with the Arkansas Historic Preservation Program, a division of the Department of Arkansas Natural and Cultural Heritage, and is responsible for public relations, gran ts and general
administrative concerns. She holds a B.A. from the University of Arkansas at Little Rock and received the Booker T. Worthen Award for Outstanding History
Graduate.
By Jacalyn Carfagno April 1985/Arkansas Lawyer/71
Arkansas serving as the first Democratic sheriff of Lafayette County since 1865 and later as a state representative and state senator. Although the KingWhatley building is no longer used as law offices it remains in the hands 01 King heirs and has recently been the subject of extensive restoration efforts. taking advantage of Federal tax incentives for preservation projects. Another historic law office now serves as the Arkansas City museum in Desha county. It was built in the final decade of the nineteenth century as a law office. One of its occupants was Xenophon Overton Pindall (more commonly referred to, not surprisingly, as ''X. 0.") who served as acting governor of Arkansas lor almost two years from May 1907 to January, 1909. The museum is close to the heart of this once thriVing river town. Only a short distance from the county courthouse it sits with its back to the levy. The building's use apparently strayed from the law when, according to local reports, a shallow cellar underneath was used as a still during prohibition. The changing uses of buildings have brought many early structures that were houses, offices of another type. government buildings and even, in one case, a jail into play today as law offices. Some of the finest restoration and rehabilitation projects carried out in Arkansas have involved law uses from the Old Post Office and Customs House in Little Rock that now serves as the University of Arkansas at Little Rock School of Law to another Old Post Office, this one in Camden, that houses the county law library. The Camden Post Office combines several uses. In addition to the law library it houses the offices of attorneys Hamilton H. Singleton and James D. Foyil as well as other office space and two retail outlets. Here again the location is critical. the Post Office sits only a block from the county courthouse and in the middle of the downtown business district. The building, 721Arkansas Lawyer/April 1985
The Guisinger building on Fayetteville's square is another adaptive use to law offices that has taken advantage of the federal tax incentives. Built in 1886 to house a hardware business the building was bought in 1925 and somewhat altered by Ivan Winford Guisinger for his music business. Guisinger had enormous success and the business
Arkansas City museum in Desha County, Photo Courtesy of Arkansas Historic Preservating Program
which had been sold as surplus by the General Services Administration (GSA) to the Berg family of Camden was the subject of grant funds administered by the AHPP and was also a project that took advantage of the tax incentives.
continued in this location, run by his sons, until 1981. It was purchased in 1982 to house the law firm of Odom, Elliott, Lee and Martin. The ground lIoor used largely as reception and clerical space gets abundant natural light through the large display windows that Guisinger installed to show his pianos and other wares. The upper story was originally one large storage space and has been adapted to private offices. Both lIoors have pressed tin ceilings which re-
main in excellent condition. The most common adaptive uses for office space are of older homes. With their formal entryways, excellent natural light and generous proportions they have lent themselves easily to
LICON SERVICES, INC. 10825 Financial Centre Parkway - Suite 400 Little Rock, Arkansas 72211 Telephone No. 224-6361 (501) Specializing in background, location of witnesses, interviews, and other general investigative work for attorneys. All are former F.B.I. agents, with extensive investigative experience. John (Jack) Kenney, President. (Former Assistant Agent in Charge for Arkansas)
office uses. The most recent such project is the PrigmoreMartin House, occupied by the firm of Eilbott Smith Eilbott Humphries & Taylor in 1984. Built in 1874 by George W. Prigmore who had come to Arkansas from Illinois the two story house occupies a prominent comer lot on Fifth Avenue, one of the main arteries in Pine Bluff. The primary rooms in the two stories are used now as private offices.
The reception area, clerical and service spaces are contained in
two additions to the rear of the house. The transformation into offices required few significant changes in the layout of the house and ample parking has been provided at the rear and sides. This project has gained considerable local support and has served as an impetus for further rehabilitation work in this older Pine Bluff neighborhood. The Walker-Stone house on Center street in Fayetteville now houses the law firm of Kincaid, Horne & Trumbo. Rehabbed in 1979 and '80 with the assistance of a historic preservation grant the house was built in 1845 by Judge David Walker. Judge Walker owned it only briefly selling it in 1850 to Stephen K. Stone, grandfather of the noted architect Edward Durrell Stone. Its present use recalls the build-
Prigmore-Martin House in Pine Bluff,
Photo courtesy of Arkansas Historic Preservation Program
, L
ing's early connection with an
attorney and is part of the exciting redevelopment that has taken place on and around the Fayetteville square. The Gann House in Benton has been one of the proudest projects accomplished in that community, restoring this 1895 Queen Anne home to a place of
Gann House in Benton.
prominence and giving it a new
use as the offices of attorneys Sam Gibson and George Ellis. Although many interior features had been lost the original stained glass remained as did some of the interior woodwork including all the mantels. Offices in the parlors make good use of those interior details as well as of the abundant light provided by the large windows. The owners of the Gann House have taken advantage of the preservation easement program
which allows owners to take a
charitable contribution deduction for granting an easement to retain the historic features of the property. The offices described here are only a sampling of the historic buildings in Arknsas that have been put to new uses. The charms of historic buildings are only a part of the reason for the surge in such projects in the last decade. They also have, as has been discussed, good location
--<>--
Photo courtesy of Arkansas Historic Preservation Program
which is critical to any successful use. Additionally rehabilitation projects are cost effective, with lower costs per square foot than construction. Those facts along with the substantial tax incentives available to preservation projects have made good investments for their owners.
Another plus, as the buildings discussed here show, is that they are good investments for their communities as well. 0 April 19851Arkansas Lawyern3
ow it costs less • to e• assoCIate WI ertz. ADAY ACROSS THE USA'
Her/z illlrodllces nell),
/tl'l!) dui~v
rules
or A rkunsas Bur A ssociulOn members. Now your Arkansas Bar Associaton membership can get you a really terrific rate on a wide range of Hertz cars. From the fuelefficient Ford Escort to the roomy Ford LTD.
NEW CAR
DAILY
CLASS
RATE
Subcompact
Compact
Mid·sizc Full-size, 2 door Full-size, 4 door
::i3; 537 '39 ,41 ,43
And in some cases (weekly or weekend rentals, for example), you may even get lower rates than the ones you see here.
So~llH,",
at 1-800-654-2200 for details and reservations_
a
'Hertz "
ller'" rem, Ford, and Ol:hcr fme tar,.
•Refueling service charge, taxes, optional COW, PAl, and PEe (where available), nOl included. Cars must be returned to renting city. Available at all corporate and panicip31ing liccns<.'C locations CXCt'Pl in Alaska and in Manhattan from .REG us PAT CFFCHEATZSVSTEMINC 3PM Friday to 3PM Sunday and during certain holiday periods. Rates slightly higher in New York City area.
741Arkansas Lawyer/April 1985
19601
"The
Ten Greatest Trials of Pulaski County," the title and subject originally assigned to this talk, emerge today alter much modification as "Some Arkansas Cases, A Few of Them Great and a Few of Them Not." The cases which I hcrve selected fall into three broad categories which for convenience I call the Little Rock cases, the cases for reform and the mystery case.
The Little Rock cases are first. and first among them is a case which involved a title controversy over the site of Little Rock itself. No sooner had the territory of Arkansas been created, than the Superior Court was enlisted to resolve a land claim dispute over ownership to the Little Rock area. Two major conflicting claims existed. One was a pre-emption claim purchased around 1819 by St. Louis land speculator, William Russell. The claim dated back to 1812 when a wandering trapper who had spent a few months here filed claim for the land based on that period of residence. Second was a claim which stemmed from the New Madrid earthquake of 1811-1812. The earthquake had dislocated many settlers around New Madrid, Missouri, and Congress in 1815 voted relief to the settlers by offering them New Madrid certificates which allowed them to resettle on land that included this area. Several men bought up the Little Rock area certificates. They included Amos Wheeler. who became Little Rock's first postmaster; Stephen F. Austin, who went on to seek his fortune in Texas; Chester Ashley, recently arrived from New England and an ambitious young lawyer, and others. Both Russell with his preemption claim and the New Madridites, with their certificates, wanted legal ownership to the land at the "point of rocks. ", The dispute grew heated. The New Madridites, in January 1820, decided Russell's claim was worthless and threw him out. Russell. not easily defeated, enlisted the press in his cause. In May of 1820 he published notice in the Arkansas Gazette of his rightful claims and his intent to press the issue vigorously. Even before this, he had taken his case to the
Some Ar kansas Ca seS By
Frances Mitchell Ross courts where he sued the New Madridites for forcible entry and detainer. Russell won the first round, lost on appeal and took the case to the Superior Court.' In June of 1821. in the first function of the territorial government at the new capitol of Little Rock,' the Superior Court ruled in the case of Russell v. Wheeler et al. that the lands were in the lawful and rightful possession of Russell and that Wheeler and the others had unlawfully driven Russell out in January of 1820.' So much for the Court's opinion. It prompted repercussions which few could have anticipated, since most of the improvements on the land had been made by the New Madridites who refused to give up.' A visitor to the city on the day after the Superior Court's decision later recounted his version of what transpired that day. "First we saw a large wood and stone building in flames and then about 100 men, painted, masked and disguised in almost every conceivable manner,
gaging in removing the town. These men, with ropes and chains, would march off a frame house on wheels and logs, place it about 300-400 yards from its former site and then return and move off another ... They all seemed tolerably drunk They were a jolly set indeed and by nightfall they had completely changed the site of the town. In one day and night. Mr. Russell's land was disencumbered of the town of Little Rock. The free and enlightened citizens of Little Rock made a change of landlords more
rapidly than Bonaporte took Moscow.'"
The court had ruled, but who had won? No court in the land could prevent the town from running away. Thus Russell negotiated with Ashley, who represented the New Madridites, and in November of 1821. they divided the area in dispute. This gcrve Ashley his start in real estate' and at least for the time being, the land dispute was resolved.' This indeed, was a famous case. It was Little Rock's first case as territorial capitol, it dealt with complicated land title issues and it produced some absolutely astounding results. Some years later, Little Rock, still in place and growing, was struck by scandal. It involved the recent failure of the Real Estate Bank of Arkansas which had gone into receivership April I, 1842. Approximately $14,000 of Real Estate Bank money had been deposited with Justice of the Peace J. D. Fitzgerald by holders of the notes. the money was stolen in a robbery of Fitzgerald's office in August 1842. Several persons were arrested in connection with the case, among them Samuel Trowbridge, recently of Maine and Illinois, William Caldwell, Mrs. Caldwell, and others. Caldwell temporarily escaped but was later found in his house, sitting by the stove in which fresh ashes of paper were found. Could it be ashes of the money? Mrs. Caldwell, also at home, was found "with a vial in her bosom containing $1.400" believed also to be the money.' Officials began to connect this robbery with a rash of recent counEditor's Note: This article by frances Mitchell Ross is the text of a speech she presented March 9, 1984, before the Pulaski County Bar Association. Ross is the coordinator of the Women's Studies Program and the Oral History Program at the University of Arkansas at Little Rock
where she is an assistan t professor in ;he Department of History. Our thanks to Dr. Robert A. Leflar for his assistance, and for help received from the staff at the
Arkansas Territorial Restoration, Bill Worthen and Louise Terzia.
April 1985/Arkansas LawyernS
terfeiting which included U.S. gold and silver coins, bank notes of other states. and corporation notes of the town of Little Rock." The same gang of thieves was later connected to a jewelry store robbery a year earlier" as well as to most of the crimes committed in
Little Rock during the past four or five years. 11 The arrests and subsequent trials of the gang were the talk of Little Rock in 1842 and 1843. People discussed almost nothing else for months and for many years it was Little Rock's most sensational criminal case. 13 It was enough that the gang of thieves and counterfeiters had been caught and were being tried. but imagine how you would have felt to learn that the chief crook. the lead thief, the man who kept the counterfeiting press and fake money in his own home. was none other than Samuel Trowbridge. the mayor of Little Rock! On the one hand he printed counterfeit money and then gave his official opinion as mayor that the very notes he knew to be counterfeit were genuine and would be redeemed. l •
In their 1843 trials. Trowbridge's being first. several members of the gang were found guilty and sentenced to the penitentiary. Trowbridge went for 21 years. You can imagine the public's outrage when about a year and a haJilater Governor Yell sliced 16 years off
terms of general in'terest aroused. it came closer than any other to being the "Creation Science trial" of the 1840¡s. I include this limited collection of Little Rock cases because they may be of interest to Pulaski County lawyers. because they were important to early Little Rock. and as a reminder that Little Rock was largely born and reared in the courts. Contemporary litigation falls into the long. costly. but olten colorful heritage of Little Rock judicial controversy. Next are the cases for reform. The first few cases for reform are fairly easily discussed together for they all point to a common legal and historical problem: the rights of married women under common law. The last case shall be saved for separate consideration.
In 1828 Benjamin Moores and his wife. Ann, appealed to the Superior Court in a case of trespass with arms against Lawrence F. Carter and others." While Mr. Moores was stationed with the army at Ft. Gibson, Mrs. Moores "lived by her own industry and had a small house furnished at her own expense in Crawford County." The Moores alleged that the defendants "with force and arms. entered the dwelling house. and threw Ann into great fear by their menacing manner. by breaking open her chests.
searching all the private apartments. greatly disturbing her and injuring the property." some of which they took away. The court decided against the Moores. first because as a married woman Mrs. Moores was improperly joined with her husband in bringing action. and second because all property purchased or owned by the wile belonged to the husband ... and he alone must sue, The court said that "every species of personal property which the wile may acquire by purchase. by her own labor. or by gilt. during the coverture belongs to the husband." and only he can bring action. The opinion furthermore said that "this doctrine is too well settled to be controverted; and it is not necessary to support it by reference to authority." In 1845. the Court ruled on a case which originated in Pulaski County and involved a woman. Harriet Kelly." who before marriage was given a slave. She later married Mr. Jeffries. Soon the slave was seized under order against her husband. The slave was sold and purchased by Mr. Lindsay. Harriet Kelly Jeffries attempted to reclaim the slave and the court had to determine if the husband through marriage acquired title to the slave so that it could be seized in action against him. Not surprisingly the court said that through "the marriage
Trowbridge's sentence. l~
In commenting on the whole sordid affair. and probably as a rebuttal to unfavorable publicity which the case had aroused elsewhere, the Arkansas Gazette wrote that "we beg leave to inform edHors at a distance that if they have any propensity to write moral lectures ... for the benefit of Arkansas. the very ringleaders of the arrested gang. and almost everyone of their subordinates. are from the lands of steady habits. to wit: Ohio, Pennsylvania. New York and Maine, ... most of them have been but a few years in this state. II we are overrun with desperadoes. it is because they have come down upon us, like Goths and Vandals. from the North. "Ifi If sensationalism makes for greatness. then the Trowbridge case should qualify. In 761Arkonsos Lawyer/April 1985
all personal chattles of the wife (are) vested in the husband ... during the coverture. While single. she could have sold and conveyed the slave to any other person. and by the marriage she conveyed to her husband." Both the sale and Lindsay's title were valid. In 1884. in Walker v. lessup" the court determined that Mrs. Walker. who had purchased land on credit for $1.280 and was later sued because the term of the credit had expired and nothing had been paid. was not in the first place able as a married woman to buy real estate on credit and bind herself personally for its payment. None of the laws passed recently had enlarged the wife's ability to contract generally. the court said. None of these cases is outstanding in itself. but together they all do relate to the common law as the common law applied to married women in the 19th Century. The common law simply relieved married
women
of
significant
rights. In a case similar to those described above. it is clear that even the justice involved questioned the justice of the law." but it is also clear that Arkansas courts in the 19th century acted to uphold tradition and to protect the established body of common law. Inequality before the law rested largely undisturbed. Indeed as late as 1912. married women were for some purposes still legally classified with children and incompetents. 2 •
The problems which these cases illustrate are no longer with us. They have been remedied by statute and constitution over a long period of years. But I do think it's worth remembering that these problems were felt by a large group of people and that reform of the law was a painfully slow process. The last case for reform concerns an issue which was never heard in any Arkansas court. but which affected countless lawyers from Arkansas and other Southern states after the Civil War. Arkansas attorney. Augustus Garland. found himself disqualified from appearing before any Federal Court because he had served in the Confederate Congress. The
U.S. Congress had passed laws requiring all government officers as well as attorneys to swear that they had never supported a government hostile to the U.S. This oath was required of attorneys in
order for them to practice in any U.S. Court and to falsely take the oath would be to perjure themselves. D Garland prepared an argument to present to the U.S. Supreme Court challenging the constitutionality of the Acts and making other points." Garland won his case24 by one vote. ~ It was a landmark case because it was seen to vindicate the rights of lawyers against legislative encroachments. it re-instated Garland. countless other southern lawyers. and brought about instant reform in the process.
Finally. the mystery case; the only case of the late 20th Century we have to consider . .. and it,
not a real case at all. Yet it has been much cited unofficially and has been used in Appellate ludges Seminars at New York University." This is. of course. the noted 1968. April I. opinion of lustice George Rose Smith in the suit of I. R. Poisson against Etienne d·Avril.~ You will recall that Poisson sued d'Avriito enforce an oral agreement by which d'Avrii sold Poisson 40 acres of bottom land in the Hot Springs Mountains. O'Avrii maintained that under the 1838 Statute of Frauds an oral contract for sale of land cannot be enforced. Poisson countered that the Omnibus Repealer of 1945. which repealed "all laws and parts of laws." had nullified the Statue of Frauds. The question then became what is the Law? Is it statute only or common law plus the digest of statues. annotated? The author of the opinion determined that it was beyond belief that the General Assembly would do away with Judge-made law saying "it is essential that the common law be preserved if we are to avoid anarchy. The statutory law is not equally essential." Thus the repealer was seen to apply only to statues. "leaving all judge-made law unmonkeyed with." The case itself called into question the nature of law and legislation generally. If we have reached the point of questioning the nature of law and
legislation. then that might call into question all that has been said thus far today. If we should throw out statutory law would we resurrect
married
women's
"rights" under common law? Can we imagine that such a situation
could arise at the Federal level? If so. what about the Little Rock land claims? Would any be legitimate? How could the court decide? Indeed. we might all be consumed wi th the burning question of who really does own Little Rock! The implications of all of this are staggering and frightening to contemplate. Having raised this weighty issue and having considered some Arkansas cases of note
and near note. I shall on that note conclude. leaving both judgemade and statutory laws unmonkeyed with. FOOTNOTES
Ira Don Richards. Story of a Rivertown. Little Rock in the Nineteenth Century ("·n.p.... 1969). pp. 6-7. 2 Margaret Ross. Arkansas Gazette. The I
Early Years 1819-1866 (Lillie Rock: Arkansas Gazette Foundation. 1969). p.
36. Ross, Arkansas Gazette. p. 37. 4 Russell v. Wheeler, Hemp. 3 (Super. Ct. of Ark. Terr. 1821). ~ Dallas T. Herndon. Why Little Rock Was Born (Little Rock. 1933). p. 141. & Herndon. Why Little Rock Was Born. p. 139-140. Herndon, for one, questions the accuracy of this colorful description. 7 Herndon. Why Little Rock Was Born. p. 3
152. Richards. Story of a River Town. p. 10. , Little Rock, Arkansas Gazette. Oct. 5. 8
t842. 10 II
Ross, Arkansas Gazette. p. 186. Little Rock. Arkansas Gazette Oct. 12.
t842. 14
Ross. Arkansas Gazette p. 186. Ross. Arkansas Gazette p. 186. Little Rock, Arkansas Gazette Aug. 21.
I~
Little Rock, Arkansas Gazette. Aug. 21,
16
Little Rock. Arkansas Gazette. Oct. 12.
17
Benjamin Moores and Ann Moores, his wife v. Lawrence F. Carter. Frederick Thomas, and William Clark, Hemp. (Super. Cl. of Ark. Terr. 1828). Lindsay v. Harrison. 8 Ark. 302. Walker v. Jessup, 43 Ark. 163. Harrison v. Trader and Wife. 27 Ark. 288. Deane v. Moore, 105 Ark. 309: lSI SW
12 13
t844. 1844. 1842.
18 I' :III 21
286. 22
Augustus Garland, "Argument in the United States Supreme Court, on His Application to be Permitted to Practice in Such Court Without Taking the Oath, As Prescribed by Act 01 Congress of July 2.
:l3
Garland, "Argument," p. 5. Garland, "Argument," p. 3-23. Augustus H. Garland. Experience in the Supreme Court of the United Stales, With Some Reflections and Suggestions as to that Tribunal (Wash .. D.C. 1898), p.
1862. and January 24. 1865." 08651. 24
25
p.
4.
20. 26
27
Robert A. Leflar, "Letter," Jan. 10, 1984. J. R. Poisson v. Etienne d'Avril. 244 Ark.
478·A.
Aprit 1985/Arkansas Lawyer/77
Toward the Bicentennial of the U.S. Constitution Introduction by Dr. Robert A. Leflar Bill W. Bristow Vincent W. Foster.
Phillip Carroll Albert M. Witte
Jr. Should negligence liability attach to the reporting by a newspaper of inaccurate information if it fails to publish a retraction within 30 days of the error?
Should prior restraints be used on newspapers where the information published interfers with a person's right to privacy?
Robert P. Cabe G. Ross Smith
Robert M. Cearley.
School board review of educational materials and school course content should it be required to remove indecent, obscene or inappropriate materials?
78/Arkansas Lawyer/April 1985
Jr. J. W. Dickey. Jr. Should there be specific controls on cable television programming that contains sexual or violent content?
u Toward the Bicentennial u I
In the United States, development of the legal concept of freedom of speech and of the press as a basic civil right dates from John Peter Zenger's New York trial for the crime of libel. and his acquittal. in 1735. That was 250 years ago. It is difficult for an informed citizen in 1985, especially if he be a lawyer, to appreciate the tremendous change that has taken place in our law of defamation since that time. Zenger was a political opponent of William Cosby, the governor of New York. Zenger's newspaper, a weekly journal. published articles written by James Alexander, a lawyer, highly critical of Cosby and his administration. Because of this, Zenger was prosecuted for libel. Cosby's new appointee as chief justice, James DeLancey, was the trial judge. Alexander planned the defense, but he apparently was a better writer than speaker, and knew it. His defense plan was primarily jury persuasion, and for this he needed appropriate eloquence. Accordingly, he asked his friend Andrew Hamilton of Philadelphia, reputedly the best trial lawyer in the Colonies, to try the case. Hamilton accepted, and the transcript of his argument constitutes the principal matter that is remembered as representing the beginning of what we now know as First Amendment rights in America. Hamilton began his part in the trial by stating that he did not deny the publication, but that what was published was true, which was his sole defense. The chief justice's response was: "You cannot be admitted, Mr. Hamilton, to give the truth of a Libel in Evidence. A Libel is not to be justified; for it is nevertheless a Libel that it is true." This was in keeping with the old Star Chamber maxim, "The greater the truth the greater the libel." Unpleasant reports were most harmful if they could not be dis-
Free Press and Free Speech: A Developing Concept By Dr. Robert A. Leflar proved. That was still the law in England, and in old New York. No evidence of the truth of Zenger's publications was admitted. The Chief Justice was specific in his instruction to the jury that truth was no defense, and he admonished Hamilton to make no argument concerning "truth" as a defense. The clever advocate thanked the judge politely, yet managed to build his entire jury argument on the importance of free public access to facts (the truth?) in matters affecting government. The jury's verdict. rendered promptly, was "Not Guilty." What happened was that the jury decided for itself. regardless of the judge's instructions, that truth should be a good defense, and that the defense existed in this case despite the lack of admitted evidence. A jury can do that. Critically analyzed, this was but a small beginning for freedom of the press. "Truth," ascertained through jurors' beliefs and prejudices, is an illusory thing. No one can know with certainty what jurors will think is "true." Yet it was a beginning. Hamilton's argument. carefully reported, was copied and reprinted throughout the Colonies. Because it had been successful. it was quoted as though it were the law.
Gradually it became the law, though it was not until the decision in Garrison v, Louisiana. 379 U.S. 64 (1964) that the United States Supreme Court so held explicitly. Blackstone stayed with the Star Chamber view, but St. George Tucker's 1803 American edition of Blackstone's Commentaries essentially agreed with Hamilton. The First Amendment to the new Constitution of the United States was in the meantime adopted. The part of it dealing with free speech and press provides only that "Congress shall make no law ... abridging the freedom of speech, or of the press ... "Obviously. that was a limitation upon federal enactments only; it was commonly said at the time that the states remained free to control speech, and .especially the press, as tbey pleased. The prohibition eventually became applicable to state law also when in the middle 1900s the Supreme Court made it clear that the Fourteenth Amendment, adopted in 1868, made the Editor's Note: Dr. Robert A. Leflar is a distinguished professor and dean emeritus
of
the
University
of
Arkansas School of Law at Fayetteville. He received an LL.B. degree, cum laude, from the University of Arkansas in 1922 and an S.].D. from Harvard Law School in 1932. Dr. Leflar was president of the Arkansas State Constitutional Convention in 1969-70 and 1978-80 and was chairman of the Arkansas Constitutional Revision Study Commission in 1967-68. He is the recipient of the Doctor of Letters (honorary degree) from Joh_, Brown University, the Justice Award of the American Judicature Society and Scribes "Most Meritorious Book" Award for Appel-
late
Judical
Opinions,
among
other awards.
April 1985/Arkansas Lawyern9
Constitution's Bill of Rights basic law for the entire nation. That left it for the Court itself to determine, hy constitutional interpretation in the cases it accepts for review, the real scope of the freedoms. At one stage it seemed that "prior restraint" on protected publications might be all that was prohibited. Near v. Minnesota 283 U.S. 697 (1931). Sanctions after publication might not be precluded. That did not make much sense. Freedom to publish, then to be punished for having published, was not much of a freedom. Ultimately the Supreme Court achieved less obscure, though still not comprehensive, interpretations. In New York Times Co. v. Sullivan. 376 U.S. 254 (1964), it limited the right of a "public figure" (municipal official) to recover for nonmalicious criticism of his conduct. and in Gertz v. Robert Welch, Inc.. 418 U.S. 323 (1974), after redefining the term "public figure," it confined somewhat the scope of libel recovery by plaintiffs who are not public figures. A dozen other cases have described, or at least hinted at. constitutional boundaries on a variety of aspects of libel law . Olhers remain for future analysis. One far-out analysis may now be deemed to have fallen by the wayside. This was the view asserted by Justice Hugo Black, that the Constitution forbids any and all legal interferences with or burdens upon completely free speech and press. "The Constitution means what it says, with no ifs, ands, or buts," he argued. He seemed to believe that the whole law of libel and slander was proscribed. One answer to that argu-
Amendment was adopted. If the word "abridging" were to be given its standard meaning, the Amendment "says" no more than that the existent relevant law should not be diminished or lessened, presumably in the meager protections it then afforded to speakers and publishers. Mr. Justice Black ignored that easy interpretation of the Amendment's words, and the Supreme Court without discussion has rejected it. The limitations established in New York Times and Gertz. for example, go far beyond a mere abridgement of protections afforded by 1791 laws. Those early laws are for all practical purposes deemed irrelevant. The Supreme Court's current approach is to give to the guaranty a meaning that will fit the needs and societal standards of the time - late twentieth century - for which the rules are laid down. It seems farfetched to call this an interpretation of the specific words employed in 1791. and it is. Still, that is the accepted approach to American constitutional interpretation, for clauses which state broad principles inexactly. Were it nol for that approach the 1789 Constitution could not have lasted for nearly two centuries already, plus a future time as yet unknowable. By that same token, the future of First Amendment rights cannot be intelligently predicted, particularly as they relate to the press. The uncertainties inherent in libel suits, especially as huge verdicts are rendered in them, can both discourage publication in advance and, later, terminate publication altogether. The modem
ment comes from a more exact
emergence of newspaper owner-
reading of the First Amendment. as to just "what it says." The wording is that there shall be "no law ... abridging" the named freedoms. To "abridge" is to diminish or lessen an existing status. There was a small body of libel and slander law in existence in America in 1791, when the First
ship chains with their monopolistic tendencies may mix anti-trust law concerns into the free press picture. Jurors may be readier to render big verdicts against big corporate publishers, and such corporations may be primarily concerned with protecting profits. Their interest in free-
SO/Arkansas Lawyer/April 1985
dom of the press may be based more upon its effect on profits than upon concern for the traditional values that the Bill of Rights was designed to protect. Big damage awards may be the only sanction that can influence them. For ordinary parties to defamation claims, however. awards
of money damages will often be less than the ideal legal remedy. Perhaps, at least for some types of cases, either the courts or the legislatures should revive the old Arkansas device of the Lie Bill. (See 6 Ark. Law Review 423). That was a realistic and effective remedy. 0
EXPERT WITNESS AMPUTATIONS AND ENVIRONMENTAL DESIGNS FOR WHEELCHAIR CONFINED -$f::)eCializing in needs of amputees & quadriplegics - 8 years experience as Executive Director. Ameficon Arrputee Foundation Inc · U1igo1ion experience · Evaluation of client employability 8< fulure loss of Income · Evaluation of ellent future needs with cost PfOjectlons · Cost evaluation of environmental. prosthetic & orthotic equipment · Knowledgeable of rehabilitation laws · Knowledgeable of environmental control
systems, electronic aids, van conversions. & other driving devices · Ucensed social WOfker • References available onrequesl • Reasonable rates
Jock M. East. LSW clo American At'r4>utee FOU"Idation. Inc 701 West 7th
Uft1e Rock 72201 501/378·0094 501/664·2379 Serving the legal profession since 1975
* Toward the Bicentennial * On January II, 1985, Frank Simps' was astonished to read the following article in his morning newspaper:
Frank Simps, 38, of 146 Piker Street was arrested Friday and charged with first-degree battery and aggravated robbery in connection with the shooting of a mailman in the 300 block of Piker Thursday afternoon. Simps is the man who approached the mail carrier. Winston Em, 52, about 2 p.m. Thursday and complained about receiving too much junk mail and about receiving a Christmas card in mid-January, about a month after the card had been mailed to him by a neighbor. When Em refused to stop and discuss the complaints, Simps pulled a pearl-handled .22caliber revolver from his waistband and shot Em in the right thigh. Simps then took several Publishers Clearinghouse sweepstakes entry packets from Em's mailbag and lied the scene. Em was taken to Jeckyll Memorial Hospital where he was reported in satisfactory condition Friday. Simps was being held under $50.000 bond Friday night in the city jail. The sweepstakes entry packets have not been recovered.
After his wife had received several phone calls from neighbors and friends indicating worry that Frank was still in jail without bond, an irate Frank Simps called the City Desk to say his only connection with the incident was as a witness. The newspaper editor later called Frank and apologized profusely and the next day the newspaper ran the following article on the same page and in the same print size as the original
story: Correction: In a news article Saturday. the Herald-Cryler incorrectly identified Frank Simps. 38, of 146 Piker Street. as the man who was arrested and charged with
Retraction and Tort Liability In Media Defamation Cases By Bill W. Bristow first-degree battery and aggravated robbery in connection with Thursday's shooting of mailman Winston Em. Actually, the man arrested for the shooting and robbery was Fred Limple, 44, of 138 Piker. a neighbor of Simps. Simps' only connection with the shooting incident was a witness. The Herald-Cryer regrets the error. This article will address itself to two issues. First. what is the effect on an action for defamation if a timely retraction is made? Secondly, if the newspaper had refused to print a retraction. would this refusal constitute an additional tortious action for which a damage remedy will lie? Under present Arkansas law, there appears to be a ready answer as to the effect of a timely retraction on an action for defamation. The Arkansas Supreme Court in a non-media defamation case, Dun & Bradstreet. Inc. v. Robinson' ruled in 1961 as follows: At any rate, of course, even though the second Dun & Bradstreet notice could possibly be considered as a full and fair correction
or
retraction,
same
could only be considered in mitigation of damages. 345 S. W. 2d at 38. It is submitted that the aforesaid rule is a sound one. As discussed in that decision, a person who is charged with a crime will generally deny that he has com-
mitted the crime, but this denial does not vindicate him in the eyes of tbe public. The Arkansas Supreme Court pointed out that if a notice were published to the effect that "it is currently reported John Smith has stolen money from his employer" and a subsequent notice is published that "John Smith denies that he stole money from his employer" that tbere would still be a question of damages. It is thus submitted that the effect of retraction itself should not be a complete and total defense to a defamation action, but the defendant charged with libel may properly defend by showing that a timely and immediate retraction eradicated or seriously reduced any damages. The issue of retraction, however, may bear markedly on the issue of punitive damages. The Eighth Circuit Court of Appeals applying Arkansas law in a diversity action in Luster v. Retail Credit Company' found the defendant's immediate correction of the offending article to mitigate against an award of punitive damages. The Court of Appeals gave the plaintiff a choice between accepting a remittitur of the punitive damages and receiving the compensatory award or alternatively having a new trial on both issues of compensatory damages and punitive damages. The case readily illustrates the effect that an immediate and complete retraction of an error can have on the question of the defendant's good faith and issues of malice, particularly as viewed by an appellate court. Editor's Note:
Bill W. Bristow, of Jonesboro. is a plaintiff's attorney who has represented several clients in defamation cases. Bristow graduated in 1975 cum laude from Harvard University. His senior thesis was designated an honor's paper and placed in the Harvard Law Library. He is a 1972 graduate of Arkansas College. suma cum laude. April 1985/Arkansos Lawyer/S1
Similar considerations as regards
Printing Company'. There, the
can in fact get the issue of the
the effect of a retraction on the issue of a plaintiff's entitlement to
newspaper printed an original ar-
failure to make a retraction before
ticle and the Plaintiff brought suit for libel. The newspaper then reported on the libel suit and commented in the article that the newspaper's answer to the suit had stated that the articles were true and accurate accounts of the proceedings. The lower court held that this second article was not admissible as a republication of the asserted libel on a theory of aggravation of damages. The Supreme Court reversed. stating as follows. viz: If the jury finds that Appellee's initial publications were libelous and not privileged, it might well also find that the subsequent report of the pleadings had another purpose which was to further
the jury, but in one species of cases it would appear to have real
punitive damages are noted in statutes in other states. 4
Thus, in Arkansas the making of a retraction is not a complete
defense but it certainly bears on the issue of damages and retraction may in fact in certain circum-
stances preclude the award of punitive damages, It is submitted that this is in fact a proper rule and is grounded in sound policy notions because to do otherwise would basically be to allow the sloppiest form of initial reporting to be insulated from liability by the simple process of making a retraction when demanded, As noted in Dun & Bradstreet v. Robinson. supra. damage may already have occurred, and the extent of this damage in the face of a retraction should be a question of fact for the jury, It is submitted that this rule in Arkansas is sound and proper and is in accordance
with the general law in other states. The more perplexing question is the effect of the failure to make a retraction when demanded. To use the factual situation set forth abave, what would Frank Simps' remedy have been if the retraction in the example given abave had been arrogantly refused? Stated in different terms, can the refusal to print a retraction be a separate basis of tort liability? It should of course be admissible as to the general pattern of events relative to the publishing defendant's state of mind to show that demand for retraction had been made and that no retraction had been published. Likewise. if there is a demand for a retraction and the newspaper were to print the demand for retraction but then state words to the effect that it stood by its story, this may arguably be a reaffirmation of the libel which would further be relevant to the defendant's good faith. The above inferences can be gleaned from the Arkansas Supreme Court decision in Jones v. Commercial
821Arkansos Lawyer/April 1985
impress its defamations upon
the since
public actual
mind.
However,
malice -
Le.,
knowledge of the falsehood or reckless disregard for the truth - is not required, the jury, even if it finds that the initial publications were unprivileged, could nevertheless find that the subsequent report was published in good fai th as a fair account of the pleadings. of course. the jury might also find that the initial publications were privileged, in which case the subsequent report has no significance. In any event, we
think the Appellee's subsequent report of a pleading should be made available for the jury's consideration. 463 S. W. 2d at 96. Therefore, it can be argued under Arkansas law that actions subsequent to the publication such as a failure to retract or a partial reaffirmation and response to a demand for retraction can be admissible as aggravating circumstances and on the question of the defendant's good faith. However. this is a different proposition from the contention that the failure to do a retraction is a separate tortious event. This may appear at first blush to be an immaterial legal distinction if one
significance.
In a case where an admittedly false article has been written but the media defendant is protected from initial liability by the New York Times v. Sullivan rule that false material must have been published with knowledge that it was false or with reckless disregard as to its falsity. a suit for tortious failure to retract might be the libeled plaintiff's only remedy. Certainly, it would appear that it would be substantially easier to prove a simple failure to
retract after demand was made than that the publication was made with knowledge that it was false or with reckless disregard of its falsity. On the other hand, the creation of this separate tort would be a substantial expansion of liability for the media compared with the present state of defamation law.
It is submitted that this aforesaid expansion of liability is justified by the same policy decisions that led to New York Times and its progeny. Maintaining a balance between the righls of the media and the rights of an individual is an extremely delicate task for courts to wrestle with and has been a source of bafflement to the general public. The reasoning of the New York Times rule was succinctly stated by the Arkansas Supreme Court in Jones v. Commercial Printing Company. supra. as follows: The fear of a costly lawsuit for inaccurately. though honestly reporting
matters
concerning
public officials would certainly discourage the exercise of that degree of freedom which the Constitution guarantees to the press. especially in matters where even good faith investigative
efforts
cannot
assure
absolute accuracy. An added incentive behind this rationale is that public figures normally have access to the various mass
media and can thereby readily correct or refute any defamatory misstatement made about them. Therefore. it is reasoned that a showing of actual malice as a prerequisite to recovery is.
in such instances. a realistic and fair requirement. 463 S. W. 2d at 95. What then about the situation where there has been an inaccurate report about a public official and the publishing defendant refuses a request for retraction? If the rationale of the protective New York Times rule is the fact that a public figure has access to the media so as to correct or refute the defamatory statement. it would appear that the refusal of the media defendant to publish or disseminate the retraction strikes at
the heart of the rationale for the protective rule. The justification for the restrictions on suits by public figures is invalidated by a media defendant's failure to allow that public figure equal access to explain the charges against that person. If the charge is true. truth is now recognized as a complete defense to libel and the media defendant may properly refuse to retract. But if the initial charge is erroneous. although reported honestly and in good faith. does not the publishing defendant have an obligation to give the claimant an opportunity to clear the record with the public? If there is no such duty. the media defendant could brazenly refuse to correct such error all the while insulated from liability by the New York Times protection. It is thus submitted that in balancing the rights of the media and individuals that the creation of tort liability for failure to retract should be a corollary of the New York Times rule. There is another legal rationale for the development of a theory of tort liability for the failure to make a retraction. It seems fair that every party should have a duty to correct hazards created by that party's actions. If a media defendant by its erroneous newspaper
article has created damage to a party's reputation. should that publisher not have the duty to at least attempt to correct the hazard created by that publisher's actions? The aforesaid argument is indeed on the fringe of the law. It perhaps can be called a separate tort of outrageous conduct or intentional infliction of emotional distress based on a theory of creating a duty to retract. An old axiom is to the effect that where there is a wrong. the law should create a remedy. Indeed, there is much to be said that the New York Times rule has given the media wide protection. The threat of costly lawsuits and extensive litigation has been found to justify this protection that allows many such claims to be handled on summary judgment. Yet, in the narrow instance
in which a media defendant would arrogantly refuse to make a retraction of an erroneous report.
should that plaintiff not have the
opportunity to have a remedy for that defendant's failure to allow the plaintiff's version of the event to be placed before the public? In summary, it is argued that the creation of a "duty to retract." with concomitant tort liability is within the spirit of the rationale of the New York Times rule and is justified by sound policy considerations. There is no Arkansas case supporting such a tort remedy. but it is argued that policy considerations would support such a holding in a proper fact situation. 0 FOOTNOTES I
This entire incident is fictional
but has been used to frame the legal discussion against a realistic fact situation.
'233 Ark. 168.345 S.W. 2d 34 (1960. , 575 F. 2d 609 (8th Cir. 1978). • 50 Am Jur 2d. Libel & Slander, at P.689-690. , 249 Ark. 952, 463 S. W. 2d 92 (1971). • 376 U.S. 254. 84 S.Ct. 710. 11 L. Ed. 2d 686 (1964).
Make Professional
LAND MANAGEMENT available to your absentee landowners. Call Ted Glaub today to set up a FREE PRESENTATION LAND MANAGEMENT DIVISION
P.O. Box 96 Wilson, Arkansas 72395 / (501) 655-8311
April 1985/Arkansas Lawyer/83
* Toward the Bicentennial * "Judge in Libel Suit, Acting on Lack of Published Retraction. Says 'Other' Steps May Follow." Thus read the headline in a story in the August 4, 1978 edition of The New York Times concerning fines assessed against two reporters for
failing to retract previous articles. The earlier articles had reported assertions by friends and relatives of a convicted Georgian that police authorities had fabricated a videotape showing the accused confessing. At a hearing subsequent to the publication of the articles, the convicted person confirmed the veracity of the confession. After the reporters failed to retract the articles in response to an order by the judge in a libel action, the Court fined them, set a new deadline for the retractions, and indicated "other measures" besides fines might be used if no retraction appeared.
Who was this judge? Soviet Court Chairman Lev Y. Almazov of the Moscow City Court. Should American jurisprudence adopt the Soviet system of assessing fines and "other measures" for
a refusal to retract? What about the proposition that an independent tort liability should attach to the refusal to publish a retraction of inaccurate defamation?
The practical difficulties presented by this proposition, together with serious First Amendment questions concerning its constitutionality, weigh against the adoption of such a new cause of action. Every responsible news-
paper
publisher
will
a
retraction to correct an uninten-
No Independent Liability For refusal To retract By Vincent W. Foster, jr. upon discovery. The difficulty with the proposal arises in the harder cases where the truth is not clear-cut or easily verified. Take, for example, the publication of defamatory quotes from a technical analysis which a newspaper printed in reliance upon the reputation of the author. Assume that the newspaper cannot be held liable for the original publication either because of a qualified privilege of neutral reporting' or because reliance upon the re-
port will not be found to have been negligent. Should the newspaper nevertheless be held independently liable for failing to print a retraction of the error if the newspaper is not qualified or has insufficient information to resolve
the facts in dispute?
wire services. Few newspapers
have the staff or financial ability to verify independently the truth of a wire article about a distant
occurrence, and would be unable to determine whether a demand for retraction was meritorious or not.
tional defamation learned to be in-
Another example: Alter an in vestigation. a government agency
ics to correct significant errors
84/Arkansas Lawyer/April t985
a prompt retraction. The publisher is now upon the horns of a dilemma. The conclusion is clearly defamatory, but its truth is at present uncertain. The printing of retraction would be an admission of error which the publisher has not yet concluded was made, but if he fails to print a retraction, under the proposed new cause of action he would be exposed to liability for refusal to retract even though the original publication is not actionable. The publisher is also in a quandary where the original publication does not clearly identify the subject of a defamatory statement. A few years ago, a statewide newspaper in Arkansas published an article about a pending federal investigation of "blockbusting:' the attempt, for profit. to induce a person to sell a dwelling by representations regarding the e'ntry into the neighborhood of persons of a different race or religion. The article did not accuse any particular indi-
viduals. The story was accompanied by a photograph showing "For Sale" signs from various
Most newspapers. particularly
small local publishers, rely heavilyon articles originated by the
accurate. I Faced with the situation described as an example in
the accompanying article by the proponent of this new liability, the publisher would readily print the retraction once he learned of the misidentification of the person arrested. The publication of a retraction not only may limit the liability or reduce the damages for the original publication, it is also a matter of basic journalistic eth-
ment report.' The contractor denies the accusation and demands
issues a finding that a private contractor has engaged in bid rigging. Your local newspaper publishes excerpts from the report. including the conclusion. Although one who republishes a libel is independently liable as if he had originally published it.' here the newspaper is immune
from liability because of the qualified privilege to accurately and fairly publish or abridge a govern-
Editor's Note: Vincent W. Foster, Ir" a member of the Rose Law Firm in Little Rock, regularly represents several newspapers in the WEHCO Media, Inc., chain, including the
Texarkana Gazette, EI Dorado News-Times, Camden News and Magnolia Banner News. He attended Vanderbilt University and the University of Arkansas, where he received a I.D. degree in 1971 with high honors. He was managing editor of the Arkansas Law Review in 1970 and a member of Omicron Delta Kappa honorary leadership fraternity. Foster is a former president of the Pulaski County Bar Association and a former delegate in the Arkansas Bar Association's House of Delegates.
real estate firms in several front lawns in a row. The name of an individual real estate agent could be read on the sign in the foreground. The agent contended that this amounted to an accusation that she was engaged in blockbusting. The author of the article did not intend to refer to this agent. but the legal test for liability is whether the article could be reasonably understood to refer to the agent.' How should the newspaper respond to a demand for a retraction? If the publisher prints a retraction stating that it was not intending to accuse the agent, then the publisher has as much as admitted that the article reasonably could be read to refer to the agent, thus increasing the risk of liability for the original publication. If the newspaper does not publish a retraction, however, and a jury later finds that the article did defame the agent, under the proposed new cause of action the publisher would be independently liable for the failure to retract. even though he may have other defenses against a libel claim for the original publication. The same dilemma arises when the article is not clearly defamatory. The subject of an article may read into it a defamatory meaning which was not intended. Under the law the meaning of the statement is that which the reader correctly, or mistakenly but reasonably, understands that it was intended to express, taking into account the entire article.' If the newspaper prints a retraction disclaiming the meaning ascribed to the article by the subject. a strong argument can be made that the publisher has admitted that the article reasonably may be read to express that meaning. This proposed independent liability for refusal to retract was argued last summer in Kaplan v, Newsweek Magazine Inc.. 10 Media L. Rptr. 2142 (U.S.D.C., N.D. Cal. July 31, 1984). An article in Newsweek on Campus characterized Professor John Kaplan's
criminal law courses as "the easiest five credits a Stanford student can earn. Attendance: unnecessary." Professor Kaplan sued for one count of libel and for a second count of intentional infliction of emotional distress for the magazine's failure to discharge its "duty to retract." The Court found that the article was not reasonably susceptible of a defamatory interpretation and dismissed the first cause of action. In also dismissing the second cause of action, the Court held that Professor Kaplan could not bootstrap another theory of liability onto his libel claim to tum one action for damages into two separate causes of action, citing the Uniform Single Publications Act.' The Single Publications Rule, which is considered the common law of many states, provides that anyone edition is considered a single publication, and a person shall not have more than one cause of action for damages for libel or any other tort founded upon any single publication, regardless of the number of times it is exposed to different people.' The proposed cause of action also raises serious constitutional questions. It presents the other side of the chilling effect of a prior restraint upon publication. Rather than restraining publication, the proposed cause of action may tend to intimidate a publisher into making a publication he would not otherwise have made. By the threat of independent liability for refusal to retract. the publisher may be compelled to publish a retraction whether or not be believes the original article is accurate or not, especially where the article would require expensive investigation to substantiate or would be troublesome to prove at trial. Thus, a primary objection to compulsory retraction is that "such a heavy burden of investigation is placed on the publisher, if he is to dispute his obligation to retract without risking liability, he will be deterred from making the original publication or co-
erced into making undeserved retractions. ", Does the First Amendment guarantee the freedom not to publish? In Miami Herald Publishing Co. v. Tornillo." the U.S. Supreme Court unanimously struck down as unconstitutional a Florida statute granting a political candidate a right to equal space to reply to criticism by a newspaper. The Court ruled that a requirement constituting a compulsion upon a newspaper to print that which it would not otherwise print is an unconstitutional infringement upon the First Amendment guarantee of a free press. The Supreme Court reviewed earlier cases from which it recognized that a compulsion to publish is as serious an infringement as a restraint from publishing. The Court also expressed grave concern that the threat of compulsory publication may result in self-censorship to avoid controversy.ll just as it had feared in New York Times v. Sullivan" that the risk of large damages in a libel suit could result in reluctance to publish articles on important issues involving public officials. Justice Brennan, in a concurring opinion joined by Justice Rehnquist. reserved consideration of the constitutionality of "retraction statutes" which would provide plaintiffs an action to require publication of retraction upon proof of a defamatory falsehood." a cousin of the legendary "lie bill" of North Arkansas Dr. Lenar has described." But the broad language of the Tornillo decision appears to be a condemnation against compulsory publication generally, which casts considerable doubt on whether the proposed independent liability for failure to retract could pass constitutional muster. The proposed liability is particularly offensive when applied to publications concerning public officials and public figures protected by New York Times vs. Sullivan and its progeny. This line of authority prohibits a public official or a public figure from reApril 1985/Arkansas Lawyer/8S
covering damages for a defamatory falsehood unless published with "aclual malice" -
knowl-
edge of falsity or in reckless disregard of whether it is true or false. A finding of recklessness requires "sufficient evidence to permit the conclusion that the defendant in fact entertained serious doubts as to the truth of his publication. "l~ These constitutional restrictions upon libel actions would seem also to prohibit secondary liability for
edies. Aside from retraction. there generally exists the opportunity for reply. While the first Amendment would likely not permit a governmentally enforced guarantee of access to the media, as a practical matter most newspapers
of independent liability, to publish a retraction upon demand. Rather than propose a second wave of liability for a single publication, the legislature should instead consider the adoption of a statute that requires as a prerequisite for a libel action a timely demand for retraction and failure to retract. Twenty-three states have enacted similar or related
immune publication unless the plaintiff can prove by clear and convincing evidence, that based
stand ready to publish the reply of a defamed subject either in a follow up article or by a letter to the editor from the subject or his supporter. In fact. Professor Kaplan availed himself of this opportunity in a later edition of Newsweek, It is. in part. the recognition of this ability of public individuals to obtain access to the media that influenced the Su-
upon new information, the pub-
preme Court to set them apart
tion of a retraction. These statutes
lisher now knows the original article was false or now entertains serious doubts as to its truth." It should not be assumed. however, that the subject of an article who unsuccessfully demands a retraction has exhausted all rem-
from private individuals in establishing standards for libel actions." This ability of public individuals to gain access to the media for a reply need not be extended to establish a right to require a publisher, under penalty
are based. in part. upon the belief that a voluntary retraction will compensate the defamation victim far better than an award of money damages." The proponents of these statutes have no sympathy with gold brickers who
failure to print a retraction of an
statutes. 17 Some make a retrac-
tion demand a condition precedent to the filing of a defamation action, while others restrict recovery to special damages or at least disallow punative damages, where there has been the publica-
An Intensive Program in
TRIAL ADVOCACY SEVENTH ANNUAL SOUTHERN REGIONAL June 12-22,1985 Southern Methodist University School of Law Dallas, Texas Thjs intensive program is designed for attorneys with less than five years of experience. The NITA method of teaching trial advocacy incorporates team teaching, video technology, faculty demonstrations and student participation, For an informational brochure and application, contact:
ill "
Professor Frederick Moss Program Director Southern Methodist University School of Law Dallas, TX 75275 (214) 692-2742
Internationally Acclaimed for Trial Advocacy Training 86/Arkansas Lawyer/April 1985
seize upon a good laith publishing error as an opportunity to seek a jury award 01 general and punative damages. As the Supreme Court has stated: "The first remedy 01 any victim 01 delamation is sell-help - using available opportunities to contradict the lie or correct the error and thereby to minimize its adverse impact on reputation. "19
Requiring a porty to attempt to mitigate his damages by promptly calling an error to the attention 01 the newspaper and giving it an opportunity to correct the error voluntarily. is more consistent with American jurisprudence than is imposing fines. independent liability or "other measures" on a publisher lor lailing to publish a retraction upon demand.
see Lellar. "The Single Publication Rule." 25 Rocky Mt. L. Rev.. 263 (1953); see also Restatement (Second) of Torts §577A, • "Vindication 01 the Reputation 01 a Public Official." 80 Harv. L. Rev. 1730. 1742-3 (1967). " 418 U.S. 241 (1974) " 418 U.S. at 257. " 376 U.S. 254 (1964). " Justice Brennan first suggested the consideration of right to reply statutes or retraction statutes as alternatives lor damages for all delamed persons. public and private alike. in Rosenbloom v. Metromedia. Inc.. 403 U.S. 29. 47 (1971). " Lellar. "Legal Remedies for Defamation," 6 Ark. L. Rev. 423 (1952). See a discussion 01 Tornillo on the concept 01 mandatory retraction in "Reply and Retraction in Actions Against the Press lor Delamation: The Effect 01 Tornillo and Gertz." 43
Fordham L. Rev. 223 (1974). "St. Amant v. Thompson. 390 U.S. 727. 731 (1968);. see also. Gallman v. Carnes. 254 Ark. 987, 497 S.W.2d 47 (1973). .. Gertz v. Robert Welch. Inc.. 418 U.S, 323. 344 (1974). "Steigleman. The Newspaperman and the Law. 319 (1971), See also Annot.. "Validity. Construction and Application 01 Statute Limiting Damages Recoverable lor Defamation." 13 A.L.R. 2d 277. 289. §6 (1950). and Annot.. "Libel and Slander: Who is Protected by Statute Restricting Recovery Unless Retraction is Demanded." 84 A.L.R. 3d 1249 (1978). .. See. e.g.. Warner v. Southern California Associated Newspapers. 35 Cal. 2d.. 121. 216 P.2d 825 (1950). app. dism·d. 340 U.S. 910. 71 S. Ct. 290 (l95!). .. Gertz v. Robert Welch. Inc.. supra.. 418 U.S. at 344.
FOOTNOTES 'Steigleman. The Newspaperman and the Law. 322, 330 (1971); Morris. "Inadvertent Newspaper Libel and Retraction." 32 Ill. L. Rev. 36 (1937). 'This new principle provides a privilege lor the accurate and disinterested reporting 01 charges against a public figure by a responsible and prominent organization. whether or not the publisher has serious doubts 01 the truth 01 the charges. See. e.q.. Edwards v. National Audubon Society. Inc.. 556 F. 2d 113 (2d Cir. 1977). cert. den.. 434 U.S. 1002 (1977). 'Restatement (Second) of Torts §578. • See e.q.. Brandon v. Gazette Publishing Co.. 234 Ark. 332. 352 S. W.2d (1961); see Restatement (Second) of Torts §611. • Thiel v. Dove. 229 Ark. 601. 317 S.W.2d 121 (1958); Restatement (Second) of Torts §564 (1977). • Restatement (Second) of Torts §S63 (1977); see. e.g.. Pigg v. Ashley County Newspaper. Inc.. 253 Ark. 756. 489 S. W.2d 17 (1973), 'Calilornia Civil Code §§3425.13425.5. The Uniform Single Publication Act has been adopted by six other states. o For an excellent discussion 01 the rule and the Uniform Act.
We do more than print the lawwe put it into perspective... ... both in our law books and our computer data service Whether it's with ALR. Am Jur. USCS, L E<1-or Auto-Citeqj). our computer formatted research service@ offers the Arkansas attorney. Am Jur 2d U.S. Supreme Gourt Reports, L Ed Am Jur Legal Forms 2d USGS Am Jur Pleading & Practice Forms Federal Procedural Forms. L Ed Am Jur Proof of Facts Federal Procedure, L Ed Am Jur Trials Bankruptcy Service, L Ed ALR System Contact your LCP representative: Arkansas
Lorraine Hall. (501)378-7038 P.O. Box 56305. Little Rock. Arkansas 72215
IIII lCP
THE LAWVERS CO-OPUATIVE PUBliSHING CO. AQUeduct Bulldll19
Rochester NewVork 14694
April 1985/Arkansas Lowyer/8?
TM
KEEP T.A.B.S. ON YOUR
FIRM WITH ... The Attorneys' Billing System IBM is a lradEln'M. oll8tll Corporation. 88/Arkansas Lawyer/April 1985
actions. Where an installment obligation is received in ex-
The Tax Reform Act of 1984 Effects on Real Estate Transactions
By Michael O. Parker On June 27. 1984, Congress passed the Tax Reform Act of 1984 (the "Act") as part of a larger body of legislation designated the Deficit Reduction Act of 1984. It is clear that a primary theme of the Act is to narrow the beneficial tax
rules previously contained in Internal Revenue Code ยง483 and applicable regulations. Under these rules, most real estate purchased on an installment basis over a period in excess of six months needed to carry a mini-
treatment given many real estate
mum "safe harhor" interest rate
transactions, and reduce the attractiveness of real estate as a tax advantaged investment. However. not all of the changes affecting real estate transactions are unfavorable. The reduction in the capital gains holding period from a year to six months and the changes in the tax treatment of property divisions on divorce are two examples of helpful revisions. However. these provisions do not relate primarily to real estate as an investment. The change in the capital gains holding period is more beneficial to securities transactions than real estate, while the tax treatment of property divisions on divorce (which will be discussed in an upcoming issue of The Arkansas Lawyer) does not directly involve investment decisions. This article will address the provisions of the Act which come into play at the various stages of com-
(usually nine percent') in order to avoid having interest imputed. or assumed by the Internal Revenue
mon real estate transactions: pro-
visions affecting acquisition and
holding; construction and rehabilitation; rental and leasing; and disposition of realty.' Provisions Affecting Acquisition and Holding of Real Estate Deferred Payment Transactions. Most business clients are familiar with the imputed interest
Service to be present. at a one per-
cent higher rate. Congress was concerned that this minimum interest rate was too low and did not react to market changes and that the timing of interest deductions taken by purchasers did not correspond to interest income recognized by sellers, due to differences in the taxpayers' accounting methods. Therefore. Congress developed new sets of rules which will relate the safe harbor and imputation rates to an "Applicable Federal Rate'" and will require matching of expense and income treatment between taxpayers in many instances. The Applicable Federal Rate will be determined by the Treasury at six month intervals for short term, mid-term and long term obligations.' A recent article in The Arkansas Lawyer discussed how the Applicable Federal Rate applies to loans between related taxpayers.~ Certain loans must carry interest at 100"10 of the Applicable Federal Rate in order to avoid gift or compensation treatment. The rule is somewhat different with respect to sales trans-
change for property, the installment obligation must bear interest at 110"10 of the Applicable Federal Rate to avoid unstated interest treatment.' If the interest being charged is less than 110"10 of the Applicable Rate. unstated interest will be present and interest will be imputed at 120"10 of the Applicable Federal Rate.' Congress carved out a few exceptions to the new rule when the Act was passed, and then passed additional legislation which tinkered with the concept further. First. the Act continues the 7% maximum imputed interest rate for land transactions between related individuals involving $500,000 or less.' Second. in the case of sale of a farm for less than $1.000.000. the safe harbor and imputed interest rates under prior law continue to apply.' Third, in the case of a sale of a principle residence. the rates under prior law continue to apply to the extent the purchase price does not exceed $250,000." Where the purchase price exceeds $250,000, a combination of old and new rates applies. After the Act was passed. the new deferred payment rules received a tremendous amount of criticism. and their future is now subject to some doubt. Late in the Congressional session an interim Editor's Note: Michaela. Parker is a partner in the Davidson. Horne. Hollingsworth Law Firm in Little Rock. He is a graduate of Vanderbilt University in Nashville. Tennessee IBA-Economics. 197J) and a 1973 honors graduate of the University of Arkansas School of Law in Fayetteville. where he served on the Board of Editors of the Arkansas Law Review. He presently serves as vice-chair of the Section of Taxation of the Arkansas Bar Association and on the Southeast Regional Internal Revenue Service-Bar Association Liaison Committee. This artlcJe is one of a continuing series by members of the Section of Taxation in its effort to keep the membership informed and up to date on important developments in tax law.
April 19a5/Arkansas Lawyer/a9
"transitional rule" was passed (P.L. 98-612)" which altered and partially suspended the use of the Applicable Federal Rate to determine if unstated interest is present on a temporary basis. Until July I. 1985. the 9"10 safe harbar. and 10% imputation rates will still apply for transactions where the borrowed amount is $2.000,000 or less. Where more than $2.000,000 is involved. a combination of the two concepts is used. 12 Assumptions of Debt. It is important to keep in mind that the new deferred payment rules apply to assumptions of existing debt as well as new borrowings. The actual mechanics ot application will be clarified by regulation. However, P.L. 98-612 contained another change which made this provision inapplicable to debt obligations issued before October 15, 1984. on a permanent rather than interim basis. I:! ACRS Recovery Period. The accelerated cost recovery system ("ACRS") was added in 1981 as an important part of Economic Recovery Tax Acl. Under ACRS, most real property placed in service after 1980 could be depreciated over a period as short as fifteen years. The Act increases the recovery period for commercial and residential real property. with the exception of low income housing. to eighteen years." The longer recovery period is also applicable to additions to an existing structure. even if the existing structure qualified for fifteen year ACRS depreciation. Other minor changes in calculating the amount of the annual deduction under ACRS were also made. to be implemented by Treasury regulation.
was allowed with respect to any costs or losses associated with the demolition of a certified historic structure. All such costs and losses had to be added to the taxpayer's basis in the underlying land and could not be expensed, depreciated or amortized. The Act eliminates any deduction for costs or losses associated. with demolition of any structure and applies the old rule for certified historic structures to the demolition of any structure, whether certified historic or nol." Therefore. in the future. taxpayers will not be able to allocate a portion of their purchase price of property to a building and later deduct their basis in the building when it is demolished. Removal of Architectural Barriers. For a period of time prior to
1983. a special deduction of up to $25,000 was allowed for expenses incurred during a taxable year in removing architectural barriers to the handicapped or elderly. This provision was rather narrow in
scope because it could not be claimed in connection with a general renovation of abuilding.
Further. it only applied to removal of certain specific types of barriers set out in the regulations. The Act reenacted this provision and increased the deduction to $35.000 per year for expenses incurred during 1984 and 1985." However. the previous limitations on the scope of the provision will continue to apply. Construction Interest and Taxes. There has been a general rule that interest and taxes incurred while a project is under construction cannot be deducted as expenses. Instead. these expenses must be capitalized and amortized over a ten year period. 17 However. this rule does not apply to construction of low income housing. and other projects which the Congress classified as not suited for profit making activity. In the past, another exception has allowed interest and
taxes incurred by corporations (but not individuals or partnerships) in connection with the construction of residential property to be deducted. These rules appear to have come /rom an attempt by the Congress to bal-
Provisions Affecting Construction
and Rehabilita1ion Demolition Deductions Disallowed. Under prior law. there was a general rule that costs and other losses incurred in connection with the demolition of a building qualified as losses and could be deducted when incurred. However, there was a general excep-
tion to the rule that such costs and losses could not be deducted and must be added to the basis in the land, if the land and building were purchased with the intent to demolish the building. fn addition. pior to 1984, no deduction SO/Arkansas Lawyer/April 1985
THE SHINI 'G STAR I
TELEPHONE A
Let our 33 years of solid information management service work for you. As the marketing division for Northern Arkansas Telephone Company, we sell only the best in telephone and microcomputer systems. And we stand behind everything we sell with fast, dependable service from highly trained, skilled professionals. Write for our free brochure or call to
0 MICROCOMPUTER SYSTEMS.
learn how we can make your information management a shining star, too.
i
~T~ Su\'a S\'Stl'I11S '" '" ,n"",. ,,.,,,....,, "",,,,,.,~n~,~,,
""
l~"'"
,,,,,r,,,
CORI'ORAT[ ONE BUIlDING. 10025 W MARKHAM STREI:."T UTILE ROCK. ARKANSAS 72205. (501) 22~-8IJJ JOI EAST MAIN STR"-L'T. FLIPPIN. ARKANSAS 726.).4. (501' "~J.885.5 1800'.82.8782
ance a concern for construction of adequate housing during the 1970's, with a concern that large construction period deductions not be available to tax shelter partnerships or individuals under most circumstances. In any event. the Act eliminates the exception which allowed deduction of interest and taxes incurred by corporations during the construction period of residential real estate. 18 However, the exception for low income housing and other "not for profit" activities continues to be available for all taxpayers. Rehabilitation Expenditures for Low Income Housing. Prior to January 1, 1984, a taxpayer could elect to amortize up to $20,000 of rehabilitation expenditures per unit of low income housing over a sixty month period. Individual apartments qualified as units under this rule. Congress extended this rule for three years through December 31. 1986." This reflects the continued concern by Congress for the rehabilitation of low income housing and use of the tax laws to divert private sector monies to projects of this type. The amount which may be amortized is also increased to $40.000 per dwelling unit if the project is certified by HUD or some other government subdivision and certain other criteria are met. New Rule For Rehabilitation Tax Credit. Under current law. the government will pay 15% to 25% of the costs of rehabilitating buildings for business or other nonresidential purposes. through tax credits. This is a valuable tax benefit which has been used in the rehabilitation of downtown business districts and other properties in Arkansas. One of the criteria for claiming the credit has been that 75% or more of the existing external walls of the building must be retained.'" This apparently created problems for some projects where the external walls were not load bearing walls and were irregularly shaped. The Act provides an alternate test which will allow other factors to be considered under certain circumstances. Under the new text. the credit will be available if: 50% of the existing external walls are retained as external walls; 75% of the existing external walls are re-
tained as either external walls or internal walls; and at least 75% of the internal structural framework is retained. 21 Provisions Effecting Rental and Leasing Accounting For Variable Payment Leases. The differences in tax treatment between accrual and cash basis taxpayers have provided a number of tax planning opportunities over the years. One of these has been in the leasing arena. A cash basis lessor is only required to recognize lease payments as income when the payment is actually received. even if the lease provides for unreasonably low payments in the early periods and unreasonably high payments in the later periods of the lease. On the other hand, an accrual basis lessee deducts rent when the obligation becomes fixed. even though the actual cash payment is deferred under the lease. Further. if a cash basis lessor sold property on which a large amount of rent had accrued was not yet due. this could make the property more valuable to the buyer and allow the seller to convert ordinary income into capital gain. The Congress used the "complexification" approach to address this problem in instances where the total aggregate consideration under a lease exceeds $250.000 and any of the payments either vary in amount or are deferred more than one calendar year. n The new rules will not apply where rent variations are due to common commercial reasons. Examples are variations determined with reference to price indices; rents based on a percentage of lessee receipts; reasonable rent holidays; and changes in amounts paid to unrelated third parties for such things as utilities and maintenance. However, where variations exist for other reasons, the actual payment and receipt of rent and the accounting method used by the taxpayer will be largely irrelevant. Under the Act. the lessor must include two items in income each year regardless of actual receipt: accrued rent and interest on rent previously accrued which remains unpaid. The amount of accrued rent each year will be the amount allocated to the taxable
year under the agreement between the lessor and lessee, plus the present value of a portion of certain types of consideration to be paid later. Where the agreement is silent on the allocation of payments. rents will be spread equally over the term of the lease. Rents will also be spread equally over the term of the lease where the agreement is part of a sale and lease back transaction. or is a long term lease which has tax avoidance as a principal purpose. The criteria for determining when a transaction has tax avoidance as a principal purpose is largely left to the Internal Revenue Service and will, no doubt. provide fertile ground for controversy. Interest on rent which has previously accrued but which remains unpaid will also be required to be taken into income by the lessor annually. Interest is at 110"10 of the Applicable Federal Rate compounded semi-annually. This does not mean that additional amounts not provided for in the lease must actually be paid as interest. However. it is presently unclear whether this provision will merely affect the timing for tax purposes of payments actually made. or will instead result in a total income to the lessor and total deductions to the lessee in excess of the total rental amounts provided. It is hoped this concern will be clarified and eliminated by regulation. Further, the effect of this new provision on leasepurchase arrangements needs to be clarified. Exempt Entity Leasing. Another innovative tax planning opportunity has been the purchase. renovation and lease back of public property by private investors. A recent attempt to use this technique which received wide attention in Arkansas was the proposed plan to renovate the Old Main Building at the University of Arkansas at Fayetteville. Under prior law, a private investor could purchase a public building and write off the purchase price over fifteen years under ACRS; renovate the building with the government paying 15%, 20% or 25% of the renovation costs pursuant to tax credits; and take advantage of other planning opportunities which were available to reduce the economic cost of the project. April 1985/Arkansas Lawyer/9l
The Act reduces or eliminates these benefits under most circum-
stances. 23 The
new limitations will apply under several circumstances. including where a purchase and lease back are involved; the tax exempt entity uses the property under a lease with a term in excess twenty years; or the tax exempt entity uses the property under a lease that contains a fixed or determinable price purchase option. If any of these circumstances are pres-
ent, the tax benefits previously available will be removed, no rehabilitation credit will be allowed and the property must be depreciated over the greater of forty years or 125% of the lease term. Some planning opportunities will still be present where a governmental entity is interested in leasing or acquiring facilities it has not used previously and where the versatile nature of the building will allow the owner to be reasonably protected even if the building is leased for a period of less than twenty years without a purchase option. However, such
restrictions will substantially limit the rehabilitation of existing government buildings by private investors. Provisions Affecting Disposition
of Realty The changes in the law with respect to the disposition of realty appear to have importance to many more taxpayers than the construction and rehabili lotion or leasing provisions. The two changes associated with business transactions
are
very
onerous,
and a change associated with gifts or bargain sales to charities will cause additional expense and compliance headaches. The one beneficial change is with respect to property settlements on divorce, which will be discussed in an upcoming issue of The Arkansas Lawyer. Depreciation Recapture on In-
stallment Sales. One of the more costly provisions of the Act deals with a new rule on the recapture of depreciation. When a taxpayer sells property which has been depreciated at a gain, some of this
gain may be treated as ordinary income under rules governing the recapture of depreciation. With respect to real property, several rules apply which will classify 92/Arkansas Lawyer/April 1985
from none to all of the depreciation taken as subject to recapture at ordinary income rates, depending on the type of real estate involved and the type of depreciation method which has been used. Under prior law. when property was sold on an installment basis, recapture was recognized as payments were made over the years of the installment sale. Under this approach, cash was generally available to pay any taxes resulting from the transaction, over time. Under the Act. all taxes resulting from the recapture of depreciation at ordinary income rates will be due in the year the transaction occurs, even if the transaction qualifies as an installment sale. 24 Any gain in excess of the recapture income will continue to be recognized under the installment method. This change will have a substantial impact on the structure of installment sales. It will be very important to obtain a cash down
payment sufficient to cover the taxes which will be due in the first year of the transaction unless the taxpayer is willing to be out of pocket for taxes. Like Kind Exchanges. It is generally recognized that a taxpayer can avoid tax on the disposition of property if he receives like kind property in exchange in the transaction. Under prior law, there was no specific requirement that any exchange be completed when a subject property was transferred or within any set period thereafter. As a result, various types of escrow arrangements and trusts were used to allow the taxpayer to direct the reinvestment of sale proceeds and then receive the newly acquired property as part of the exchange transaction. Congress classified this as "too good to be true." The Act provides that any property received by the taxpayer more than 180 days after the date on which the taxpayer transfers property. or the due date of the transferor's tax return (whichever
DO YOU REALLY KNOW WHO IS ON YOUR JURY? . .. WHO WILL BE RECEPTIVE TO YOUR CASE? TAKE THE GUESSWORK OUT OF JURY SELECTION: • Statewide jury monitoring • Ideal juror profiles • Jury panel analysis (criminal and civil) • Suggested voir dire topics
REASONABLE FEES; NO CHARGE FOR INITIAL CONSULTATION
Call:
TRIAL BEHAVIOR CONSULTANTS Drew C. Camp, M.S., Licensed Psychological Examiner 700 West 4th Street Suite 200, Little Rock, AR Phone: (501) 374-3133
occurs earlier) will not qualify as like kind of property.~ In addition, the property to be received must be designated by the taxpayer within 45 days of the date the transferred property is relinquished. This designation requirement may be satisfied if the contract between the parties specifies a limited number of properties which may be transferred. with the particular property to be determined by contingencies beyond the control of both parties. Regulations will be important to develop the Treasury position on contingencies which qualify for this purpose. Appraisals For Gifts of Property. During 1983, a group of museum curators. art dealers and other experts who make up the special IRS Arts Advisory Panel examined taxpayers' evaluations of 223 donated works of art and found that more than half required adjustment. These works were over valued by an average of 671%.s Studies such as this provided the impetus for a new provision in the Act which will require written appraisals of charitable contributions of property in many
instances. The Act requires that the Treasury issue regulations which will require any individuaL closely held corporation, or personal service corporation claiming a charitable deduction for property to obtain a qualified appraisal of the property contributed, attach a summary of the appraisal to the return on which a deduction is first claimed for such contribution, and include certain other information prescribed by regulation.'" This rule will apply if the charitable gift or gifts exceeds $5000 in the aggregate. Regulations will also require that the appraiser be independent of both the donor and donee and that the appraiser's fee not be based on a percentage of the appraised value of the property. The appraiser can be assessed a penalty of up to $1000 for aiding or assisting in the preparation or presentation of an appraisal resulting in an understatement of tax liability and can also be barred from offering evidence before the Internal Revenue Service. Further, if the value of the gift claimed on the return is 50"10 or more greater than the actual
value as determined by a court or settlement agreement. the taxpayer is required to pay a penalty equal to 30"10 of the understatement of tax. There is very limited authority to the Treasury to waive this penalty. This article provides an overview of the impact of the Act on many types of common real estate transactions and also illustrates the present Congressional focus on the tax treatment and planning opportunities afforded real estate transactions. Congress will continue to address the issue of broadening the tax base and true tax reform in 1985 with a seriousness not seen in recent memory. Proposals which are presently being considered range from the elimination of interest deductions and beneficial capital gains tax rates to a modified flat tax and other more innovative proposals. Both the discussion and adoption of such changes can be expected to have substantial impact on the real estate market and will effect both property values and the structure of transactions in the future. A review of the Tax Reform Act of 1984 illustrates how the com-
Arkansas Criminal Code 1984 EDITION Arkansas Criminal Code, 1984 Edition contains all chapters of Title 41 of the Arkansas Statutes Annotated in a convenient, one-volume manual. This latest edition includes revised and supplementary commentaries written by Judge Frank B. ewell and Professor L. Scott Stafford. Arkansas Criminal Code is fully annotated and offers editorial notes, collateral references and a comprehensive index.
$24.00* Appx. 650 pages, durable softbound Š 1984, The Michie Company
_ =THE=======
MICHIE COMPANY A_~~~~~TIT~Â For customer service contact: ALL! R. JONES P.O. Box 1306 Conway, Arkansas 72032 (501) 327-6526
Or call toll-free 1-800-446-3410. 'plus shipping, handling and sales tax where applicable
April 1985/Arkansas Lawyer/93
plexity of our present tax structure contributes to this mood for re0 form. FOOTNOTES
There are other provisions in the Act which affect real estate transactions. but where the focus is on the nature of the parties to the transaction rather than on whether realty is involved. Examples are transactions involving foreign persons. the dissolution and liquidation and swapping of interests in partnerships and similar types of transactions. , Reg. §1.483-1 (d) (I) (ii) (C). , Act §4I(a); Code §1274. • Id. , Westbrook. "Congress Changes The Rules For LowMarket Loans." 19 Arkansas Lawyer Vol. I, p. 41 (1985). • Act §41 (a); Code §1274 (c) (3). , Act §41 (a); Code §1274 (b) (2). • Act §41 (b); Code §483 (I). , Act §41 (a); Code §1274 (c) (4) (A). " Act §41 (a); Code §1274 (c) (4) (C). " CCH. Standard Federal Tax Reporter. '16722 (1984). " PI.. 98-612. §2. " Id. " Act §1lI; Code §168. " Act §1063; Code §280B. " Act §1062; Code §190(d). " Code 189. " Act §93; Code §189(d). " Act §1064; Code §167 (K). .. Code §48 (g) (I) (A) (iii). " Act §1043; Code §48 (g). " Act §92; Code §467. " Act §31; Code §§48.168. " Act §112; Code §453(il. ~ Act §77; Code §1031. '" Matthew Bender. Analysis of the Tax Reform Act of 1984 ~124 (1984). " Act §155 (a); Code §§605OL. 6659. 6660.
LAWYERS' MART classified advertising for members
1
~Arkansas
f-Heritaget--WeeR---t May 11-19. 1985 94/Arkansas Lawyer/April 1985
BOOKS FOR SALE For Sale: Am Iur Legal Forms 2nd Am Iur Plead. & Pract. Ann. Aviation Law Aviation Accident Law Benders Disc. Forms Benders Plead. & Proc. Benedict on Admiralty Blashfield Automobile Law & Pract. Law of Liability Ins. Modern Legal Forms; Neg. Camp. Cases Ann. USCA West's Legal Forms 2nd
(Business Organization with Tax Analysis) Bankruptcy Service.
Contact Christa Black. P. O. Box 1470. Little Rock. AR 72203 or call 376-3021.
FOR SALE: Complete and Current ALR 2nd. 3rd. and 4th; excellent condition. Steve Bell. P. O. Box 4282. Batesville. Arkansas 72503. 501-793-4141.
WANTED TO PURCHASE of WANTED: Up-to-date set Arkansas Statues. Ann. Contact; Edwin B. Cantrell III. First National Bank at Springdale. Springdale. AR 72764 WANTED: ARKANSAS LAW REVIEW. Vol. 13 to 28. inclusive. Contact Wayne Boyce. SIS Second Street. Newport. AR 72112 or phone 501-523-5242.
OFFICE SHARING arrangement Office-sharing available; spacious, convenient downtown LR location. share secretary. access to computer. Bill Crowe 374-8203.
Its an Index. Its aCase Finder. Its g Johnnycake Lane Little Rock, AR 72211 Phone: (res) 501/225-3652 Little Rock 501/378-4676 Springfield 417/887-3093
WEST PUBlISHING COMPANY April 1985/Arkansas Lawyer/95
BULLETIN IOLTA UPDATE By Norwood Phillips In the past several years, a number of states have considered and adopted an 10LTA (Interest on Lawyers' Trust Accounts) program, at the urging of state and local bar groups and bar-related organizations. On September 17, 1984, the Arkansas Supreme Court unanimously approved the repetition of the Arkansas Bar Association to establish a voluntary 10LTA program. In approving the concept of 10LTA, the Court reversed its prior decision by holding that client consent is not an element of the 10LTA program. However, the client must be informed of the program. At the present time, there are 10LTA programs in 29 states. The interest income received. has ranged froni a low of $1,500 in Idaho (implementation date of January L 1984) to a high of $4,900,000 in California (implementation date of March L 1983). It is readily apparent that even though the results have been uneven due to such factors as population and implementation dates, the potential for generating funds for public needs and projects is present. The Internal Revenue Service, in Revenue Ruling No. 81-209, has determined that interest income earned路 on lawyers' trust accounts under the Florida 10LTA program will not be taxable income to the clients. The key to the determination by the Internal Revenue Service is that the client cannot control by consent or veto whether his or her nominal or short-term funds may be placed by the
Editor's Note: Norwood Phillips, of El Dorado, is a member of the Shackleford, Shackleford & Phillips, P.A. law firm. He is chair of the Interest on Lawyers' Trust Account ([aLTA) Education and Recruitment Subcommittee. 96/Arkansas Lawyer/April 1985
attorney in an 10LTA account. If client consent were required, then under the long standing doctrine of "assignment of income," the client would be taxed on the income. Further requirements are that the organizations receiving the 10LTA income must be tax exempt under Section 501(c) (3) of the Internal Revenue Code, and such must be used for approved, charitable and public service purposes which must comport with the applicable trade deregulations and revenue rulings.
The Supreme Court, in its decision approving 10LTA, established ten guidelines as follows: I. Interest be made available under the program only on a voluntary basis. 2. No earnings from the funds may be made available to the attorneys or firms.
3. Clients may specify that their
funds are to be deposited in interest-bearing accounts for their benefit as long as these funds are neither nominal in amount nor to be held for a short period of time. 4. Although client consent is not an element. attorneys and law firms participating in the program must inform their clients of their participation by sending to each client a notice in the form prescribed by the Supreme Court. 5. Clients' funds which are nominal in amount or to be held for a short period of time by attorneys and law firms not participating in the 10LTA program must be retained in noninterest-bearing, demand accounts. 6. An Arkansas nonprofit corpo-
ration must be founded to receive the interest earnings.
The Board of Directors shall be comprised of the chief justice and two associate justices,
five members of the lay public appointed by the governor (of whom three shall be repre-
sentatives of low income persons), three lawyers appointed by the president of the Arkansas Bar Association, and the president of the Arkansas Bar Association. With the exception of the members of the Supreme Court and the president of the Association, terms of the directors are to be on a staggered basis. 7. The nonprofit corporation is required to obtain IRS certificates of exemption from income taxes as necessary to
insure that no participating lawyer or any affected client would be charged with or taxed upon any interest paid on funds in a trust account used in participation with the program. The corporation is charged with the duty of allocating net income as follows: 8. The individual lawyer should notify his bank of intention to participate in the program in writing. Tbe bank then should transmit interest earnings directly to the corporation, making period reports of earnings and disbursements to the lawyer. The bank is permitted to make reasonable charges for such services against the interest earnings of the respective accounts.
9. The determination of whether
a client's funds are nominal in amount or to be held for a short period of time rests in the sound judgment of each lawyer or law firm. 10. The Court reserved the prerogative of imposing additional guidelines as to what constitutes funds "held for a short period. of time" or "nominal in amount."
funds
Herman L. Hamilton, Jr., of Hamburg, has chaired the Committee since its inception. Following approval of the concept. President Wilson appointed Larry Yancey of Little Rock to chair the Technical Implementation Subcommittee
and Norwood Phillips of El Dorado to chair the Education and Recruitment Subcommittee. Joe Irwin and Ron Clark of Little Rock are members of the Subcommittee chaired by Larry Yancey. William D. Haught of Little Rock and Richard L. Ramsay of Pine Bluff are members of the Subcommittee chaired by Norwood Phillips. A corporation named Arkansas IOLTA Foundation, Inc. has been formed, and it has applied for appropriate IRS certificates of exemption. By the time this article is published, it is anticipated that the IRS approval will have been obtained and the funding commenced. After the IRS approves the plan, it is contemplated that participation in the program can be obtained by the stroke of a pen. The participating lawyer (or law firm) will simply notify, on a form furnished by Arkansas IOLTA, Inc., his depository bank of his intention to be a part of the IOLTA program. This singular act will permit the depository bank to make periodic distributions of interest income to IOLTA for so long as the trust account is maintained. A nominal fee may be charged by the bank, but this fee will come from interest income. The participant is required to make neither IRS filings nor reports. He simply must notify his clients who have funds on deposit in his trust account of his participation. A joint committee of the Arkansas Bankers' Association and IOLTA will finalize the anticipated procedure.
GllflAlflS A TIIAL•••YOU'LL LIKIOUI STYLII SPECIAL LOW FLAT IIATE JUST FOil MEMBEIIS OF THE AIIKMlSAS BAIl ASSOCIATIOII:
a day. For only $33 a day, you can take your choice of a car from any available car group, SUbcompact through full size 4-door, at Avis. It's a special low rate just for Arkansas Bar Association members. What's more, when you rent an Avis car, a world of convenience and service is included - and, with our flat rate, there's never a charge for mileage at Avis. So, next time you need to rent a car, give Avis a trial. You're sure to like our style! For information on our many convenient services or for fast and easy reservations, call toll free:
'-800-33'-'2'2 And be sure to mention your Avis Worldwide Discount Number:
AlB 314500
AVIS
We try harder. Faster.'"
-
Flat rates are nondlscountable, available at all corporate and parlicipating licensee locations In the contiguous U.S. and subject to change without notice. For all olher car groups, I 25% discount on Avis "We Mean Business" rates applies. Cars and panicular car groups subject to availability and must be returned to r&flling city or 8 drop·off charge and hlgh8l' rate may apply. These ralltS are not available in Manhattan trom Fliday. 1 PM through Sunday. 3 PM and during holidays. A S3/day surcharge applies 10 all Manhanan and New Yortl City area airporl locations. Refueling service charges. laxes, opfional COW, PAl and PEP are not included. Renter must meel standard AVIS age. drlV1tl' and credit requirements.
€I 1985Avls Rent ACar System. Inc.. Avi#
While Arkansas is a relatively poor state economically, it is rich in legal heritage and tradition. There has heretofore been an urgent need for additional funds to provide legal services for the poor and other law-related public purposes. Our IOLTA program, as evidenced by the experience of other states, will become a significant source for such funding. It is submitted that the IOLTA program in Arkansas will be another factor in helping Arkansas retain its position as a leader within the legal profession. 0
YOUR FUTURE ... IS OURS TOO! Call toll-free 1-800-835-2764, and find out how you as an Arkansas Attorney can write title insurance as part of your real estate practice.
INSURED TITLES, 328 N. Main, Wichita, KS 67202. April 19a5/Arkansas Lawyer/9?
EXECUTIVE DIRECTOR'S REPORT And the Snows Came . . .
By William A. Martin FIRST WEATHER CANCELLATION IN 15 YEARS - That is what happened to our Family Law Section program on "The Growing Federalization of Divorce and Family Law," planned for February 1-2. It has been rescheduled for Friday, June 7, during the annual meeting. Calling off a program that has had so much effort put into it is never easy. With speakers coming from New Jersey and Wisconsin, our decision early Thursday morning was made while only a
very fine snow was falling. We thought, "What if the weather forecasters aTe wrong and we doo't have snow?". When Friday dawned with 7 inches of snow in Little Rock we knew we made the right choice. Ben Rowland, who had knocked himself out preparing an outstanding program, had to have been terribly disappointed. He got on the phone and caught one speaker, William M. Troyan, before he left Red Bank, New Jersey. He caught the other, Allan R. Koritzinsky, at O'Hare Airport in Chicago. Members of our stafl. Virginia Hardgrave and Barbara Tarkington, spent most of the day calling those who registered in advance to tell of the postponement. This experience points up a
couple of advantages of preregistration. We were able to con-
tact pre-registrants about the post-
family law, plus an update to the original volume for $75, plus $3 for packing and mailing costs. Your Association is embarking
on a most exciting and important youth education effort. With funding from the Arkansas Bar Foundation, the Association will lease the "Ways of the Law" instructional television program on
our system of justice. "Ways of the Law," and a lesson guide to be compiled by the Young Lawyers' Section, will reach the state's schools beginning with the Fall 1985 semester. These IS, 20-minute programs will be broadcast over the Arkansas Educational Television Network to high schools for videotaping. They can be used in civics. government, history. fami-
ly living, economics or other appropriate classes. The 15 programs are about the right number to use each week for a semester.
Developed in South Carolina, "Ways of the Law" has been enthusiastically received both there and in Louisiana, where the state bar associations co-sponsored the programs. A survey in Louisiana
showed it the most widely used video program in their secondary schools in the fall of 1982. When these programs get started in Arkansas, you may be approached by teachers or principals with an invitation to speak to and lead one or more of their classes centered around the series. We hope you will say "yes" to
busy pushing the Association's legislative package and the Association's position on other bills. She also has a big job going through all the bills filed to decide which ones are of general interest to the membership and then boiling down their descriptions to a reasonable length. The Legislative Newsletter will be useful in letting you know what is being considered by the Legislature. We welcome your suggestions on how we can serve you better.
You may have read the article by UALR Law School Professor Richard K. Burke in Volume 38, Number 1 of the Arkansas Law Review entitled "Truth in Lawyering'; An Essay on Lying and Deceit in the Practice of Law." The Law Review is one of the publications which you get with your membership in the Arkansas Bar Association.
Dr. Burke and the article were the subject of a feature article in the Arkansas Gazette and of a talk show on radio station KAHN. He raised some troubling questions about the ethics of our profession that we should give our thoughtful consideration. He points out most lawyers are honest. fair and bargain in good faith and asks why we should protect those who are not. He gives numerous examples
of the harm those who lie, deceive or countenance clients doing so do to society, to the legal profession and to themselves. Throughout the article he makes a persua-
ponement and. those who had
t~eir
request. The students will
sive plea that rigorous pursuit of
ordered the new Volume II to the Domestic Relations System will get it at the seminar price and get their registration fee refunded, to boot. Other members can buy this
greatly benefit from having contact with a lawyer and you will be
honest, good faith, and fairness is a duty owed to the profession and society that is prior to any duty owed an individual client and our codes of ethics should unequivocally say so. If you have not read the article, I commend it to your attention. 0
wealth of information on how re-
cent federal legislation impacts 98/Arkonsas Lawyer/April 1985
making a
contribution
to our
youth having a better appreciation of the need to respect and obey our laws. Martha M. Miller, our new lobbyist for the Association, is
YOUNG LAWYERS' UPDATE 'Ways of the Law' on AETN
Martha M. Miller, Chair This year's Trial Practice Seminar ought to be of the best yet. The fourth annual event, scheduled for April 4-6, 1985, at the Arlington Hotel, will feature Judge William R. Overton, U.S. District judge for the Eastern District of Arkansas, Nicholas H. Patton, a trial attorney from Texarkana, and Mary Wolff, a trial attorney from Memphis. Jim Simpson, Little Rock, and Bob Ridgeway, Hot Springs, have done an excellent job of organizing this event. The program will begin with an informal reception for those arriving early on Thursday evening. Our speakers' presentations are scheduled for Friday and Saturday mornings and will conclude in plenty of time for registrants to get to Oaklawn Park before the daily double window closes.
If you haven't already preregistered, you may register at the door. For more information, call Sandy Casteel at the AICLE office. Her number is 371-2024. Other YLS seminars were held February 16 in Little Rock and March 2 in Fayetteville to assist local bar associations with National Law Week activities. Since most Law Week activities are presented at the local level, the Young Lawyers' Section Law Week Committee began last year to focus their efforts on providing technical assistance to local bar associations so that Law Week activities could be tailored to the needs of individual communities. Tom Ray, Little Rock, and John Moore, Little Rock (formerly of Mountain Home), have done an outstanding job coordinating these efforts. The Arkansas Bar Foundation also deserves credit for this program. Without their generous financial support this program would not be possible.
Another seminar which the YLS will be working on is the annual Fall Legal Institute presented by AlCLE. This seminar, scheduled for September in Fayetteville, will feature the Criminal Law Handbook which should be hot off the press in June. Sam Perroni. YLS Committee chair, has put together an impressive publication. Sam will also serve as program coordinator of Fall Legal. In addition to these continuing projects, YLS has recently initiated two new projects of major importance. The first is the Statewide Mock Trial Competition which will be held April 27. Teams of high school students will be competing at both regional and state-wide levels. This project is chaired by Terry Derden of Little Rock. The second new project is a youth education project called "Ways of the Law." A series of IS, twenty-minute videotaped programs will be aired on AETN during the 1985-86, 1986-87, and 198788 school years and accompaning teachers guides and student handbooks will be distributed by AETN in cooperation with the Arkansas Department of Education. The programs trace the roots of law, looks at why we need law, examines the criminal process and law enforcement, and discusses family law, wills and estates, contract! consumer law, civil law, environmental law, and due process. The program was developed by the South Carolina Education Department and has been aired in almost 30 states with great success. Martha Jean McHaney, Little Rock. will chair this effort. Again, a special thanks goes to the Arkansas Bar Foundation for funding this project. Two recent YLS appointments to American Bar Association positions deserve mention. Frank C. Elean, II of Harrison, has been
appointed as the ABA Young Lawyers' Division liaison to Judicial Administration Division Lawyers' Conference, and Carl A. Crow, Jr. of Hot Springs, has been appointed as the ABA Young Lawyers' Division liaison to the Forum Committee on Franchising. Both Frank and Carl are past chairs of the Arkansas YLS. This is the last YLS Update you will receive before the Annual Meeting in Hot Springs on June 58, 1985. The Young Lawyers' business is scheduled during the afternoon of Thursday, June 6. At that time, we will be electing officers for the '85-86 Bar year. I urge each of you to attend and participate in this process. D
Liberty & Justice Liberty & Justice Liberty & Justice Liberty & Justice Liberty & Justice Liberty & Justice Liberty & Justice Liberty & Justice Liberty & Justice Liberty & Justice Liberty & Justice Liberty & Justice Liberty & Justice Liberty & Justice Liberty &Justice
ForAll
Law DayllBAIMay1 April t985/Arkansas Lawyer/99
ARKANSAS BAR FOUNDATION Foundation Funds Educational Programs
By Robert L. Jones, III In 1984 the Arkansas Bar Foundation began the annual award of a research fellowship for a professor at both the University of Arkansas School of Law at Fayetteville and the University of Arkansas School of Law at Little Rock. The grant enables the professor to undertake research and study during the summer months. The Foundation is pleased to report on these two research fellows. The 1985 research fellow for the U of A School of Law at Fayetteville is Robert B. Lellar. The fellowship will enable Professor Lellar to write a law review article on the discovery and use of federal regulatory evidence in private litigation. The 1985 Foundation research fellow at the UALR School of Law is Glen Pasvogel. Professor Pasvogel plans to research mortgage law in Arkansas and draft a set of forms for use in mortgage law practice. The Foundation is proud of the service to the legal profession exhibited by these two research fellowships. The Foundation is continuing to fund other educational causes. At the meeting on January 17, 1985, its Trust Committee approved a grant of $2,275.00 to the Young Lawyers' Section of the Arkansas Bar Association for the purpose of funding a statewide law week project. The Foundation is pleased to report that it has awarded $1.000.00 to the Young Lawyers' Section to assist in the distribution of the Senior Citizens' Handbook, During the past, the Foundation has made possible the printing of 65,000 copies of this handbook. This has been one of the most successful projects of the Foundation in the last few years. IOO/Arkansas Lawyer/April 1985
The Foundation has allocated $5,665.51 to the Arkansas Bar Association for such matters as: a. The distribution of a special brochure familiarizing Arkansas lawyers with interest on lawyers' trust accounts; b. A reprinting of the booklet entitled, How Do Lawyers Set Their Fees: c. A reprinting of the booklet entitled, Marriage and the Law: d. A reprinting of the booklet entitled, Small Claims Court in Arkansas: and e. A reprinting of the booklet entitled, The Reporter's Guide to Legalese, The Foundation is most pleased to report that it has granted $4,610.00 to the Young Lawyers' Section for a youth education project entitled "Ways of the Law." This project is to fund the "Ways of the Law" video program which is an instructional guide for teachers. It is designed to acquaint high school students with areas of the law they are likely to come into contact with as adults. The
program traces the roots of the law, looks at why we need law, examines the criminal process and law enforcement and discusses family law, wills and estates, contracts/consumer law, civil law, environmentallaw and due process. The Foundation manages and provides income from funds which have been contributed for scholarships to students at both the Fayetteville law school and the UALR School of Law. The following is a list of current scholarship recipients at the University of Arkansas School of Law at Fayetteville. Friday, Eldredge & Clark Gary Fogleman; Harry P. Warner - Dave Jacobson;
C. R. Warner-Garland Yarber; Rather, Beyer & Harper Cynthia Rodgers;
Edward Lester - Mark Long; Henry Woods - Steve Gilbert; R. A. Eilbott. JI. - Michael Lee Murphy; Arkansas Bar Foundation Cindy Ann Falls; Arkansas Bar Foundation Robert Montgomery; Judge John Miller - Dana Dean; Bud & Bernard Whetstone Thomas Kase; Judge John Fogleman Patricia Jackson; Col. C. E. Ransick Addie Burks; Fellowship Recipient - Lonnie R. Beard The following is a list of current scholarship recipients at the University of Arkansas School of Law at Little Rock. Friday. Eldredge & Clark (Jerry T. Light) - Kenny W. Henderson; Friday, Eldredge & Clark (Boyce R. Lovel - Larry K. Cook; Harry P. Warner James Pender; Cecil R. Warner James Pender; Rather, Beyer & Harper Ronnie F. Craig; Edward Lester- Vicki Sandage; Judge Henry Woods - Oscar Jerome Green;
R. A. Eilbott, JI. - Paul Dickerson;
E. Charles Eichenbaum Robert Ivan Bland, Mary M. Bell and Debra L. Cagle; Arkansas Bar Foundation Lynn F. Plemmons; Rose Law Firm - Scott Lancaster;
U. M. Rose - David Schoen; Judge John A. Fogleman David O. Bowden; Judge 1. Smith Henley - Rita S. Looney; Bud & Bernard Whetstone Wanda C. Wyeth; Colonel C. E. Ransick S. Randolph Looney; Fellowship Recipient - Arthur Murphey 0
IN-HOUSE NEWS Law Schools, AIeLE and House of Delegates
UNNERSITY
addition,
OF
area for the legal clinic will be provided. Rear-
ARKANSAS SCHOOL OF
LAW AT FAYETTEVILLE By J. W. Looney Expansion Of Waterman
Hall Construction is under-
way for a major expansion of Waterman Hall. The expansion is designed to provide crucially needed library space, and, in the process. some renovation of
the original portion of Waterman Hall. The library addition to Waterman Hall. completed in 1974, was designed for library holdings slightly in excess of 100,000 volumes. The current holdings have expanded to approximately 185,000 volumes and, thus, the space is no longer adequate to accommodate both the library holdings and the need for study space for students. In addition to the additional space for the Robert A. and Vivian Young Law Library, a new faculty research library will also be included along with additional classroom space for computer training. In
two
small
courtrooms and a new
rangement
of
secre-
tarial staff work area and administrative offices will also be included as a part of the project. Construction is expected to be completed by the 1986 Spring Semester. Faculty Activities And Publications Lonnie R. Beard (who teaches courses in federal
taxation,
taxation'
of estates, gifts, and trusts, agricultural taxation, and farm estate and business planning) along with 1983 graduate Pati L. Hoffman have an article in the Arkansas
Law
Review:
"Selected Tax Issues Arising During the Development Stage of Orchards, Groves and Vineyards." A chapter entitled "No Task for the ShortWinded" written by Dr. Robert A. Leflar is included in a recent book Handbook for Judges, published by the American Judicature Society. A new textbook coauthored by Donald B. Pedersen, director of the Agricultural Law Program, was recently released by West Publishing Company. The text, Agricultural Law: Cases and Materials, is accompanied by a teacher's manual. This textbook will be used in Agrieul tural
Law courses
in a number of law schools. Rodney Smolla was a speaker at the University of Toronto Law School on "Media and the Law." Dean's Activities
Jake Looney was a speaker at a meeting of the Great Plains Resource Economics Council, Denver, on "Water Conflicts, How They Are Addressed by Courts and Legislatures;" at the Arkansas Seed Growers Association meeting on
"Water Legislation in Arkansas;" at the National Association of Animal Breeders meeting in Denver on "Tax Im-
plications of Embryo Transfers;" at an Agricultural Policy Forum in Gainesville, Florida on "Government Regulation and Property Rights;" and at a meeting of the American Embryo Transfer Association on "Legal Considerations in Embryo Transfers."
UNIVERSITY OF
ARKANSAS AT LITTLE ROCK SCHOOL OF LAW By John M. Sheffey Alumni News Sheffield Nelson,
a
1968 graduate of the law school, joined the Little Rock firm of House, Wallace, Nelson and Jewell on January I. 1985. Nelson had served as chairman and president of Arkansas Louisiana Gas Company for 12 years. He is now a senior partner of the law firm and serves as the firm's chairman of the Board. Frank B, Whitbeck, a member of the 1975 graduating class. was recently featured in Arkansas Business, The profile of Whitbeck traced his career as president of American Foundation Life Insurance Company, as a lawyer in private practice, and as founder and chief executive officer of Signature Life Insurance Company of America. Numerous graduates of tbe School of Law and its predecessors are cur-
rently serving in elective pasitions. Notable among those are Senator Max Howell (who has served in the Arkansas Legislature since 1947), Art Givens, Cliff Hoofman and Doug Wood, all of whom hold seats in the Legislature. Judicial posts are held by Robert Garrett (Saline County chancellor) and Floyd Lofton and Thomas Digby (Pulaski County Circuit Court), Dan Stephens (Chancery judge in Clinton) and J. Hugh Lookadoo (judge in Arkadelphia). Floyd "Buddy" Villines April 1985/Arkansas Lawyer/WI
and Tom Prince were recently elected to the Little Rock City Board of Directors. Prince has also been elected to serve a two-year term as
mayor of the city of Little Rock. The monthly luncheon gatherings of our Alumni Association continue to draw interest from our graduates who practice in central Arkansas. Recent speakers have included Judge Thomas Glaze of the Arkansas Court of Appeals, who spoke on evaluation of judges; Jody Mahony, a member of the Arkansas Legislature from El Dorado, who discussed what he considered the
culminated with the position of general counsel, Office of the United States Trade Representative, Executive Office of the President. In that capacity he was the senior executive branch legal officer responsible for international trade matters. His address was entitled, "Resolving International Conflicts Over Economic Regulation: A Modest Proposal." It was particularly timely for Arkansas, because of the state's increasing participation in international trade. Faculty News
significant issues facing
the current session of the Legislature, and Phillip Carroll, a Little Rock attorney with the Rose Law Firm, who gave a very entertaining
slide presentation on the trial of Lizzie Borden. Terry Derden and Sherry Bartley, co-program chairmen. have promised further interesting programs for the upcoming luncheon meetings. Altheimer Lecture
The eleventh Ben J. Altheimer Lecture featured Robert Charles Cassidy, Jr., a partner in the prestigious Washington, D.C. law firm of Wilmer, Cutler and Pickering, and an expert in international trade matters. Before going into private practice, he had a distinguished career in government where he
served in the Office of Legislative Counsel of the United States Senate and the staff of the U.S. Senate Finance Committee. In both he specialized in international trade and tax matters. His government career
lO2IArkansas Lawyer/April 1985
Donaghey Distinguished Professor Robert R. Wright has been elected a fellow of the American Law Institute. This is a prestigious position to which only a very few legal scholars and practitioners are elected. The only other Arkansas members are Phillip Anderson (a member of the Council of the American Law Institute), and the two Arkansas law school deans.
Professor Wright is not teaching during the spring semester but has been granted an offcampus duty assignment. He is engaged in writing a treatise on the Arkansas law of property. Professor Wright also addressed the Arkansas Municipal League and city attorneys on December 15 in Hot Springs on planning and zoning law. Professor Richard K. Burke delivered the Seventh Annual Clark Y. Gunderson Lecture at the University of South Dakota School of Law. Professor Burke's topic was, "More Judges or
Less Litigation - A Federal Question?". His address will be published by the University of South Dakota. Professor Burke is a former professor of law and dean of the School of Law of the University of South Dakota. Professor Burke's article, "'Truth in Lawyering': An Essay on Lying and Deceit in the Practice of Law," appeared in Vol. 38 of the Arkansas Law Review. Professor Judy Lansky, a supervisor in the Law School's Legal Clinic, was elected secretary of the Board of Advocates for Battered Women. Professor Susan W. Wright addressed the Eighth Circuit Court of Appeals as a representative of Judge Henley's former law clerks. The occasion for the en banc court session was the unveiling of Judge Henley's portraii. to be hung in the Eighth Circuit Courtroom in St. Louis. Judge Henley has now been elevated to senior status. Professor Wright has also been appointed to the local arrangements committee of the Eighth Circuit ludicial Conference, to be held in Little Rock next summer.
The American Association of Law Schools met in Washington, D.C. on January 3-6. The law school was well represented by Dean Averill
and
Professors
Adams, Gitchel. Gould, Spears, Robert Wright and Susan Wright. Professor Adams also attended the meeting of the Law School Admission Council while he was in Washington.
A.I.e.L.E. NEWS By Claibourne W. Patty, Jr. The Mid-Year Meeting of the Arkansas Bar Association, held at the Camelot Hotel in Little Rock on January 18-19, devoted one day of its CLE portion to an intensive review of recent developments in six areas
of the law. Under the leadership of Robert L. Jones, m, program chairman, and Professors L. Scott Stafford and Rodney Smolla, program co-chairs, the following topics were developed: Arkansas Federal Court Rules and Civil Procedure, by Chief U.S. District Judge H. Franklin Waters; Legal Advertising by Jerry Cavaneau; Specialization by Richard Hatfield; Pitfalls in the Trail of Lawsuits by Annabelle Clinton, former Pulaski County Circuit judge, John Patterson, Circuit judge, Fifth ludicial Circuii. and Han. Howard Templeton, Chancery and Probate judge, Second Chancery Circuit; Bad Faith Claims by William H. Sutton and William R. Wilson, Jr.; and Significate Arkansas Appellate Decisions by David Newbern, Arkansas Supreme Court justice. A total number of 160 persons attended. 23rd Arkansas Federal Tax Institute The 23rd annual Arkansas Federal Tax Institute, co-sponsored with the Arkansas Society of Certified Public Accountants, was held December 6-7, 1984 at the Excelsior Hotel. Little Rock.
The faculty, consisting of lawyers and CPAs of national and statewide
Bar Association NewsBulletin and The Arkansas Lawyer,
prominence.
1985 Banking AICLE Joins Private Satellite Network On October 23, 1984, the TV Satellite Program on "Banks and Their Borrowers"; produced by Practising Law Institute, was shown at the UALR Conference Center in Little Rock. On March 20th, a TV satellite program produced by the Section of Urban, State and Local Government of the American Bar Association will be shown by AICLE concerning the topic of Governmental Liability Under Anti路Trust Laws. Programs concerning the Durable Power of Attorney will be shown April 24, 1985; on May 8th The Lawyer Buying a Computer; on March 26th, Estate Planning for the Aged, Incapacitated Client; on May 14th, Evaluating a Personal Injury Case - The Brain Damaged Child; on May 15th, UCC Strategies under articles 2-9; and finally scheduled is Blue Sky Laws produced by PLI to be shown June II. 1985. Until the Bar membership is notified otherwise all TV satellite programs will be shown at the two locations UALR Conference Center in Little Rock and the University of Arkansas Conference Center, Fayetteville. Brochures produced by the cosponsors will be mailed to the Bar membership sufficiently in advance of the program so that they may mark their calenders and attend. You will be notified of future programmings in AICLE Brochures, the Arkansas
Law Seminar
The 1985 Banking Law Seminar, sponsored with the Banking Law Committee of the Arkansas Bar Association, was held March 2223, 1985 at the Sheraton Hotel in Hot Springs. This program was chaired by V. Markham Lester, and dealt with usury problems on Friday morning. The Saturday morning sessions dealt with recent developments in bankrupcty laws and the RICO statute as applied to banks. Labor Law Institute The 8th annual Labor Law Institute, jointly sponsored with the Labor Law Section of the Arkansas Bar Association, the National Labor Relations Board, and the Industrial Research and Extension Center of UALR, will be presented at DeGray Lodge, Arkadelphia, on April 19-20, 1985. Please mark your calendars lor these upcoming annual
programs: YLS Trial Practice Program, April 5-6, Arlington Hotel. Hot Springs Tax Awareness Institute. April 26. UALR Conference Center. Little Rock Federal Court Orientation Program.
May 6. 1985, United States Post Office. Courthouse. Little Rock
ARKANSAS BAR ASSOCIATION HOUSE OF DELEGATES MEETING JANUARY 19, 1985 The House 01 Delegates 01 the Arkansas Bar Association held its Semi-Annual meeting at the Camelot Inn in Little Rock. Arkansas, on January 19, 1985. President William R. Wilson, Jr., presided. The House approved the minutes 01 the last Executive Council meeting, the financial statement as 01 December 31, 1984, association membership statistics, the annual report of the secretary-treasurer lor the fiscal year 1983-84, and the report 01 the auditing committee.
The House adopted Resolution No. 85-1 endorsing Philip S. Anderson lor chairman of the American Bar Association House 01 Delegates and Resolution No. 85-2 endorsing an amendment to the state's Constitution which enables the General Assembly to confer jurisdiction 01 juvenile or bastardy matters upon chancery. cir-
cuit or probate courts. or to establish separate juvenile courts. Annabelle Davis Clinton, chair of the Committee to Consider Guidelines lor Selection 01 Federal Judges and Election of State Judges, reported that the Committee recommended consideration of the merit system for the selection 01 state judges and that this matter be
relerred to the recently appointed Merit Selection Committee. With respect to the selection of federal judges, the Committee concluded that a proposal 01 guidelines for selection of federal judges would be advisory and, therelore, 01 minimum value, in view
of the power reposed in the President 01 the United States to appoint federal judges with the advice and consent 01 the United States Senate. Jane Knight, co-chair 01 the Committee to Study Resolutions and "Special" Meetings of the House 01 Delegates, reported that the Committee recommended the following amendments to Article XII of the Association's Constitution: (I) the House 01 Delegates, by a twothirds vote of those present and voting, may waive
the
notice
re-
quirements 01 the article; (2) the House 01 Delegates, by a twothirds vote of those present and voting, may consider resolutions at a special meeting 01 the House 01 Delegates. The Committee also recommended that the fall House 01 Delegates meeting become a re-
gular meeting under Article XIV of the Constitution. The proposed amendments will be submitted to the House 01 Delegates at its June meeting. Martha M. Miller, association lobbyist. reported that 01 the nine bills in the Association's legislative package, the Guardianship bill and the Judicial Compensation Commission bill were the subject of the most attention. The House 01 Delegates voted to remove the Judicial Compensation ComApril 1985/Arkansas Lawyer/103
mission bill from the Association's legislative package. Miller further reported that the Arkansas Medical Society is not opposing the Uniform Determination of Death Act and that the additional staffing requirements of both the Arkansas Supreme Court and the Arkansas Court of Appeals will be incorporated in their re-
spective budgets. The House of Delegates endorsed the work of the Statute Revision Commission including the Commission's budget request. Miller concluded by requesting that members of the House of Delegates pledge contributions to LAWPAC. Justice John Fogleman noted that a bill may be introduced in support of consolidating the Judicial Retirement System and the State Employees Retirement System. Justice Fogleman observed that the enactment of such a bill would be devastating to judicial retirement. John Forster proposed a bill allowing judges to set punishment in all cases other than murder Class A and Class Y felonies. A motion to endorse the proposed amendment was tabled. The House adopted an amendment to Article II of the Association's Bylaws, so as to exempt
new admittees from the payment of dues for the balance of the bar year in which they are admitted to the bar, without application. The House authorized the Group Insurance Committee to hire an independent consultant for the purpose of evaluating the group insurance needs of the Association. This consultant would not be permitted to bid or write the 104/Arkansas Lawyer/April 1985
Association's group insurance
package.
Further, the House appropriated $2,500.00 for expenses incurred in connection with reten-
tion of an independent consultant.
Herman Hamilton, chair of the Interest on Lawyers' Trust Accounts (I0LTA) Committee, reported that the nonprofit corporation to administer IOLTA is expected to be operational
soon. The House approved a motion to apply to Legal Services Corporation for an implementation grant. The House approved a slightly modified version of the American Bar Association's Model Rules on Professional Conduct and directed the special Association Committee on the Model Rules to petition the Arkansas Supreme Court to adopt the Model
Rules of Professional Conduct as the rules governing the professional conduct of lawyers in Arkansas. President Wilson announced that the Association's 1985 annual meeting will be June 5-8, 1985, and that the first regional state trial practice seminar will be held in Camden. The meeting was then adjourned. Annabelle Clinton
You are invited to attend a national conference
Advance Directives in Medicine: Ethical. Legal. and Medical Considerations May 2-4, 1985 University Conference Center Little Rock, Arkansas Living wills, durable powers of attorney, "no code" orders and other methods of directing one's future medical care provide the focus of this interdisciplinary conference. Nationally recognized scholars in medicine, law and medical ethics will address: - appropriate uses of advance directives. - roles of physicians. attorneys. and nurses. -
economic considerations.
- legislative proposals and judicial decisions, and - liability of physicians and health care institutions. For more information and registration materials please contact: Division of Medical Humanities
University of Arkansas for Medical Sciences 4301 West Markham - Slot 646 Little Rock, Arkansas 72205 (501) 661-5622
Trial Consultation Melissa A. McMath. M.S.. L.A.C. Worthen Bank Bldg. Little Rock. Ark. 72201 50l-374-1169 Jury Selection Witness Preparation Verbal-Nonverbal Analysis
Case Presentation Voir Dire Analysis Post Trial Jury Review
Association of Behavior Trial Consultants
ATTORNEY'S ECONOMIC CONSULTANTS "A Division of Education and Research Associates. Inc." SERVING THE LEGAL PROFESSION WITH EXPERTISE IN THE fOLLOWING AREAS: Workmen's Compensation (Lump-Sum Settlement Calculations) Evaluation of Lost Earnings Capacity from Partial or Tolal Perma-
nent Disability or Wrongful Death Economic Valuation of Pecuniary Damages in Business Tort, Con· Iract and Anti-Trusl Cases Valuation of Minority Stock Holdings in Estate Settlements Economic Analysis for Charters or Branch Applications for Finan· dol Institutions Structured Seulement Pricing and Design
QUAUFIED AS EXPERT WITNESS IN ARKANSAS AND OTHER JURISDICTIONS
P.O. Box Drawer 34117 Little Rock. Arkansas 72203
Attention Lawyers • Provide liquidit.v for e'5tate'i,
We Buy
Real Estate Notes
bankruptcies and divorce",.
• Convert fir'5t and c;econd mortgages
to ca.h. • Pero;;onal or business
loan., on re'5idential or commercial propert.v.
Pioneer Financial Services Founded 1932
Ca II 1-800· FOR-LOAN
(501) 661-0161
Telex: 78-3081 In Arkansas call: 1-800-221-2715 Out-aI-state call: 1-800-221·2717
SERVICE DIRECTORY MISSING AND UNKNOWN HEIRS LOCATED NO EXPENSE TO THE ESTATE
WORLD· WIDE SERVICE fOR
COURTS - LAWYERS - TRUST OFFICERS ADMINISTRATORS - EXECUTORS
AMERICAN ARCHIVES ASSOCIATION INTERNATIONAL PROBATE RESEARCH 449 WASHINGTON BUILDING WASHINGTON. D.C.
LEGAL BRIEF PRINTING PARAGON Printing & Stationery Company has been printing BRIEFS for over 35 years. May we be of service to you? 311 East Capitol
375-1281 Little Rock
• BEACH ABSTRACT & GUARANTY COMPANY REPRESENTING: TICOR TITLE INS. CO. ABSTRACTS-ESCROWS-TITLE INSURANCE 100 Center 51. - Lillie Rock. AR 376-33 t.he reasons• Everyt.hing (including seal) is inside t.he "all-in-one" corporate outfit.• Improved corporate record book and slip case in lustrous black vinyl with high quality gold stamped border. The st.urdy, dust.-proof slip case reserves place on shelf when corporate record book is removed .• Hidden rivets and gold label window on spine for attractive appearance and quick identification.· Interior pocket neatly holds loose
",,,,,,,"'' ' !' "'
docum en ts~....
• Improved 1 \i,".• 50 sheets, rag content paper. Or printed Minutes and By-laws with tax materials updated to conform with the Economic Recovery Tax Act of 1981. Minutes and By-laws include up-to-date IRC *1244 Resolution, Subchapter S Materials, separate section. Complete Black Beauty· Outfit No. 70 (Green No.7}) 50 sheets blank
$42.50
minute paper No. 80 (Green No. 81) with
printed minute~ and by-laws Charge to American Express MasterCard or Visa
$46.00
You may also select Green Beauty with the same fine features.
Excelsior-Legal R,.:quest C,tt;l!oj.{ vf Law Productli and Scrvic¢;
New York· Georgia· Illinois· Texas
----------
--------------------------------
TO: £XCELSIOH-LEGAL SOUTHWEST, INC. P.O. IJQx 5683
Plc(f.'ie Ship:
o
n
No. 70 0 No. 71 ..$42.50 No. 80 0 No. 81 ..$46.00
Plell.." e include S1.00 for shipping and handling:,
State
year
_
Arlin)!lon, TX "11 'Print l"QrporaU,o na'm: ~xactly a... 011 cl;lruflcllte ofirkurpunltltll'l. Iflunger Ihull 45 cnunJcter;; :}fld ~pl'lCl,."'.lldd $7.00 for 2" dw :>i!aLl
o Shipment within 24 hours ~dl«r r,..." Ct'ipt of order
=,-_
PY $_ _
NPV or 0
Capitalization $
e"eh
Certificates sig-ned by President and
0
Ship via Air-$6.00 exira
fScucwry-tn'asurer, unlt',;" otnl'l"WlBe Iipeclfi"d;
IRe *1244 complete sel-rel;oJ., dir. min .• treatise. law etc" $4.95 extra. rJ AMEX Charge n Me Q
SHIP VIA AIR:
$6.00 ADDITIONAL WITHIN THE 48 CONTICUOUS STATES. ($8.00 El..SEWHEICI::.)
----------
o
VISA
Number
Expires
Si~nHture
Ship to _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ Zip Code
..
AZ
--~._-----------------_ _--~-~----- | http://issuu.com/arkansas_bar_association/docs/april-1985?mode=embed | CC-MAIN-2016-07 | refinedweb | 33,413 | 54.83 |
The Jupyter Notebook is a fantastic tool for generating and interactively presenting data science projects. This post will show you how to set up Jupyter Notebooks on your system and use it for data science projects.
But first, what exactly is a “notebook”?
A notebook combines graphics, narrative prose, mathematical equations, and other rich media with code and output in a single document. To put it another way, it’s a single page where you can run code, see the results, and add explanations, formulas, and charts to make your work more transparent, repeatable, and shared.
At firms worldwide, using Notebooks is now an essential element of the data science workflow. If you want to work with data, a Notebook will streamline your process and make it easier to communicate and share your findings.
Jupyter Notebooks are also absolutely free because they are part of the open-source Project Jupyter. The software is available separately or as part of the Anaconda data science toolset.
Although you can use Jupyter Notebooks with various computer languages, this article will focus on Python because it is the most popular use case. On the contrary, R Studio is the more popular choice among R users.
Jupyter Notebooks are a helpful tool for writing and iterating on Python data analysis code. You can write several code lines and run them one time rather than writing and rewriting a complete program. Then, if you need to modify, you may return to the same window and make your changes while rerunning the program.
IPython refers to an interactive way of running Python code in the terminal using the REPL concept, the foundation of the Jupyter Notebook (Read-Eval-Print-Loop). The computations are done via the IPython Kernel, connecting with the Jupyter Notebook front-end interface. It also enables Jupyter Notebook to work in a variety of languages. Jupyter Notebooks give additional features to IPython, such as storing code and output and allowing you to keep markdown comments.
Jupyter Notebook Installation
Installing Anaconda is the most straightforward approach for newcomers to get started with Jupyter Notebooks. Anaconda is the most popular Python data science distribution, and it comes pre-installed with all of the most popular libraries and tools.
NumPy, pandas, and Matplotlib are among the most popular Python libraries included with Anaconda; however, the 1000+ list is extensive. As a result, Anaconda allows us to get right into a fully equipped data science workshop without the effort of managing several installs or worrying about dependencies or OS-specific (read: Windows-specific) installation concerns.
To obtain Anaconda, follow these steps:
- Anaconda for Python 3.9 is now available. Go to the official website & download it.
- Follow the instructions on the download page and in the executable to install Anaconda.
If you’re a more advanced user who already has Python installed and prefers to handle your packages manually, use pip:
pip3 install jupyter
Putting together your first Notebook
We’ll learn how to execute and save notebooks and familiarize ourselves with their structure and interface in this section. We’ll learn some basic vocabulary that will help you gain a practical grasp of how to utilize Jupyter Notebooks on your own.
Creating a Notebook
To start a Jupyter notebook, open your terminal and go to where you want to save your Notebook. The application will create a local server at localhost:8888 if you execute the command jupyter notebook (or another specified port).
tuts@codeunderscored$: jupyter notebook
Otherwise, you can alternatively opt to use the address it gives you to open a browser window using the Jupyter Notebook interface. Each has its token because the software employs pre-built Docker containers to put notebooks on their unique path. Hit the Control-C twice from the terminal to stop the server and shut down the kernel.
On Windows, you can start Jupyter by pressing the shortcut Anaconda adds to your start menu, which will open a new tab in your default web browser, similar to the screenshot below.
This is the Notebook Dashboard, which is dedicated to keeping track of your Jupyter Notebooks. Consider it a starting point for exploring, editing, and creating notebooks. Remember that the dashboard will only offer you access to the files and folders in Jupyter’s start-up directory (i.e., where Jupyter or Anaconda is installed). The start-up directory, on the other hand, can be altered.
The dashboard’s URL is when Jupyter Notebook is open in your browser. The term “localhost” does not refer to a website but rather to the material supplied from your computer.
Jupyter’s Notebooks and dashboards are web apps, and Jupyter creates a local Python server to provide these apps to your web browser, effectively making it platform-independent and allowing for more direct online sharing. The crucial thing is that, while Jupyter Notebooks appears in your browser, it is hosted and operated locally on your computer. Until you choose to share your notebooks, they aren’t technically on the internet.)
The interface of the dashboard is mainly self-explanatory.
Jupyter Notebook
You’ve now entered the Jupyter Notebook interface, where you may view all of the files in your current location. The notebook icon next to their name distinguishes all Jupyter Notebooks. If you already have a Jupyter Notebook open in your current directory, locate it in your files list and double-click it to launch it.
How to start a new notebook
Go to New and pick Notebook – Python 3 to start a new notebook. If you have any other Jupyter Notebooks on your system that you’d like to use, click Upload and navigate to that file.
Notebooks that are currently running will have a green icon, while those that are not will have a grey icon. To see a list of all currently running notebooks, go to the Running tab.
The Notebook’s Interior
At first glance of opening a Jupyter notebook, you’ll notice that it has a cell in it.
Cells are the building blocks of notebooks, and they’re where you write your code. Click on a cell to select it, then hit SHIFT+ENTER or the play button in the toolbar above to run the code. In addition, the Cell dropdown menu offers many cell-running options, including running one cell at a time or all cells at once. The output of the cell’s code appears in the space below when you run it. To stop a section of code from running, press the stop button.
Use the addition (+) button in the toolbar to add new cells or press SHIFT+ENTER on the last cell in the Notebook. Select the cell you wish to change and go to the Edit button in the navigation bar to see your options for cutting, copying, deleting, or just editing it in general.
You can include text-only cells that use markdown to create and organize your notebooks in addition to running lines of code. It will be a Code cell when creating a new cell by default. To make a markdown-based cell, go to the Cell menu in the navigation bar, scroll down to Cell Type, and select markdown.
You may need to restart the kernel on occasion. Restart the kernel by going to the Kernel dropdown menu. You can shut down a kernel by clicking Shutdown, which will prompt you with a dialogue box asking if you want to do so. To force a shutdown, go to the File menu and select Terminate and Halt, and the browser window will close on its own. Be aware that restarting and shutting down kernels will impact your variables.
You’ll discover important information like keyboard shortcuts and links to other documentation for modules like Numpy, SciPy, and Matplotlib in the Help submenu.
There are various shortcut buttons for everyday activities on the toolbar. For example, save, create a new cell, cut chosen cells, copy selected cells, paste cells below, move selected cells up, move selected cells down, run, interrupt the kernel, restart the kernel, a dropdown to alter the cell type, and a shortcut to open the command palette are all available from left to right.
Jupyter Notebook files are automatically saved as you type. They’ll appear as a JSON file with the extension .ipynb in your directory. Jupyter Notebooks are also exported in various forms, such as HTML. Go to the File menu, scroll down to Download as, and choose the file format you want. A popup will open, asking where you want to save the new file. Save and Checkpoint when you’ve browsed to the correct directory.
What is an ipynb file, and how do I open one?
The short answer is that each .ipynb file represents a single notebook. Thus, a new .ipynb file is also created when creating a new notebook.
The lengthier explanation is that each .ipynb file is a text file that uses the JSON format to represent the contents of your Notebook. Each cell and its contents, such as picture attachments converted to text strings, are listed, along with some metadata.
You can edit this yourself if you know what you’re doing by going to the Notebook’s menu bar and selecting “Edit > Edit Notebook Metadata.” By selecting “Edit” from the dashboard controls, you may also see the contents of your notebook files. However, the term “can” is crucial. In most circumstances, manually editing your notebook metadata is unnecessary.
Shortcuts on the Keyboard
Finally, you may have noticed that when you run your cells, their border turns blue when it was green while editing. There is always one “active” cell marked with a border whose color defines its current mode in a Jupyter Notebook:
The cell has a green outline, indicating that it is in “edit mode.” Cell in “command mode” has a blue outline.
So, what can we do with a cell in command mode with it? We’ve seen how to run a cell using Ctrl + Enter so far, but there are plenty of other options. Keyboard shortcuts are the best way to use them. Because they enable a quick cell-based workflow, keyboard shortcuts are a popular feature of the Jupyter environment. When the active cell is in command mode, you can do several of these activities.
A list of Jupyter’s keyboard shortcuts is provided below. You don’t have to memorize all of them right away, but this list should give you a fair idea.
First, start by toggling between the edit and the command mode with the help of the Esc and Enter keys, respectively.
What you can do in command mode:
- Scrolling up and down the cells using both the Up and Down keys.
- Pressing the A or B keys to insert a new cell above or below the active cell.
- M transforms the currently active cell to a Markdown cell.
- Y is responsible for setting the active cell to a code cell.
- D + D or D double deletes the currently active cell.
- Z is responsible for undoing a given deletion of cells.
- Hold Shift and subsequently press Up or Down to select many cells simultaneously. After that, use Shift + M to merge your multiple cells selection.
Ctrl + Shift + -, while you are in edit mode, split the currently active cell at the cursor point. Alternatively, click Shift + Click in the margin to the left of your cells to select them.
Feel free to experiment with these in your Notebook. Create a new Markdown cell when you’re ready, and we’ll learn how to format the text in our notes.
Markdown
Markdown is a simple markup language for styling plain text that is lightweight and easy to learn. Because its syntax is identical to HTML tags, some prior knowledge would be advantageous, although it is not required.
Because you produced this article in a Jupyter notebook, you’ll notice that all of the narrative text and graphics you’ve seen so far were created using markdown.
There are three conspicuous options when attaching images:
- Make use of an online image’s URL.
- Use a local URL to a picture you’ll maintain with your Notebook, such as in the same git repository.
- Add an attachment by selecting “Edit > Insert Image”; the image will be converted to a string and stored in your notebook’s.ipynb file.
Please keep in mind that this will significantly increase the size of your .ipynb file!
There’s a lot more to markdown, especially for hyperlinking, and you may also use plain HTML. You can refer to John Gruber’s website if you find yourself stretching the limitations of the basics above.
Cells
We’ll return to kernels later, but now, let’s get a handle on cells. A notebook’s body is made up of cells. The box with the green outline in the screenshot of a new notebook in the previous section is an empty cell. We’ll look at two different types of cells:
A code cell is a block of code that the kernel will execute. When the code is run, the output is displayed underneath the code cell that generated it in the Notebook. The output is displayed when a Markdown cell is run, and the content is formatted using markdown. A code cell is always the first cell in a new notebook.
Let’s now put it to the test with a traditional print scenario:
Type print(‘Hello Codeunderscored!’) and press the run button in the cell. Select the option RUN in the toolbar above or press Ctrl + Enter.
The result will appear as follows:
print('Hello Codeunderscored!')
The cell’s output is displayed below, and the label to its left has changed from In [] to In [1].
Because the output of a code cell is part of the document, it can be seen in this article. Because that label is contained in code cells have on the left, and Markdown cells do not, you can always discern the difference between them. The label’s “In” part stands for “Input,” while the label number showed when you run the cell on the kernel — in this case, the cell was run first.
When you rerun the cell, the label will change to In [2], indicating that it was the second cell to be executed on the kernel. When we look into kernels more closely, it will become evident why this is so useful.
To create a new code cell beneath your first, click Insert and pick Insert Cell Below from the menu bar. Next, let’s try the following code to see what occurs. Is there anything you’ve noticed that’s different?
import time time.sleep(5)
This cell does not provide any output, but it does execute in five seconds. Notice how Jupyter changes the cell label to In [*] when it is currently running. In general, a cell’s output is made up of any text data that was mainly written during the cell’s execution. In addition, the value of the cell’s last line could be a single variable, a function call, or something else. Consider the following scenario:
def code_greetings(owner): return 'Hello, {}!'.format(owner) code_greetings('Codeunderscored')
You’ll find yourself using this in practically every project you work on, and we’ll see more of it in the future.
Kernels
Every Notebook has its kernel. The code in a code cell is executed within the kernel when you run it. Any output is returned to the cell that will be shown. The state of the kernel endures across time and between cells; it applies to the entire document rather than individual cells. Importing libraries or declaring variables in one cell, for example, will make them available in another. You can use the Interrupt option if your kernel becomes stuck on computation and you want to stop it.
Selecting a Kernel
You may have noticed that Jupyter allows you to alter the kernel, and there are various options to pick from. When choosing a Python version to use when creating a new notebook from the dashboard, you decide which kernel to use.
There are kernels for various Python versions and over 100 languages such as Java, C, and even Fortran. R’s and Julia’s kernels and imatlab and the Calysto MATLAB Kernel for Matlab may be of particular interest to data scientists.
Within a single notebook, the SoS kernel supports many languages. Each kernel has its own set of instructions for installation, although you’ll almost certainly need to run specific commands on your computer.
When people talk about sharing their notebooks, they’re usually thinking about one of two models. Individuals frequently publish the result of their work, such as this article, which typically entails sharing non-interactive, pre-rendered versions of their notebooks. Alternatively, use version control tools such as Git or online platforms such as Google Colab to collaborate on notebooks.
What to do before sharing your Notebook
When you export or save a shared notebook, it will look exactly as it was when you last saved it, including the output of any code cells. As a result, performing a few actions before sharing your Notebook to verify that it is share-ready is crucial:
Select "Cell > All Output > Clear". Select "Kernel > Restart & Run All" command.
Patiently await completion of your code cells execution before verifying that everything went as planned. It ensures that your notebooks don’t have any intermediate output, aren’t in a stale state, and execute in the correct order when shared.
Getting Your Notebooks Out There
Jupyter has innate support for exporting to HTML, PDF, and various other formats, which you may find in the “File > Download As” menu.
This feature may be all you need if you only want to share your notebooks with a small group of people. Indeed, because many university researchers are allocated public or internal webspace, and because you may export a notebook to an HTML file, Jupyter Notebooks can be a convenient way for researchers to share their findings with their peers. If sharing exported files isn’t enough for you, there are a few other widely used means of sharing.
ipynb files are accessible more easily via the web.
GitHub
With over 1.8 million public notebooks on GitHub as of early 2018, it is unquestionably the most popular independent platform for sharing Jupyter projects with the rest of the world.
On its website, GitHub has incorporated functionality for rendering .ipynb files directly in repositories and gists. If you’re unfamiliar with GitHub, it’s a code hosting platform for version control and collaboration for Git projects. To access their services, you’ll need an account. However, regular accounts are free.
The most straightforward approach to sharing a notebook on GitHub doesn’t require Git once you have a GitHub account. Since 2008, GitHub has offered its Gist service, allowing users to store and share code snippets in their repository.
- Go to gist.github.com after logging in.
- In a text editor, open your .ipynb file, select all, and copy the JSON inside.
- In the Gist, paste the notebook JSON.
- Give your Gist a name, including the .iypnb extension, or otherwise, it won’t work.
- Select “Create secret gist” or “Create public gist” from the dropdown menu.
You’ll be able to share the URL of your public Gist with anyone, and others will be able to fork and clone your work.
This tutorial does not cover creating your Git repository and posting it on GitHub, but GitHub has many resources to help you get started. If you’re using Git, make a .gitignore exception for the hidden.ipynb checkpoints directories Jupyter creates so you don’t commit checkpoint files unnecessarily to your repo.
Nbviewer
NBViewer is outstanding as a notebook renderer on the web has rendered hundreds of thousands of notebooks every week by 2015. If you already have a place to put your Jupyter Notebooks online, such as GitHub or another service, NBViewer will display your Notebook and provide you with a shareable URL. It is supplied at nbviewer.jupyter.org as a free service as part of Project Jupyter.
NBViewer, created before GitHub’s Jupyter Notebook integration, allows anyone to enter a URL, Gist ID, or GitHub username/repo/file, and the Notebook will be shown as a webpage. The ID of a Gist is the number at the end of its URL; for example, in the string of letters after the final backslash is the ID. You’ll see a rudimentary file browser if you enter a GitHub login or username/repo, allowing you to explore a user’s repository and contents.
The URL displayed by NBViewer when showing a notebook is a constant depending on the URL of the Notebook it is rendering. So, share it with anyone, and it will work as long as the original files stay available — NBViewer doesn’t cache data for very long.
Conclusion
Jupyter Notebook files, as we’ve seen, are convenient. You can use your mouse to browse between dropdown menus and buttons or utilize keyboard shortcuts. They let you run little chunks of code at a time, store them in their present state, or restart them and have them revert to their previous state. We can use markdown to organize our notebooks cleanly, so they are presentable to others in addition to running code. | https://www.codeunderscored.com/how-to-use-jupyter-notebook-in-python/ | CC-MAIN-2022-21 | refinedweb | 3,576 | 63.09 |
Odoo Help
Odoo is the world's easiest all-in-one management software. It includes hundreds of business apps:
CRM | e-Commerce | Accounting | Inventory | PoS | Project management | MRP | etc.
[V9] How to Inherit write function
I'm write code for python to inherit res.partner.
This code is when user click save button to update record, it will set state into draft (state = 'draft') if state = approved.
Any idea or clue to write this code?
class res_partner(models.Model):
_inherit = 'res.partner'
print "write procedure inherit awal"
STATE_SELECTION = [
('draft', 'Draft'),
('approved', 'Approved'),
]
state = fields.Selection(STATE_SELECTION, 'Status', readonly=True,
help="Draft Record "
"Approved Record. ",
select=True,default='draft')
def write(self, vals):
if vals.get('state'):
if vals.get('state')=='approved':
state = 'draft'
return super(res_partner, self).write(vals)
it doesn't work.
Thanks.
About This Community
Odoo Training Center
Access to our E-learning platform and experience all Odoo Apps through learning videos, exercises and Quizz.Test it now
Did you get it?
Yup. Thanks Akhil P Sivan | https://www.odoo.com/forum/help-1/question/v9-how-to-inherit-write-function-92397 | CC-MAIN-2018-26 | refinedweb | 169 | 53.47 |
input: 8 numbers
output:a random number between 1-100 base on the input numbers
any idea for doing this ?
Printable View
input: 8 numbers
output:a random number between 1-100 base on the input numbers
any idea for doing this ?
Post some code first. As far as the random number goes, read this SRAND - set seed for random number generation.
i know how s rand and rand work but if i use them its not base on the numbers!
i want the program choose random numbers in some rule
for example if more than half of numbers are lower than 1000 the chance for give output numbers that are lower than 50 increese by 20 percent or sth like this!
Why?
Anyway, here's an approach. (Why anyone would use it rather than a direct rand() value is beyond me though)
Code:
int randbased(input *array) // input is in array[0] to array[7]
{
int k, s = 0;
for (k = 0; k < 8; k++) s += input[k];
for (k = 0; k < s; k++) rand(); /* ignore s random numbers */
return rand();
}
You need to define those rules for us to be able to help you.
If you don't know the rules, but can show a complete set of inputs and outputs, then we can help you deduce the rules. Then we can help you implement those rules in code. But we cannot divine your wishes.
Please be specific, as vague partial examples are just frustrating to everyone. We need detailed, specific information, to help you.
as i said before i want the program do this...
Code:
#include <stdio.h>
int main()
{
int a[8];
int i,b;
for(i=0;i<8;i++)
scanf("%d",&a[i]);
for(i=0;i<8;i++)
if(a[i]<100)
b++;
if(b>4)
//give a random number lower than 200 that its chance for become lower than 100 is 2times more than becom higher than 100
{}
}
Generate a random number between 0 and 300.
If it is greater or equal to 200, subtract 200, getting a new number between 0 and 100.
Result: numbers between 0 and 100 are twice more likely to come up than numbers between 100 and 200.
Yeah I can't help you, you keep adding random weird requirements every time you post. | http://cboard.cprogramming.com/c-programming/151988-random-number-printable-thread.html | CC-MAIN-2014-35 | refinedweb | 387 | 77.87 |
Hello again! Today's problem is one that is bothering me. My research into it has once again gone to waste, so I hope somebody here can help me understand why this is happening. The problem is everything is working honky dory, however I find myself having to enter the same command up to 3 times to get it to register. How do I make the program more efficient so I only have to enter a command once?
#include <stdio.h> #define MAX 105 /*what the pop price is in cents*/ #define MIN 5 char c; int leftover=POPPRICE; // int value; // what was entered void entryChecker (char c) { if (c=='d' || c=='D'){ printf("Dime detected!"); c='\0';} else if (c=='q' || c=='Q'){ printf("Quarter detected!"); c='\0';} else if (c=='n' || c=='N'){ printf("Nickel detected!"); c='\0';} else if (c=='r' || c=='R'){ printf("Returning money!"); c='\0';} else{ printf("That was not a valid command.");} } int main(int argc, char *argv[]) { value=atoi(argv[1]); if ((value % 5) != 0&&value<=MAX&&value>=MIN) { printf("Please enter a number of multiples of 5\n"); printf("Make sure the price is between 5 - 105 cents\n"); } else { printf("The price of pop is %d, cents\n", value); printf("Please insert any combination of nickels [N or n],\n"); printf("dimes [D or d] or quarters [Q or q].\n"); printf("You can also return your money to you by pressing R or r\n"); printf("%d",value); while ((c=getchar())!='e' && (c=getchar())!='E') { scanf("%c",&c); entryChecker (c); } } }
Once again, I deeply appreciate any assistance thrown my way.
EDIT: I also realize using atoi is not the best way to handle this, however for time constraints it's what i'm using now. | https://www.daniweb.com/programming/software-development/threads/118298/having-to-enter-a-command-many-times-for-one-action | CC-MAIN-2021-49 | refinedweb | 296 | 70.53 |
A web service is a communication mechanism defined between different computer systems. Without web services, custom peer-to-peer communication becomes cumbersome and platform specific. It is like a hundred different kinds of things that the web needs to understand and interpret. If computer systems align with the protocols that the web can understand easily, it is a great help. A web service is a software system designed to support interoperable machine-to-machine interaction over a network, World Wide Web Consortium (W3C),.
Now, in simple words, a web service is a road between two endpoints where messages are transferred smoothly. Here, this transfer is usually one way. Two individual programmable entities can also communicate with each other through their own APIs. Two people communicate through language. Two applications communicate through the Application Programming Interface (API).
The reader might be wondering; what is the importance of the API in the current digital world? The rise of the Internet of Things (IoT) made API usage heavier than before. Consciousness about the API is growing day by day, and there are hundreds of APIs that are being developed and documented all over the world every day. Notable major businesses are seeing futures in the API as a Service (AAAS). A bright example is Amazon Web Services (AWS). It is a huge success in the cloud world. Developers write their own applications using the REST API provided by the AWS.
A few more hidden use cases are from travel sites like Ibibo and Expedia, which fetch real-time prices by calling the APIs of third-party gateways and data vendors. Web services are often charged these days.
Topics to be covered in this chapter are:
- The different Web Services available
- Representational State Transfer (REST) architecture in detail
- Introduction to Single Page Applications (SPA) with REST
- Setting up a Go project and running a development server
- Building our first service for finding Roman numerals
- Using Gulp to auto-compile Go code
There are many types of web services which have evolved over time. Prominent ones are :
- SOAP
- UDDI
- WSDL
- REST
Out of these, SOAP became popular in the early 2000s, when XML was on the top wave. The XML data format is used by various distributed systems to communicate with each other. SOAP is too complex to implement. Criticizers of SOAP point out how bulky the SOAP HTTP request is.
A SOAP request usually consists of these three basic components:
- Envelope
- Header
- Body
Just to perform an HTTP request and response cycle, we have to attach a lot of additional data in SOAP. A sample SOAP request looks like>
This is a standard example of SOAP from the W3C standard (). If we observe carefully, it is in XML format, with special tags specifying the envelope and body. Since XML operates on a lot of namespaces to function, additional information comes into play.
The name Representational state transfer (REST) was coined by Roy Fielding from the University of California. It is a very simplified and lightweight web service compared to SOAP. Performance, scalability, simplicity, portability, and modifiability.
When you are using a mobile app on your phone, your phone might be secretly talking to many cloud services to retrieve, update, or delete your data. REST services have a huge impact on our daily lives.
REST is a stateless, cacheable, and simple architecture that is not a protocol but a pattern. give back the response. Once a request is served, the server doesn't remember if the request has arrived after a while. So the operation will be a stateless one.
- Cacheable: Many developers think a technology stack is blocking their web application or API. But in reality, their architecture is the reason. The database can be a potential tuning piece in a web application. In order to scale an application well, we need to cache content and deliver it as a response. If the cache is not valid, it is our responsibility to bust it. REST services should be properly cached for scaling.
- Scripts on demand: Have you ever designed a REST service which serves the JavaScript files and you execute them on the fly? This code on demand is also the main characteristic REST can provide. It is more common to request scripts and data from the server.
- Multiple layered system: The REST API can be served from multiple servers. One server can request the other, and so forth. So when a request comes from the client, request and response can be passed between many servers to finally supply a response back to the client. This easily implementable multi-layered system is always a good strategy for keeping the web application loosely coupled.
- Representation of resources: The REST API provides the uniform interface to talk to. It uses a Uniform Resource Identifier (URI) to map the resources (data). It also has the advantage of requesting a specific data format as the response. The Internet Media Type (MIME type) can tell the server that the requested resource is of that particular type.
- Implementational freedom:REST is just a mechanism to define your web services. It is an architectural style that can be implemented in multiple ways. Because of this flexibility, you can create REST services in the way you wish to. Until it follows the principles of REST, your server has the freedom to choose the platform or technology..
A
GET method fetches the given resource from the server. To specify a resource,
GET uses a few types of URI queries:
- Query parameters
- Path-based parameters
In case you didn't know, all, take this sample fictitious API. Let us assume this API is created for fetching, creating, and updating the details of the book. A query parameter based
GETrequest will be in this format:
/v1/books/?category=fiction&publish_date=2017
- The preceding URI has few query parameters. The URI is requesting a book from the book's..
The
DELETE API method is used to delete a resource from the database. It is similar to
PUT but without any body. It just needs an ID of the resource to be deleted. Once a resource gets deleted, subsequent
GET requests return a 404 not found status.
Note
Responses to this method are not cacheable (in case caching is implemented) because the
DELETE method is idempotent...
This process explains the CORS:
If bar.com feels like supplying resources to any host after one initial request, it can set Access control to * (that is, any).
The following is the diagram depicting the process happening one after the other:.
200 and 201 fall under the success family. They indicate that an operation was successful. Plain 200 (Operation Successful) is a successful CRUD Operation:
- 200 (Successful Operation) is the most common type of response status code in REST
- 201 (Successfully Created) is returned when a
POSToperation successfully creates a resource on the server
- 204 (No content) is issued when a client needs a status but not any data backand
HEADare exceptions.:
You need to understand why Single Page Applications (SPA) are the hot topic today. Instead of building the UI in a traditional way (request web pages), these SPA designs make developers write code in a totally different way. There are many MVC frameworks, like AngularJS, Angular2, React JS, Knockout JS, Aurelia, and so on, to develop web UIs rapidly, but the essence of each of them is pretty simple. All MVC frameworks help us to implement one design pattern. That design pattern is No requesting of web pages, only REST API.
The modern web frontend development has advanced a lot since 2010. In order to exploit the features of Model-View-Controller (MVC) architecture, we need to consider the frontend as a separate entity which talks to the backend only using the REST API (most preferably, REST JSON).
All websites go through the following steps:
- Request a web page from the server.
- Authenticate and show the Dashboard UI.
- Allow the user to modify and save.
- Request as many web pages from the server as needed to show individual pages on the site.
But in the SPA, the flow is quite different:
- Request the HTML template/s to the browser in one single go.
- Then, query the JSON REST API to fill a model (data object).
- Adjust the UI according to the data in the model (JSON).
- When users modify the UI, the model (data object) should change automatically. For example, in AngularJS, it is possible with two-way data binding. Finally, make REST API calls to notify the server about changes whenever you want.
In this way, communication happens only in the form of the REST API. The client takes care of logically representing the data. This causes systems to move from Response Oriented Architecture (ROA) to Service Oriented Architecture (SOA). Take a look at the following diagram:
eight-plus years since its first appearance. It matured along the way with a developer community jumping in and creating huge scale systems in it.
One can choose Python or JavaScript (Node) for their REST API development. The main advantage of Go lies in its speed and compile-time error detection. Go is proved to be faster than dynamic programming languages in terms of computational performance by various benchmarks. These are the three reasons why a company should write their next API in Go:
- To scale your API for a wider audience
- To enable your developers to build robust systems
- To invest in the future viability of your projects
You can look at the neverending online debates for more information about REST services with Go. In later chapters, we try to build the fundamentals of designing and writing the REST services.
This is a building series book. It assumes you already know the basics of Go. If not, no worries. You can jump start and learn them quickly from Go's official site at. Go uses a different way of developing projects. Writing a standalone, simple program doesn't bother you much. But after learning the basics, people try to advance a step further. For that reason, as a Go developer, you should know how Go projects are laid out and the best practices to keep your code clean.
Make sure you have done the following things before proceeding:
- Install Go compiler on your machine
- Set
GOROOTand
GOPATHenvironment variables
There are many online references from which you can get to know the preceding details. Depending on your machine type (Windows, Linux, or macOS X), set up a working Go compiler. We see more details about
GOPATH in the following section.
GOPATH is nothing but the current appointed workspace on your machine. It is an environment variable that tells the Go compiler about where your source code, binaries, and packages are placed.
The programmers coming from a Python background may know the Virtualenv tool to create multiple projects (with different Python interpreter versions) at the same time. But at a given time, one activates the environment and develops his like this:
>mkdir /home/naren/myproject export GOPATH=/home/naren/myproject
Now we install external packages like this:
go get -u -v github.com/gorilla/mux
Go copies the project called
mux into the currently activated project
myproject.
Note
For Go get, use the
-u flag to install updated dependencies of the external package and
-v to see the verbose details of installation.
A typical Go project has the following structure, as mentioned on the official Go website:
Let us understand this structure before digging further:
bin: Stores the binary of our project; a shippable binary which can be run directly
pkg: Contains the package objects; a compiled program which supplies package methods
src: The place for your project source code, tests, and user packages
In Go, all the packages which you import into your main program have an identical structure,
github.com/user/project. But who creates all these directories? Should the developer do that? Nope. It is the developer's responsibility to create directories for his/her project. It means he/she only creates the directory
src/github.com/user/hello.
When a developer runs the following command, the directories bin and package are created if they did not exist before.
.bin consists of the binary of our project source code and
.pkg consists of all internal and external packages we use in our Go programs:
go install github.com/user/project
With the concepts we have built upto now, let us write our first basic REST service. This service takes the number range (1-10) from the client and returns its Roman string. Very primitive, but better than Hello World.
Design:
Our REST API should take an integer number from the client and serve back the Roman equivalent.
The block of the API design document may look like this:
Implementation:
Now we are going to implement the preceding simple API step-by-step.
Note
Code for this project is available at.
As we previously discussed, you should set the
GOPATH first. Let us assume the
GOPATH is
/home/naren/go. Create a directory called
romanserver in the following path. Replace narenaryan with your GitHub username (this is just a namespace for the code belonging to different users):
mkdir -p $GOPATH/src/github.com/narenaryan/romanserver
Our project is ready. We don't have any database configured yet. Create an empty file called
main.go:
touch $GOPATH/src/github.com/narenaryan/romanserver/main.go
Our main logic for the API server goes into this file. For now, we can create a data file which works as a data service for our main program. Create one more directory for packaging the Roman numeral data:
mkdir $GOPATH/src/github.com/narenaryan/romanNumerals
Now, create an empty file called
data.go in the
romanNumerals directory. The
src directory structure so far looks like this:
;
Now let us start adding code to the files. Create data for the Roman numerals:
// data.go package romanNumerals var Numerals = map[int]string{ 10: "X", 9: "IX", 8: "VIII", 7: "VII", 6: "VI", 5: "V", 4: "IV", 3: "III", 2: "II", 1: "I", }
We are creating a map called Numerals. This map holds information for converting a given integer to its Roman equivalent. We are going to import this variable into our main program to serve the request from the client.
Open
main.go and add the following code:
// main.go package main import ( "fmt" "github.com/narenaryan/romanNumerals" "html" "net/http" "strconv" "strings" "time" ) func main() { // http package has methods for dealing with requests http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { urlPathElements := strings.Split(r.URL.Path, "/") // If request is GET with correct syntax if urlPathElements[1] == "roman_number" { number, _ := strconv.Atoi(strings.TrimSpace(urlPathElements[2])) if number == 0 || number > 10 { // If resource is not in the list, send Not Found status w.WriteHeader(http.StatusNotFound) w.Write([]byte("404 - Not Found")) } else { fmt.Fprintf(w, "%q", html.EscapeString(romanNumerals.Numerals[number])) } } else { // For all other requests, tell that Client sent a bad request w.WriteHeader(http.StatusBadRequest) w.Write([]byte("400 - Bad request")) } }) // Create a server and run it on 8000 port s := &http.Server{ Addr: ":8000", ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, MaxHeaderBytes: 1 << 20, } s.ListenAndServe() }
Note
Always use the Go fmt tool to format your Go code.
Usage example:
go fmt github.com/narenaryan/romanserver
Now, install this project with the Go command
install:
go install github.com/narenaryan/romanserver
This step does two things:
- Compiles the package
romanNumeralsand places a copy in the
$GOPATH/pkgdirectory
- Places a binary in the
$GOPATH/bin
We can run the preceding API server as this:
$GOPATH/bin/romanserver
The server is up and running on. Now we can make a
GET request to the API using a client like
Browser or the
CURL command. Let us fire a
CURL command with a proper API
GET request.
Request one is as follows:
curl -X GET "" # Valid request
The response is as follows:
HTTP/1.1 200 OK Date: Sun, 07 May 2017 11:24:32 GMT Content-Length: 3 Content-Type: text/plain; charset=utf-8 "V"
Let us try a few incorrectly formed requests.
Request two is as follows:
curl -X GET "" # Resource out of range
The response is as follows:
HTTP/1.1 404 Not Found Date: Sun, 07 May 2017 11:22:38 GMT Content-Length: 15 Content-Type: text/plain; charset=utf-8 404 - Not Found
Request three is as follows:
curl -X GET "" # Invalid resource
The response is as follows:
"HTTP/1.1 400 Bad request Date: Sun, 07 May 2017 11:22:38 GMT Content-Length: 15 Content-Type: text/plain; charset=utf-8 400 - Bad request
Our little Roman numerals API is doing the right thing. The right status codes are being returned. That is the point all API developers should keep in mind. The client should be informed why something went wrong.
We just updated the empty files in one single go and started running the server. Let me now explain each and every piece of the file
main.go:
- Imported a few packages.
github.com/narenaryan/romanNumeralsis the data service we created before.
net/httpis the core package we used to handle an HTTP request through its
HandleFuncfunction. That function's arguments are
http.Requestand
http.ResponseWriter. Those two deal with the request and response of an HTTP request.
r.URL.Pathis the URL path of the HTTP request. For the CURL Request one, it is
/roman_number/5. We are splitting this path and using the second argument as a resource and the third argument as a value to get the Roman numeral. The
Splitfunction is in a core package called
strings.
- The
Atoifunction converts an alphanumeric string to an integer. For the numerals map to consume, we need to convert the integer string to an integer. The
Atoifunction comes from a core package called
strconv.
- We use
http.StatusXXXto set the status code of the response header. The
WriteHeaderand
Writefunctions are available on the response object for writing the header and body, respectively.
- Next, we created an HTTP server using
&httpwhile initializing a few parameters like address, port, timeout, and so on.
- The
timepackage is used to define seconds in the program. It says, after 10 seconds of inactivity, automatically return a 408 request timeout back to the client.
EscapeStringescapes special characters to become valid HTML characters. For example, Fran & Freddie's becomes
Fran & Freddie's".
- Finally, start the server with the
ListenAndServefunction. It keeps your web server running until you kill it.
Gulp is a nice tool for creating workflows. A workflow is a step-by-step process. It is nothing but a task streamlining application. You need NPM and Node installed on your machine. We use Gulp to watch the files and then update the binary and restart the API server. Sounds cool, right?
The supervisor is an application to reload your server whenever the application gets killed. A process ID will be assigned to your server. To restart the app properly, we need to kill the existing instances and restart the application. We can write one such program in Go. But in order to not reinvent the wheel, we are using a popular program called supervisord.
Sometimes your web application may stop due to operating system restarts or crashes. Whenever your web server gets killed, it is supervisor's job to bring it back to life. Even the system restart cannot take your web server away from the customers. So, strictly use supervisord for your app monitoring.
We can easily install supervisord on Ubuntu 16.04, with the
apt-get command:
sudo apt-get install -y supervisor
This installs two tools,
supervisor and
supervisorctl.
supervisorctl is intended to control the supervisord and add tasks, restart tasks, and so on.
On macOS X, we can install
supervisor using the
brew command:
brew install supervisor
Now, create a configuration file at:
/etc/supervisor/conf.d/goproject.conf
You can add any number of configuration files, and supervisord treats them as separate processes to run. Add the following content to the preceding file:
[supervisord] logfile = /tmp/supervisord.log
[program:myserver] command=$GOPATH/bin/romanserver autostart=true autorestart=true redirect_stderr=true
By default, we have a file called
.supervisord.conf at
/etc/supervisor/. Look at it for more reference. In macOS X, the same file will be located at
/usr/local/etc/supervisord.ini.
Coming to the preceding configuration:
- The
[supervisord]section tells the location of the log file for supervisord
[program:myserver]is the task block which traverses to the given directory and executes the command given
Now we can ask our
supervisorctl to re-read the configuration and restart the tasks (process). For that, just say:
supervisorctl reread
supervisorctl update
Then, launch
supervisorctl with the command:
supervisorctl
You will see something like this:
Since we named our romanserver
myserver in the supervisor configuration file, we can start, stop, and restart that program from
supervisorctl.
With the little introduction we gave about Gulp in the preceding section, we are going to write a gulpfile for telling the computer to execute a few tasks.
I install Gulp and Gulp-shell using
npm:
npm install gulp gulp-shell
After this, create a
gulpfile.js in the root directory of the project. Here, it is
github.com/src/narenaryan/romanserver. Now add this content to
gulpfile.js. First, whenever a file changes, install binary task gets executed. Then, the supervisor will be restarted. The watch task looks for any file change and executes the preceding tasks. We are also ordering the tasks so that they occur one after the other synchronously. All of these tasks are Gulp tasks and can be defined by the
gulp.task function. It takes two arguments with task name, task.
sell.task allows Gulp to execute system commands:
var gulp = require("gulp"); var shell = require('gulp-shell'); // This compiles new binary with source change gulp.task("install-binary", shell.task([ 'go install github.com/narenaryan/romanserver' ])); // Second argument tells install-binary is a deapendency for restart-supervisor gulp.task("restart-supervisor", ["install-binary"], shell.task([ 'supervisorctl restart myserver' ])) gulp.task('watch', function() { // Watch the source code for all changes gulp.watch("*", ['install-binary', 'restart-supervisor']); }); gulp.task('default', ['watch']);
Now, if you run the
gulp command in the
source directory, it starts watching your source code changes:
gulp
Now, if we modify the code, then the code is compiled, installed, and the server restarted in a flash:
In the gulpfile, we are performing the following instructions:
- Import Gulp and Gulp-shell.
- Create tasks with
shell.taskas the function to execute.
shell.taskcan execute a command-line instruction. Keep your shell commands inside that function.
- Add a watch task for watching source files. The task list will be executed when files are modified.
- Create a default task for running. Add a watch to it.
Gulp is a great tool for these kinds of use cases. So, please go through the official documentation of Gulp at. have something called SOAP, which uses XML as the data format. REST operates on JSON as the primary format. REST has verbs and status codes. We saw what a given status code refers to. We built a simple service which serves the Roman numerals for given numbers. In this process, we also saw how to package a Go project. We understood the GOPATH environment variable. It is a workspace defining a variable in Go. All packages and projects reside in that path. We then saw how to reload a development project on the fly with the help of supervisord and Gulp. These are node tools but can help us to keep our Go project up and running.
In the next chapter, we dig deeper into URL routing. Starting from the built-in router, we explore Gorilla Mux, a powerful URL routing library. | https://www.packtpub.com/product/building-restful-web-services-with-go/9781788294287 | CC-MAIN-2021-17 | refinedweb | 3,974 | 57.57 |
This content has been marked as final. Show 34 replies
15. Re: Propose adding opage/inplace object instance to the languagedcminter Aug 16, 2004 4:40 PM (in response to 843853)
And I prefer not to talk to people like thatYou do have a choice, so fuck off.
if I have a choice.
16. Re: Propose adding opage/inplace object instance to the language843853 Aug 18, 2004 3:46 PM (in response to 843853)IMHO, the ability to allocate objects on the stack, not the heap, would be more cleanly dealt with by the run-time. The VM can prove that some objects referred to in a code block have no references that escape the block. The VM could then chose to allocate these objects on the stack, not the heap.
In the general case, because of polymorphism (a reference of type Foo can refer to an object of any type extending or implementing Foo), it would be /very/ hard to validate this constraint at compile time. Trivial changes to your code (or code it calls) could invalidate the 'non-escaping-pointer' constraint. E.g. a class that regsiters the instance with some other resource during construction, leaking the pointer from your block.
However, since hotspot progressively inlines larger and larger blocks, it should be able to allocate more and more of the objects on the stack, giving progressive gc-related performance enhancements.
To realy get the best out of this, you would need to find some way of eliding out the class references and locks on the object, so that an instance could be allocated on the stack directly as its fields and all methods inlines. Of course, this would also be impossible to check at compile-time, but if you can do it at run-time, it should make some types of code go blisteringly fast.
Anyway, whichever way you cut it, this smells like a run-time optimization, not a compile-time switch to me. If you are still interested, grab the current 5.0 hotspot source and start hacking the optimizer - if this was trivial to do, I would have expected someone at SUN to have done it - it's a fairly obvious fix.
17. Re: Propose adding opage/inplace object instance to the language843853 Aug 18, 2004 5:26 PM (in response to 843853)
Statically (in C++ sense) allocated objects are placed on the stack. No dispute on this.
The VM can prove that some objects referred to in a code block have no references that escape the block. >The VM could then chose to allocate these objects on the stack, not the heap.This will not be possible. The reason is that objects are allocated before used. So, detecting their use before allocation is not easily, if not possible (or have to resort to tradeoff, such as going through all execution path before hand to see if it escape). Oneway is to keep track of allocated objects's reference in a scope to see if it escapes the scope, if so, then all objects in this scope that is referenced by the escaped object also escape this scope (and moved to the new scope if possible).
That's fine for optimization. However, because keeping track of this may cost cpu time (if possible), that's why I propose statically allocated object (remember the word statically is not the same as Java key word static).
Because statically allocated object is marked beforehand by compiler, and sits on the stack, there is significant CPU cost for keeping track of them (no need to find out if they're out of scope). In a sense, this is just the same way primative type was handled, except that it's composite of many other things and functions. Ofcourse, the language is different because there are cases that object content cannot be copied (like iostream class in C++ cannot be copied), spec on how inherited objects can be copied to another one, and functionality to bridge the dynamically allocated object and statically allocated object (such as autobox statically allocated object to dynamically allocated object (create an object dynamically, and copy the content), and the other way around (create statically an object, and copy the content from a dynamically allocated object's handle/reference, note on the null pointer).
So in a sense, the language change helps the VM to do the job better. The VM will have to be modified for this to work.
No change to the GC, because it only deals with dynamically allocated object.
Practically, if GC can be improved to a point that performance and memory is not a problem, then this suggestion can be ignored. The reason is that the suggestion introduces many more concepts and complexities to the language. Personally, I don't have problem with the complexity this feature introduced in C++ (users have to know the different between statically and dynamically allocated object, keep in mind copy constructor, override assignment operator, etc.), but some people may have. Also, the goal of Java was simplicity.
Anyway, this is why I posted this up for discussion. Show that there is one more way to do optimization on the memory and cpu area. It does introduce more complexity to the language, and change to the JVM. If there are other way to optimize better, then should not follow this path. If there isn't, then this could help.
18. Re: Propose adding opage/inplace object instance to the language843853 Oct 14, 2004 12:54 PM (in response to 843853)Hm, I wonder if I got you right:
Lets look at a code sample like this:
So in your opinion, the object created by new LargeObject(), remains in memory after the execution
public void foo() { LargeObject largeObject = new LargeObject(); ... ... }
of the method has finished, thats why you want to make it kind of static and mark it for immediate removal?
Well, the instance doesn't stay in the memory, its immediatelly removed by the GC. I think you have a wrong image of the garbage collector. The GC is part of the VM, so whenever a reference to an instance is removed, this happens after the execution of the method, because the stack, which is the only reference to the instance of this LargeObject is removed, the VM checks the reference count of the instance, if its 0 the object is immediatelly freed/removed/whatever from memory. So instances which are no longer used, are always immediatelly removed from memory.
You wonder why there is still a GC called once a while? Well, instances might have circular references, so they would not be removed from memory by the technique described above. But by calling the GC externally, the reference count is re-calcualted and instances with circular references are also removed.
Actually this is the way the GC of Smalltalk works, I think the Java GC is heavily improved since Smalltalk is about 25 years old. But still I think it tries to keep the memory usage of the VM as low as possible.
19. Re: Propose adding opage/inplace object instance to the language843853 Oct 15, 2004 11:33 PM (in response to 843853)the opaque, inplace word I used means non-dynamic allocated memory, or as some other said: stack based memory. The VM has to be modified for it to work this way. Right now, only primative types and Object pointer are non-dynamic allocated memory. For example:
int a;
a will be created automatically without: a = new int();
Also, when going outside of the scope of a, it will be safely discarded without the help of virtual machine. Also, allocating a is faster this way (I believe) because less locking. For object, I would have it this way:
when largeObject is out of scope, it will be discarded right away, thread safe, so it's very fast. And as the result, memory foot print tends to be smaller (because no wait for the GC to kick in).
public void foo() { inplace LargeObject largeObject(); //now the object already created, there is no object reference here //largeObject is not a handle/pointer, but it is the object itself, like a in the "int a;" //for object with constructor different than empty constructor: inplace MoreObject moreObj(1,2,3); }
Now, you may ask how this would work if you want to work with the "normal object". As you may already know, normal object are dynamically allocated, and you refer to them using object pointer or handle. So, copying information between this inplace object and pointer object must be specified out clearly (if you know C++, you know what I mean).
Also, passing inplace object to functions has to be passed by copy. You may argue that this is no better than current way, because thing has to be copied anyway (and worse, because of copy CPU cycle). True for the copy CPU cycle, but C and C++ shows that this is minimal. Also, The copied object will be cleaned out cleanly without garbage collection either.
inplace object will also have problem of not copiable. This is like iostream in C++. The way they solve this problem is using 2 constraints:
1) Have key word saying this object is not copiable (such as having private copy constructor).
2) Passing this object by reference . this is not the same as passing object by pointer like C or Java. Because the reference variable cannot be assigned to another reference variable, it's scoped safe, so the object will be guarantied to be released correctly when it's out of scope.
In Java, we also need way to specify this.
I know for sure that doing this, the GC will have much less work, because most of the object can be created using "inplace" method. This way also allow allocated memory to be much faster because no global locking is needed when looking for memory.
20. Re: Propose adding opage/inplace object instance to the language843853 Oct 18, 2004 2:16 PM (in response to 843853)But what if:
What happens with the crap in the map?
public class Foo { private final static Map theFoos = new HashMap(); public Foo() { theFoos.put(new Long(System.currentTimeMillis()),this); } public static void main(String[] args) { inplace SuperFoo Foo(); //Do some freaky sh*t with SuperFoo //The second SuperFoo gets anally morphed into a spook-object } {
21. Re: Propose adding opage/inplace object instance to the language843853 Oct 18, 2004 3:12 PM (in response to 843853)
This is a good issue to address. There has to be more than one solution to this. One way is to auto-unbox the object into another copy with dynamic memory allocation. Because as you know, "theFoos" takes an object pointer, not inplace object. So, "this" in this case is a pointer to inplace object, which can be known at run time. Because of this, the object can be copied into dynamic allocated memory. There could be 2 problems to deal with this:
1) Constructor (like your case)
Auto boxing and unboxing will generate infinite number of objects (recursive).
A runtime error could be created for autoboxing or unboxing in the constructor is one way to handle this.
2) None clonable object (if Foo is marked as not supporting autoboxing or unboxing). This has been discussed before in this thread. It just generate exception for these type of object (run time).
When I says autoboxing, unboxing, this is what I mean:
autoboxing: with a pointer/handle to an dynamic allocated object, it will create a copy with inplace object and use that instead. (this is like passing an object in C++, a temporary object will be created, and the copy constructor will be called to copy the content over).
auto unboxing: with a pointer/handle to an inplace object ("this" of an inplace object), or an inplace object, you create a dynamic allocated memory object, and copy the information over.
Your post raise a very interesting point: "this" will be interpreted differently, at runtime for different scenario, depending if this object is inplace or not. It is inplace if the object it points to is inplace, and dynamically allocated if the object is dynamically allocated.
I know that these runtime exceptions are not an ideal solution, so if someone can think of a better way to do this, please share.
On the performance issues, C++ introduce pass by reference. In this case, it's possible, and there will be no problem with it. However, the function that accept pass by reference must be declared so. For this example, "put" of Map must have an overload that accepts pass by reference. Also note that reference here is not pointer. Passing pointer is by value, not reference. An inplace pointer is actually created, then copy over the value, it's the memory the pointer is pointed to is not copied. Also note that a reference variable cannot be assigned to another, except when you initialize a variable that is declared referenced. This could cause a reference to be created that gets initialized to a inplace reference. To prevent this, do not allow a reference variable to be member of a class (it can only be declared inside function or constructor), or not allow them to be declared anywhere at all except as parameters.
Obviously, all of these stuffs has to be clearly thought out for this to work. And scenario like this must be addressed before the thing can be implemented.
22. Re: Propose adding opage/inplace object instance to the languagedcminter Oct 18, 2004 3:20 PM (in response to 843853)
(yawn)
So, have you done any work to implement your "brilliant" ideas?
No? Astonishing! One might even imagine that it's because you're too ignorant to do so - but no, surely that couldn't be.
Dave.
23. Re: Propose adding opage/inplace object instance to the language843853 Oct 18, 2004 4:28 PM (in response to 843853)
I'd like to add more comment to my previous post:
1) Constructor (like your case)This is usual case, and has nothing to do in particular with inplace object. For example, you would get runtime exception in java if in the constructor, you do things like this:
Auto boxing and unboxing will generate infinite number of objects (recursive).
A runtime error could be created for autoboxing or unboxing in the constructor is one way to handle this.
class Foo{ public Foo(){ Foo foo = new Foo(); } }
2) None clonable object (if Foo is marked as not supporting autoboxing or unboxing). This has been >discussed before in this thread. It just generate exception for these type of object (run time).Note that almost all object oriented languages have this feature (not Java, obviously). So the science is already invented. This is nothing new. If someone still think there's problem with this, I would recommend looking at other language that has this feature and learn what they do. From this thread, it seems most questions comes from mixing pointer and object, conversion/reference between them, scope, function parameter, function return value. In case you know C++, you can answer all of these questions yourself.
So far, I haven't seen a problem with the "inplace" feature that hasn't been addressed and solved yet.
24. Re: Propose adding opage/inplace object instance to the languagedcminter Oct 18, 2004 4:46 PM (in response to 843853)
So far, I haven't seen a problem with the "inplace"Leaving aside your competence, try "it doesn't exist". If you want it to exist, write it. If you don't write it, nobody is going to do it for you, and talking about how much you like the idea won't convince anyone.
feature that hasn't been addressed and solved yet.
I'll take you seriously (and so will others) when you prove this feature has some value by creating it. Until then your vague and inaccurate descriptions of how things work at the moment are sufficient to deter any serious interest.
If, as I suspect, you can't implement this feature because you don't know how, then why do you think you're competent to say how it would "work"? If I'm wrong, why don't you completely show me up by doing a bit of work?
Dave.
25. Re: Propose adding opage/inplace object instance to the languagenotivago Oct 18, 2004 5:43 PM (in response to dcminter)
I think Dave have put it on a very rude manner and I agree with you that you have not to be a specialist to be entitled to sugest new features. But indeed this opaque Idea seems very opaque to me.
In first place it defeats the Idea of GC, for it is transfering the responsability of keeping track of the objects life from the VM to the programers.
As I have understood, it would create objects that live on the stack, it would mudle the water of how objects are handled by the VM. People are enough confused by this for us to add mor complexity.
Finnaly, once a while people come up with this C++ have X feature but java does not so we need X feature in java. I think it's a gross mistake. Java is not C++ and any new feature should be evaluated on its merits for java in the java context.
May the code be with you.
26. Re: Propose adding opage/inplace object instance to the language843853 Oct 18, 2004 8:42 PM (in response to notivago)
I agree with you that doing this will add complexity to the language. I have no problem with it in C++, but someone may. I also agree with you that any new feature must be evaluated on its merits for Java.
As I said in one of the posts in this thread, there are plus and minus to this feature. On the plus side, it will help the GC and reduce the gc() pause. On the minus side, it will create more complexity to this. So why I think of this idea? Because after so many generation of Java, it seems Sun still cannot fix this GC pauses, memory hog, memory allocation slowness problem. They improved it, but users still complaint greatly about it.
With regard to transfering the responsibility from VM to programmers, it is not totally so. First, users have to learn the new features, and their limitation. Second, the JVM will manage everything, except the fact that users have to be awared of the type of objects they're working with. I agree that this is just add more complexity. So, as I said in one of the post, if memory allocation and GC implementation improves, this feature will not be needed, except one thing I haven't mention:
Dynamic memory allocation is a blessed, but it is also has its weakness: it flats out the hierarchy of OO design. This means it's a global object, that can be passed around anywhere you want. Using in place object, you gain some of the control of the object scope and hierarchy. I said this just because I want to disect the issue further, not to disagree with your point of view.
Look at a broad view, it would be great if the GC and Java memory allocation is faster, rather than adding this complexity to the language. In C++, it's more complex than without it, but it's the forethought feature, so they have everything in place for it to work. In fact, it's the default way of object creation (without any special tag, like here, you must need something like "inplace", or "opaque"). They also thought out all the constructor problem (mechanism to initialize inplace members object with constructors that accept 1 or more arguments). Pass by reference also helps it to reduce the number of temporary objects and object copy problem. The language also provide copy constructor feature so users will have more power over the object creation and copy. So, adding this feature as an after thought to Java may not be a good idea, and also as computers go faster, better algorithm is found, the problem reduces to none issue.
My conclusion: the concept is possible, and implementable in Java, but this feature is not needed unless there's no way of enhancing the GC any better.
27. Re: Propose adding opage/inplace object instance to the languagedcminter Oct 19, 2004 7:33 AM (in response to notivago)
I think Dave have put it on a very rude mannerFair enough. I think vy_ho is a fool, so yes, I'm being extremely rude.
and II disagree, and I think vy_ho is demonstrating why you need to have an understanding of the internal behaviour of the JVM and the compiler to make this sort of suggestion. Note that:
agree with you that you have not to be a specialist to
be entitled to sugest new features.
1. He doesn't understand how the JVM works
2. He doesn't understand how the compiler works
3. He uses incorrect terminology.
In some ways the last point is more important than the others - even if this were an insightful and useful idea, it would be
But indeed thisAs it does to me.
opaque Idea seems very opaque to me.
Finally, the point I'm trying to make in my rude way, is that I could be nice as pie and terribly encouraging, but since nobody is going to write it for him it won't make a jot of difference either way. If he pulls his finger out and tries to implement this feature, I'll be delighted to give him a hand where I can, even though I think it's of doubtful merit.
But I think it's conceited to think that we care about his fatuous idea otherwise, and pompous to believe that anyone else should implement it for him. Which is why I'm 'quite' hostile.
Dave. Who is not good on Monday mornings, and only slightly less surly on Tuesdays.
28. Re: Propose adding opage/inplace object instance to the languagenotivago Oct 19, 2004 1:07 PM (in response to dcminter)
vy_ho, a thing I would like to point to you is that your proposed feature will not help the GC for the gc will have to run anyway for still there is all the others objects to clean and probably reorgnizing the remaining objects in the heap is much more expensive than to discard the garbaged ones.
Dave, quoting helloween:
There's a million ways to see the things in life
A million ways to be the fool
In the end of it, none of us is right
Sometimes we need to be alone
Everyone have the righteous right to not be right at Mondays and also at Tuesdays, so I think you can be let pass with that.
May the code be with you.
29. Re: Propose adding opage/inplace object instance to the language843853 Oct 19, 2004 2:54 PM (in response to notivago)
If you can reduce the number of dynamic allocated objects 80%, how could that be not helping the GC? I am not saying 80% is the actual number. What you said is all or nothing.
And you Dave, get the fuck off. | https://community.oracle.com/thread/1685403?tstart=45&start=15 | CC-MAIN-2017-30 | refinedweb | 3,907 | 67.69 |
A framework for automated feedback with Python and org-mode
Posted October 03, 2015 at 08:23 PM | categories: python, emacs | tags: | View Comments
Updated October 03, 2015 at 08:29 PM
Autolab is an autograding service that automatically grades code assignments. It uses a program to evaluate a program on a secure virtual system. Using this requires you to run a server, and run code from students. I have never liked that because it is hard to sandbox code well enough to prevent malicious code from doing bad things. Autolab does it well, but it is a heavy solution. Here we explore a local version, one that is used to test for correctness, and not for grading. Here, if you are malicious, you reap what you sow…
The basic idea I am working towards is that Emacs will provide content to be learned (through org-mode) with active exercises. The exercises will involve a code block, and the user will run a command on their code (or an advised C-c C-c) that checks the solution for correctness. A user will be able to see the solution, and maybe get hints.
Suppose we have a problem to solve \(e^x = 3\). This is a simple problem to solve, and here is a solution.
from scipy.optimize import fsolve import numpy as np def objective(x): return np.exp(x) - 3 def solve(): return fsolve(objective, 3) print solve()
[ 1.09861229]
We would like to test this for correctness. We code this in a function-based form because we will later use the function
solve to test for correctness. Let's see how we could test it with a test function. We will use exec on a string representing our code to get it into our namespace. I don't see a security issue here. You are writing the code! Eventually, we will be passing code to the test framework this way from an org-mode source block.
import unittest TOLERANCE = 1e-5 s = '''from scipy.optimize import fsolve import numpy as np def objective(x): return np.exp(x) - 3 def solve(): return fsolve(objective, 3)[0] print solve()''' def test_solve(s): exec s in globals() if (abs(np.log(3) - solve()) <= TOLERANCE): print('Correct') else: print('incorrect') test_solve(s)
1.09861228867 Correct
Next, we need to think about how we could generate an import statement from a code block name, import in python, and run a test function. We can assume that the test code will be in a file called "test_%s.py" on your python path. Here are the contents of test_solve.py.
import numpy as np TOLERANCE = 1e-5 def solve_solution(): from scipy. optimize import fsolve import numpy as np def objective(x): return np.exp(x) - 3 return fsolve(objective, 3)[0] def test_solve(s): exec s in globals() if (abs(solve_solution() - solve()) <= TOLERANCE): print('Correct!') else: print('Incorrect')
Now, we can import that, and use the functions. Here is the Python script we need to run to test it.
import test_solve test_solve.test_solve(''' from scipy. optimize import fsolve import numpy as np def objective(x): return np.exp(x) - 3 def solve(): return fsolve(objective, 3)[0] print solve()''')
1.09861228867 Correct!
Now, an elisp block to do that. One way to do this is to just run a shell command passing the string to a python interpreter. This is a short way away from an Emacs command now.
(let* ((string "import test_solve test_solve.test_solve(''' from scipy. optimize import fsolve import numpy as np def objective(x): return np.exp(x) - 3 def solve(): return fsolve(objective, 3)[0] print solve()''')")) (shell-command-to-string (format "python -c \"%s\"" string)))
1.09861228867 Correct!
Ok, now to wrap it all up in a function we can run from Emacs in a code block to test it. With the cursor in a code block, we get the name, and build the python code, and run it. The function is more complex than I anticipated because I end up running the code block essentially twice, once to get a results block and once to get the test results. For short problems this is not an issue. I also add the test results in a way that is compatible with the current results.
(defun check () (interactive) (let* ((src-block (org-element-context)) (name (org-element-property :name src-block)) (code (org-element-property :value src-block)) (end (org-element-property :end src-block)) (results) (template (format "import test_%s test_%s.test_%s('''%s''')" name name name code)) (output (format "\n%s\n" (s-join "\n" (mapcar (lambda (s) (if (s-starts-with? ":" s) s (concat ": " s))) (s-split "\n" (shell-command-to-string (format "python -c \"%s\"" template)))))))) ;; execute block as normal (org-babel-execute-src-block) ;; and add some output to the Results block (if (org-babel-where-is-src-block-result) (progn (goto-char (org-babel-where-is-src-block-result)) (setq results (org-element-context)) ;; delete results line (kill-line) ;; delete the results (setf (buffer-substring (org-element-property :begin results) (org-element-property :post-affiliated results)) "") ;; paste results line back (yank) ;; and the output from your code (insert output)) (message "%s" output))))
check
Now, we use a named src-block so we can call M-x check in it, and check the answer.
from scipy.optimize import fsolve import numpy as np def objective(x): return np.exp(x) - 3 def solve(): return fsolve(objective, 3) print solve()
[ 1.09861229] Correct!
I would like to be able to provide a solution function that would show a user my solution they were tested against. Python provides the
inspect module that can do this. Here is how we get the code in Python.
import inspect import test_solve print inspect.getsource(test_solve.solve_solution)
def solve_solution(): from scipy. optimize import fsolve import numpy as np def objective(x): return np.exp(x) - 3 return fsolve(objective, 3)[0]
This makes it easy to wrap up a function in emacs that will show this from at src block. We just get the block name, and build the python code and execute it here.
(defun show-solution () (interactive) (let* ((src-block (org-element-context)) (name (org-element-property :name src-block)) (template (format "import inspect import test_%s print inspect.getsource(test_%s.%s_solution)" name name name))) (switch-to-buffer-other-window (get-buffer-create "solution")) (erase-buffer) (insert (shell-command-to-string (format "python -c \"%s\"" template))) (python-mode)))
show-solution
That summarizes the main features. It allows me to write a test module that has some name conventions to define a solution function, and a test function. Emacs can generate some boilerplate code for different problem names, and run the test to give the user some feedback. Most of the code in this post would not be directly visible to a user, it would be buried in a python module somewhere on the path, and in elisp files providing the glue. I am not sure how much obfuscation you can put in the python files, e.g. just providing byte-compiled code, so it is less easy to just read it. That is not as big a deal when it is just a study guide/feedback system.
From an authoring point of view, this seems pretty good to me. It is feasible I think to write an org-source document like this with tangling for the test modules, and an export to org that does not have the solutions in it. The only subtle point might be needing to alter Python paths to find the test modules if they aren't installed via something like pip.
I think this is pretty flexible, and could handle problems that take arguments, e.g. write a function that sorts a list. Here is a simple example of that. First we write the test_sort.py file with a solution, and some tests.
def sort_solution(LIST): return LIST.sort() def test_sort(s): exec s in globals() if sort([3, 4, 2]) == [2, 3, 4]: print('passed test 1') if sort(['z', 'b']) == ['b', 'z']: print('passed test 2')
def sort(LIST): s = sorted(LIST) return s
passed test 1 passed test 2
Maybe it would make sense to use unittests, or nose or some other testing framework if it makes writing the tests easier. Another day.
Copyright (C) 2015 by John Kitchin. See the License for information about copying.
Org-mode version = 8.2.10 | http://kitchingroup.cheme.cmu.edu/blog/2015/10/03/A-framework-for-automated-feedback-with-Python-and-org-mode/ | CC-MAIN-2020-05 | refinedweb | 1,415 | 64.71 |
This first chapter covers the principles of reactive programming and ReactiveX. It is composed of three parts. The first part explains what reactive programming is and how it compares to other concepts and paradigms that are often used in event-driven programming. The second part explains the foundations of ReactiveX and RxPY, its Python implementation. This exploration of RxPY is explained with a simple example that allows us to understand the basics of ReactiveX. Finally, the last part is dedicated to the documentation of the ReactiveX project and the documentation of your projects. By the end of this chapter, you will be able to write some ReactiveX code and understand existing code.Â
The following topics will be covered in this chapter:
- What is reactive programming?
- An introduction to ReactiveX and RxPY
- A reactive echo application
- Marble diagrams
- Flow diagrams
Reactive programming has gained a lot of popularity since 2010. Although its concepts and usage date from the early days of computing, this recent popularity is mainly due to the publication of the ReactiveX project. This might seem surprising for developers who had rarely used event-driven programming before. However, for people who faced tremendous state machines or callback hell, this seems more of an inevitable fact.
Â
Before playing with ReactiveX and RxPY, this first part describes the principles being used in reactive programming and how they are used in asynchronous frameworks. This initial study of low-level features is not strictly necessary when using ReactiveX and asynchronous frameworks, but it helps a lot to understand how they work, which thus helps us to use them correctly.
What is the common connection between state machines, Petri net, Kahn Process Networks (KPN), the observer design pattern, callbacks, pipes, publish/subscribe, futures, promises and streams? Event-driven programming!
By definition, any program has to deal with external events through inputs/outputs (I/O). I/O and event management are the foundations of any computer system: reading or writing from storage, handling touch events, drawing on a screen, sending or receiving information on a network link, and so on. Nothing useful can be done without interacting with I/O, and I/O are almost always managed through events. However, 50 years after the creation of the first microprocessor, event-driven programming is still a very active topic with new technologies appearing almost every year.
Â
The main purpose of this important activity is that, despite the fact that event-driven programming has existed since the beginning of computer science, it is still hard to use correctly. More than writing event-driven code, the real challenge lies in writing readable, maintainable, reusable, and testable code. Event-driven programming is more difficult to implement and read than sequential programming because it often means writing code that is not natural to read for human beingsâinstead of a sequence of actions that execute one after the other until the task to execute is completed, the beginning of an action starts when an event occurs, and then the actions that are triggered are often dispersed within the program. When such a code flow becomes complexâand this starts only after few indirect paths in a codeâthen it becomes more and more difficult to understand what is happening. This is what is often called the callback hell. One has to follow callbacks calling callbacks, which call further callbacks, and so on.
During the late nineties, event-driven programming became quite popular with the advent of graphical user interfaces (GUIs). At that time, developers had the following options to write GUI applications:
- Objective-C on NextStep and macOS
- C++ on Windows
- C or eventually C++ on Unix (with X11)
- Java, with the hope of writing the same application for all these systems
All these environments were based on callbacks and it stayed that way for a very long time, until programming languages included features to improve the readability of event-driven code.
So event-driven code is often more difficult to read than sequential code because the code logic can be difficult to follow, depending on the programming language and the frameworks being used. Reactive programming, and more specifically ReactiveX, aims at solving some of these challenges. Python and its relatively recent support of
async/
await syntax also aims to make event-driven programming easier.
It is important to understand that reactive programming and event-driven programming are not programming paradigms, such as imperative or object-oriented programming, but are orthogonal to them. Event-driven programming is implemented within an existing paradigm. So, one can use event-driven programming with an object-oriented language or a functional language. Reactive programming is a specific case of event-driven programming. This can be seen in the following figure:
Figure 1.1: Event-driven programming and programming paradigms
So what is reactive programming?
Â
An easy way to get the idea behind it is to use an analogy with people's behavior: someone who is proactive is somebody who takes initiatives. A proactive person will propose ideas or test things before somebody asks him to do so. On the other hand, a reactive person is somebody who waits for information before doing something. So, a proactive person acts on his own while a reactive person reacts to external changes. There are pros and cons to each behavior: a proactive person proposing solutions ahead of time is great, but may have difficulties dealing with unexpected changes. On the other hand, a reactive person may be very efficient in dealing with very dynamic environments.
Reactive programming can be considered as implementing a behavior in a similar way to a reactive person. A reactive system reacts on external events and provides a result that depends only on the event it has received. So why would reactive programming be better than sequential programming? Better is always a matter of preferences and context, so reactive programming may not be the solution most adapted to all the problems you will encounter. However, as you will see through this book, reactive programming shines at implementing event-driven code.
Reactive programming is inherently asynchronous. So it makes it easier to deal efficiently with inputs and outputs than with synchronous paradigms. Reactive programming favors composition. Each component is completely independent from another and can be plugged in with other components. This also makes testing quite easy and, as a consequence, it also helps to refactor existing code. Moreover, it is quite engaging, and with experience you will see that almost everything is a flow of events.
When looking for information on event-driven programming concepts, two other similar terms are often mentioned: the reactor and the proactor. These are notions that are not really important when using high-level libraries such as ReactiveX and AsyncIO. Still, it is interesting to know what they are so that you can better understand what is going on under the hood. They are two kinds of low-level APIs that allow us to implement an event-driven library. For example, AsyncIO, which is the Python asynchronous API which can use a reactor or a proactor to expose the same APIs. Using a reactor or a proactor as the foundation of a framework is driven by the support, or not, of the proactor on the operating system. All operating systems support a reactor via the POSIXÂ
select system call or one of its derivatives. Some operating systems such as Windows implement proactor system calls. The difference between these two design patterns is the way I/O are managed.
Â
Figure 1.2 shows a sequence diagram of how a reactor works. The three main components involved in this pattern are as follows:
- Reactor
- Event handler
- Event demultiplexer
When the Main Program needs to execute an asynchronous operation, it starts by telling it to the Reactor, with the identification of the Concrete Event Handler that will be notified when an event occurs. This is the call to theÂ
register_handler. Then the Reactor creates a new instance of this Concrete Event Handler and adds it to its handler list. After that, the Main Program calls
handle_events, which is a function that blocks until an event is received. The Reactor then calls the Event Demultiplexer to wait until an event happens. The Event Demultiplexer is usually implemented through the select system call or one of its alternatives, such as
poll,
epoll, or
kqueue.
select is called with the list of handles to monitor. These handles are associated with the handlers that were registered before. When an event that corresponds to one of the handles occurs, the Event Demultiplexer returns the list of handles that correspond to the event that happened. The Reactor then calls the associated event handlers, and the event handlers implement the actual service logic. The following diagram demonstrates this:
Figure 1.2: The reactor design pattern principles
Figure 1.3 shows a sequence diagram of how a Proactor works. On a Proactor system, asynchronous operations can be executed by an Asynchronous Operation processor. This is an entity which is provided by the operating system, and not all operating systems have support for it. There are more components involved in a Proactor than in a reactor. First, an Initiator asks the Asynchronous Operation processor to execute and operate. With this request, the Initiator provides the information about the operation to execute, as well as the instance of the Completion Handler and Completion Event Queue associated to the operation. Then the Asynchronous Operation processor creates an operation object that corresponds to the request of the Initiator. After that, the Initiator asks the Proactor to execute all pending operations. When an event associated with one of the operations happens, the operation notifies the Asynchronous Operation processor about it. The Asynchronous Operation processor then pushes this result to a Completion Event Queue. At that point, the Completion Event Queue notifies the Proactor that something happens. The Proactor then pops the next event from the Completion Event Queue and notifies the Completion Handler about this result. The Completion Handler finally implements the actual service logic.
On a Proactor, the Initiator and the Completion Handler may be implemented in the same component. Moreover, this chain of actions can be repeated indefinitely. The implementation of the Completion Handler can be an Initiator that starts the execution of another Asynchronous Operation. This is used to chain the execution of asynchronous operations:
Figure 1.3: The proactor design pattern principles
As you can see, both patterns are somehow similar. They are both used to execute asynchronous operations. The main difference is in the way operations can be chained. On a reactor, asynchronous operations can be chained only by the main program once the blocking call to the event demultiplexer has been completed. On the other hand, a proactor allows the completion handlers to be initiators and so execute themselves new asynchronous operations.
Being aware of this is important because it allows us to understand what is going on behind the scenes. However, this is completely invisible with all the recent asynchronous frameworks. They all expose APIs whose behavior is similar to the proactor pattern because they allow us to easily chain asynchronous operations while others are still pending. However, they will still use a proactor depending on the operating system that you use. On some frameworks, when both the reactor and proactors are available, it is possible to select what pattern to use via configuration APIs.
This book will cover many aspects on reactive programming. But an important thing to be aware of is that using reactive programming does not mean implementing a reactive system. A reactive system is much more than implementing a component with asynchronous and reactive programming. These are two notions that may be easily mingled due to the similarities in the way they are named, but they are completely different. As already explained, reactive programming is a way to code. On the other hand, a reactive system is an architecture pattern that allows us to write robust systems; that is, applications that are made of many components communicating via network channels, and with instances running on several (many?) servers, virtual machines, or containers. This architecture pattern is described in the reactive manifesto ().
Â
The four pillars of the reactive system are shown in the following figure:
Figure 1.4: A reactive system
These four pillars are interdependent. The value of a reactive system is being reactive thanks to an elastic and resilient design. A reactive system relies on a message-driven communication between the components of the system. More specifically:
- A reactive system is responsive: It responds to events and user interactions rapidly and consistently. Responsiveness ensures that the application stays usable, and that, in case of a problem, these problems can be detected very quickly and thus handled correctly. Responsiveness is achieved thanks to the three other pillars of a reactive system.
- A reactive system is resilient: The system stays responsive even in the event of failure. Resilience can be achieved in several ways, such as replication and isolation. Failures are handled and contained in each component. Other components are dedicated to recover the components that failed and replication allows it to provide high-availability.
- A reactive system is elastic: The system stays responsive when the workload varies. The system can adapt to workloads that increase or decrease so that the allocated resources of the system are not oversized or undersized. In order to provide elasticity, the design must be vertically and horizontally scalable, with no performance bottleneck.
- A reactive system is message-driven: The different components of the system communicate via asynchronous message channels. Communication via messages allows us to isolate components. Saturation is controlled via back-pressure.
As you can see, reactive programming does not provide these four pillars in itself. Reactive programming is one of the tools that can be used to implement a reactive system, but it is not sufficient. Many other tools, such as message brokers, containers, orchestrations, or monitoring tools are needed to build a reactive system.
ReactiveX is a library which aims to make asynchronous programming easy. As the header of the project's website says, it is:
The Observer pattern done right
. ReactiveX is a library based on the idea of observable streams. A stream is an entity that emits zero, one, or several items, over a period of time. This stream of items can be observed by other entities that are interested in receiving these items and manipulated by them. This simple idea is the basis of what has become an incredibly successful way of doing asynchronous programming.
As said in the very first paragraph of this book, asynchronous programming is a very active field. ReactiveX is a typical example of technologies that did not exist a few years ago but that are now heavily used. It was originally one of the components of the Volta project at Microsoft. This project consisted of a set of developer tools to help with developing client and server parts of web applications. The Volta project was suspended in 2008 but ReactiveX continued to be developed, up to the point when it was publicly released for the .NET platform in 2010. The library was very successful, with a community starting to grow up and big companies such as Netflix and GitHub using it. In 2012, implementations for .NET, JavaScript, and C++ were published as open source projects. Since that time, ReactiveX has even impacted the standardization of some programming languages. ReactiveX now has official implementations for almost 20 programming languages and was the foundation of the Java reactive streams () standard and the EcmaScript observable () API. Nowadays, many other libraries, heavily inspired by ReactiveX, are available for virtually any programming language.
All of this is based on concepts that have already existed for many years, such as the observer design pattern, the iterator design pattern, and some principles from functional programming. The ingenuity came from combining them in such a way that it avoids the callback hell. Even better, it is equally suited for frontend applications that deal with user events and GUI widgets, and backend applications that work with network and database requests.
Â
Â
Â
ReactiveX is based on two entities: observables and observers. These are the only things that one needs to understand to be able to start writing code. Everything else is based on the behavior of one of these two entities.
Observables represent a source of events. An observable is an entity that can emit zero or one of several items. An observable has an explicit lifetime with a start and an end. When an observable completes or faces an error, it cannot send items anymore; its lifetime has ended. An observable may never end. In this case, it is an infinite source of events. Observables are a way to manage sequences of items in an asynchronous way. Table 1.1, which follows, shows a comparison between how to access items in a synchronous or asynchronous way. As you can see, observables fill a gap and are allowed to operate on multiple items in an asynchronous way.
Table 1.1: Accessing an asynchronous sequence of items if possible
Observables work in push mode, as opposed to the pull mode of an iterable. Each time a new item is available, the observable pushes it to its observer. Table 1.2 shows the difference between the pull mode of an iterator and the push mode of an observable. This is what makes the behavior reactive and easy to handle with asynchronous code: whether items are emitted immediately or later is not important to the observer receiving it, and the code semantic is very similar to the one used in synchronous code:
Table 1.2 : Observables are push based
Observers are the receiving part of the items. An observer subscribes to an observable so that it can receive items emitted by this observable. Just as the observable emits items one after another, an observer receives them one after another. The observable informs the observer of the end of the sequence, either by indicating that the observable has completed (successfully) or by indicating that an error has occurred. These two kinds of completion are notified in a similar way, and so can be handled in a similar way. With ReactiveX, the error management is not a special case, but on a par with the items and completion management. In contrast to iterables that use exceptions, there is no radically different way of handling success from failure.
The implementation of RxPY (as well as all other implementations of ReactiveX) involves two other entities: a subscription function and a disposable object. Figure 1.5 shows a simplified representation of these entities. The
AnonymousObservable class is the class that is almost always used to create an observable (directly or via another subclass). This class contains two methods to manage the lifetime of the observable and its observer. The first one,
init, is not even a method but the constructor of the class. It takes a
subscription function as an input argument. This
subscription function will be called when an observer subscribes to this observable. The observable constructor returns a disposable function that can be called to free all resources used by the observable and observer. The second method of the
AnonymousObservable class is
subscribe. This is the method that is used to attach an observer to an observable and start the observable; that is, to make it start emitting items. The
AnonymousObservable class can be used directly, but there are many cases where using an existing RxPYÂ
AnonymousObservable subclass is easier. This is typically the case when you need to create an observable from an iterable object or a single object.
The
Observer class is a base class that contains three methods. They correspond to the behavior explained previously. This class must be subclassed to implement these three methods. The method
on_next is called each time an item is emitted by the observable. The method
on_completed is called when the observable completes successfully. Finally, the method
on_error is called when the observable completes because of an error. The
on_item method will never be called after the
on_completed or the
on_error methods.
Â
Â
The subscription entity is a function that takes an observer as input parameter. This function is called when the subscribe method of the observable is called. This is where the emission of items is implemented. The emission of these items can be either synchronous or asynchronous. Items are emitted in a synchronous way if the
subscription function directly calls the
on_items methods of the observable. But items can also be emitted asynchronously if the observer instance is saved and used later (after the
subscription function returns). The
subscription function can return a
Disposable object or function. This
Disposable object will be called when the observable is being disposed.
Finally, the
Disposable class and its associated
dispose function are used to clean up any resources used by an
Observer or a
subscription. In the case of an asynchronous observable, this is how the
subscription function is notified that it must stop emitting items, because
Observer is no more valid after that. The following figure shows these components:
Figure 1.5: RxPY components
Let's try to make more sense of all these definitions. The following figure shows a sequence diagram of how these calls are organized when an observable is created, subscribed, and finally disposed:
Â
Figure 1.6: RxPY dynamics. An example of the creation of a synchronous observable and its subscription and disposal
First the application creates an
AnonymousObservable and provides the
subscription function associated to this observable. It then creates an
observer object (actually a subclass of
Observer). After that, the observable is subscribed, with reference to the
observer object provided as an input parameter. During the call to
subscribe, the
subscription function is called. In this example, the
subscription function is synchronous: it emits three items (the integers
1,
2, and
3), and completes the observable. When the
subscription function returns, the observable is already completed. At that point, the
subscribe method of
AnonymousObservable returns theÂ
Disposable function to the application. The application finally calls this
dispose function to clean up any resource still used byÂ
subscription and
observer.
Â
Now the principles of observables and observers should start to be more clear. However, you may wonder: how can this make development of asynchronous code easier? After all, what was described in the previous section is almost exactly the description of the observer design pattern, with additions for the management of completion and errors. The answer is that this is not the whole story, but the foundation of an extensible framework. What made ReactiveX different from other frameworks is its inspiration from functional programming, with the availability of many operators that can be chained in a pipeline. In the RxPY implementation, operators are methods of the
Observable class. On some implementations of ReactiveX, they are implemented as functions which allow us to add new operators very easily. Look at the following example of pseudo-code:
Observable.from_(...) .filter() .distinct() .take(20) .map(...)
This is what a ReactiveX code looks like. It is a succession of operators that modify the items flowing through them. An operator can be seen as a monad: a construction that encapsulates program logic instead of data. (I apologize to functional programmers for this very simplistic definition.) An operator takes an observable as input and returns another observable. So, we can consider the observable data type as an abstract type that is used to compose functions together. Some operators accept other input parameters to provide additional program logic that will be executed on each item received on the operator. For example, the
map operator that will be used later takes a function as a parameter. This function contains the code logic that will be executed on each item sent on the input observable.
Operators are not limited to the code logic of items. Since they work on the observable data type, they can also be used to manage observables' completion and errors. For example, some operators use completion events to chain observables one after another. Other operators use error events to gracefully manage these errors.
The RxPY implementation contains about 140 operators. We will cover the most used, which is about half of them. As you will be writing RxPY code, you will also be writing your own operators, even if they will not be directly usable in the kind of pipeline that we saw earlier. As we will see, writing a custom operator is the way to factorize code and make functions simpler when using ReactiveX.
Â
RxPY is available as a Python package published on PyPI (), so it can be installed with
pip. Depending on your operating system, you may already have
pip installed. Otherwise refer to the
pip installation documentation ().
By following the examples in this book, you will install several libraries and sample packages that you may not want to keep on your system. In order to avoid cluttering your environment, you should run all these examples in a
virtualenv.
virtualenv is a tool that allows you to create isolated Python environments. With it you can create many different Python environments, potentially using different Python interpreters that are independent from each other. This is a great tool when developing in Python because it allows you to:
- Test libraries without installing them on your system
- Test some code with different versions of Python interpreters
- Test some code with different versions of dependency packages
- Have one independent and reproducible execution environment per project
If you are not already familiar with it, I encourage you to use it when running the example code that we will use. The installation of
virtualenv is very easy via PyPI, using the following command:
pip3 install virtualenv
Creating a new virtual environment is also quite easy, in a single line with three parameters, using the following line of code:
virtualenv --system-site-packages -p /usr/local/bin/python3 venv-rx
The
--system-site-packagesoption indicates that we want to use system packages when they are already installed. If you omit this parameter you will create a complete Python environment from scratch. This would be better for isolation but requires much more space because each dependency will be reinstalled inÂ
virtualenv. In our case, we do not need a strict isolation from the system; we only want to avoid installing new packages in our system. The
-poption indicates what the Python interpreter will use. You should adapt it to your environment. The
/usr/local/binvalue corresponds to a macOS system. On Linux, the
cpython interpreter is usually located at
/usr/bin. Finally the
venv-rxparameter is the name of
virtualenv created. After running this command you will see a new directory named
venv-rx.
Â
Once
virtualenv is created, you can enter it and leave it. Once you have enteredÂ
virtualenv, all actions done by the Python interpreter are done in this isolated environment. Entering intoÂ
virtualenv is done by sourcing a script in its
bin directory, as can be seen in the following code:
source venv-rx/bin/activate (venv-rx)$
When you are inside
virtualenv, the name of
virtualenv is printed in parentheses before the shell prompt. This is how you know if you are inside an isolated environment or on your system environment. Leaving
virtualenv is done by executing the
deactivate function, as can be seen in the following code:
(venv-rx)$ deactivate $
From that point, the
rx package can be installed via the
pip tool, as can be seen in the following code:
$ source venv-rx/bin/activate (venv-rx)$ pip install rx
If you want to install the latest development version, you can also install it directly from the GitHub sources. First clone the repository, and then install RxPY from the local sources, as demonstrated in the following code:
(venv-rx)$ git clone (venv-rx)$ cd RxPy.git (venv-rx)$ python3 setup.py install
After this short introduction to ReactiveX and RxPY, the time has come to see some concrete code and write a first example. This first RxPY application is a command line interface (CLI) program that echoes the parameters that are provided as input. Save the following code in a file called
echo1.py, or use the
echo1.py script from the Git repository of this book, as shown in the following code:
import sys from rx import Observable argv = Observable.from_(sys.argv[1:]) argv.subscribe( on_next=lambda i: print("on_next: {}".format(i)), on_error=lambda e: print("on_error: {}".format(e)), on_completed=lambda: print("on_completed"))
Ensure that you are running in
virutalenv, as shown in the following code:
$ source venv-rx/bin/activate
And when you run it, you should see the following output:
(venv-rx)$ python3 echo1.py hello world ! on_next: hello on_next: world on_next: ! on_completed
We ran the program with three parameters (
hello,
world, and
!), and it printed these three parameters as well as information on the end of
Observable. Let's detail each line of this program. We will start by importing the modules that we will use, as in the following code:
import sys from rx import Observable
The
sys module allows us to access the command line arguments. The
rx module is the name of the RxPY package, which we installed from
pip. We do not import the complete
rx module, but just the
Observable class. In many cases we will only need this class, or a few other ones. Then we can create an observable from the command line arguments, as in the following example:
argv = Observable.from_(sys.argv[1:])
sys.argv is a list containing the command line arguments that were used to run the program. The first argument is the name of the script being executed. In this case its value is
echo1.py. Since we do not want to use this argument we omit it with a slice, using the second up to the last argument of the list. An observable is created from this list with the
from_ creation operator. This operator creates an observable from a Python iterable object, which is the case of our argument list. We affect the reference of this observable to the
argv variable. So,Â
argv is a reference to an observable that will emit items containing the arguments provided on the command line, one item per argument. After this affectation the observable is created, but does not emit any item yet; items are emitted only once the observable is subscribed. On the last part of the program, we subscribe to this observable and print text depending on the event being received, as can be seen in the following code:
argv.subscribe( on_next=lambda i: print("on_next: {}".format(i)), on_error=lambda e: print("on_error: {}".format(e)), on_completed=lambda: print("on_completed"))
Three callback arguments are provided to the subscribe method:
on_next,
on_error, and
on_completed. They are all optional, and they correspond to the reception of the associated events. As already explained, the
on_next callback will be called zero or more times, and the
on_error and
on_completed callbacks can be called once at the most (and never if the observable never ends, which is not the case here). The call to the
subscribe method is the one that makes the
argv observable start emitting items. In this simple application, the code of each callback is very simple, so we use
lambda instead of functions.
Lambdas are anonymous functions; that is, functions that can be referenced only from where they are defined, because they have no name. However, lambdas have restrictions over functions, which makes them only suitable when simple manipulations are done with the data:
- Lambdas can use only expressions, not statements
- Lambdas contain only one expression
- Lambdas cannot declare or use local variables
So, lambdas are very useful when you need to do an action on one or several input parameters. For more complex logic, writing a function is mandatory. Lambdas are used a lot when developing RxPY code because many operators take functions as input. So, such operators are functions that accept functions as input parameters. Functions that accept functions as input are called higher order functions in functional programming and this is another aspect of functional programming used a lot in ReactiveX.
As you can see, the
on_next callback is called once for each argument provided on the command line, and the
on_completed callback is called right after. In this example application, we use a synchronous
Observable. In practice, this means that all items are emitted in the context of the
subscribe call. To confirm this, add another
argv.subscribe( on_next=lambda i: print("on_next: {}".format(i)), on_error=lambda e: print("on_error: {}".format(e)), on_completed=lambda: print("on_completed")) print("done")
Then run the program again. You should see the following output:
(venv-rx)$ python3 ch1/echo1.py hello world ! on_next: hello on_next: world on_next: ! on_completed done
As you can see, the
done print is displayed after the observable completes because the observable emits all its items during the call to
subscribe.
We will now add some functionality to this echo application. Instead of simply printing each argument, we will print them with the first letter in uppercase. This is the typical case of an action that must be applied to each item of an observable. In the current code, there are two possible locations to do it:
- Either by using an operator on the
argvobservable
- By modifying the
on_nextcallback in the
subscribecall
In a real application, there will usually be only a single place where the action must be applied, depending on whether the action must be done in the observer or on the observable directly. Implementing the action in the observer allows you to isolate the change to this single observer. The other way of implementing the action on the observable allows you to share this behavior with several observers. Here we will implement the action on the observable with the
map operator. Modify the code as in the following example, or use the
echo2.py script from the GitHub repository () of the book:
argv = Observable.from_(sys.argv[1:]) \ .map(lambda i: i.capitalize())
The
map operator takes an observable as input, applies a transformation function on each item of this observable, and returns an observable which contains all input items, with the transformation applied to them. Here we have used
lambda that returns the item (a string) capitalized; that is, with its first letter in uppercase. If you run this new code you should get the following output:
(venv-rx)$ python3 ch1/echo2.py hello world ! on_next: Hello on_next: World on_next: ! on_completed done
As you can see, the output is the same, but with capitalized names. Congratulations; you have just written your first reactive application!
The ReactiveX project is composed of several hundreds of operators, and the Python implementation contains about 140 of them. When writing ReactiveX code, especially in the early days, you should regularly refer to the operator's documentation. Do not hesitate to read through it to find the most adapted operator for your needs. This is a good way to discover operators that you may use later, and you may find an operator doing exactly what you want to implement.
Unfortunately, this documentation is often difficult to understand. A representative of this situation is the
FlatMap () operator description:
"Transform the items emitted by an Observable into Observables, then flatten the emissions from those into a single Observable"
This simple description isâobviouslyâcorrect, but may not be easy to comprehend. This is why there is also a more detailed explanation on how the operator works. In the case of the
flat_map operator, the behavior is to take an observable as input and apply a transformation on each item of this observable. The transformation is done by a function also provided as an input of the operator. This function is called for each item emitted by the input observable and returns an observable at each execution (that is, for each item). Finally,
flat_map merges all the observables returned by the transformation function in a single output observable.
This is a very detailed description of how the operator works, but even when you are used to the ReactiveX terminology, you need to spend some time carefully reading each word of the documentation to understand what it means. Marble diagrams are a clever application of the a figure is worth a thousand words idiom. They represent graphically an example of the behavior of an operator. All operators are documented with their descriptions, and a marble diagram. Most of the time, the marble diagram allows you to understand the behavior of the operator without even having to read the documentation.
Figure 1.7 shows the structure of a marble diagram. A marble diagram is composed of three parts: input timelines, a transformation description, and output timelines:
Figure 1.7: Marble diagram
A timeline represents an observable state according to the time that goes on. It is drawn as an arrow going from left to right. Each item emitted on the observable is drawn as a circle. The official documentation uses different shapes and colors to represent items. In this book, we will only use circles with labels. Depending on the operator, there may be one or several input timelines.
Below the input timeline is the transformation description drawn as a rectangle. Some brief information about the transformation being performed is printed inside this rectangle. There are dashed arrows between the input timeline items and the transformation description each time the transformation is applied to an item or some items.
Finally, below the transformation description are the output timelines. They represent the result observables of the operator. In the example of Figure 1.7 each input letter is transformed to uppercase, so
a becomes
A,
b becomes
B, and
j becomes
J. Just like input timelines, most of the time there is only one output timeline. But some operators may return several observables, and some return observables of observables. This is shown in the following figure, in which for each item a new observable is generated, emitting the next three letters:
Figure 1.8: Observable of observable
An observable of observables is an observable that emits items that are themselves observables. While this may surprise at first, this is just one level of composition; an observable can convey items of any type, including observables. So, at some point you may work with several layers of observables being composed this way. Such observables are called higher order observables in this book, borrowing the naming convention used for higher order functions.
The last thing to understand in marble diagrams is the way timelines can end. An observable lifetime ends either on completion (that is, on success) or on error. These are respectively represented as a vertical line and as a cross, as shown in the following figure:
Figure 1.9: The end of an observable. On the left an observable that completes successfully and on the right an Observable that terminates in an error
Let's see a real example with the
map operator. This operator takes a source observable as input and returns an observable as output. It applies a function to each item of the source observable, and emits the result of this function on the output observable. Hopefully, its marble diagram, shown in the following figure, should make the description much more clear:
Figure 1.10: The map operator
The marble diagram shows an input timeline with three integer items:
1,
12, and
7. The transformation is described with syntax similar to that of the Python lambda. Note that the official ReactiveX documentation uses the JavaScript arrow function notation, because it uses marble diagrams from the JavaScript implementation. In this example, the transformation is a multiplication by
3 of the source item. The output timeline contains also three items, corresponding to the input items values multiplied by
3.
The prototype of this operator is the following one:
Observable.map(self, selector)
The
selector parameter is the function that will be executed on all items of the input observable.
TheÂ
from_ operator is the operator that was used in the previous example to create an observable from a list. The marble diagram of this operator is shown in the following figure:
Figure 1.11: The from_ operator
Note
The name of this operator is strange because it ends with an underscore. The reason for this underscore is that
from is a reserved keyword in Python, so it was not possible to name this operator as it should be; that is,Â
from. If you dislike this notation, there is an alias named
from_list. You can use it for a more Pythonic code at the expense of a longer name.
The prototype of this operator is the following one:
Observable.from_(iterable, scheduler=None)
Â
Â
Â
Â
Â
Â
Â
Â
Â
Â
Â
Â
Â
Â
Â
Â
Â
Â
The first parameter accepts any iterable object. This includes lists, tuples, dictionaries, and any class that implements the iterator methods
__iter__ and
next. The second parameter is used to provide a scheduler that will be used to emit the items of the observable. This parameter is present on all creation operators. It is useful when running in an asynchronous environment or an environment with concurrency. We will study schedulers in detail in Chapter 5, Concurrency and Paralellism in RxPY.
The
from_ operator creates an observable that emits one item per entry in the iterable. It then completes the observable. Here are some examples of usage which show the items that they return:
Observable.from_(sys.argv) # argv[0], argv[1], argv[2]..., completed Observable.from_([1, 2, 3, 4]) # 1, 2, 3, 4, completed Observable.from_({'foo': 'fooz', 'bar': 'barz'}) # 'foo', 'bar', completed
Note that when using a dictionary, the observable contains the keys of the dictionary and not the values. This is the same behavior as a classic Python iteration on a dictionary using a
for loop.
Marble diagrams are a great way to explain how an operator works. However, they are not suited to describe how a program, a function, or a component works. Marble diagrams can show from example how a transformation on one observable is applied, but they cannot be used to describe how operators are combined to achieve a more complex operation on the data. We need a kind of diagram that shows the complete transformations applied on observables without the details of each operator being used. We need a diagram in which one considers that the operators are known by the reader but the overall behavior of a component must be described.
Fortunately, we can use diagrams inspired from a tool used in sequential programming: UML activity diagrams. An activity diagram is the UML name of something you may know as a flowchart. These diagrams are used to describe the sequences of actions which are performed by a program, but they can also express repetitions, alternatives, joins, merges and so on. Activity diagrams with only few tweaks are a great way to represent the behavior of an RX component. We will call them reactivity diagrams.
Â
Â
The main difference between an activity and a reactivity diagram is that an activity diagram represents actions that are performed when the component is called, while a reactivity diagram represents actions which are performed each time an item is emitted on one of the source observables. Other than that, the elements defined by UML are used in almost the same way. Let's detail this with the example shown in the following figure:
Figure 1.12: A reactivity diagram
This is an example of a function which takes two observables as input and provides two observables as output. This function counts the number of dogs emitted on the
Dogs input observable and sends back the name of all animals emitted on both the
Dogs and
Cats input observables. Input observables are observables that the component observes. They emit the items that will be transformed by the component. Input observables are represented as black circles. Output observables are observables that are the result of the transformation of the component. Output observables are represented as encircled black circles.
Â
The previous example shows an important point in RX programming: from now onâalmostâeverything that you will write will deal with observables. It means that almost all components are written as functions that take observables as input and return observables. This is the way reusability is achieved via composition.
The same transformation is applied to the items of both input observables: capitalize the name of the animal. Then the capitalized dog name items are being shared; that is, they are being emitted on two observables. Finally, the capitalized dog name items are counted and the value of this count is emitted in the dogs count observable. On the right side, the dog and cat name observables are merged to an observable that emits the capitalized names of all animals.
So, if such a component is used with the following observables, it will be shown as in the following example:
dogs = Observable.from_(["sam", "max", "maggie", "buddy"]) cats = Observable.from_(["luna", "kitty", "jack")
It will emit the following items on the output observables:
dog_count: 1, 2, 3, 4 animals: sam, luna, max, maggie, buddy, kitty, jack
The actual ordering of the items emitted on the
animals observable will depend on when they are emitted on the input observable.
Reactivity diagrams can be constructed from the following elements:
- Circles:Â Observables are represented as circles. An input observable is represented as a black circle. An output observable is represented as an encircled black circle. Two other notations allow us to indicate when actions are done: when an observable terminates on completion or on error. This notation is similar to the marble diagrams; an observable error event is represented as a circle with a cross in it, and an observable completion event is represented as a circle with a bar in it. This is shown in the following figure:
Figure 1.13: Observable notations. From left to right: input, output, error, completion
- Rectangles:Â Operators are represented as rounded rectangles. The text inside the rectangle describes the actions being performed. The first line contains the name of the operator and its parameters. The following lines contain the description of the action. This notation can also be used for components being used in the current component. This notation can also be used as a merge point for operators that combine several observables. This is shown in the following figure:
Figure 1.14: Operators notation
Figure 1.15: Items flows notation
Diamond:Â Decisions are represented as a diamond. The decision notation is used only for operators that take an observable as input and split it into two or more observables, the split being based on a segmentation logic described in the diamond. The text inside the diamonds describes the segmentation logic in the same way as the operator's notation. This is seen in following figure:
Figure 1.16: Decisions notation
- Horizontal or vertical black bar: Share and merge are represented as a horizontal or vertical black bar. An observable is shared when there is one incoming observable and several outgoing observables on the bar. Observables are merged when there are several incoming observables and one outgoing observable on the bar.This is demonstrated in the following figure:
Figure 1.17: Share and merge notation: share (center), merge (right)
- Rectangle with the upper-right corner bent: Out of monad actions are represented as a rectangle with the upper-right corner bent. Out of monad actions are the actions that are not done via an operator or a component operating on observables. The typical usecase is the code of the subscription associated to an observer. The text in the rectangle describes briefly the actions being done. This can be seen in the following figure:
Figure 1.18: Out of monad notation
We will complete this tour of the reactivity diagrams by writing the echo example. Its diagram is shown in the following figure:
Figure 1.19: The echo app reactivity diagram
This simple diagram should allow any developer to understand what is going on, provided that he knows that it applies to each item emitted on the
argv input observable. First, the input observable is created from the
argv variable. Then each item is capitalized with the
map operator. Finally, each event type (item, completion, or error) is printed. Note that the content of each element is not a copy of the code, but a small description of what it does. The echo example was quite simple, but in a real application you want to document the behavior with reactivity diagrams, not duplicate the code on a diagram.
You should now understand what event-driven programming is, what reactive programming is, and what are the common points and differences between them. It is important to remember that event-driven programming is not a programming paradigm, but a way to structure the code flow. Knowing the basics of the reactor and proactor design patterns is also important to better understand how the frameworks that will be used in the next chapters work.
From now, you can start writing reactive code for tasks that you may have written in a sequential way. This kind of exercise, even for very simple algorithms, is good training in how to structure your code as a data-flow instead of a code-flow. Switching from a code-flow design to a data-flow design is the key point in writing ReactiveX applications.
Last but not least, you should now be able to navigate easily in the ReactiveX documentation and understand more easily the behavior of each operator, thanks to marble diagrams. Never hesitate to use them when you need to write your own operator or component. This is always a good way to show what you want to achieve. For a more dynamic view, reactivity diagrams will help you design bigger components or document how they are composed together.
The next chapter will introduce how asynchronous programming is done in Python, and, more specifically, with its dedicated module of the standard library, AsyncIO. But before that, detailed explanations of the underlying principles of asynchronous functions will be provided so that you can understand what's going on under the hood.
Â
Â
- Is event-driven programming possible only with some programming languages?
- What are the differences between reactive programming and reactive systems?
- What is an observable?
- What is an observer?
- Are observables pull-based or push-based?
- What makes reactivity diagrams different from activity diagrams?
- How do you create observable emitting integers from 0 to 10,000?
- How do you create an observable from another observable where all items are multiplied by 3?
The description of the observer design pattern was originally documented in the book
Design Patterns: Elements of Reusable Object-Oriented Software
. You can read it to understand one of the foundations of ReactiveX. This book contains the description of all base design patterns used in object-oriented programming.
A detailed description of the reactor and proactor design patterns is available in the book
Pattern-Oriented Software Architecture, Patterns for Concurrent and Networked Objects, Volume 2.
This book contains information on concurrency, synchronization, and event handling.
The ReactiveX documentation is available online here:. This documentation is generic to all programming languages, featuring marble diagrams of each operator. Refer to this documentation when looking for an operator. For each operator, it contains links to the specificity of each implementation.
The Reactive Manifesto is a great source of information to understand what is a reactive system and how to implement such a system:.
You must read and learn The Observable Contract available here:. It describes in a few words the rules that govern observables and observers. Once you are at ease with these concepts, you will be able to write and read ReactiveX code in an efficient way. | https://www.packtpub.com/product/hands-on-reactive-programming-with-python/9781789138726 | CC-MAIN-2020-50 | refinedweb | 8,683 | 54.52 |
Oracle just released its newest version of Oracle Data Access Components (ODAC) that incudes support for Entity Framework 4.0. You can read more about this release here You can also read this article about usage of ODP (Oracle Data Provider) with Entity Framework models
One important note is that Code First is not officially supported in this release, and will be supported in a future release. Having said that, I wanted to see if I can use it, since Code First builds on top of EF 4, which is supported by this release. I was able to confirm that I can indeed access Oracle data and update it.
Here are step-by-step instructions.
You will need one prerequisite – Oracle engine itself. I used 11g Express edition, which is free for developer. You can download it from this page
Event those it is not required, I also installed Sql Developer, which is akin to SQL Server Management Studio, well mostly anyway. You can download it from this page
Once that is done, download and install ODAC from here
At this point, I ran SQL Developer, connected to my instance and looked at the existing database. You have to create a new connection for that, using File – New..->Database Connection menu. Under Other Users node I found HR, which contains a sample HR database.
Personally, I reset password for HR user to something that I know. This way I do not have to use SYS login.
Now that those tasks are out of the way, you are ready to get started. I assume you already have VS 2010 installed.
Now, start new project (I used Console application) and install Entity Framework Code First package reference into this project. You can use NuGet for that, which is what I did. Also add a reference to Oracle ODP assembly – Oracle.DataAccess. Then, I create a POCO class to match Countries table and setup DbContext. I use fluent API to configure that table. I just do it in the context class instead of creating a separate configuring class. Here is my country class.
public class Country
{
public string CountryID { get; set; }
public string CountryName { get; set; }
public decimal RegionID { get; set; }
}
And here is DbContext class:
public class Context : DbContext
{
public Context()
: base(new OracleConnection(ConfigurationManager.ConnectionStrings["OracleHR"].ConnectionString), true)
{
}
public DbSet<Country> Countries { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Conventions.Remove<IncludeMetadataConvention>();
modelBuilder.Entity<Country>().Property(p => p.CountryID).HasColumnName("COUNTRY_ID");
modelBuilder.Entity<Country>().HasKey(p => p.CountryID);
modelBuilder.Entity<Country>().Property(p => p.CountryName).HasColumnName("COUNTRY_NAME");
modelBuilder.Entity<Country>().Property(p => p.RegionID).HasColumnName("REGION_ID");
modelBuilder.Entity<Country>().ToTable("COUNTRIES", "HR");
}
}
Now, you have to setup connection string in app.config:
<?xml version="1.0"?>
<configuration>
<connectionStrings>
<add name="OracleHR"
connectionString="DATA SOURCE=localhost:1521/XE;PASSWORD=****;PERSIST SECURITY INFO=True;USER ID=HR;"
providerName="Oracle.DataAccess.Client" />
</connectionStrings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0" />
</startup>
</configuration>
Here is the code that gets data from the table and inserts a new row.
using (var ctx = new Context())
{
var data = ctx.Countries.ToList();
ctx.Countries.Add(new Country() { CountryID = "CL", CountryName = "Chile", RegionID = 2 });
ctx.SaveChanges();
}
Here are a few important points.
- Make sure to put correct password into connection string.
- I configure column names explicitly to match the database table.
- I had to use correct .NET types to match the Oracle data types. Here is MSDN article that describes this mapping
- I am manually creating Oracle Connection and passing it into constructor of my context class. I tried to avoid that, but I kept getting exceptions. This approach worked perfectly.
In summary, one apparently can use newest Oracle provider to use with Code First. This approach is not officially supported by Oracle, at least not yet. So, use it at your own risk. You definitely cannot create new database as you can in SQL Server, so you have to maintain database separately. From my research, only DevArt provides full Code First support for Oracle with their own provider, at least according to their product page
You can download my sample solution
[Update 2/12/2012] – this scenario is not officially supported by Oracle, so you should not use this in production.
Thanks, and feedback is appreciated.
Agreed.. I never rename the columns.. its good to name them properly..
Hi! Nice Article. Thanks.
Could you send me an example when the Country has a “Active” Boolean Property, please? The Column type is NUMBER(1,0) in the database, but I don’t know how can I implement the conversion NUMBER to Boolean?
Thanks!
It seems the provider does not handle automatic conversions between NUMERIC(1,0) and bool. One workaound I can suggest is to define a constant for 1 and 0 and do the following:
var data = ctx.Countries.Where(c=>c.IsActive == 1).ToList(); // where 1 would be your constant
public class Country
public string CountryID { get; set; }
public string CountryName { get; set; }
public decimal RegionID { get; set; }
public byte IsActive { get; set; }
modelBuilder.Entity().Property(p => p.IsActive).HasColumnName(“ACTIVE”);
Oh, nothing could be simpler. 🙂
Thanks.
I’m trying this in my project, but get “Unable to determine the provider name for connection of type ‘Oracle.DataAccess.Client.OracleConnection'”. Any ideas what might be the cause of this?
Thank you for the sample code, It finally worked for me.
1. I needed my application to work with SQL and Oracle at the same time. Mapping fields one by one will separate my application into two versions?
2. Should i use Oracle 10g to have Code First working as it does with SQL Server?
This is just my opinion, but I would not use Code First for that without testing a provider you picked very thoroughly. Oracle does not support Code First officially, and thus you will not get support from then if you encounter issues. You can try DevArt and see if it works for you. To my knowledge, DevArt is the only provider that advertises Code First support. If you would like to minimize the risk, you can always go with DB First approach and just make sure your models are compatible (read DB are compatible as well). Then you can isolate data access layer into a single DLL, and simply have your business layer refer to this DLL by name. Then have your two projects with your models (one for SQL Server, the other for Oracle) have exact same name and namespace so that you can distribute one or the other depending on your target.
Sergey, Please help!
I have two classes.
public class Customer
{
}
public int Id { get; set; }
public string Username { get; set; }
public int? JobtitleId { get; set; }
public virtual Jobtitle Jobtitle {get; set;}
public class Jobtitle
{
}
public int Id { get; set; }
public string JobtitleName { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove();
modelBuilder.Entity().ToTable(“CUSTOMER”, “MYSCHEMA”);
modelBuilder.Entity().HasKey(c => c.Id);
modelBuilder.Entity().Property(c => c.Id).HasColumnName(“ID”);
modelBuilder.Entity().Property(c => c.Username).HasColumnName(“USERNAME”);
modelBuilder.Entity().Property(c => c.JobtitleId).HasColumnName(“JOBTITLEID”);
modelBuilder.Entity().HasOptional(c => c.Jobtitle).WithMany().HasForeignKey(c => c.JobtitleId).WillCascadeOnDelete(false);
modelBuilder.Entity().ToTable(“JOBTITLE”, “MYSCHEMA”);
modelBuilder.Entity().HasKey(j => j.Id);
modelBuilder.Entity().Property(j => j.Id).HasColumnName(“ID”);
modelBuilder.Entity().Property(j => j.JobtitleName).HasColumnName(“JOBTITLENAME”);
base.OnModelCreating(modelBuilder);
}
when I add a new customer and call SaveChanges() I have an error.
var customer = new Customer(){Username = “John”};
_db.Customers.Add(customer);
_db.SaveChanges();
error: Object cannot be cast from DBNull to other types.
When I remove ‘public virtual Jobtitle Jobtitle’ property from Customer it’s works. Save a new customer to database with JobtitleId null value.
Some customer has Jobtitle and some hasn’t. Can you help me?
Thanks.
@SeatDevil
Could you please inlcude script for those two tables?
Thanks.
I solved the problem 🙂
I changed the int ID to decimal, and add ‘HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)’ string to modelBuilder and it works fine.
Thank you.
Thanks, This article help me specially for the connection string for Oracle.
Can you tell me if it’s possible to have an MVC web application using Oracle database and the DATABASE FIRST approach : generating my data model (.edmx) from an existing oracle database (700+ tables!) ??? how can I generate my data model?
@KrazyNeg
Although code first works, I would be very careful when it comes to using something in production that is not officially supported by Oracle. You can certainly reverse engineer the model by creating an edmx from your database, then using DbContext template to create Code First model. You simply right click on the mode and select Add Code Generation Item, then pick DbContext template. If you do not see that option, just download the appropriate template from VS Gallery, but I think VS 2010 ships with that one.
Hello Sergey,
Nice example.
But is code first now already fully supported by the beta ODP driver?
Thanks in advance.
Gertjan Smit
One more question 🙂
Is lazy and eager loading fully supported?
@Gertjan Smit
I have not tried, but I fully expect they are.
Hello, Sergey Barskiy.
i use entity framework 5 . but get ‘No MigrationSqlGenerator found for provider ‘Oracle.DataAccess.Client’. Use the SetSqlGenerator method in the target migrations configuration class to register additional SQL generators.’
when i update database.
i installed the oracle odp latest edition and oracle client 10g.
Thanks.
@bigboy
Indeed Microsoft only ships SQL Server migrations provider. You can either write your own by implementing required interfaces or wait for Oracle to implement the same. Alternatively, you can use a third party product to maintain your database schema separately from EF classes.
Hi Sergey,
Thanks for the interesting post. I’m looking for a possibility to support the oracle sequences in EF. So possibility to use the select seq_xxx.nextval in linq. I do not want to create at trigger on insert in oracle to handle the id’s. Do you have any idea how to do this with ODP.
Thanks a lot.
@Luc,
I think you would need to execute SQL with your sequence code before you save and put the value into your primary key property. DbContext has method to Execute arbitrarily SQL you can use.
Excellent article, very clean and usefull, thanks.
any updates in 2013 using VS 2012, ODP.NET ?
Not as far as I know. They are releasing managed driver soon though, it is in beta now. That might change a few things, but not the Code First supports as far as I know.
Thank you!!!!! Your solution finally helped me.
I don´t know why, but the context-constructor was able to establish the Connection, the naming convention – as I usually do it – failed …
Segey, I have a problem with the OracleProvider they show me this message of error ‘Unable to determine the DbProviderFactory type for connection of type ‘Oracle.DataAccess.Client.OracleConnection’
I saw this message, but never if I send the connection to the DbContext’s constructor. Is this what you are doing? This should have improved in EF 6, but Oracle still does not have support for Code First officially.
any updates using VS 2013, ODP.NET Managed Driver ?
No official support from Oracle for Code First yet.
Hi,
I m using The code Give above but getting following error.
A null was returned after calling the ‘get_ProviderFactory’ method on a store provider instance of type ‘Oracle.DataAccess.Client.OracleConnection’. The store provider might not be functioning correctly.
I have latest ODAC
Sorry I m new to MVC and I have to use MVC with oracle only..
Thanx in advance.
@Vishal
I am not sure at this point, just not enough information. Make sure you have client installed that matches your web site platform – 32 vs 64 bit. Check your machine.config to ensure Oracle provider is there. Look for inner exception to get more clues. Doublecheck your connection string….
Thanks a lot sir. It works for me.
please can you text the oracle entity provider in web.config
@Info. I am not sure what you are asking here.
For all those who are asking about Oracle DataAccess Provider configuration, You need to add below configuration on config file,
Hi Sergey,
Great to see some nice info in this blog !! It is really helpful !
I am also trying to use Entity Framework code first approach for oracle data source. but after trying for a week now I am not getting any success in retrieving the data. I have tried using Entity Framework 4.2.0.0 & 5.0.0.0 with .net framework 4.5 , latest odac components & odp manager.
the issue is improper query eg.
Query : SELECT
“Extent1″.”EmployeeId” AS “EmployeeId”,
“Extent1″.”DepartmentId” AS “DepartmentId”,
“Extent1″.”RelatedEntityFqdn” AS “RelatedEntityFqdn”,
“Extent1″.”EmailAddress” AS “EmailAddress”
FROM “schemaname”.”EMPLOYEE” “Extent1”
here first thing you notice is ‘From’ section, it is taking schema name & table name in double quotes while in normal scenario it should be without quotes.
and the second thing is column names, in that too it is taking double quotes while it should not. so can you tell the exact cause of the issue? and what do i need to do so that entity framework generates proper query for oracle?
Apart from that, i would also like to know the specific versions that are supported for Entity Framework code first approach for Oracle.
It will be a great help from your side if i get to the some solution.
Thanks in advance !!!
EF is using quoted identifiers because this is the only way to be safe. You probably need to use explicit table and column names in configurations to ensure they match Oracle. Maybe even schema name as well.
Hi Sergey, Nice to see your quick response !!
I have also tried giving column names, table name & schema name explicitly but didn’t get any success 🙁 , it is still generating the query with double quotes so it gives me “table or view does not exists” error. and i have tried many workarounds but still not getting rid of that double quotes so can you suggest any approach through which entity framework would generate correct query for oracle?
Thanks in advance !!
As I mentioned before, quoted identifiers are used for safety, you cannot suppress them as far as I know. However, if you supply correct schema names, column names, and table names in you mapping configuration classes, your query will work just fine.
Hi Sergey,
I am facing some issues related with mapping the boolean property with oracle database.
The description of the exception is as follows :
Error : Schema specified is not valid. Errors: (27,12) : error 2019: Member Mapping specified is not valid. The type ‘Edm.Boolean[Nullable=False,DefaultValue=]’is not compatible with ‘OracleEFProvider.number[Nullable=False,DefaultValue=,Precision=38,Scale=0]’
I had tried to add the following code in the project’s config file.But still didnt worked
Can you you help me out with this?
Thanks in advance !!
I am guessing you are using large numbers as booleans ind you DB. You have to teach EF provider how to map those. For example you can do this in your config file.
You can also opt to just use numbers in your model.
Sergey,
I am getting the following error while connecting to Oracle 11G Database with ASP.NET MVC4 and EF 5.
Error: A null was returned after calling the ‘get_ProviderFactory’ method on a store provider instance of type ‘System.Data.OracleClient.OracleConnection’. The store provider might not be functioning correctly.
Web.Config ConnectionString Details:
I am guessing you did not install oracle data provider ODP / ODAC on your machine. Or you are not using managed provider.
base(new OracleConnection(ConfigurationManager.ConnectionStrings[“OracleHR”].ConnectionString), true)
in above line of code configurationManager is showing error that , this is not in context
@ummidikondababu. Maybe you are not referencing System.Configuraion? Hard to say without seeing full error text.
Hi Sergey,
Need your help !!! Again 🙂
I am trying to use Entity Framework code first approach for oracle data source.Now for security purpose we are not using connection string from web config, rather using a variable while initializing context class, like,
public class EmployeeContext : DbContext
{
{
}
public EmployeeContext()
: base(DbConnection)
Database.SetInitializer(null);
etc…etc…
Here “DBConnection” variable contains the connection string.
Now with oracle, I need to give provider name along with the connection string otherwise it throws error so can you please tell me the way to tell DBContext about which Provider Name to use?
Thanks in advance !!
@Nirav
Should be Oracle.DataAccess.Client, assuming you have ODP installed. You can look it up in machine.config under system.data.
I can’t download Oracle Express 11g in my country, Cambodia. Can anyone help me? | http://www.dotnetspeak.com/entity-framework/oracle-odp-and-entity-framework-code-first-4-2/ | CC-MAIN-2022-21 | refinedweb | 2,798 | 58.69 |
In my last post, I discussed how to increase the error logs through the GUI and explained the back end stored procedure that is used to set the value in the registry. In this post, I will cover a technique to automate this and dig a little into Windows Management Instrumentation (WMI).
As Rob and Rudy Komacsar pointed out in the comments section of my first post, there are a plethora of ways to automate this setting. The approach I took was a little different than theirs although their approaches are equally valid and effective at getting the job done – nice work and thanks to both of you for the tips!
For this post, the approach I took was to leverage WMI directly as it affords me the opportunity to easily segue into a discussion around WMI which is a powerful tool to manage SQL Server. There are other benefits and reasons I chose this route including the fact that it allows you to configure the setting without ever having to connect to the engine, and it can be applied to all instances and versions on the server in one fell swoop.
If you don't know what WMI is, here's a link to some background information. WMI is not only integral to Windows but is accessible through Windows via the Get-WMIObject cmdlet. That cmdlet allows you to retrieve an instance of a specific WMI class. Each WMI class belongs to a namespace which is essentially a path or a unit of scoping for a class. Let's get into some examples and see how SQL Server leverages WMI.
The namespace for the SQL Server WMI provider is root\microsoft\sqlserver\computermanagementxx where xx is the version of SQL Server (10 = 2008, 11=2012, 12=2014 and 13=2016). Before we get into code, there's an interesting tool you can use to enumerate the list of classes and instances of a WMI class. That tool is WBEMTest and is installed on all Windows machines. To run it, hit a command prompt, type wbemtest and enter.
Click Connect and enter the respective namespace (in my case - root\microsoft\sqlserver\computermanagement13) and click connect
Click Enum Classes
Click OK
This box shows the list of all classes available in this namespace. The class we are interested in is SqlServiceAdvancedProperty. Double click on it.
Within this class are three methods (SetBoolValue, SetNumericalValue and SetStringValue). There are several properties (IsReadOnly, PropertyIndex, etc.). This class provides a set of name/value pairs for the properties of each SQL Server service. If you click Instances, you can browse the actual data in the WMI repository. A great tool for just plain spelunking.
I've provided a PowerShell script that will dump out the data from that class for each instance/service/version of SQL Server on the local machine.
cls $namespaceBase = "root\microsoft\sqlserver\computermanagement" for ($index = 10; $index -le 14; $index++) { $advProps = Get-WmiObject -Namespace ($namespaceBase + $index.ToString()) -Class "SqlServiceAdvancedProperty" -ErrorAction Ignore if ($advProps -ne $null) { Write-Output ("Found Properties Under: " + $namespaceBase + $index.ToString()) foreach ($property in $advProps) { $output = ($property.ServiceName + " --> " + $property.PropertyName) # String Type if ($property.PropertyValueType -eq 0) { $output += (" = " + $property.PropertyStrValue) } #Boolean Type if ($property.PropertyValueType -eq 1) { $output += (" = " + [System.Boolean]$property.PropertyNumValue) } # Int Type if ($property.PropertyValueType -eq 2) { $output += (" = " + $property.PropertyNumValue) } $output } } }
This script will output a lot of information about EVERY instance installed on the server. One Name/Value pair included in the output is REGROOT.
Note, this is the same path that is used/translated by xp_instance_regwrite. You just need to add in the extra \MSSQLServer at the end, and you are looking at the key where the NumErrorLogs value is located.
Now that you have the path, all you need to do it set the value to the number of error logs you want. An example of setting the value through PowerShell is shown below. This will set the value for all instances of SQL Server 2016.
$numLogs = 42 $objects = Get-WmiObject -Namespace "root\microsoft\sqlserver\computermanagement13" -Class "SqlServiceAdvancedProperty" | where-object {$_.PropertyName -eq "REGROOT" -and $_.SqlServiceType -eq 1} foreach ($object in $objects) { Write-Output ("Setting " + ("HKLM:\" + $object.PropertyStrValue + "\MSSQLServer\NumErrorLogs") + " to " + $numLogs.ToString() + ".") Set-ItemProperty -Path ("HKLM:\" + $object.PropertyStrValue + "\MSSQLServer") -Name "NumErrorLogs" -Value $numLogs }
If you are interested in digging into the other WMI classes provided by SQL Server, here is an MSDN link to that documentation.
I hope this helped open your eyes to the power of PowerShell and WMI for SQL Server Automation.
I use PowerShell SMO to do this
$srv = New-Object Microsoft.SqlServer.Management.Smo.Server $server
$srv.Settings.NumberOfLogFiles = $Number
$srv.Alter()
I have placed the script on the gallery as well | https://blogs.msdn.microsoft.com/sql_pfe_blog/2017/02/09/__trashed/ | CC-MAIN-2019-18 | refinedweb | 784 | 57.06 |
ASP.Net MVC 3 - An Overview Part 3
In ASP.Net MVC Part2 we have digged deep inside Controller.For eg: We have seen triple actions related to controller. ie; Action Method, Action Result, Action Filter. In this section we will dig a bit deeper inside ASP.Net MVC 3 View. As you know we are not using viewstate or session in ASP.Net MVC for state management. We will see here how to handle state in MVC,Razor View Engine,Layout Template,Html Helpers,Partial Views etc.
View in depth
View as it name implies gives user interface to the end user.In ASP.Net MVC, it is the view engine which is responsible for generating the view. Views does not contain any business logic or data validation logic.They are similar to ASP.Net web forms but like web forms views cannot be directly accessed via web browser.As I told you earlier, views are always rendered by a controller.
When ever a request comes to the MVC application,the controller handles the incoming request and depends upon the application logic it will communicate with the model to retrieve or update the data. The model in turn communicate with the database and updates the controller and the controller will render the
appropriate view. The view renders the appropriate UI by the help of data that is passed to it from the controller.There are different mechanisms for passing data from controller to view and vice versa. The controller action method passes the data to the view using the View method.
public class TestController : Controller
{
public ActionResult Welcome()
{
ViewBag.Message = "Welcome to world of ASP.NET MVC 3";
return View();
}
Here,the View method will call the view engine, which uses the data in the viewBag/ViewData to render to the view and to display it in the browser. Here parameter which is passed to the view is the ViewBag which is a property of the view and controller. ViewBag is a new feature introduced in MVC 3.
We can pass any data between view and controller ranging from a simple data type to a collections of a complex object.There are different methods for passing data from view to view,controller to view or vice versa.
Important among them are :
1. Viewdata : It is derived from ViewDataDictionary object. so it is a dictionay object and hence we can access its data by using key/value pair. It is fast and easy to implement. But It has a drawback. Since by default, in view data everything is stored as an object, we need to explicitly cast its contents to appropriate type.
a) Setting value in ViewData in Controller Action method :
public ActionResult Index()
{
ViewData["Test"] = "Test View Data";
return View();
}
b) Retrieving value from Viewdata in the View :
@ViewData["Test"] // @ is the razor syntax
2. ViewBag: This feature is not available in prior versions of MVC 3. It is a wrapper built above ViewData, and it is dynamic in nature.They are
stored as key/value pair in the viewdata dictionary.Since its dynamic no explicit casting is required. Also we can dynamically set/get values in viewbag without the use of strongly-typed classes.
a) Setting value in ViewBag in Controller Action method :
public ActionResult Index()
{
ViewBag.Test = "Test the View Bag";
return View();
}
b) Retrieving value from ViewBag in the View :
@ViewBag.Test // @ is the razor syntax
3. TempData : Like Viewdata,it is also a dictionary type property.It is used to store data at the time of redirection.Its like ASP.Net Session object but of short life span. While redirecting from one controller to another, both ViewBag and ViewData properties cannot be used. Here we can use Tempdata since it works for subsequent requests.
public class ProductController : Controller
{
[HttpPost]
public ActionResult Save(FormCollection formValues)
{
ProductModel productModel = new ProductModel();
TempData["UpdatePoduct"] = productModel; // set value in Tempdata
return RedirectToAction("SaveSuccess");
}
[HttpGet]
public ActionResult SaveSuccess()
{
ProductModel productModel = TempData["UpdatePoduct"] as productModel; // retrieve data from TempData.
return View(productModel);
}
}
4.ViewModel : We can use the ViewData, ViewBag, and TempData objects for the purposes of transporting small amounts of data from and to specific locations (ie; controller to view or between views). If we want to work with larger amounts of data like reporting data, dashboards, or work with multiple disparate sources of data, we will go for ViewModel object.
We can say view model is simply a class that hold all data that is needed by a view. Usually they are specific to each view and are not often reused
between views.
public class TestViewModel
{
public string Test { get; set; }
}
public Action Test()
{
var Testmodel = new TestViewModel { Test = "bar" };
return View(Testmodel);
}
View Specifications
As a convention we should keep in mind the following points while creating a view.
1. Once we create a new project in ASP.Net MVC, it contains a Views folder.
2. Views folder contains folder per each controller and has same name as
controller.
3. Each view folder contains a view for each action method with in the controller with name same as action method.
Strongly Typed Views
A strongly typed view bind form data to a particular class or view. A strongly typed view inherits from System.Web.Mvc.ViewPage<T> where T refers to the model class.Since we are specifying the type here we can access the intelliSense for the model class.Here is the advantages of using a strongly typed view.
1. Clean Syntax.
2. Strong Typing.
3. Compile Time Checking of property and method names.
4. Take advantage of Visual Studio intellisense.
What is Razor View Engine ?
It is one of the new feature introduced in ASP.Net MVC3. It is the default view engine in ASP.Net MVC 3. In C# razor view's extension is .cshtml and in vb it is .vbhtml. It has following advantages while comparing to its prior view engine(.ASPX) counterpart.
1. Developer friendly since it is based on existing languages such as C# or VB.
2. Syntax is clean and concise compared to its prior view engine counterpart.
3. It has intellisence support.
4. Test Driven Development approach can easily followed by the help of razor view.
Following is the razor syntax.
@{
var items = new string[] {"mango","apple","orange"};
}
<body>
foreach(var item in items)
{
<li> @item </li>
}
</body>
In .ASPX view engine we used xml like tag with percentage sign to indicate the start and stop of code sequence as follows.
<% foreach(var item in items)
{%>
<% item %>
<% } %>
But In case of razor view, it uses @ character.Unlike its ancestor, Razor does not require you to explicitly close the code-block. Also Razor is smart enough to understand the general pattern of email.
ie; In the following example,it won't treat @ as a code delimiter.
some.body@anywhere.com
In the above example, if you don't want to consider @ chracter,then you can say @@ in the place of @.
some.body@@anywhere.com will display as some.bodyanywhere.com.
What is code Expression ?
In razor view, we can write any C# or Vb code statement that we want with in @()syntax. The transition from C#/Vb to mark up and vice versa is possible through @ character. There are 2 basic types of transitions. It can be implicit code expressions or explicit code expression. Code expressions are evaluated and written to the response.
Example of Implicit Code Expression:
The item is @item
Example of Explicit Code Expression:
@(item.hours/8) //expression are placed in brackets
What is Code Block ?
Code block also starts with @ and it contains one or more statements and will be enclosed in curly braces.
@{
ViewBag.Title = "Code Block Example";
}
What is Layout ?
Layouts are used to maintain consistent look and feel across multiple views. They behave like master pages in ASP.Net Web form but it provides more flexibility and simpler syntax than master pages.
Layout template can contain placeholders where views can place their content.The content placeholders can be defined using 2 methods.
1. @RenderBody() :It is located in the Layout page.It is same as ContentPlaceHolder in a Master Page but remember a layout page can contain maximum only one RenderBody.
2. @RenderSection() It is used to place fragments of markup in a layout page. Unlike RenderBody we can have as many RenderSection are possible in a layout page.
3. @RenderPage() : It will help to reuse markup and code that doesn't change across the site. Ex:Header and Footer.
A view must specify content for each section defined in the template, otherwise an exception will be thrown.
The following is an excerpt from the body tag of a sample Laypout template which is located as /Shared/_SampleLayout.cshtml.
<html>
<head>
<title>Layout Example </title>
</head>
<body>
@RenderSection("SiteMap")
//@RenderPage("Shared/_Header.cshtml") It will read from file you provided.
@RenderBody()
@RenderPage("Shared/_Footer.cshtml")
</body>
</html>
Here is my WebPage1 contents. We need to refer the above Layout page in WebPage1 on top as follows.
@{
Layout = "/Shared/_SampleLayout.cshtml";
}
@section SiteMap {
.
. // Your mark up goes here
.
}
<span> WebPage 1 specific content goes here <span>
Here mark up in the shared file _Footer.cshtml will be replaced in the footer.
Also note that, you can use RenderSection and RenderPage interchangeably.But there a slight difference how they works. From the above example you can see that, RenderPage will always reads the content from a physical file, whereas RenderSection runs code blocks that we provides in the content pages.
Html Helpers
As I mentioned in earlier sections, ASP.Net doesn't have any server controls so we need to create the controls using Html tags. For an experienced developer it may be easy. But for others it may not be an easy task. Here comes the importance of Html Helpers.
Html Helpers are methods that returns a string where the string can represent any type of content. They help to render HTML content and thus reduce the tedious task of typing Html tags.
We can even write without any Html helper if you are experienced MVC developer. But Html helper helps the developer task easier.In short, Html helpers are similar to ASP.Net Web Controls except that they doesn't support viewstate,post back or eventmodel.
Some standard Html helpers are :
1. Html.ActionLink()
2. Html.BeginForm()
3. Html.TextArea()
4. Html.ListBox() etc.
What is custom Html Helper ?
ASP.Net MVC provides a limited number of Html helpers by default. But we have the freedom to create our own custom html helpers. In order to create custom Html Helper we need to create an extension method on the Html helper class.
To build custom html helpers, we can also take the help of TagBuilder class which is a utility class which makes it easier to build HTML tags.
Partial Views
Partial views are reusable components.In ASP.Net we have used UserControl and Custom controls to provide this functionality. Unlike ASP.Net server controls they wont use view state,post back or events to manage state information.They can be rendered inside a layout or regular view.
The syntax that render partial view is implemented as Html helper.
Html.partial helper method allows viewData/ViewBag objects to pass data between views or partial views.
@Html.Partial("_PartialViewExample")
//name of partial view without extension is the argument here
Sometimes we just need to write the content to Html response similar to Response.Write in ASP.Net Web forms. In that case we can go for Html.RenderPartial helper method.
@Html.RenderPartial("_PatialViewwithRenderPatial")
As a convention partial views name starts with underscore.If the partial views needs to be shared across views then it need to be created under Views/Shared folder.
Creating partial view is similar to views except we need to check the "Create Partial View" checkbox in the add view dialog box.
Really its useful . simple and good | https://www.dotnetspider.com/resources/43781-ASP-Net-MVC-Part.aspx | CC-MAIN-2022-05 | refinedweb | 1,985 | 59.09 |
19 November 2012 09:22 [Source: ICIS news]
SINGAPORE (ICIS)--?xml:namespace>
The gas fractionation unit is expected to produce on-spec propylene late in the week ending 23 November, the source added.
Shandong Dongfang Hualong shut the unit down on 2 October for maintenance, the source said.
The Chinese producer also restarted its 1.4m tonne/year catalytic cracking unit (CCU) unit on 7 November and finished the repairs for its propylene tanks on 15 November, the source added.
There are concerns that the output from Shandong Dongfang Hualong’s unit will exert downward pressure on propylene prices in the coming weeks as the domestic propylene supply | http://www.icis.com/Articles/2012/11/19/9615239/chinas-shandong-dongfang-hualong-restarts-gas-fractionation.html | CC-MAIN-2015-18 | refinedweb | 108 | 62.88 |
Re: Programming is the Engineering Discipline of the Science that is Mathematics
Date: Tue, 6 Jun 2006 10:00:16 +0300
Message-ID: <e638vo$ne2$1_at_nntp.aioe.org>
"Marshall" <marshall.spight_at_gmail.com> wrote in message
news:1149566505.233718.323040_at_u72g2000cwu.googlegroups.com...
>.
One day I tryed to find the bug in a program and couldn't find it for hours. After a glass of alcohol, the brownian motion accelerated and I instantly found the error. It was right under my nose. A glass of alcohol might be just what you need to get out of a loop. :-)
One interesting error I once encountered was in a numerical program due to too much copy/paste. The program produced correct answers but too slow. The error was just one character that needed to be changed from + to - :-)
Other interesting error was due to a far call with near return (or something like that). The program entered in an infinite loop because returned to a place above a call to the same rutine. The program was written in Pascal and used no pointers. :-) Received on Tue Jun 06 2006 - 09:00:16 CEST
Original text of this message | http://www.orafaq.com/usenet/comp.databases.theory/2006/06/06/0588.htm | CC-MAIN-2017-30 | refinedweb | 194 | 66.23 |
Function Objects
A user-defined function object is created by a function definition (see def). It should be called with an argument list containing the same number of items as the function’s formal parameter list.
Special attributes:
- func_doc The function’s documentation string, or None if unavailable. (Writable.)
- __doc__ Another way of spelling func_doc. (Writable.)
- func_name The function’s name. (Writable.)
- __name__ Another way of spelling func_name. (Writable.)
- __module__ The name of the module the function was defined in, or None if unavailable. (Writable.)
- func_defaults A tuple containing default argument values for those arguments that have defaults, or None if no arguments have a default value. If not None, the len(func_defaults) arguments have default values. (Writable.)
- func_code The code object representing the compiled function body. (Writable.)
- func_globals A reference to the dictionary that holds the function’s global variables — the global namespace of the module in which the function was defined. (Read-only.)
- func_dict The namespace supporting arbitrary function attributes. (Writable.)
- func_closure None or a tuple of cells that contain bindings for the function’s free variables. (Read-only.) type-code). | http://effbot.org/pyref/type-function.htm | crawl-002 | refinedweb | 183 | 57.98 |
Agenda
See also: IRC log
<trackbot> Date: 03 August 2007
minutes from the 12/6 and 10/7 approved: we discussed this in Nice and decided to at least add another pattern to ensure the reference was within the same schema document
jonc: doesn't everyone use this pattern?
pauld: for document/literal
wrapped many tools generate this?
... would: BT "standard header" is an
element in another namespace
... and this works well with tools?
jonc: yes!
pauld: OK haven't seen evidence this doesn't work, though being cautious I'd want to remove it too ..
This is scribe.perl Revision: 1.128 of Date: 2007/02/23 21:38:13 Check for newer version at Guessing input format: RRSAgent_Text_Format (score 1.00) Succeeded: s/en parlant de ca j'aimerai bien que les lieux de meetings changent un peu, meme si EDI c'est sympa// Succeeded: s/many tools generate this/many tools generate this?/ Succeeded: s/BooleanAttribute fails BooleanElement works, go figure!// FAILED: s/BooleanAttribute fails BooleanElement works, go figure!// Succeeded: s/Decmial/Decimal/ Succeeded: s/Axis can't cope with GlobalElementSequence!// Succeeded: s/used/used - Advanced/ No ScribeNick specified. Guessing ScribeNick: pauld Inferring Scribes: pauld WARNING: No "Present: ... " found! Possibly Present: Yves databinding gcowe joined jonc left pauld: 3 Aug 2007 Guessing minutes URL: People with action items: pdowney WARNING: Input appears to use implicit continuation lines. You may need the "-implicitContinuations" option.[End of scribe.perl diagnostic output] | http://www.w3.org/2007/08/03-databinding-minutes.html | CC-MAIN-2013-48 | refinedweb | 242 | 59.5 |
IRC log of xproc on 2008-04-10
Timestamps are in UTC.
15:01:24 [RRSAgent]
RRSAgent has joined #xproc
15:01:24 [RRSAgent]
logging to
15:01:53 [alexmilowski]
alexmilowski has joined #xproc
15:01:59 [Zakim]
+Jeroen
15:02:01 [Zakim]
-Jeroen
15:02:02 [Zakim]
+Jeroen
15:02:10 [Zakim]
+Norm
15:02:16 [Zakim]
+??P13
15:02:18 [ruilopes]
Zakim, ?? is me
15:02:18 [Zakim]
+ruilopes; got it
15:02:20 [Norm]
Meeting: XML Processing Model WG
15:02:20 [Norm]
Date: 10 Apr 2008
15:02:20 [Norm]
Agenda:
15:02:20 [Norm]
Meeting: 107
15:02:20 [Norm]
Chair: Norm
15:02:21 [Norm]
Scribe: Norm
15:02:23 [Norm]
ScribeNick: Norm
15:02:58 [ht]
zakim, please call ht-781
15:02:58 [Zakim]
ok, ht; the call is being made
15:03:00 [Zakim]
+Ht
15:03:00 [Norm]
Zakim, who's on the phone?
15:03:01 [Zakim]
On the phone I see PGrosso, Jeroen, Norm, ruilopes, Ht (muted)
15:03:26 [Zakim]
+alexmilowski
15:03:27 [Norm]
Zakim, jeroen is Voycheck
15:03:29 [Zakim]
+Voycheck; got it
15:03:35 [Norm]
Zakim, jeroen is Vojteck
15:03:35 [Zakim]
sorry, Norm, I do not recognize a party named 'jeroen'
15:03:43 [Norm]
Zakim, Voycheck is Vojteck
15:03:43 [Zakim]
+Vojteck; got it
15:03:45 [Zakim]
+??P49
15:03:47 [richard]
zakim, ? is me
15:03:47 [Zakim]
+richard; got it
15:03:48 [Norm]
Zakim, who's on the phone?
15:03:48 [Zakim]
On the phone I see PGrosso, Vojteck, Norm, ruilopes, Ht, alexmilowski, richard
15:04:03 [Norm]
Zakim, Vojteck is Vojtech
15:04:11 [Zakim]
sorry, Norm, I do not recognize a party named 'Vojteck'
15:04:29 [Norm]
Present: Paul, Vojtech, Norm, Rui, Henry, Alex, Richard
15:04:34 [Norm]
Zakim, who's on the phone?
15:04:34 [Zakim]
On the phone I see PGrosso, Vojtech, Norm, ruilopes, Ht, alexmilowski, richard
15:05:23 [AndrewF]
AndrewF has joined #xproc
15:05:52 [Norm]
Present: Paul, Vojtech, Norm, Rui, Henry, Alex, Richard, Andrew
15:06:11 [mzergaou]
mzergaou has joined #xproc
15:06:17 [Zakim]
+??P0
15:06:20 [AndrewF]
zakim, ? is Andrew
15:06:20 [Zakim]
+Andrew; got it
15:06:43 [MSM]
zakim, please call MSM-617
15:06:43 [Zakim]
ok, MSM; the call is being made
15:06:45 [Zakim]
+MSM
15:07:09 [Norm]
Present: Paul, Vojtech, Norm, Rui, Henry, Alex, Richard, Andrew, Michael
15:07:19 [Norm]
Topic: Accept this agenda?
15:07:19 [Norm]
->
15:07:28 [Norm]
Accepted
15:07:34 [Norm]
Topic: Accept minutes from the previous meeting?
15:07:34 [Norm]
->
15:07:39 [Norm]
Accepted
15:07:44 [Norm]
Topic: Next meeting: telcon 17 April 2008?
15:08:09 [Norm]
Rui gives regrets for 17 and 24 April.
15:08:19 [Norm]
Alex gives regrets for 17 April.
15:08:35 [Norm]
Topic: Adjusting base URIs
15:09:18 [Norm]
Norm and Richard summarize.
15:09:41 [Norm]
->
15:11:31 [Norm]
Richard: we need to say what the base URI of an empty document node is.
15:11:50 [Norm]
...And we need to say what happens if a document in the pipeline has no base URI.
15:12:58 [Norm]
Richard: I also suggested a relativize function, but it turns out to be less useful, I think.
15:13:41 [Norm]
Alex: Is there anything different from the XPath 2.0 functions?
15:13:52 [Norm]
Richard: No, but they'll be available to XPath 1.0 processors if we put them in our namespace.
15:15:41 [Norm]
Norm: I think we want to make sure that XPath 1.0 implementations can do these things.
15:15:47 [mzergaou]
mzergaou has joined #xproc
15:15:50 [Norm]
Alex: I think this is a slippery slope.
15:16:23 [Norm]
Richard: If we don't put this in, XPath 1.0 impls will have to indepently invent this. This way, they have a uniform name and will be interoperable.
15:16:38 [Norm]
...Especially if we want to add some sort of relativize function.
15:17:06 [Norm]
Alex: I think if we do this, we must make it exactly the same as the XPath 2.0 functions.
15:17:59 [richard]
15:19:32 [Norm]
Some discussion of whether we have to invent our own errors or return the XPath 2.0 errors.
15:20:03 [Norm]
Norm: I'd be content to say that they return the F&O error codes.
15:20:26 [Norm]
Norm: I could go the other way as well.
15:21:38 [Norm]
The editor can decide when he's writing it up.
15:22:02 [Norm]
Proposed: Add p:base-uri() and p:resolve-uri() as spec'd by Richard, to be the same as the XPath 2.0 functions.
15:22:17 [Norm]
Accepted.
15:22:30 [Norm]
Topic: Error ports
15:22:42 [Norm]
->
15:23:00 [Norm]
Vojtech summarizes.
15:25:25 [Norm]
Norm: The catch step can read from an error port, so I think it follows that there must be ports that connect to it. Even if the user can't read it.
15:26:22 [Norm]
Some discussion of the motivation.
15:26:42 [Norm]
Norm: Anyone have any thoughts on what we might do or say differently?
15:27:05 [Norm]
Richard: I haven't looked in a while, there isn't any concept that a subpipeline aggregates the error ports of its steps or anything like that is there?
15:27:06 [Norm]
Norm: No.
15:27:40 [Norm]
Vojtech: I found this sentence most confusing "All steps have an implicit output port for reporting errors that must not be declared."
15:27:41 [mzergaou]
mzergaou has joined #xproc
15:28:07 [Norm]
Norm: Well, why don't we ask the editor to try to make this a little clearer.
15:28:51 [Norm]
Richard: Minor point: sometimes we call the "error ports" and sometimes "error output ports". It would be good to make them consistent.
15:29:09 [Norm]
Topic: Pipeline names/types
15:29:11 [Norm]
Norm summarizes.
15:31:22 [Norm]
Richard/Henry: Why can't the type be in no namespace?
15:32:03 [Norm]
Norm: Well, because it helps prevent name collisions if you import them.
15:32:20 [Norm]
Vojtech: The purpose of type is for importing, right?
15:32:22 [Norm]
Richard: Yes.
15:32:50 [Norm]
Vojtech: Removing the name is a bit strange, because you have to use this type. Everywhere else you use 'name'. I think that's a bit strange.
15:33:00 [Norm]
...We could have both.
15:33:21 [Norm]
...That's what I'd like: bring back the name.
15:33:44 [Norm]
Henry: We thought it was confusing to have both name and type.
15:34:05 [Norm]
Vojtech: You only need type for import.
15:34:24 [Norm]
Richard: It used to be the other way around, if you had a name but not a type, the type got constructed.
15:35:04 [Norm]
Richard: I agree it's dual purpose is a bit odd.
15:37:35 [Norm]
Norm: We used to have all sorts of magic, but now that we've removed that, I think maybe the simplest thing would be to put back both name and type.
15:37:55 [Norm]
Richard: We could have some magic syntax like "name='*'" to refer to the pipeline.
15:38:17 [Norm]
Norm: Er, yeah, well.
15:39:11 [Norm]
Richard: The name you invent isn't visible anywhere else, so that seems a bit odd.
15:39:21 [Norm]
More discussion about leaving 'step=' off.
15:39:28 [Norm]
s/"name=/"step=/
15:39:36 [mzergaou]
mzergaou has joined #xproc
15:40:04 [Norm]
What are the options:
15:40:08 [Norm]
1. The status quo
15:40:25 [Norm]
2. Leaving 'step=' out makes the pipe refer to the ancestor pipeline.
15:40:31 [Norm]
3. Use '*' as the name of the ancestor pipeline
15:40:42 [Norm]
4. We could have both name and type attributes, functioning independently
15:40:58 [Norm]
Zakim, who's on the phone?
15:40:58 [Zakim]
On the phone I see PGrosso, Vojtech, Norm, ruilopes, Ht, alexmilowski, richard, Andrew, MSM
15:44:19 [Norm]
Vojtech: If we put the name attribute on the pipeline, then it would also have to be on declare step.
15:46:45 [Norm]
<p:pipeline>
15:46:45 [Norm]
<p:declare-step name="foo" type="x:one"...>
15:46:45 [Norm]
<p:declare-step name="bar" type="x:two"...>
15:46:45 [Norm]
<p:declare-step name="baz" type="x:three"...>
15:46:45 [Norm]
<p:identity>
15:46:46 [Norm]
<p:input
15:46:48 [Norm]
<p:pipe
15:46:50 [Norm]
...
15:49:09 [Norm]
Richard: I think the names on declare-step and pipeline shouldn't go in the surrounding environment.
15:49:50 [Zakim]
-MSM
15:49:51 [Norm]
Norm: We could add that rule.
15:50:20 [Norm]
Norm: I don't think we have the idea that some steps are not steps.
15:50:35 [Norm]
Henry: Sure we do. None of variable, pipelinfo, or documentation are steps.
15:52:06 [Norm]
Straw poll: which do you prefer, 1-4.
15:53:26 [Norm]
Results: five for choice 4 and two for choice 2
15:53:38 [Norm]
Propose: we adopt choice 4.
15:53:47 [Norm]
Accepted.
15:54:04 [Norm]
Topic: Any other business?
15:54:41 [Norm]
None.
15:54:50 [Norm]
Adjourned.
15:54:55 [Zakim]
-ruilopes
15:54:57 [Zakim]
-Ht
15:54:58 [Zakim]
-Norm
15:54:58 [Zakim]
-richard
15:54:58 [Zakim]
-PGrosso
15:55:00 [Zakim]
-Vojtech
15:55:00 [Zakim]
-Andrew
15:55:01 [Zakim]
-alexmilowski
15:55:03 [Zakim]
XML_PMWG()11:00AM has ended
15:55:04 [Zakim]
Attendees were PGrosso, Norm, ruilopes, Ht, alexmilowski, richard, Vojtech, Andrew, MSM
15:55:17 [Norm]
RRSAgent, set logs world-visible
15:55:21 [Norm]
RRSAgent, draft minutes
15:55:21 [RRSAgent]
I have made the request to generate
Norm
15:56:44 [MSM]
MSM has joined #xproc
15:56:52 [Norm]
We've adjourned, MSM
15:57:05 [mzergaou]
mzergaou has joined #xproc
15:57:17 [Norm]
RRSAgent, bye
15:57:17 [RRSAgent]
I see no action items | http://www.w3.org/2008/04/10-xproc-irc | CC-MAIN-2013-20 | refinedweb | 1,751 | 81.22 |
Please read these notes carefully to know what this is all about. The source code for all firmware images published on this page is available from the Espressif SDK for ESP32 repository, its Pycom fork and the Pycom MicroPython repository.
More details about the individual builds can be found on Inofficial firmware bakery for Pycom/ESP32 devices.
Kudos to all people from MicroPython, Pycom Limited, Espressif Systems, FreeRTOS and the authors of countless 3rd party modules for their hard work bringing these things to the community. You know who you are.
There are various flavors. Enjoy!
VARIANT=PYBYTESenabled.
Note 1: Roberts builds usually include some utility scripts in frozen bytecode:
mount.py- For mounting the SD card.
pye_mp.py- The Micropython-Editor is a small on-board editor for the PyBoard, ESP8266, ESP32 and Pycom devices written in Python. It is typically imported as
from pye_mp import pyeand invoked by
pye("filename").
uping.py- A ping utility.
upysh.py- A small set of unix-like commands, typically imported as
from uping import *.
Note 2: There is also a firmware image for a generic ESP32 board. The difference to Pycom WiPy is that GPIO pins can be called “GPIOxx” instead of “Pxx”. Limitation: This works either on a Rev0 board without SPIRAM or a Rev1 board with SPIRAM.
The software and respective customized builds are provided WITHOUT ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR PURPOSE.
While apparently open source licenses like the MIT and the GPLv3 and the respective licenses of 3rd-party modules apply in general, please take special notice about the license notes Pycom published through Pycom FAQ v2.2 and Pycom Licences v2.2.
This software was developed by Pycom Limited for the WiPy, LoPy and SiPy series of boards and is copyright (c) 2017 Pycom, Damien P. George, Espressif Systems and others. | https://packages.hiveeyes.org/hiveeyes/foss/pycom/ | CC-MAIN-2020-29 | refinedweb | 314 | 56.15 |
It seems to me that we’re down to
.tmPreferences being the last Sublime related file that must be in Apple PLIST format.
Will there be a .sublime-something replacement for the .tmPreferences file format?
It seems to me that we’re down to
0 Likes
Thanks for the references Keith.
Is the following the full landscape? Anything missing or incorrect in my table?
2 Likes
Nice, check below if there are something you would like to add to your table:
import sys from pathlib import Path print("\n".join(sorted(list({ v.suffix for v in Path(sys.argv[1]).glob("**/*.sublime*") } | { v.suffix for v in Path(sys.argv[1]).glob("**/*.tm*") }))))
output:
.cache .rcache .sublime-build .sublime-color-scheme .sublime-commands .sublime-completions .sublime-keymap .sublime-macro .sublime-menu .sublime-mousemap .sublime-package .sublime-settings .sublime-snippet .sublime-syntax .sublime-theme .sublime_session .tmLanguage .tmPreferences .tmTheme
1 Like
Good idea. I tried
sublime.find_resources myself.
I’ve added
.sublime-package
and that you found to the table. They’re kind of meta-level I guess.
.sublime_session
Edit: There’s also
.sublime_license. I won’t in fact include
_session and
_license because these underscore-containing ones are an implementation detail of the main app and aren’t related to extensibility.
0 Likes | https://forum.sublimetext.com/t/will-there-be-a-sublime-something-replacement-for-the-tmpreferences-file-format/43159/2 | CC-MAIN-2022-33 | refinedweb | 213 | 52.76 |
This tutorial details how AWS Lambda and API Gateway can be used to develop a simple code evaluation API, where an end user submits code, via an AJAX form submission, which is then executed securely by a Lambda function.
Check out the live demo of what you’ll be building in action here.
WARNING: The code found in this tutorial is used to build a toy app to prototype a proof of concept and is not meant for production use.
This tutorial assumes that you already have an account set up with AWS. Also, we will use the
US East (N. Virginia) /
us-east-1 region. Feel free to use the region of your choice. For more info, review the Regions and Availability Zones guide.
Objectives
By the end of this tutorial you will be able to…
- Explain what AWS Lambda and API Gateway are and why would would want to use them
- Discuss the benefits of using AWS Lambda functions
- Create an AWS Lambda function with Python
- Develop a RESTful API endpoint with API Gateway
- Trigger an AWS Lambda function from API Gateway
What is AWS Lambda?
Amazon Web Services (AWS) Lambda is an on-demand compute service that lets you run code in response to events or HTTP requests.
Use cases:
For more examples, review the Examples of How to Use AWS Lambda guide from AWS.
You can run scripts and apps without having to provision or manage servers in a seemingly infinitely-scalable environment where you pay only for usage. This is “serverless” computing in a nut shell. For our purposes, AWS Lambda is a perfect solution for running user-supplied code quickly, securely, and cheaply.
As of writing, Lambda supports code written in JavaScript (Node.js), Python, Java, and C#.
Project Setup
Start by cloning down the base project:
$ git clone \ --branch v1 --single-branch $ cd aws-lambda-code-execute
Then, check out the v1 tag to the master branch:
$ git checkout tags/v1 -b master
Open the index.html file in your browser of choice:
Then, open the project in your code editor:
├── README.md ├── assets │ ├── main.css │ ├── main.js │ └── vendor │ ├── bootstrap │ │ ├── css │ │ │ ├── bootstrap-grid.css │ │ │ ├── bootstrap-grid.min.css │ │ │ ├── bootstrap-reboot.css │ │ │ ├── bootstrap-reboot.min.css │ │ │ ├── bootstrap.css │ │ │ └── bootstrap.min.css │ │ └── js │ │ ├── bootstrap.js │ │ └── bootstrap.min.js │ ├── jquery │ │ ├── jquery.js │ │ └── jquery.min.js │ └── popper │ ├── popper.js │ └── popper.min.js └── index.html
Let’s quickly review the code. Essentially, we just have a simple HTML form styled with Bootstrap. The input field is replaced with Ace, an embeddable code editor, which provides basic syntax highlighting. Finally, within assets/main.js, a jQuery event handler is wired up to grab the code from the Ace editor, when the form is submitted, and send the data somewhere (eventually to API Gateway) via an AJAX request.
Lambda Setup
Within the AWS Console, navigate to the main Lambda page and click “Create a function”:
Create function
Steps…
Select blueprint: Click “Author from scratch” to start with a blank function:
Configure Triggers: We’ll set up the API Gateway integration later, so simply click “Next” to skip this part.
Configure function: Name the function
execute_python_code, and add a basic description -
Execute user-supplied Python code. Select “Python 3.6” in the “Runtime” drop-down.
Within the inline code editor, update the
lambda_handlerfunction definition with:
import sys from io import StringIO def lambda_handler(event, context): # get code from payload code = event[‘answer’] test_code = code + ‘\nprint(sum(1,1))’ # capture stdout buffer = StringIO() sys.stdout = buffer # execute code try: exec(test_code) except: return False # return stdout sys.stdout = sys.stdout # check if int(buffer.getvalue()) == 2: return True return False
Here, within
lambda_handler, which is the default entry point for Lambda, we parse the JSON request body, passing the supplied code along with some test code -
sum(1,1)- to the exec function - which executes the string as Python code. Then, we simply ensure the actual results are the same as what’s expected - e.g., 2 - and return the appropriate response.
Under “Lambda function handler and role”, leave the default handler and then select “Create a new Role from template(s)” from the drop-down. Enter a “Role name”, like
api_gateway_access, and select ” Simple Microservice permissions” for the “Policy templates”, which provides access to API Gateway.
Click “Next”.
Review: Create the function after a quick review.
Test
Next click on the “Test” button to execute the newly created Lambda:
Using the “Hello World” event template, replace the sample with:
{ "answer": "def sum(x,y):\n return x+y" }
Click the “Save and test” button at the bottom of the modal to run the test. Once done, you should see something similar to:
With that, we can move on to configuring the API Gateway to trigger the Lambda from user-submitted POST requests…
API Gateway Setup
API Gateway is used to define and host APIs. In our example, we’ll create a single HTTP POST endpoint that triggers the Lambda function when an HTTP request is received and then responds with the results of the Lambda function, either
true or
false.
Steps:
- Create the API
- Test it manually
- Enable CORS
- Deploy the API
- Test via cURL
Create the API
To start, from the API Gateway page, click the “Get Started” button to create a new API:
Select “New API”, and then provide a descriptive name, like
code_execute_api:
Then, create the API.
Select “Create Resource” from the “Actions” drop-down.
Name the resource
execute, and then click “Create Resource”.
With the resource highlighted, select “Create Method” from the “Actions” drop-down.
Choose “POST” from the method drop-down. Click the checkmark next to it.
In the “Setup” step, select “Lambda Function” as the “Integration type”, select the “us-east-1” region in the drop-down, and enter the name of the Lambda function that you just created.
Click “Save”, and then click “OK” to give permission to the API Gateway to run your Lambda function.
Test it manually
To test, click on the lightning bolt that says “Test”.
Scroll down to the “Request Body” input and add the same JSON code we used with the Lambda function:
{ "answer": "def sum(x,y):\n return x+y" }
Click “Test”. You should see something similar to:
Enable CORS
Next, we need to enable CORS so that we can POST to the API endpoint from another domain.
With the resource highlighted, select “Enable CORS” from the “Actions” drop-down:
Just keep the defaults for now since we’re still testing the API. Click the “Enable CORS and replace existing CORS headers” button.
Deploy the API
Finally, to deploy, select “Deploy API” from the “Actions” drop-down:
Create a new “Deployment stage” called ‘v1’:
API gateway will generate a random subdomain for the API endpoint URL, and the stage name will be added to the end of the URL. You should now be able to make POST requests to a similar URL:
Test via cURL
$ curl -H "Content-Type: application/json" -X POST \ -d '{"answer":"def sum(x,y):\n return x+y"}' \
Update the Form
Now, to update the form so that it sends the POST request to the API Gateway endpoint, first add the URL to the
grade function in assets/main.js:
function grade(payload) { $.ajax({ method: 'POST', url: '', dataType: 'json', contentType: 'application/json', data: JSON.stringify(payload) }) .done((res) => { console.log(res); }) .catch((err) => { console.log(err); }); }
Then, update the
.done and
.catch() functions, like so:
function grade(payload) { $.ajax({ method: 'POST', url: '', dataType: 'json', contentType: 'application/json', data: JSON.stringify(payload) }) .done((res) => { let message = 'Incorrect. Please try again.'; if (res) { message = 'Correct!'; } $('.answer').html(message); console.log(res); console.log(message); }) .catch((err) => { $('.answer').html('Something went terribly wrong!'); console.log(err); }); }
Now, if the request is a success, the appropriate message will be added - via the jQuery html method - to an HTML element with a class of
answer. Add this element, just below the HTML form, within index.html:
<h5 class="answer"></h5>
Let’s add a bit of style as well to the assets/main.css file:
.answer { padding-top: 30px; color: #dc3545; font-style: italic; }
Test it out!
Next Steps
- Production: Think about what’s required for a more robust, production-ready application - HTTPS, authentication, possibly a data store. How would you implement these within AWS? Which AWS services can/would you use?
- Dynamic: Right now the Lambda function can only be used to test the
sumfunction. How could you make this (more) dynamic, so that it can be used to test any code challenge (maybe even in any language)? Try adding a data attribute to the DOM, so that when a user submits an exercise the test code along with solution is sent along with the POST request - i.e.,
<some-html-element data-test="\nprint(sum(1,1))" data-results"2" </some-html-element>.
- Stack trace: Instead of just responding with
trueor
false, send back the entire stack trace and add it to the DOM when the answer is incorrect.
Thanks for reading. Add questions and/or comments below. Grab the final code from the aws-lambda-code-execute repo. Cheers!
What do you think? | https://realpython.com/blog/python/code-evaluation-with-aws-lambda-and-api-gateway/ | CC-MAIN-2018-05 | refinedweb | 1,529 | 63.19 |
Do Notation
The main way to handle monads is do-notation. It can "unwrap" monads easily, with do and arrows. Here is an example with the IO monad, inside of the main function.
main = do
fileHandle <- openFile "test.txt" ReadMode
x <- hGetContents fileHandle
let x-lines = lines x
return ()
In this block of code, the Handle is "extracted" from the IO Monad in the second line of code. <- will take a Monad, and bind its wrapped value to a named value. Note that this is still lazily evaluated. Afterwards, a new String is taken from an IO (String) and put into x. The next important line, "return ()", uses one of monad's core methods. This is because main must return an IO monad. However, you can see that it is inefficient to bind so many variables. So, here is how to use another one of Monad's methods, >>=, to chain actions together.
main = do
xlines <- openFile "test.txt" ReadMode >>= hGetContents
return ()
This is such an essential usage of Monads that >>= is the unofficial symbol representing Haskell. As you can see, the result of the openFile command is "pushed" into hGetContents. It's important to note that a monad is going into hGetContents, and a monad is coming out. <- is what unbinds it.
Functors and Monads
So, you still have to use the <- to "de-monad" the monad you get before it can be used, right? Wrong. There is a typeclass called fmap, which is generally applicable to everything. One of the monad laws dictates the behavior of fmap, so it damn well better be able to manipulate our monads. Here is the program once again rewritten:
main = fmap putStrLn $ openFile "test.txt" ReadMode >>= hGetContents
Here, fmap is a function with the type signature of "String -> IO ()", applied to the result of hGetContents on the monad pushed into it by the openFile. fmap maps putStrLn over the results, and the IO is returned as a result. Nifty? Nifty.
Applicatives
So, the last piece of the puzzle is this: You have multiple monads, and you want to add the result of them without binding temporary variables. This can be done with Applicative Functors. They are like Functors, but with some added goodies. To use Applicative functors, include Control.Applicative and test out this chunk of code:
main = fmap putStrLn $ pure (++) <*> (openFile "test.txt" ReadMode >>= hGetContents) <*> (openFile "test2.txt" ReadMode >>= hGetContents)
This will take the ++ function, turn it into one which can work with Applicatives, and then apply it partially over the <*> elements. If the function can already handle Applicatives, then <$> can be used instead.
In Conclusion
Monads were a tricky subject for me for a long time. Most of my programs look like my first chunk of code, where I did one monadic operation per line. However, learning to master Monads in Haskell to control side-effects and efficienty keep track of your state is of utmost importance in commanding the language. So go on, don't pick up that monad. Wear that >>= with pride. | http://profectium.blogspot.com/2014/01/using-monads-in-haskell.html | CC-MAIN-2015-22 | refinedweb | 503 | 74.59 |
:
How to use the Arc Teleport in Vizard
Vizard 7 now includes the ability to move through VR using the “arc teleport” method, as well as “snap rotation” for rotating. This is an effective way to navigate large spaces while eliminating any motion sickness associated with smooth movement using a controller. If a target is valid, you will see a green “arc” project out with a platform showing where you will teleport to. If a target is not valid (such as the side of a wall), the arc will be red and no platform will be shown.
Presets
There are presets that you can quickly choose from to allow this to be used with either the Oculus line of headsets, Vive/Steam VR line (which includes the Vive Pro, Vive Cosmos and more), as well as the WinMR line of headsets.
For Vive and SteamVR headsets, Use RH Trackpad to teleport (click once to place, and release to teleport) and LH Trackpad for smooth locomotion. For Oculus headsets, use RH 'B' button to teleport and LH Stick for smooth locomotion.
Setting Up Manually
To add an arc teleport manually, follow these steps:
Choose the “Advanced Configuration” menu
From the “Transports” tab, choose “Virtual- Arc Teleport”
Click “Add a group” under “arc source node”, give it a name if you like and then select that group to be the arc source node. Can also adjust the range of the arc and, if you’re using multiple transports, choose a transportation group.
In the vizconnect “Scene Graph” drag the group to be under the hand or object you want the arc to project from. In this case, we’re using the right hand.
Then, drag the avatar to be under the arc teleport transport you added
Lastly, click on “Mappings” and choose which button you want to initiate the arc teleport. To have the snap button be used to both place and teleport, use the “while” and “while not” options
You can now use the arc teleport in any scene you apply this vizconnect file to
Snap Rotation
For a vizconnect with added “snap” rotations, download a premade vizconnect file here (for the Vive/SteamVR preset).
You can modify which buttons are used to rotate under the “Events” tab under “Mappings”
To set up snap rotation manually, follow these steps:
Add a custom event under the “Events” tab and name one “Snap_Left” and a second one named “Snap_Right”
Under “Mappings” choose which buttons you want to use to rotate
Add this code in the postinit section of your vizconnect file by opening the vizconnect directly in Vizard and editing it:
def turnLeft(e):
vizconnect.getRawTransport('main_transport').snapLeft()
viz.callback(viz.getEventID('SNAP_LEFT'), turnLeft)
def turnRight(e):
vizconnect.getRawTransport('main_transport').snapRight()
viz.callback(viz.getEventID('SNAP_RIGHT'), turnRight)
Undoing a Teleport
Using a similar method to adding the events for snap rotation, create an event to use the undo teleport method, set your mappings and add this code to your postinit section:
def UndoTeleport(e):
vizconnect.getRawTransport('main_transport').undoTeleport()
viz.callback(viz.getEventID('UNDO_TELEPORT'), UndoTeleport)
For additional modifications and questions, see the Vizard documentation or contact support@worldviz.com
For more information on any of Worldviz products
Underwater Effect
The example script in this article simulates the type of visual distortion that occurs in an underwater scene. It uses a custom post-process effect created using Vizard's vizfx.postprocess library and GLSL (OpenGL shading language).
Read more
Launching
Introduction
Lens Correction
Vizard can perform lens correction on the output image to account for distorted displays, such as HMDs. The video below shows a scene with and without lens correction.
Read more
Embedding resources in scripts
This article describes how to embed certain texture and model resources within your script. Using this technique allows you to distribute or move your script to different locations without needing to worry about copying any resources along with it. | http://kb.worldviz.com/topic/scripts | CC-MAIN-2021-31 | refinedweb | 651 | 53.75 |
I am a massive AWS Lambda fan, especially with workflows where you respond to specific events.
In this tutorial, I will keep it basic to demonstrate the power of how you can trigger a AWS Lambda function on a S3 PUT event, so that this can give the reader a basic demonstration to go further and build amazing things.
What will we be doing?
In this tutorial we will be converting CSV files to JSON with the help of Lambda using the Python language.
The workflow will be like this:
- User uploads his csv file to S3, lets say bucket/input/*.csv
- We then use CloudWatch events to trigger when data is uploaded to the bucket/uploads/input prefix and has a suffix of .csv
- We will then trigger our Lamda function to convert the CSV file and write the JSON file to bucket/uploads/output/{year}/{month}/{day}/{timestamp}.json
You can go furhter than that by using S3 Lifecycle Policies to delete objects when they are older than, lets say 30 days.
Create the S3 Bucket
Head over to AWS S3 and create a New Bucket (or use an existing one):
Use a descriptive name of your choice:
Then your S3 bucket should appear in your console:
Create your Lambda Function
Head over to AWS Lambda and create a function. I will be using Python 3.7 and will be calling it
csv-to-json-function:
You can then save the function as is, we will come back to the code.
S3 Events
So what we essentially want to do, when ever someone uploads an object to S3, which MUST match the prefix
uploads/input and has the suffix of
.csv we want to trigger our Lambda function to act on that event to load the CSV and convert that object to JSON.
Head over to your S3 Bucket:
Select properties and and select events:
and you should see:
click add notification and provide what needs to happen. This step is very importantand should not be done wrong as it could incur in a lot of costs f done wrong.
We are configuring this S3 Event to trigger a Lambda Function when a object is created with a prefix for example:
uploads/input/data.csv , lets say for example your Lambda function writes a
.csv file back to the input prefix, your Lambda will go in a triggering loop and will cost a LOT of money, so we have to make sure that our event only listens for
.csv suffixes on a
uploads/input prefix.
Provide a Name, on the PUT event, provide the prefix
uploads/input as an example, then provide the suffix
.csv as we only want to trigger if csv files are uploaded and trigger your Lambda function:
it should look like:
IAM User
Now we want to create a IAM user that will be uploading the CSV files to S3.
Head over to IAM, select Policies, Create Policy:
{ "Version": "2012-10-17", "Statement": [ { "Sid": "VisualEditor0", "Effect": "Allow", "Action": [ "s3:PutObject" ], "Resource": "arn:aws:s3:::ruanbekker.demo.blogpost/uploads/input/*" } ] }
I will call this policy
s3-uploads-csv-policy, select users, create a new user and tick programmatic access:
Hit next, assign the policy to the user:
Hit create user and make note of your aws access and secret key as the secret key is not retrievable after creation:
AKIAXXXXXXXXXXXXXXXX ZCTfXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Head to your terminal and configure the credentials for that user, I will configure it under the profile
csv-uploader:
$ aws configure --profile csv-uploader AWS Access Key ID [None]: AKIAXXXXXXXXXXXXXXXX AWS Secret Access Key [None]: ZCTfXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX Default region name [None]: eu-west-1 Default output format [None]: json
Lambda Function
Let's head back to Lambda and write some code that will read the CSV file when it arrives onto S3, process the file, convert to JSON and uploads to S3 to a key named:
uploads/output/{year}/{month}/{day}/{timestamp}.json
When the S3 event triggers the Lambda function, this is what's passed as the event:
{ "Records": [ { "eventVersion": "2.1", "eventSource": "aws:s3", "awsRegion": "eu-west-1", "eventTime": "2020-04-08T19:50:35.471Z", "eventName": "ObjectCreated:Put", "userIdentity": { "principalId": "AWS:x" }, "requestParameters": { "sourceIPAddress": "102.132.218.115" }, "responseElements": { "x-amz-request-id": "x", "x-amz-id-2": "x/x/x" }, "s3": { "s3SchemaVersion": "1.0", "configurationId": "TriggerLambdaToConvertCsvToJson", "bucket": { "name": "ruanbekker.demo.blogpost", "ownerIdentity": { "principalId": "x" }, "arn": "arn:aws:s3:::ruanbekker.demo.blogpost" }, "object": { "key": "uploads/input/foo.csv", "size": 0, "eTag": "x", "sequencer": "x" } } } ] }
So we have context on the key name as well as the bucket name.
Onto the code of our Lambda Function, there's probably better ways such as streaming to do this, but the focus is on what the task is doing and not really on the code.
I am reading the CSV file, writing it to the
/tmp directory (only path which is writable), processing the data convert to json and write as a json file, then uploads to S3 and remove the files from the disk:
import json import csv import boto3 import os import datetime as dt s3 = boto3.client('s3') def lambda_handler(event, context): datestamp = dt.datetime.now().strftime("%Y/%m/%d") timestamp = dt.datetime.now().strftime("%s") filename_json = "/tmp/file_{ts}.json".format(ts=timestamp) filename_csv = "/tmp/file_{ts}.csv".format(ts=timestamp) keyname_s3 = "uploads/output/{ds}/{ts}.json".format(ds=datestamp, ts=timestamp) json_data = [] for record in event['Records']: bucket_name = record['s3']['bucket']['name'] key_name = record['s3']['object']['key'] s3_object = s3.get_object(Bucket=bucket_name, Key=key_name) data = s3_object['Body'].read() contents = data.decode('utf-8') with open(filename_csv, 'a') as csv_data: csv_data.write(contents) with open(filename_csv) as csv_data: csv_reader = csv.DictReader(csv_data) for csv_row in csv_reader: json_data.append(csv_row) with open(filename_json, 'w') as json_file: json_file.write(json.dumps(json_data)) with open(filename_json, 'r') as json_file_contents: response = s3.put_object(Bucket=bucket_name, Key=keyname_s3, Body=json_file_contents.read()) os.remove(filename_csv) os.remove(filename_json) return { 'statusCode': 200, 'body': json.dumps('CSV converted to JSON and available at: {bucket}/{key}'.format(bucket=bucket_name,key=keyname_s3)) }
Save the Lambda function.
Upload CSV to S3
Back to your terminal, create a CSV file, in my case:
$ cat > data.csv << EOF name,surname,age,country,city ruan,bekker,33,south africa,cape town james,oguya,32,kenya,nairobi stefan,bester,33,south africa,kroonstad EOF
Now upload the data to S3
uploads/input/foo.csv . The destination filename can be anything, as long as the prefix is
uploads/inputs and suffix with
.csv:
$ aws --profile csv-uploader s3 cp data.csv s3://ruanbekker.demo.blogpost/uploads/input/foo.csv upload: ./data.csv to s3://ruanbekker.demo.blogpost/uploads/input/foo.csv
As we can see from our Lambda Execution Logs on CloudWatch, our execution was successful:
Looking at S3, we can see our key was created as
bucket/uploads/output/{year}/{month}/{day/{timestamp}.json
Selecting our object, hit actions and select open, we can see that our CSV file was converted to JSON (note: I pretty printed the file manually for better readability):
Thank You
This was a very basic example of what you can do with S3 Events and Lambda, the sky is the limit, you can do awesome things! | https://sysadmins.co.za/convert-csv-to-json-files-with-aws-lambda-and-s3-events/ | CC-MAIN-2021-10 | refinedweb | 1,205 | 53.71 |
Tooling Tuesday: Catch the news!
Right now there is a lot of news going on, stay informed!
So what is it?
Newscatcher is a Python library to collect the news from the top one thousand websites using the Newscatcher API
So how do I install it?
Via pip!
Linux / Mac
pip3 install newscatcher
Windows
pip install newscatcher
So how do I use it?
First we need to import the Newscatcher library into our code.
from newscatcher import Newscatcher
Then we tell the library which website we want to get the news from. In this case the New York Times.
website = Newscatcher('nytimes.com')
The URL (web address) of the site should have no http:// or www, for example bigl.es rather than.
Now we get the top ten headlines from that website.
website.print_headlines(n = 10)
Running these few lines in the Python REPL I received this output.
1. | Coronavirus Live Updates: Costs of Containment Grow; New York City Braces for a Deluge of Patients 2. | Global Stocks Rally on Hopes of a U.S. Economic Deal: Live Updates 3. | Trump Considers Reopening Economy, Over Health Experts’ Objections 4. | Democrats Again Block Action on Coronavirus Stimulus, Seeking Restrictions on Corporate Aid 5. | How an Upscale Connecticut Party Became a Coronavirus 'Super Spreader' 6. | Free Access to Coronavirus Coverage 7. | Trump Has Given Unusual Leeway to Fauci, but Aides Say He’s Losing His Patience 8. | In Daily Coronavirus Briefing, Trump Tries to Redefine Himself 9. | Texas and Ohio Include Abortion as Medical Procedures That Must Be Delayed 10. | Dip in Italy’s Cases Does Not Come Fast Enough for Swamped Hospitals
We cannot get the news from every website, for example I tried BBC News and The Guardian and I got an exception error message
Exception: website is not supported
Your help makes this blog possible!
Sorry to interrupt! It would be great if you could buy me a cup of coffee / make a donation via Ko-Fi. It helps me to pay for hosting this blog, and to buy stuff to hack from Poundshops / Dollar Stores / Aliexpress which are used in free projects on this blog. Thanks!
So can we build a quick project with this?
Sure!
This nine line Python script will create a quick app to send the top three headlines from wired.co.uk to the desktop as notifications. For this I installed the
notify2 Python library.
pip3 install notify2
Here is all the code!
import notify2, time from newscatcher import get_headlines news = get_headlines('wired.co.uk') notify2.init("Latest News from Wired.co.uk") for i in range(3): n = notify2.Notification(news[i]) n.show() print(news[i]) time.sleep(1)
I also print each headline to the REPL for debug. | https://bigl.es/tooling-tuesday-catch-the-news/ | CC-MAIN-2020-29 | refinedweb | 457 | 76.32 |
Somtimes, we need write and read some information in windows registry. In this tutorial, we will intorduce you how to do using winreg library.
Preliminary
We should import winreg library.
import winreg
We should notice: windows registry is organized as a tree structure.
In order to write and read information from registry, we should notice the key.
Write information to windows registry
In this example, we will write some information in HKEY_CURRENT_USER.
Here is an example:
path = winreg.HKEY_CURRENT_USER def save_reg(k = 'pdfpagespliter', v = 0): try: key = winreg.OpenKeyEx(path, r"SOFTWARE\\") newKey = winreg.CreateKey(key,"ByteBash") winreg.SetValueEx(newKey, k, 0, winreg.REG_SZ, str(v)) if newKey: winreg.CloseKey(newKey) return True except Exception as e: print(e) return False
In this example, we will write {pdfpagespliter: 0} in HKEY_CURRENT_USER\SOFTWARE\ByteBash
ByteBash does not exist in HKEY_CURRENT_USER\SOFTWARE\, we will create it using winreg.CreateKey() firstly.
Then will use winreg.SetValueEx() to write key and its value.
Run this function, you will find this result.
Read information from windows registry
We also will write a function to read information from windows registry.
Here is an example:
def read_reg(k = 'pdfpagespliter'): try: key = winreg.OpenKeyEx(path, r"SOFTWARE\\ByteBash\\") value = winreg.QueryValueEx(key,k) if key: winreg.CloseKey(key) return value[0] except Exception as e: print(e) return None
In order to read information from windows registry, we should open a key and read value.
The core code is:
value = winreg.QueryValueEx(key,k)
You should notice: the value is in 0 index of value. | https://www.tutorialexample.com/python-read-and-write-windows-registry-a-step-guide-python-tutorial/ | CC-MAIN-2021-31 | refinedweb | 257 | 52.76 |
Introduction
copy command (Windows) or the
cp command (Unix).
You'll notice that many of these methods, in both the
shutil module and the
os module, have very similar functionality (which shouldn't be surprising), but each varies in functionality from each other very slightly, which I'll explain as well.
Copying Files with the shutil Module
The shutil module offers several high level methods to copy files. Here below are the main ones:
copyfile
This method copies the content of one file into another file. The destination provided to it must be a writable file, and have a different name than the source file. If the names are the same then it will generate an error. If the destination file already exists, it will be replaced with the newly copied file.
The syntax for this method is:
shutil.copyfile(src_file, dest_file, *, follow_symlinks=True)
For example, the following code will copy a file named "file1.txt" into a file named "file2.txt":
import shutil shutil.copyfile('file1.txt', 'file2.txt')
One interesting and potentially useful feature of
shutil.copyfile is the
follow_symlinks Boolean argument. If it is set to
False, and the source file is a symbolic link, then instead of copying the file, a new symbolic link will be created.
copy
This method is very similar to
copyfile, with the main difference being that in addition to copying the content of the source file, it goes one step further and also copies the file's file system permissions. Copying file permissions is not a trivial task in most programming languages, so this is a nice feature to have.
The syntax is as follows:
shutil.copy(src_file, dest_file, *, follow_symlinks=True)
Each of these parameters are the same as in the
copyfile method. For example, the following code will copy "file1.txt" into "file3.txt".
import shutil shutil.copy('file1.txt', 'file3.txt')
Note: Make sure you don't name your script the same as one of the module you're importing (which I mistakenly did when testing code for this article). If you do, then you'll get an error when trying to import that module due to a circular import problem.
copy2
As with the previous methods,
copy2 method is identical to the
copy method, but in addition to copying the file contents it also attempts to preserve all the source file's metadata. If the platform doesn't allow for full metadata saving, then
copy2 doesn't return failure and it will just preserve any metadata it can.
The syntax is as follows:
shutil.copy2(src_file, dest_file, *, follow_symlinks=True)
Again, these parameters are the same as in the previous commands we've mentioned so far.
For example, the following code will copy "file1.txt" into "file4.txt", as well as preserve the metadata of the original file, "file1.txt".
import shutil shutil.copy2('file1.txt', 'file4.txt')
$ python copy-files.py $ ls -l total 32 -rw-r--r-- 1 scott staff 91 Oct 27 11:26 copy-files.py -rw-r--r-- 1 scott staff 6 Oct 27 11:27 file1.txt -rw-r--r-- 1 scott staff 6 Oct 27 11:29 file3.txt -rw-r--r-- 1 scott staff 6 Oct 27 11:27 file4.txt
As we can see from executing our code above, "file1.txt" was copied to "file4.txt". However, you may have noticed the creation date was preserved on the new file, unlike with
shutil.copy, which copied "file1.txt" to "file3.txt" and gave it a new creation date.
copyfileobj
This method copies the content of a source file into a destination file, from the current source-file position. What this means is that if you read data from your source file object, then the position you stop reading at is the position
copyfileobj starts copying from.
The syntax is as follows:
shutil.copyfileobj(src_file_object, dest_file_object[, length])
The meanings of source and destination file parameters are similar to the previous commands, but now, they refer to objects. The length parameter is optional and represents the buffer size that is the number of bites kept in memory during the copy process. This option can be useful when copying very large files, as it can speed up the copying process and avoids uncontrolled memory usage.
For example the following code will copy "file1.txt" into "file5.txt"
import shutil filename1 = 'file1.txt' fileA = open(filename1, 'rb') filename2 = 'file5.txt' fileB = open(filename2, 'wb') shutil.copyfileobj(fileA, fileB)
As we can see, in order to use
copyfileobj, we need to open the files in binary mode (which is the "b" part of "rb" and "wb"). In addition, the source file must be opened as readable and the destination file must be opened as writable (the "r" and "w" parts, respectively).
Copying Files with the os Module
The os module provides a way to use the operating system functionality to copy your files. In most (if not all) of the examples from here on out we provide examples that work for both Windows and Unix. The examples are different because of the shell commands used, so be sure to pay attention to how each function call is labeled in the Python comments.
popen
This method opens a pipe to or from your command. However, note that this method was deprecated in Python 2.6, so we don't recommend using it unless you have to. As an alternative, the Python documentation advises us to use methods from the subprocess module instead.
The syntax is as follows:
os.popen(cmd[, mode[, bufsize]])
Here the value returned is a file object that is connected to the pipe. This object can be read from or written to depending on the mode. The default mode is 'r', which allows reading of the file contents.
The example below will copy "file1.txt" into "file6.txt":
import os # Windows os.popen('copy file1.txt file6.txt') # Unix os.popen('cp file1.txt file6.txt')
Running the command in this way is exactly the same as if you ran it directly from the command line of your terminal.
system
This method executes the specified command in a subshell. It is available for both Unix and Windows. The syntax is as follows:
os.system(command)
Here
command is a string containing the DOS or Unix shell command. In our case, this is where we'll put the
copy or
cp command.
For example, the following code will copy "file1.txt" into "file7.txt"
import os # Windows os.system('copy file1.txt file7.txt') # Unix os.system('cp file1.txt file7.txt')
This looks identical to the previous
os.popen command we just used, but the command is executed in a subshell, which means it is executed in a separate thread in parallel to your executing code. To wait for its completion, you need to call
.wait() on the object returned by
os.system.
Copying Files with the subprocess Module
The subprocess module intends to replace some methods in the
os module (particularly
os.system and the
os.spawn* methods), and it presents two main methods to access the operating system commands. These methods are
call and
check_output. Once again, for Unix systems, the command "copy file1.txt file2.txt" should be replaced by "cp file1.txt file2.txt".
call Method
The Python documentation recommends us to use the
call method to launch a command from the operating system.
The syntax is as follows:
subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False)
The
args parameter will include our shell command. However, a word of caution, as the Python documentation warns us that using
shell=True can be a security risk.
Using this function call, we can run our copy command as follows:
import subprocess # Windows status = subprocess.call('copy file1.txt file8.txt', shell=True) # Unix status = subprocess.call('cp file1.txt file8.txt', shell=True)
As the example above shows, we simply need to pass a string with the shell command, as before.
And as expected, the operating system will copy "file1.txt" into a file named "file8.txt".
This method also allows us to execute a command within a shell. It is very much like the
subprocess.run command, except that by default it pipes data from stdout as encoded bytes. The syntax is as follows:
subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, universal_newlines=False)
Here the
args parameter includes the shell command we want to use. Once again, the Python documentation warns us of using
shell=True, so use this method with caution.
In the following code we'll copy "file1.txt" to "file9.txt" using the
import subprocess # Windows status = subprocess.check_output('copy file1.txt file9.txt', shell=True) # Unix status = subprocess.check_output('cp file1.txt file9.txt', shell=True)
And as with all of the commands we've shown in this article, this will copy the file "file1.txt" to the destination we specified, which is "file9.txt" here.
Wrapping Up
Python offers us many different ways to copy files, some of which are part of the Python set of methods. Others use some of Python's powerfull methods to execute commands in a shell, which utilize shell commands like
copy or
cp.
Not sure which one is right for you? We presented a lot of different ways to copy files here, so that's understandable. The method you use to copy a file is completely up to you and will depend on your specific needs. Although in most cases one of the
shutil commands will work just fine for you. Try starting with
shutil.copy2 and see if that does what you need.
Which method do you use and why? Let us know in the comments! | https://stackabuse.com/how-to-copy-a-file-in-python/ | CC-MAIN-2019-43 | refinedweb | 1,623 | 67.65 |
Hi,
I want to invoke PyCharm from command line with specifying file name and line number, similar to emacsclient.
For example, emacsclient command invokes Emacs such as:
$ emacsclient -n +123 example.py
Or mate command to invoke Textmate:
$ mate -l 123 example.py
Is there any equvarent command to emacsclient or mate for PyCharm?
Thank you.
Hello makoto,
Not yet. It's likely that we'll support this in PyCharm 1.1.
--
Dmitry Jemerov
Development Lead
JetBrains, Inc.
"Develop with Pleasure!"
This is very good to know! Thanks for this feature!
Hi Dmitry, thank you for your replay.
I wonder that it may be a little hard to create 'mate'-like command for PyCharm because it is implemented in Java which is os-independent language.
Eclipse also doesn't provide 'mate'-like command, but it has a small plug-in to accept file name and line number via TCP port.
eclipsecall:
This plugin invokes a small server in Eclipse, and client can send file name and line number to it.
## client program example
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('localhost', 2341))
sock.send('file.txt|123')
sock.close()
I hope this will help you to implement 'mate'-like command for PyCharm. | https://intellij-support.jetbrains.com/hc/en-us/community/posts/205801599-How-to-invoke-PyCharm-from-command-line-with-file-name-and-line-number- | CC-MAIN-2019-22 | refinedweb | 206 | 68.97 |
List deployments and deploy directly from Strapi.
🕹 f3l1x.io | 💻 f3l1x | 🐦 @xf3l1x
To install latest version use NPM.
npm install --save strapi-plugin-vercel
If you want to use Vercel as a platform for your website built on Strapi, you need to tell Vercel when to rebuild your site. Of course, you can use webhook, but it can trigger a lot of pipelines. With this plugin, you will have a recreation of the vercel dashboard on your strapi dashboard, with which you can easily trigger deploys.
This plugin solves:
Install plugin.
Edit configuration.
{strapi}/config/server.js
There must be root key
vercel.
module.exports = ({ env }) => ({ { ... }, vercel: { // Required token: env('VERCEL_TOKEN'), // Required projectId: env('VERCEL_PROJECT_ID'), // Optional (required if you use teams) teamId: env('VERCEL_TEAM_ID'), // Required (hooks) triggers: { production: env('VERCEL_TRIGGER_PRODUCTION') }, // Optional config: { // Number of latest deployments deployments: 10 } } });
Token is required.
Generate token on. You should set the scope to your team.
Team ID is optional, but if you set team's scope to your token, than you should provide team ID.
You can find it on your team's settings page:{team}/settings.
It should begin with
team_.... If you use personal account, you don't need it.
Project ID is required.
You can find it on your projects's settings page: h{team}/{project}/settings
It should begin with
prj_.... If you use personal account, you still need it.
Trigger (deploy hook) is required.
You can generate it on your projects's settings git page: h{team}/{project}/settings/git | ^^ ^^ | / project id / hook id /
Copy only hook id.
Edit administration section. Create these directories if you don't have them yet.
{strapi}/admin/src/containers/HomePage/index.js
import React, { memo } from "react"; import { Padded } from "@buffetjs/core"; import { Header } from "@buffetjs/custom"; import { Deployments, DeployButton } from "./../../../../plugins/strapi-plugin-vercel/admin/src/view"; const Dashboard = () => { return ( <> <Padded top right left <Header title={{ label: "Dashboard" }} actions={[ { Component: DeployButton }, ]} /> </Padded> <Padded right left <Deployments /> </Padded> </> ); }; export default memo(Dashboard);
Profit 🚀
Consider to support f3l1x. Also thank you for using this package. | https://openbase.com/js/strapi-plugin-vercel | CC-MAIN-2022-40 | refinedweb | 341 | 58.79 |
A Unity ID allows you to buy and/or subscribe to Unity products and services, shop in the Asset Store and participate
in the Unity community.
Using TMPro;
public class TextMeshProDemo : MonoBehaviour {
[SerializeField]
private TextMeshPro textMeshPro;
void Start() {...
Stop() method is obsolete in Unity 2019 or greater versions. So use enabled flag and set it to false for disable the animation....
Ensure that the scene contains EventSystem
Don't forget to add EventSystem in your scene. If the scene doesn't have any event trigger is not able to track any events that's happening in the...
if(Application.internetReachability == NetworkReachability.NotReachable)
{
Debug.Log("Error. Check internet connection!");...
You can try this one
It's happened due to the low-quality score of the image. ARCore reference image library accepts images of type .png and .jpg only. Also, It shows...
I think you are not enabled the Vuforia support in Player settings -> XR Settings.
public static string GetLocalIPAddress()
{
var host = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName());
foreach (var... | https://forum.unity.com/search/6238150/ | CC-MAIN-2021-25 | refinedweb | 170 | 51.14 |
Skipping an article in CityScript
A chunk of one of my pages:
<h3>Top story</h3>
<P>{$foreach 1 x in (folder "Articles")$} </P>
<P><A href="{$x.link$}">{$x.headline$}</A><BR>
<FONT size=1>{$setDateTimeFormat "English" "dd MMM, yyyy" "hh:mm"$}{$x.filedDate$}</FONT>
<BR>
{$x.body$}</P>
<P>{$x.extra2$}</P><table border="0" bgcolor="#99ffff">
<tr>
<td width="100%"><b> {$x.sidebar$}</b></td>
</tr>
</table>{$next$}
<hr>
<h3>Previous stories</h3>
<P>{$foreach 10 x in (folder "FrontPageNews")$} </P>
<P><A href="{$x.link$}">{$x.headline$}</A><BR><FONT
size=1>{$setDateTimeFormat "English" "dd MMM, yyyy"
"hh:mm"$}{$x.filedDate$}</FONT>
<BR>
{$x.teaser$}<BR> {$x.extra2$}</P>
<P>{$next$}
The effect of this is to show the full text of the top story, and then just headlines and teaser info for stories 1-10.
What I'd really like, of course, is to show headlines and teaser info for stories 2-10, rather than repeating the headline for the first story.
I'm probably just missing some obvious CityScript feature here, right?
(If you want to see the page in action, it's at )
Mike Gunderloy
Saturday, December 28, 2002
Oops...assume the same folder name for both foreach loops...
Mike Gunderloy
Saturday, December 28, 2002
the best way I can think of to do this would require you to change the first article in some way: put it in a different folder or add a keyword. This requires a little bit of maintenence, e.g., moving the article from the "FIRST ARTICLE" folder to the "OTHER ARTICLES" folder...
Joel Spolsky
Tuesday, December 31, 2002
Well, if you can't think of a better way, I'm pretty sure there isn't one :)
I tried the "separate folder" solution for a while - the problem is that external links then break when I move the article to the permanent folder. I've got a custom 404 page that takes care of that, but still, a nuisance.
Keywords, though, is an obvious solution that I should have thought of myself.
Meanwhile, you might add "generalized foreach" to the "vague and impossible to implement customer wishlist" section of your CityDesk 2 planning.
Mike Gunderloy
Wednesday, January 1, 2003
I you have a custom 404 page, you can make it 'active' (by adding client or server side scripts). Also, if you are allowed to redirect 404's you may be allowed create a redirection list as well. So you can redirect all first/articles to older/articles and control this by cityscript.
Adriaan van den Brand
Thursday, January 2, 2003
Yup, I already use my 404 scripting to fix things up. Poor solution, though; if you do a server-side redirect, then the bad links hang around out there and continue to cause extra work and confusion; if you do a client-side redirect, it takes extra time for the browser.
Mike Gunderloy
Thursday, January 2, 2003
For server side redirect: you can specify the return code so spiders etc. know that the page has moved. But it is still a poor work around for a limitation in cityscript.
You could maintain a variable which you keep set to (say) the filename of the first article, then use SSI conditionals to supress the unwanted summary as the page is served.
To make this technique more automatic, you could have an outer loop selecting only the first article, and an inner one selecting all 10. This will still only loop through all 10 articles once, but you can compare the two sets of loop variables in SSI to select a different format for the first article. Something like :
{$foreach 1 x in (folder "foo")$}
{$foreach 10 y in (folder "foo")$}
<!--#if expr=" '{$x.filename$}' = '{$y.filename$}' " -->
{$y.body$}
<!--#else -->
{$y.teaser$}
<!--#endif -->
The pre-SSI HTML could get rather long this way, but if you also use SSI to include the article body, only the one you want will get pulled in. This may involve creating a new template family, though.
Michael Wild
Thursday, January 2, 2003
Have you noticed that the foreach 10 doesn't seem to always only get you 10?
I am just putting together my site now, so the .filedate property on all the files is the same. When I use code straight from the help file to get the 10 highest filedates, I actually get 12-16 files...
So I'd say don't count on getting explicitly the number of files that the foreach specifies.
John
John
Friday, January 17, 2003
Recent Topics
Fog Creek Home | https://discuss.fogcreek.com/CityDesk/5120.html | CC-MAIN-2019-22 | refinedweb | 763 | 62.48 |
User talk:Muffinscope
From Uncyclopedia, the content-free encyclopedia
edit ToblerONE
This article and its sub-articles appear to be some sort of inside joke with a lot of vanity references and as such have been nominated to Uncyclopedia:Pages for deletion. If you would like the article can be saved as a personal page by moving it to User:Muffinscope/ToblerONE; I will probably do so for you if it is voted for deletion. --Sir gwax (talk)
19:39, 30 January 2006 (UTC)
- Hello there. Since your own talk page mentions not replying there, hopefully you will see this message soon. I have a point I'd like to make regarding the toblerONE page that you listed for deletion, and a question to ask.
- First off regarding "vanity," I would like to mention that the user name was chosen specifically because it was a key point in the article (and not the other way around, i.e. it's a key point in the article because it's my username, which would be vanity). I don't know if you'd still consider it vanity in this case, but it does change the scenario. We (there were four writers) only created the username so we could upload the various images, hence the username being based off the article.
- Secondly, you list it for deletion because it "seems to be another fantasy world sort of thing." Could you please point me in the direction of the elements of the article that lead you to believe this is about some sort of fantasy world? There are plenty of Uncyclopedia articles about time travel, which is the only major stretch the article makes, in my opinion.
- I apologize that you find it stupid and not funny. We put a lot of effort into it, and it does make a lot of (in fact, it is mostly) inside jokes. Because of that, it probably will not be saved, but I like to think that at least some people will see the humor in it, or catch the references (they're not just inside jokes to my circle of friends, there are inside jokes to things that potentially plenty of readers will catch).
- Thank you for your time. Muffinscope 00:03, 31 January 2006 (UTC)
- Two other points I want to make (and I hope you respond to these soon) regarding the inside joke status of the page. First, if inside jokes are seriously that frowned upon, why is there an entire category devoted to them? Secondly, I'd like to point out that large parts of the article are not inside jokes (for example, the conspiracy theory section should be fairly universally understandable and funny). I would appreciate it if you responded to these points soon. Thank you. Muffinscope 17:58, 31 January 2006 (UTC)
Ok, I'm willing to accept the possibility that I just don't get it, which happens sometimes but it really does seem like an inside joke to me. In general, inside jokes are frowned upon; Category:Inside jokes primarily contains jokes that are inside to Uncyclopedia and funny to the general public (Kitten Huffing, AAAAAAAAA!, etc.) or that are inside to admins and manage to sleeze past policies (Edit War (video game), Fisher Price, etc.). Based on my analysez of toblerONE and the possibility that I might be wrong or other people would find it funny, I put it up on vfd and as such it's no longer a matter for me to make executive decisions about. I strongly recommend weighing your case on vfd and seeing how other people feel about the matter. Thanks and I hope this can be resolved amicably. --Sir gwax (talk)
19:32, 31 January 2006 (UTC)
edit VFD
Are you following the discussion on Uncyclopedia:Pages for deletion? There's some good discussion going on there and a few suggestions that might allow your article to remain in the general namespace. --Sir gwax (talk)
05:37, 2 February 2006 (UTC) | http://uncyclopedia.wikia.com/wiki/User_talk:Muffinscope | CC-MAIN-2014-35 | refinedweb | 670 | 57.4 |
95494/please-provide-shell-script-which-runs-migrate-from-svn-git
Hi@shashi,
You can run the git-svn command. If you are trying to run with python script then run the command with os.system.
$ git svn clone <address>
You don't need any advanced knowledge. You need to import some modules in your script.
import os
os.system("git svn clone <address>"
user_data should be used as it is ...READ MORE
One idea would be to launch the ...READ MORE
use feature flags as a solution to ...READ MORE
Hi!
You can start off by understanding ...READ MORE
There are API docs in the footer ...READ MORE
Download necessary CA certificate.
"/etc/ssl/certs/ca-certificates.crt", -> Debian/Ubuntu "/etc/pki/tls/certs/ca-bundle.crt", ...READ MORE
You can use unless inside your state ...READ MORE
Use the following command
cf restart-app-instance
This will issue ...READ MORE
I would first check which part of ...READ MORE
Hi@Lakshminarayanan,
You can find command to remove your ingress ...READ MORE
OR
At least 1 upper-case and 1 lower-case letter
Minimum 8 characters and Maximum 50 characters
Already have an account? Sign in. | https://www.edureka.co/community/95494/please-provide-shell-script-which-runs-migrate-from-svn-git | CC-MAIN-2021-31 | refinedweb | 197 | 70.7 |
>>: (Score:1)
They must lose the power to do this.
No one can be trusted. The system/infrastructure must be designed to take into account untrustworthiness of all parties involved. WoT [wikipedia.org].
Re: (Score:2)
If you think that might work, then keep learning. The botnets' "vote" only gets counted if someone decides to trust all of them. And if you can arrange that, then you don't need a botnet, you just need one node.
All that matters is how your fake node (or web of fake nodes) is connected to the victim.
Re: (Score:2)
Oops, didn't realize we were talking about something like that.
That plugin is a kind of neat idea (I approve) but it's very poorly named and doesn't seem to have anything in common with a real "web of trust." I'd probably be madder about the atrocious name if I didn't happen to like the plugin.
That gives me an idea: I should make a program for X11 users, where the five hundredth and ninth time someone opens a new window, it generates a PDF containing an extravagant statement of the accomplishment. Then I
Re:Repercussions? (Score:5, Insightful)
This yet again highlights that the three-party trust system is broken.
There are ways around it, but there is no great solution - only workarounds.
Re:Repercussions? (Score:4, Interesting)
Re: (Score:2)
Re: (Score:2)
Never do business with anyone who outsources customer service at all. The 'representative' only has the power to read from the flip chart. They absolutely do not have the authority to fix the problem and they do not know who does or how to contact them.
Re: (Score:2)
Re: (Score:2)
They do know who the boss is and who his boss is. They know who signs their paychecks. They may not tell, but they know.
With internal CS, there is at least a chance that it is supposed to be more than an impenetrable barrier between the customer and someone with authority.
Re: (Score:2)
Outsourced customer service is generally paid by the call. This means that the ideal call is a short one where the customer is satisfied enough not to raise a ruckus, but will run into problems and have to call back. Even if there is any way to pass feedback to the software vendor, it isn't in the customer service's interest to provide it, as clarifying a confusing thing in the software could lead to serious loss of revenue. That also means that the software vendor doesn't have the information to either
Re: (Score:3)
What happens now is that there's an investigation. Depending on the outcome the CA may be revoked for good, or merely forced to reissue lots of certificates. The deciding factor is the reason for the screwup - for instance they may have got hacked, rather than been actively corrupt. In that case Microsoft will have to decide if they have patche
Re: (Score:3)
Expecting CA's to be able to reliably fight off professional hackers from dozens of governments and never ever fail is likely an impossible standard to ever meet.
Yet that is exactly what they are supposed to do. Its not even really that hard.
Every CA hack to date has been preventable as was the fault of the CA simply not putting the required effort into doing their job or being flat out malicious. Stop trying to make it out like its an uber hard job, its not.
Re: (Score:2)
Who do they think they are? (Score:5, Funny)
Re: (Score:1)
Who in the world do you think gathers intelligence?
Only the NSA?
Need a bridge? I have one for sale.
Re: (Score:2)
Re: (Score:1)
Strawman? Not so much.
So does the NIC have a legal mission to gather intelligence? Does forging certificates constitute legitimate intelligence collection?
Who can say? Do you have any thoughts on the matter?
Re: (Score:2)
Name one intelligence agency that doesn't use other government agencies to assist its endeavours.
Re: (Score:2)
Re: (Score:2)
All countries keep an eye on their neighbours, just like all people keep a general awareness of their surroundings. All countries don't tap the phones of their neighbours's leaders, or install malware on equipment sold to them, or even spies over. Morals aside, taking hostile action tends to backfire, as the US is learning. Reputation is a resource, and
Re: (Score:2)
Typical (Score:1)
Good old Indian "ethics".
Re: (Score:3, Insightful)
Re: (Score:1)
All about trust (Score:2)
Re: (Score:3)
Re:All about trust (Score:5, Insightful)
And, really, if the US is saying it's their right to tap into anything they want to
... how is it different when India does it?
India already forced BlackBerry to allow them to access BBM and the like.
Uncle Sam is causing as much disruption to US businesses abroad as anything, because people are realizing that American companies are effectively just extensions of the US spy apparatus -- because the PATRIOT act means they can demand whatever data they have, and you more or less have to assume they're doing it and being prevented from telling you.
Which means Indians are already being spied on by (at least) their own government AND the USA.
Do you expect there to be sympathy for an American company when a foreign government taps into them? Because I hear an awful lot of people saying they think it's perfectly OK when the US does it to foreigners.
Re: (Score:2)
It's only fair that you either get to protest when every and any country pulls something like this, or not at all.
Re: (Score:2)
I don't disagree with you, but the hypocrisy of "but that's the job of the NSA" that I hear when someone points this out is maddening.
And one which was doing business in their country. Like it or not, Google in India is subject to India's laws.
How many corporations and people in fore
Re: (Score:2)
Still, Google may have a presence in India but it's not an Indian company,
Re: (Score:1)
The only thing that will come out of this is lack of trust for som
Re:All about trust (Score:5, Insightful)
As a US resident, I'd be perfectly content to see the heads of various rights-invading federal agencies put away in prison.
So no, it's not ok. Not for the US, not for India.
Re: (Score:2)
Agreed. They might or might not put the bodies in prison with the heads, I'm good with it either way.
:-)
Re: (Score:1)
No one is going accept a cert from them again.
Yeah. Just like no one trusts Comodo CA. Oh wait.
Re: (Score:2)
Re: (Score:1)
Remember DigiNotar ?
They went bankrupt because nobody trusted them anymore.
Re: (Score:2)
Re: (Score:2)
The whole point of issuing certs is to be a trusted third party. No one is going accept a cert from them again.
Sounds like what we need is a cert-issuing protocol based on Bitcoin security. Everyone (plus or minus epsilon) trusts that Bitcoins can't be forged.
Re: (Score:2)
Pseudonyms exist to protect people from the rabid - like yourself.
Think about the stupidity of comparing the establishment of a pseudonym to posting your SSN? LOL.
Re: (Score:1)
Funny, I looked up "Assmasher" in the White Pages and various international name lookup services and didn't get a single hit. It's almost as if you're hiding your identity no differently than the very ACs that you proclaim to want to be abolished. Man up and give us all your personal details or STFU.
Re: (Score:1)
Wow, I guess the guys who built
/. who thought AC should stand for "Anonymous Coward" didn't know that "Desler" knows best and that and AC and a registered user are exactly the same thing. Wonder why they bothered with creating the AC system? Idiots. Really. I mean, they should have just asked you obviously.
Ignoring the rest of the stupidity of what you posted, maybe you could come to realize that the difference between AC and a registered user is that registered users can develop a reputation for their
Re: (Score:1)
How does having a registered account mean anything? You can register one with a throwaway email account. Plus many registered people do use AC from time to time.
Re: (Score:2)
Because it's a pain to do so. It helps cut down on the DB anonymous posting. You can quickly discern if they're schills, flametards, et cetera.
I agree, I post on occasion as AC when I'm on another device, and like I said, I never had any problem with people posting AC until the past few years when people seem to be using it to simply spam
/. with total garbage, or hatred, et cetera.
Re: (Score:1)
Because it's a pain to do so
Yeah clicking a button and typing a couple dozen characters is sooo hard. Registration takes less than 5 minutes in total.
Re: (Score:2)
Doesn't it require a valid e-mail address and confirmation first? It certainly used to.
Re: (Score:2)
5 minutes is a lot of time for the people who go around spouting hatred and ugliness all over internet forums. This is why the don't register, because it's not worth the effort - especially when they get banned - especially if that ban is by IP.
Re: (Score:1)
No it's not.
Old-media contact info (Score:2)
Re: (Score:2)
I was gonna say set your preferences to -5 AC posts, but I can't find the setting at the moment - did they get rid of it for beta? Somebody probably can post the link to the scoring prefs.
Re: (Score:2)
Somebody probably can post the link to the scoring prefs. [slashdot.org]
Or you can click on one of the "edit" links in the score details window.
Re: (Score:2)
The difference between India and some other countries is that India is 2nd-rated enough to be caught immediately when they do something like this. That makes them more stupid, but less of a threat than, say, the US.
So SSL is nothing more than an honor system? (Score:4, Insightful)
Re:So SSL is nothing more than an honor system? (Score:5, Insightful)
Re: (Score:2)
That's a cop-out, though. Yes, there is always an element of trust in whatever you do. That's unavoidable, though it's smart to minimize the amount of trust you must put in others. Taken to the extreme it's ludicrous, as you've pointed out. But, that doesn't mean that there's no merit in limiting the amount of trust you put in third parties. Just because you can't completely trust your OS or compiler, doesn't mean that you should throw the entire concept of limiting trust out the window. It's dishonest to s
Re: (Score:2)
You're just figuring this out? Have you been living under a rock for the past ~20 years or are you just incredibly naive?
Re: (Score:3)
This is nothing new.
And, let's face it, I bet the NSA et al have demanded more private keys be handed over to them than you'll ever know about. Where's your outrage over that?
The five eyes all use each other to spy on their own (and others) citizens, and share the information among themselves. Where's your outrage over that?
I see this as a symptom of a greater problem, but no different from what a bunch of other countries are already doing.
Until someone creates
Re: (Score:2)
Until someone creates a new encryption system which isn't susceptible to MITM attacks
Uh, some of the earliest encryption algorithms ever created are immune to MITM.
The core of the MITM issue is that anything sent over it could be intercepted or spoofed.
So ALL your communication must be encrypted.
All you need a pre-shared key to initiate the connection. Whether that's a password or a certificate or something else makes no difference. What matters is the pre-sharing. You have to fucking know and trust the source of that key. If you're just using a list of certs issued by people you don't
Re: (Score:2)
Yes, and they were built for communications between two parties, who knew they'd be communicating, and could exchange keys in advance.
Now, tell me one which is applicable to the problem of a large number of potential users, all unknown up front, and coming from random devices.
The problem with modern public key encryption (and its strength as well) is that you don't need to pre-exchange keys. But this opens you up to MITM attacks
Re: (Score:3)
Anybody that looked into the SSL certificate system has known that for a very long time. Quite a few people used to use self-signed certificates, as as least there somebody that bothered to find out could be sure it was secure.
I think the fundamental brokeness of the SSL certificate system is because of deep naivety with regard to the trustworthiness of governments and because of active sabotage of by said governments way back. I hope at least that issue is fixed after Snowden. Governments are even more evi
Re: (Score:3)
SSL goes beyond the naivety of government trust. It also suffers from what amounts to a global namespace/trust/etc issue.
Any CA can issue a certificate for any domain, a domain generally can only have one certificate, and the trusted CA list is managed by the browser, not the user.
So, if you trust your government (naievely), and distrust everybody else, it won't work. Your browser will constantly be wanting to add CAs you don't trust, and might not include ones you trust. Then, if you drop a bunch of CAs
Re: (Score:2)
Indeed. That is why I wrote "governments" as in the sum of all of them. One corrupt one is enough to break things.
Re: (Score:2)
There are two TLS extensions that fix these problems - one is including your certificate fingerprint in DNS and the other is multiple signatures. Both have good standards and the industry is painfully slow to adopt them.
Re: (Score:2)
It's a shame that browsers have such freakouts over self signed certs, because there is really little difference between them and officially signed certs. IMHO SSH did a better job of this by simply having you inspect the certs the first time you log on to a site and storing the result, only freaking out if the cert changes. It eliminates the complex chain of trust that in the end comes down to just trust
Re: (Score:2)
It's a shame that browsers have such freakouts over self signed certs, because there is really little difference between them and officially signed certs
Exactly. Especially since you can get a "real" cert from one of many, many, free cert signing services. What is the point?
Re: (Score:2)
Re: (Score:2)
That is an existing capability within the SSL process. NIC will be restricted to issuing certificates only for a set of domains that are specific to India. Just be careful if you want to have financial transactions over the Web with institutions based in India.
Re: (Score:2)
There are any number of proposals out there to replace or augment CA certificates for SSL purposes (the EFF has Sovereign Keys, there is the DANE proposal to store certificates in DNS with DNSSEC security and there are other proposals out there designed to make it much harder for these kinds of "bogus certificate" type attacks)
Why aren't any of these proposals actually gaining any traction?
Re: (Score:2)
It sounds like we need the ability to limit the scope of certificate authorities to signing for only certain domains.... [ietf.org]
Internet Explorer IS vulnerable though (Score:2)
This is a big deal. If you use a browser on Windows that does NOT counter this, such as Internet Explorer, then you ARE vulnerable. I imagine Microsoft will come out with a special-purpose patch, but still, this is a pretty nasty issue.
Untrustworthy CAs have been a problem for a long time; we need mechanisms to address them. The terrible cert revocation system makes it even worse; you can't be sure that the certs are checked in many cases. Chrome's CRLSets are not the answer; they are not even the be
Isn't it time we apply name constraints? (Score:2)
I think intermediate CA certificates issued to certificate vendors, ISPs, governments, should all have name constraints so that they can be used to sign only certificates for an appropriate part of the namespace.... [ietf.org]
Not a Problem with Mozilla-Based Applications (Score:5, Informative)... [mozilla.org].!!
Corruption is cultural (Score:2) | https://it.slashdot.org/story/14/07/10/1228253/indias-national-informatics-centre-forged-google-ssl-certificates?sdsrc=next | CC-MAIN-2017-04 | refinedweb | 2,879 | 71.24 |
Agenda
See also: IRC log
<trackbot> Date: 31 March 2009
<fjhirsch> trackbot-ng, start telecon
<trackbot> Meeting: XML Security Working Group Teleconference
<trackbot> Date: 31 March 2009
<tlr_> Hi
<tlr_> On cab to airport now.
<tlr_> Might be late for call.
<fjhirsch> Scribe: Ed Simon
<fjhirsch> ScribeNick: esimon2
<fjhirsch> Next meeting: 7 April 2009, Hal Lockhart is scheduled to scribe
<fjhirsch> 24 April Kelvin, 28 April John Wray, 5 May Bruce Rich
RESOLUTION: April 14 teleconference is cancelled
<fjhirsch> Please complete F2F Registration (12-13 May) Questionnaire
<fjhirsch>
<fjhirsch> Minutes from 24 March 2009
Minutes are approved for March 24
<fjhirsch>
RESOLUTION: Minutes are approved for March 24
Editorial updates are done and have been closed
<fjhirsch> ACTION-231?
<trackbot> ACTION-231 -- Brian LaMacchia to update XML Encryption 1.1 for ACTION-227 proposal -- due 2009-03-24 -- PENDINGREVIEW
<trackbot>
<fjhirsch> ACTION-231 close
<fjhirsch> ACTION-231 closed
<trackbot> ACTION-231 Update XML Encryption 1.1 for ACTION-227 proposal closed
<fjhirsch> ACTION-225?
<trackbot> ACTION-225 -- Kelvin Yiu to propose text for a note potentially to be added to XMLDSIG provide recommendation for the two higher security level curves with reference -- due 2009-03-03 -- CLOSED
<trackbot>
<fjhirsch> ACTION-240?
<trackbot> ACTION-240 -- Magnus Nyström to add proposed text to 1.1 -- due 2009-03-31 -- CLOSED
<trackbot>
<fjhirsch> ACTION-242?
<trackbot> ACTION-242 -- Magnus Nyström to add schema comment regarding ECKeyValue -- due 2009-03-31 -- CLOSED
<trackbot>
<fjhirsch> ACTION-227?
<trackbot> ACTION-227 -- Brian LaMacchia to draft text encryption algorithms regarding ECC algorithms and what curves should be used -- due 2009-03-10 -- CLOSED
<trackbot>
<fjhirsch> ACTION-243?
<trackbot> ACTION-243 -- Scott Cantor to update 1.1 draft with DEREncodedKeyValue proposal -- due 2009-03-31 -- OPEN
<trackbot>
<fjhirsch> ACTION-244?
<trackbot> ACTION-244 -- Pratik Datta to update transforms note sec. 4.5 -- due 2009-03-31 -- OPEN
<trackbot>
<fjhirsch> ACTION-244 closed
<trackbot> ACTION-244 Update transforms note sec. 4.5 closed
<fjhirsch> New public working draft of Widget Signature, please review (31 March)
Widget signature spec will be published today; please review it.
<fjhirsch>
<fjhirsch> Planned schedule for Widget Signature, publish today, LC end of April, CR in June
Thomas says one concern is that Widget Signature's faster than XML Signature's
We would have to get XML Signature 1.1 within last call faster than is possible. They will go to CR then wait.
<tlr> tlr: wondering about dependencies and timing
<tlr> fjh: they'll wait for us when they're in CR
<tlr> tlr: ah fine
<fjhirsch> No new info on interop
Sean will be getting in test cases
Anything to talk about?
<fjhirsch> nothing noted
<fjhirsch> High level list of decisions
Thomas put out a list of design decisions in the transform note.
<fjhirsch>
fjh: Let's discuss event stream model, then other issues.
<fjhirsch>
<fjhirsch>
<tlr> tlr: happy for pratik to go first
Pratik: High level comments are
about why declarative model is needed.
... Main concern is with procedural models is that more steps make it harder to know what is signed.
... Model needs to be easy to understand so it is easy to know what is signed and what is not.
... That is biggest advantage of declarative model.
fjh: +1 to declarative model
<klanz2> you mean what of the referenced data object is actually covered by the signature as opposed to processing the digest-input/pre-canonicalization node-set
fjh: asks are there any issues with declarative model?
<klanz2> .. @pratik
<fjhirsch> concerns with declarative model include extensibility and adoption
<scantor> +1 to the XSLT issue
<fjhirsch> tlr notes that xslt extension point is not good in new model, since it introduces turing complete extension
<klanz2> -1 to the XSLT issue
tlr: doesn't like introduction of XSLT in model
(Ed: I can't understand Thomas)
<tlr> tlr: both models have turing complete languages (due to XSLT)
<klanz2> (klanz2: I can understand him as well, but the use case of deriving viewable data is completely removed)
<tlr> ... so the distinction between the two models doesn't work out very well ..
<klanz2> fjh: why not out of xmlsig processing
<klanz2> klanz2: it's a deployment issue
<tlr> fjh: let's defer this one
<fjhirsch>
<fjhirsch>
fjh: Is having an event stream too much of a processing issue?
Pratik: main issue is transforms
are based on node set
... want a different type of model for representing doc subset
<fjhirsch> pratik notes event stream is one model, but another model would be ok
Pratik: event stream is easily understood though it is more complicated to program.
<fjhirsch> pratik agrees harder to program but fairly common
Pratik: difficulty is to know
info that is outside the document subset
... still need to support those cases; suggest that inside streaming parser , add namespace context
<fjhirsch> what is outside the document subset - namespace declarations, xml base, ?
Pratik: for XML attributes, no
solution at present
... event stream model is good but more complicated than what is wanted
... can we think of another model that is easier to understand
<klanz2> how about spec language, what do you think is easier written/understood?
<fjhirsch> pratik notes alternative is contstrained nodeset
<klanz2> node-set vs. streams?
fjh: in reponse to fjh's question, would we not have the same issues in event model?
Pratik: would work like XML nodeset
<klanz2>
Pratik: every element would have
its own namespace node
... whenever namespace is encountered, it is added; when it goes out of scope, it is removed
<fjhirsch> maintaining context avoids performance issue of copy which exists with nodesets
fjh: xml:base
<fjhirsch> pratik notes xml base and xml lang, xml base combination rules
<bal> +1 to thomas's comment
<fjhirsch> thomas asks would all transforms work with events without requiring buffering for an event stream
<bal> +q
<tlr> tlr: do the xpath subset and the xslt transform work with this stream?
Pratik: In transform notes, there
is an XPath subset which can be implemented within the XPath
stream
... Node would work off this event stream.
<tlr> NO!
Konrad, please type in your comments.
<tlr> konrad: xslt transform in xml dsig is octet stream to octet stream
<tlr> tlr: NO! I want to know whether the new processing model could accommodate xslt without canonicalization and all that, working just on event streams
<klanz2> agree with thomas to get rid of this
Brian: Is raising the same
concern as Thomas
... If you want to go to event stream processing, need to review canonicalization, need new c14n algorithm which would be a good idea.
<fjhirsch> bal notes that going to event stream would mean redefining what we mean by canonicalization so it is a better fit
<klanz2> Exclusive discussed this already:
Scott: Our current c14n model doesn't fit this.
fjh: Need to remember other models are possible like the constrained node approach.
Pratik: Want XML streaming so document doesn't have to be in memory
<fjhirsch> pratik notes requirement - not having to have entire document in memory
Pratik: At no point, in other
transforms, is the whole document required to be in
memory.
... DOM model is easier than stream based; so maybe we can define two implementations -- DOM and stream
<klanz2> well isn't this too low level?
<klanz2> .. for a spec
<fjhirsch> +1 to konrad
Pratik: When defining doc subset, no need to follow programming language model; can use theoretical model.
fjh: can we use a more abstract model?
<tlr> I think we need to have an idea about the model that we want to achieve.
fjh: nothing is said about how states handle their context
<tlr> We don't need to (and should not) force implementations to actually use that model.
fjh: Is event model going to be implemented anyway?
Pratik: For many implementations, like Web services, things are done in a streaming way and DOM not used; hence, the preference for stream support
<klanz2> @pratik: are you worried when specifying at a contrained node-set level that there is a gap of being specific with respect to behaviour?
fjh: There's declarative and
event models but no intermediate model
... Restricted nodeset model allows one to do a little more analysis.
<klanz2> @pratik: isn't the main problem that c14n isn't agnosic re. if inheritable attributes are in the input node set
fjh: More thought needed; let's
continue this discussion on the list.
... Is it a decision for backward compatibility or something new?
... Is there a place for processing instructions in the new model?
<bal> frederick
<tlr> fjhirsch?
<tlr> Chris was speaking up
<fjhirsch> oops, hold on, will dial in again.
<tlr> let's wait for frederick to come back
<csolc> PI's have a problem where you have to modify the data being signed,
<csolc> and that may not be allowed to modify the content being signed
fjh: suppose we went PIs for hints about processing efficiency
<tlr> csolc, can you check whether we actually say that in the requirements?
chris: may not have control over waht is being signed; cannot modify that with PIs
Ed agrees with Chris
<tlr> 3.2, point 4
<tlr>
<klanz2> going rather further up, than down is maybe a good idea
<fjhirsch> chris notes that signing content that is not local will not allow you to modify it necessarily, not allowing PI to work
<klanz2> .. with respect to the model
<fjhirsch> chris notes should attempt to have a consistent model that works with or without streaming
<klanz2> that would be XMLInfoSet then
<tlr> infoset is the abstract model you use to talk about XML. It is not a format.
<fjhirsch> would prefer unified abstract model
Chris: next version would have a simplified signing mechanism
<fjhirsch> chris notes want higher performance, easier to use
<fjhirsch> scott - consider 2.0 not as a successor but as companion
<fjhirsch> how would this work?
<tlr> +1 to scott
<tlr> ok, so where we're heading is defining a lighterweight subset of 1.1.
<klanz2> I do not disagree, but should not be called XMLDSIG then ....
scott: 2.0 would XML Siganture lite, not replacing 1.1
<klanz2> different NAME
Scott: No need to interoperate
betweeen 1.1 and 2.0
... Might have to use a different name.
... As like as possible, but not alike
... Define 2.0 with a specific set of use cases
<klanz2> something new
fjh: Question for Konrad; did not allow XSLT, would that be a problem?
Konrad: the constraint node model
would have to increase performance
... Might be a valid way for a 1.2, but if there is something really disruptive, it MUST be a new name.
<fjhirsch> general discussion notes that the WG could agree to a new name for a new declarative work without xslt transform and find that useful
fjh: How will people know which spec to use?
<fjhirsch> konrad notes that xml signature had transforms to deal with html, css etc to generate viewable output
Konrad: In current spec, chain of transforms was for creating output that was viewable.
<csolc> XML Content Signatures 1.0
<fjhirsch> konrad add clarity, it xml processing signature, not supporting document use case
<klanz2> Raw XML Signature
<fjhirsch> pdatta notes 1.1 will exist for a long time
Pratik: If one says 2.0 is successor, 1.1 will be used for a long time.
+q
<fjhirsch> having simpler and narrower specification could be beneficial, issue of positioning
<fjhirsch> infoset like model document for signature, more abstract
tlr: Our charter says we can consider breaking changes.
<fjhirsch> tlr notes separate model might be bad
<fjhirsch> could have new model document with obvious mapping to new streaming and noted relation to 1.1
Ed: I'm not against breaking changes (actually, I'm for them); I just don't think the idea of two independent XML Signature spec streams will fly.
<tlr> right
<csolc> may not be incompatible. XML 1.1 since it is touring complete, in theory we could map all 2.0 syntax to 1.1
<klanz2> profile?
<fjhirsch> by defining a model for the new constrained nodeset and declarative approach we could define a document that is not signature 2.0 per se
<fjhirsch> this model could be clearly mapped to eventing and streaming
<klanz2> "In standardization, a profile consists of an agreed-upon subset and interpretation of a specification." wikipedia ;-)
<fjhirsch> it could also be mapped to 1.1 with caveat that some features in 1.1 are no longer in the model
Konrad: If we want compatibility, profiles will be appropriate.
<fjhirsch> profile presumes that non-breaking changes, no extensions, etc
Konrad: Bottom line if XSLT is removed, then the possiblity of transforming and deriving PDF, HTML, etc from XML is lost and we lose compatibility.
<fjhirsch> pratik notes that if not compatible then need new name, a new 1.0
<tlr> what's the result that we're getting at with this distinction?
Scott: we already have specs not adopting XML Signature
XMPP not comfortable with XML Signature.
Scott: streaming issue is tough; canonicalization cannot be solved with current model
<klanz2>
<klanz2> it's there
fjh: We are not replacing 1.1 but are doing something in addition to 1.1
Ed: agrees with fjh as long as we are not continuing development of 1.1 (and that could be tricky)
Scott: There's negative connotations wth the current brand.
<tlr> fjh: If we do a "companion spec" then we can be more minimalistic
<scantor> I think it's probably not viable to stop maintaining the old spec if we did a subset as a new spec
Konrad: XML Signature was built with the concerns at the time; it's good but not optimized for today's world
<fjhirsch> document model versus networking model
<fjhirsch> minimal xml signature :)
(tlr, please type in your comments)
fjh: We need to work on requirments for this.
<fjhirsch> changing brand might be useful as well, not 2.0 but different name, negative concerns might relate to community and
<tlr> tlr: minimal xml signature makes sense; enabling minimalism by doing core spec that fits together with 1.1 makes sense. If need to change branding, let's change it when we know that. Wondering what additional details we need to move ahead.
<fjhirsch> use purpose
<fjhirsch> pdatta - a companion not a successor, might be less interesting
<pdatta> I need to drop off now
fjh: There are signals that people are choosing something other than XML Signature so we need to take some action.
Pratik: Working on use cases for streaming.
<scantor> I think if we don't simplify/improve dramatically, we should align any improvements to the existing spec, rather than forge something new
<tlr> 1. Focus on minimalism
tlr: focus on minimalism; focus on limited use cases;...inaudible
<tlr> 2. Use Pratik's model as a basis
<klanz2> well, iff the name is changed
<tlr> 3. Stick to format to the extent possible.
<klanz2> or augmented and it's a 1.0
<tlr> +1
<tlr> klanz, I think your concern about the branding is recognized
fjh: if we cut too much, we lose the value
<klanz2> that's not only branding, but also responsibility
fjh: we aim toward the declarative approach, but not the event stream, need an abstract model
<klanz2> you take or don't
<tlr> responsible branding ;-)
Konrad: Must be responsible to customers in branding.
<fjhirsch> Current rough agreement - focus on minimalism and reduced requirements, and focus on meeting performance with usability requirements.
<fjhirsch> Use Pratik's declarative design if possible, and revised model, either event or possibly more abstract
<fjhirsch> Need clarity of purpose and name should reflect that, relationship to continued use of 1.1 where appropriate
Konrad: If it is called 2.0, then document use cases have to stay
<fjhirsch> konrad notes concern that document use case must be supported if 2.0 but not if different than 2.0
Konrad: Required for government use cases
<fjhirsch> issue: clarify role of document use case in renamed 2.0 versus 1.1
<trackbot> Created ISSUE-111 - Clarify role of document use case in renamed 2.0 versus 1.1 ; please complete additional details at .
<fjhirsch>
<fjhirsch> issue-31?
<trackbot> ISSUE-31 -- Role for XML processing instruction, if any -- OPEN
<trackbot>
<fjhirsch> ISSUE-32?
<trackbot> ISSUE-32 -- Define metadata that needs to be conveyed with signature, e.g. profile information -- OPEN
<trackbot>
Gerald: Requriements and issues need to be distrininguished
If one can specify the profile, then the signature has to be processed according to the profile.
<fjhirsch> the signature properties document defines a profile element that can be used for this purpose
<fjhirsch> if we use signature property then defines where and how to be place
Ed: Profile should be specified as an attribute on the <Signature> element.
<fjhirsch> signature property specifies profile as a URI
<fjhirsch>
<fjhirsch> konrad notes keyinfo can become a size issue with CRLs
Konrad: base64-encoded
certificates can be big, does not agree with specifying it a
signature property
... common for standalone signatures
<tlr> perhaps using a reference (which could be either in-document or external) is the right thing?
Sean: Not sure he agrees; CRLs are being specified throguh the extension, not imbedded
<fjhirsch> sean notes maybe not an issue with CRLs in keyinfo these days, due to extension in cert
fjh: use of ocsp instead of crl
<fjhirsch> sean notes these may be streaming concerns
fjh: let's continue to discuss latere
<fjhirsch> issue-31?
<trackbot> ISSUE-31 -- Role for XML processing instruction, if any -- OPEN
<trackbot>
Gerald will update issues.
<g-edgar> Make that an action for me.
fjh: XML PIs issue; should we
close it?
... Can be regarded as work we incorporate when needed.
<scribe> ACTION: geral to update issues [recorded in]
<trackbot> Sorry, couldn't find user - geral
<fjhirsch> ISSUE-37?
<trackbot> ISSUE-37 -- Simplified c14n for signing versus more general c14n, e.g. not produce compliant xml document -- OPEN
<trackbot>
<scribe> ACTION: gerald to update issues [recorded in]
<trackbot> Created ACTION-245 - Update issues [on Gerald Edgar - due 2009-04-07].
<scribe> ACTION: g-edgar to update issues [recorded in]
<trackbot> Sorry, couldn't find user - g-edgar
<scribe> ACTION: gedgar to Update Issues [recorded in]
<trackbot> Created ACTION-246 - Update Issues [on Gerald Edgar - due 2009-04-07].
fjh: close issue-37?
<g-edgar> c14n is not required for input
<fjhirsch> issue-37 closed in pratik's draft, end of processing chain
<trackbot> ISSUE-37 Simplified c14n for signing versus more general c14n, e.g. not produce compliant xml document closed
<fjhirsch> ISSUE-38?
<trackbot> ISSUE-38 -- Profile for signature processing for non-XML or for constrained XML requirements -- OPEN
<trackbot>
<fjhirsch> close issue-38
<trackbot> ISSUE-38 Profile for signature processing for non-XML or for constrained XML requirements closed
<fjhirsch> issue-45?
<trackbot> ISSUE-45 -- Signing with multiple intended receivers, and/or long lived signatures -- OPEN
<trackbot>
<klanz2> who owns this?
<klanz2>
fjh: set of references to sign and need it to be valid for multiple parties (ed, do you mean multiple signers?)
<klanz2> search for 45
<fjhirsch> gerald notes need to accomidate key rollover
<scribe> ACTION: gedgar to Rework ISSUE-45 [recorded in]
<trackbot> Created ACTION-247 - Rework ISSUE-45 [on Gerald Edgar - due 2009-04-07].
<fjhirsch> ISSUE-51?
<trackbot> ISSUE-51 -- Effects of schema normalization on signature verification -- OPEN
<trackbot>
<fjhirsch> scott notes best practices was done, but should be factored into c14n revision | http://www.w3.org/2009/03/31-xmlsec-minutes.html | CC-MAIN-2015-06 | refinedweb | 3,232 | 60.45 |
Python 3 has been in existence for 7 years now, yet some still prefer to use Python 2 instead of the newer version. This is a problem especially for neophytes that are approaching Python for the first time. I realized this at my previous workplace with colleagues in the exact same situation. Not only were they unaware of the differences between the two versions, they were not even aware of the version that they had installed.
Inevitably, different colleagues had installed different versions of the interpreter. That was a recipe for disaster if they would’ve then tried to blindly share the scripts between them.
This wasn’t quite their fault, on the contrary. A greater effort for documenting and raising awareness is needed to dispel that veil of FUD (fear, uncertainty and doubt) that sometimes affects our choices. This post is thus thought for them, or for those who already use Python 2 but aren’t sure about moving to the next version, maybe because they tried version 3 only at the beginning when it was less refined and support for libraries was worse.
Two Dialects, One Language
First of all, is it true that Python 2 and Python 3 are different languages? This is not a trivial question. Even if some people would settle the question with: “No, it’s not a new language”, as a matter of fact several proposals that would have broken compatibility without yielding important advantages have been rejected.
Python 3 is a new version of Python, but it’s not necessarily backwards compatible with code written for Python 2. At the same time it’s possible to write code that is compatible with both versions, and this is not by chance but a clear commitment of the Python developers that drafted the several PEP (Python Extension Proposal). In the few cases in which syntax is incompatible, thanks to the fact that Python is a language with which we can dynamically modify code at runtime, we can solve the problem without relying on preprocessor with a syntax completely alien to the rest of the language.
The syntax is thus not a problem (especially ignoring versions of Python 3 before 3.3). The other big difference is the behavior of code, its semantics and the presence/absence of big libraries only for one of the two versions. This is indeed a significant problem, but it’s not completely unique or new for those who already have experience with other programming languages. You probably already happened to get an old codebase/library that fails to build with recent versions of the same compiler used originally. It’s the compiler itself in these cases that will help you (in Python, instead help will come from your own test suite).
Why make the new version different then? What advantages will these changes bring to us?
A Concrete Example
Let’s assume we want to write a program to read the owner of files/directories (on a Unix system) in our current directory and print them on screen.
# encoding: utf-8 from os import listdir, stat # to keep this example simple, we won't use the `pwd` module names = {1000: 'dario', 1001: u'олга'} for node in listdir(b'.'): owner = names[stat(node).st_uid] print(owner + ': ' + node)
Does everything work correctly? Apparently it does. We specified the encoding for the file containing the source code, if we have a file created by олга (uid 1001) in our directory its name will be printed correctly, and even if we have files with non-ASCII names these will be printed correctly.
There’s still a case that we haven’t covered yet though: a file created by олга AND with non-ASCII characters in the name…
su олга -c "touch é"
Let’s try to launch again our small script, and we’ll obtain a:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128)
If you think about it, a similar situation could be nasty: You have written your program (thousands of lines long instead of the few 4 of this example), you start to gather some users, some of them even from non-English speaking countries with more exotic names. Everything is okay, until one of these users decides to create a file that users with more prosaic name can create without any problem. Now your code will throw an error, the server might answer every request from this user with a error 500, and you’ll need to dig in the codebase to understand why suddenly these errors are appearing.
How does Python 3 help us with this? If you try to execute the same script, you’ll discover that Python is able to detect right away when you’re about to execute a dangerous operation. Even without files with peculiar names and/or created by peculiar users, you’ll receive right away an exception like:
`TypeError: Can't convert 'bytes' object to str implicitly`
Related to line:
print(owner + ': ' + node)
The error message is even more easy to understand, in my opinion. The str object is
owner, and
node is a bytes object. Knowing this, it’s obvious that the problem is due to the fact that
listdir is returning us a list of bytes objects.
A detail that not everybody knows is that
listdir returns a list of bytes objects or unicode strings depending on the type of the object that was used as input. I avoided using
listdir('.') exactly to obtain the same behavior on Python 2 and Python 3, otherwise on Python 3 this would’ve been an unicode string that would’ve made the bug disappear.
If we try to change a single character, from
listdir(b'.') to
listdir(u'.') we’ll be able to see how the code now works on both Python 3 and Python 2. For completeness, we should also change
'dario' to
u'dario'.
This difference in the behavior between Python 2 and Python 3 is however supported by a radical difference in how the two versions handle string types, a difference that is mainly perceived when porting from one version to the other.
In my opinion, this situation is emblematic of the maxim: “splitters can be lumped more easily than lumpers can be split”. What was lumped together in Python 2 (unicode strings and default strings of byte, which could be freely coerced together) has been split in Python 3.
Tools for Automated Conversion
For this reason tools like 2to3, even if well written and extremely useful to automate the conversion of every other difference, have some limitations. With the bytes/unicode split the difference in behavior surfaces at runtime, and a tool that can only do parsing/static analysis thus won’t be able to save you if you have a huge Python 2 codebase that mixes these two types. You’ll have to roll up your sleeves and properly design your API to decide if functions that until now accepted indiscriminately any type of strings should now work only with some of these (and which ones). Conversely, though getting a lot less use, tools of conversion from Python 3 to Python 2 have much easier life. Let’s see an example:
Sometime ago, I wrote a toy HTTP server (only dependency: python-magic), and this is the version for Python 2 (automatically converted from the Python 3 one without any need for manual changes):
Now, if you want you can have a look directly at the code converted to Python 3 with 2to3, or you can convert it directly on your system. When trying to execute it you’ll realize how every error that you can try to fix by hand is related to the bytes/unicode split.
You can manually apply changes like these:
And thus, you get your program working again on Python 3. These are not complex changes, but they require nonetheless to reason on which data types your functions are working upon, and on the control flow. It’s 13 lines of changes out of 120, a ratio not too easy to handle: with thousands of lines of code to port, you could easily end up with hundreds to modify.
If you’re curious, you could then try to convert this code that you just brought to Python 3 back to Python 2. Using 3to2 you’d obtain this:. In which the only change that had to be applied manually is
.encode('utf-8') at line 55.
Starting from Python 3 (if you’ll ever need to convert it back to Python 2), it’s much easier. But if you need to have your code working on another version, a complete conversion like this is not the best choice. It’s much better to maintain compatibility with both versions of Python. To do that you can rely on tools like futurize.
Python 3 Is Not Just about Unicode
Even if you don’t have the chance to use Python 3 in production (maybe one of the libraries that you’re using is bulky and compatible with Python 2 only), I’d suggest for you to keep your code compatible with Python 3. You could even stub/mock out the incompatible libraries, just so that you could run continuously your tests on both versions. This will make it easier for you when in the future you’ll finally be ready to migrate to Python 3, not to mention how it can help you in better design your API, or to identify errors like in the example at the beginning of this post.
All this talking about porting and byte/unicode difference, even if you were initially skeptical about using/starting with Python 3, probably led you to think of it as the lesser evil rather than tackling the porting in the future. But if porting is the stick, where’s the carrot? Is it the new features added to the language and to its standard library?
Well, after 5 years of time from the release of the last minor version of Python 2, there are plenty of interesting tidbits that are piling up. For example I found myself relying quite often on things like the new keyword-only arguments.
Optional Keyword Arguments
When I wanted to write a function to merge an arbitrary number of dictionaries together (similar to what
dict.update does, but without modifying the inputs) I found it natural to add a function argument to let the caller customize the logic. This way this function could be invoked as follows to simply merge multiple dictionaries by retaining values in the rightmost dicts.
merge_dicts({'a':1, 'c':3}, {'a':4, 'b':2}, {'b': -1}) # {'b': -1, 'a': 4, 'c': 3}
Likewise, to merge by adding the values:
from operator import add merge_dicts({'a':1, 'c':3}, {'a':4, 'b':2}, {'b': -1}, withf=add) # {'b': 1, 'a': 5, 'c': 3}
Implementing such an API in Python 2 would have required to define a
**kwargs input and look for the
withf argument. If the caller did mistype the argument as (e.g.)
withfun the error would be silently ignored, though. In Python 3 instead it’s perfectly fine to add an optional argument after variable arguments (and it will be usable only with its keyword):
def second(a, b): return b def merge_dicts(*dicts, withf=second): newdict = {} for d in dicts: shared_keys = newdict.keys() & d.keys() newdict.update({k: d[k] for k in d.keys() - newdict.keys()}) newdict.update({k: withf(newdict[k], d[k]) for k in shared_keys}) return newdict
Unpacking Operator
Since Python 3.5, the naive merging can actually be done with the new unpacking operator. But even before 3.5 Python got an improved form of unpacking:
a, b, *rest = [1, 2, 3, 4, 5] rest # [3, 4, 5]
This has been available to us since 3.0. Akin to destructuring, this kind of unpacking is a limited/ad-hoc form of the pattern matching commonly used in functional languages (where it is also used for flow control) and it’s a common feature in dynamic languages like Ruby and Javascript (where support for EcmaScript 2015 is available).
Simpler APIs for Iterables
In Python 2, a lot of APIs that dealt with iterables were duplicated, and the default ones had strict semantics. Now instead everything will generate values as needed:
zip(),
dict.items(),
map(),
range(). Do you want to write your own version of
enumerate? In Python 3 it’s as simple as composing functions from the standard library together:
zip(itertools.count(1), 'abc')
Is equivalent to
enumerate('abc', 1).
Function Annotations
Wouldn’t you like to define HTTP APIs as simply as this?
@get('/balance') def balance(user_id: int): pass from decimal import Decimal @post('/pay') def pay(user_id: int, amount: Decimal): pass
No more
'<int:user_id>' ad-hoc syntax, and the ability to use any type/constructor (like
Decimal) inside your routes without having to define your own converter.
Something like this has already been implemented, and what you see is valid Python syntax, exploiting the new annotations to make it more convenient to write APIs that are also self documenting.
Wrapping Up
These are just a couple of simple examples, but the improvements are far reaching and ultimately help you in writing more robust code. An example is exception chain tracebacks enabled by default, showcased in the aptly named post “The most underrated feature in Python 3” by Ionel Cristian Mărieș, which is also covered in this other post by Aaron Maxwell, together with the stricter comparison semantics of Python 3, and the new
super behavior.
This is not all. There are plenty of other improvements, these are the ones I feel have the most impact day-to-day:
- Several functions/constructors now return contextmanagers, simplifying closing up objects and managing errors: gzip.open (already from 2.7), mmap, ThreadPoolExecutor, memoryview, FTP, TarFile, socket.create_connection, epoll, NNTP, SMTP, aifc.open, Shelf, and more.
- lzma, for an improved compression compared to gzip
- asyncio, for asynchronous programming in Python
- pathlib, a more pythonic and expressive way to manipulate paths
- ipaddress
- lru_cache, to automatically cache the results of expensive functions
- mock (the same module mentioned above, previously available only from PyPI)
- A more efficient string representation in memory
- OrderedDict, everyone needed it at least once
- autocompletion inside pdb
- the __pycache__ directory, that helps to avoid littering every other project folder with
.pycfiles
A more thorough panorama can be obtained with the “What’s New” pages of the documention, or for another overview of the changes I also suggest this other post by Aaron Maxwell and these slides from Brett Cannon.
Python 2.7 will be supported until 2020, but don’t wait until 2020 to move to a new (and better) version! | https://www.toptal.com/python/python-3-is-it-worth-the-switch | CC-MAIN-2019-39 | refinedweb | 2,472 | 56.59 |
Markup Validation in Visual Web Developer
When you edit markup in Source view of the Visual Studio Web designer, the editor continually checks that the markup you are creating is valid. Markup validation works like the spelling checker in a word processing program. The editor examines the markup and adds wavy red lines under the elements or attributes that are not valid.
The editor determines what is valid based on the currently selected validation schema. For example, if you have set the current browser to Internet Explorer 6, the editor compares the markup in your page against a schema that defines what Internet Explorer 6 considers valid HTML. Internet Explorer 6 does not require tag attributes to have quotation marks around them. Therefore, the editor does not mark the text attribute in the following code example.
In contrast, if you change the current browser schema to XHTML 1.0 Transitional, the editor marks the value of the text attribute, because XHTML requires that all attributes be within quotation marks.
A validation error does not prevent the page from running. It simply provides you with feedback that the markup in the page does not conform to the current browser schema.
Visual Studio includes schemas for commonly used browsers (such as Netscape Navigator and Internet Explorer) and for common standards (such as XHTML Transitional 1.0). You can select a schema from the drop-down list in the HTML Source Editing toolbar. Alternatively, you can select a validation schema in the Options dialog box. For details, see How to: Select Validation Schemas for HTML Editing in Visual Web Developer.
Viewing Validation Errors
The editor shows you validation errors in the following ways:
Underlined elements Elements or attributes that are invalid are underlined with wavy red lines.
ToolTips If you hold the mouse pointer over an underlined element, a ToolTip displays details about the error.
Error List If you have the Error List window open, you can see a list of all the validation errors. Double-clicking an error in the Error List window takes you directly to the error in the editor.
Markup validation checks for the following:
Allowed tags Some browser schemas support tags that are not allowed in others. For example, the <blink> tag is supported only in Netscape browsers, so this tag is marked as invalid in other schemas.
Allowed attributes Validation checks that the attributes in an element are allowed for that element.
Required attributes Validation checks that any required attributes are included. For example, in XHTML, the <script> tag must have a type attribute.
Allowed attribute values If an attribute supports only certain enumerated values, such as true or false, validation marks any values that do not conform to the allowed values.
Allowed CSS values Validation checks that the cascading style sheet (CSS) values for the style attribute are allowed.
Allowed child elements Validation checks that child elements are allowed for a given parent element.
Proper use of quotation marks around attribute values Depending on the schema, quotation marks around attribute values might be required. For schemas where quotation marks are not required, validation checks that if a value is enclosed in quotation marks, they are balanced. For schemas where quotation marks are optional, validation checks them according to the validation options you set. See "Customizing Validation" later in this topic.
Casing rules Depending on the schema, element and attributes names might need to be in lowercase letters. If the schema allows uppercase or lowercase letters in names, validation checks them according to the validation options you set. See "Customizing Validation" later in this topic.
Unique element IDs Validation ensures that element IDs are unique throughout the page.
Well-formed elements Validation confirms that all opening tags have corresponding closing tags, if the schema requires it.
Element opening and closing order Validation checks that you do not have crossed opening and closing elements, such as <b><i>text</b></i>.
Outdated tags or attributes A schema such as XHTML 1.0 Transitional will mark tags such as <font> with an error that tells you that the tag is no longer recommended.
Valid targets for relative hyperlinks and graphics Validation confirms the validity of any targets that are relative to the current site, but it does not check the validity of fully qualified URLs.
Validation is a distinct operation from generation. When you work in the designer, Visual Studio adds, or generates, markup to your page. The markup created by the designer is not determined by the current browser schema. Instead, the Web page designer in Visual Studio always generates XHTML 1.1–compatible markup. For details, see XHTML in the Visual Studio Web Designer.
Validation checks the markup of the page in the designer. It cannot guarantee that when the page runs in the browser, the output of the page will validate against a specific schema. Individual ASP.NET server controls and the page itself render markup, and sometimes script, into the page when the page is processed. That output is not accessible to validation in the designer.
The markup and scripts that are created at run time will be valid for most browsers. ASP.NET pages and server controls render markup that is XHTML 1.1–compatible. Most browsers now target standards rather than supporting browser-specific tags, specifically XHTML. Because XHTML output is compatible with most browsers, the markup rendered at run time by the page and controls will be valid.
For more information, see XHTML Standards in Visual Studio and ASP.NET.
Specifying a target browser controls not just validation, but the list of tags and attributes that are available in IntelliSense. For example, the Internet Explorer 3.02 schema does not offer style attributes because Internet Explorer 3.02 does not support them. Similarly, the XHTML 1.0 Transitional schema does not offer the <font> tag because <font> tags are deprecated in XHTML.
Depending on the browser schema that you are using, you might be able to specify additional validation options. For example, if you are using the Internet Explorer 6 schema, you can select whether validation marks element and attribute names that are not in lowercase letters. For details, see How to: Set Validation Options for HTML Editing in Visual Web Developer.
If you do not want to use validation, you can turn it off. For details, see How to: Set Validation Options for HTML Editing in Visual Web Developer.
In a Web page, it is possible to include blocks of markup that are declared with their own namespace. For example, an ASP.NET Web page might include a block of embedded XML that includes a declaration for the namespace in which the XML elements are defined. In that case, validation is based on a union of the current page schema and the namespace for the embedded block. | http://msdn.microsoft.com/en-us/library/f940516c(v=vs.100).aspx | CC-MAIN-2014-10 | refinedweb | 1,136 | 55.13 |
Graph App Development for Neo4j Desktop
This guide explains how to develop a Graph App for Neo4j Desktop.
This article assumes that you already have a basic understanding of HTML and CSS. It will also discuss some concepts of Single Page Applications.
Basic knowledge of HTML and JavaScript and an understanding of Single Page Applications (SPAs)
Knowledge of the offical JavaScript Drivers
If you haven’t already, download and install Neo4j Desktop
Introduction
So, you would like to build a Graph App? You are in good company, many enterprises and community developers are building Graph Apps for a wide range of use cases. These range from utility tools like monitoring tool Halin and educational Graph Apps like Neuler to visulisation apps including GraphXR by Kineviz and NeoMap.
Graph apps can be built with vanilla HTML and JavaScript, but most commonly we see these built with modern front end frameworks like React or Vue.js. Whichever framework you choose to build your application, you will interact with the Graph the same way; by running a Cypher Query through the Official JavaScript drivers. There is plenty of content over on the JavaScript developer guides so we will not cover this in too much detail, only the nuances around how the driver works with the Neo4j Desktop API.
If you are looking for inspiration, head over to the Graph App Gallery to see what other developers have built. Otherwise, let’s get started.
Installing Driver Dependencies
The official JavaScript driver is available via npm using the
npm install or
yarn add command.
npm install --save neo4j-driver
Alternatively, if your graph app will be used in a context where the always has an active internet connection, you can obtain the driver via a CDN.
<!-- unpkg CDN non-minified --> <script src=""></script> <!-- jsDelivr CDN non-minified --> <script src=""></script>
Enabling Developer Tools
Neo4j Desktop comes with a Development App that can be used while developing and debugging your Graph App.
To enable Development Mode, click on the Settings
icon in the bottom left hand corner of the screen to reveal the Settings pane.
At the bottom of the Settings pane, you will see a Developer Tools form. Click Enable Development Mode and add fill out the Entry Point and Root Path.
Entry Point: This is the path to your app, either a location of a HTML file (for example) or a HTTP url where your app is being served (for example).
Root Path: This is the path to the root of your development project. If you are running Background Processes, this should be the location of the files that contain your Java or Node.js processes - if in doubt, you can just set it to
/.
Getting the Context
If you require access to the the list of projects and databases that the user has configured in Neo4j Desktop, you can access this via the Context API. There are two ways of accessing Neo4j Desktop’s context, either through the Injected API or using GraphQL.
Neo4j Desktop provides information about the current desktop environment via the
neo4jDesktopApi object that is injected into the window.
This will provide you with a list the Projects and Database that the user has created.
Injected API
The Injected API is provided through the
neo4jDesktopApi object.
The
getContext() method returns a Promise which in turn resolves to an object containing a
projects key.
Each Project contains a list of Neo4j Databases and a list of files.
if ( window.neo4jDesktopApi ) { neo4jDesktopApi.getContext() .then(context => { // Access to the list of projects will be through context.projects }) }
If the context should change for any reason, for example if the active database changes or has been stopped, an event will be fired.
You can listen for these changes using the
onContextUpdate method on the API which provides an Event object which includes the type of event (for example), the new context and the previous context.
let online = true let context = await neo4jDesktopApi.getContext() neo4jDesktopApi.onContextUpdate((event, newContext, oldContext) => { // If the database has stopped, go into an 'Offline' mode if ( event.type === "APPLICATION_OFFLINE" ) { online = false } // Keep the context context = newContext })
The following events will trigger a context update via the API:
GraphQL API
The GraphQL API contains the same information as the injected API, but instead is accessed via a GraphQL library. For this example we will use Apollo Boost. The Apollo Boost package is available via npm or yarn
npm install apollo-boost graphql # or yarn add apollo-boost
The information required to access the GraphQL API are provided as part of the URL.
neo4jDesktopApiUrl: The URL of the GraphQL service
neo4jDesktopGraphAppClientId: A token generated by Neo4j Desktop to verify any requests made by the Graph App
const url = new URL(window.location.href) const apiEndpoint = url.searchParams.get("neo4jDesktopApiUrl") const clientId = url.searchParams.get("neo4jDesktopGraphAppClientId") import ApolloClient from "apollo-boost" const client = new ApolloClient({ uri: apiEndpoint, headers: { clientId: clientId } });
You can then use the Apollo Client to query the GraphQL API endpoint. For example, the following code will give you a list of all projects and their databases.
import gql from 'graphql-tag' const GET_DATABASES = gql` query { workspace { projects { name graphs { name status connection { info { version edition } principals { protocols { bolt { tlsLevel url username password } } } } } } } } ` client.query({ query: GET_DATABASES }) .then(({ data }) => { // Access the list of projects through data.workspace.projects })
Creating a Driver Instance
The next step is to create an instance of the JavaScript driver.
This will be the point of interaction with a Neo4j Database.
Now that we have the credentials from the previous step, we can run a series of filter and reduce functions to produce a list of graphs that a driver instance can be created for.
There will be a maximum of one Active graph in Desktop (with the status
ACTIVE), but you may also have remote graphs that could be displayed.
To find any active graphs, you could run a reduce and filter on the current context.
const graphs = context.projects .map(project => ({ graphs: project.graphs.filter(graph => graph.status === "ACTIVE" || graph.connection.type === "REMOTE") })) .reduce((acc, { graphs }) => acc.concat(graphs), []) const { url, username, password } = graphs[0].connection.configuration.protocols.bolt
Once you have the correct credentials, you can create an instance of the Driver and run the session.
const driver = new neo4j.driver(url, neo4j.auth.basic(username, password)) const session = driver.session() session.run('MATCH (n) RETURN n LIMIT 20') .then(res => { // Handle the Results })
Getting ready for Production
There are a few steps to follow in order to get your Graph App ready for Production.
package.json
If you use npm or yarn, you will be familiar with the
package.json file.
This file sits in the root of your project and holds various metadata including the name of your project and any third-party dependencies.
Adding a
neo4jDesktop setting to your package.json will allow you to tie your Graph App to a particular version of the Neo4j Desktop API or {#permissions}[request certain permissions].
The
name and
version of the project are read from package.json and used when deciding whether to install a new Graph App or update an existing install.
{ "name": "my-graph-app", "version": "1.0.0", "description": "(desktop)-[:LOVES]->(apps)", "homepage": "", "neo4jDesktop": { "apiVersion": "^1.4.0", "permissions": [ "allGraphs" ] } }
In this example, we are tying the Graph App to the Neo4j Desktop API version 1.4.0 or higher and requesting permission to access all Graphs created in Neo4j Desktop.
manifest.json
The
manifest.json file is read during the installation process to gather additional information to Neo4j Desktop about your Graph App.
In a packaged install of a Graph App (either .tar file or via npm), this file should be added to the
/dist folder before packaging.
For Graph Apps hosted on the internet, the manifest.json file should be served in the same directory as your
index.html file.
{ "name": "my-graph-app", "description": "(desktop)-[:LOVES]->(apps)", "icons": [ { "src": "./my-image.png", "type": "png" }, { "src": "./my-vector-image.svg", "type": "svg" }, { "src": "data:image/svg+xml;base64,[data]", "type": "data" } ], "homepage": "" }
The following image demonstrates how the values from manifest.json are used by Neo4j Desktop.
Any values provided in
manifest.json will override a value provided in
package.json.
For example, if
package.json lists version
1.0.0 but
manifest.json specifies
1.2.3, the value
1.2.3 will be used.
Deploying your Graph App
File Structure
At the minimum, your project should consist of a
dist/ directory containing an index.html file plus any other JavaScript and CSS files that are required to run the Graph App.
The root directory should also include a
package.json file and optionally a set of latest release notes in
release-notes.md.
dist/ app.js index.html manifest.json package.json release-notes.md
Deployment via .tar file
The most common option for deploying a Graph App is to create a
.tar file.
This can be created by running the
npm pack command.
If you have created a project with a command line tool (for example
create-react-app or
@vue/cli) then the build scripts should be configured for you already.
If not, you can create a build script in
package.json to move the appropriate files to the
dist/ folder.
Once the files are in the dist folder, you can run the npm pack to package the graph app into a
.tar file.
npm pack
Any files or directories that you do not want to include in the
.tar file can be listed in a
.npmignore file.
By default, the file will be named using the name and version properties from
package.json.
The resulting
.tar file can be installed either by pasting a URL or dragging the tar file into the Install form at the bottom of the Graph Apps pane in Desktop.
Deployment via npm
Any published npm package can be installed by copying and pasting the npm registry URL. For example, the Neo4j Cloud Tool Graph App can be installed via Neo4j’s npm registry with the URL. Neo4j Desktop will periodically check for updates to npm packages and install them automatically.
More information on the
npm package command is available on docs.npmjs.com.
Online Deployments
A good example of an Online Deployment is Halin. You can install the hosted version of Halin by entering into the Install form at the bottom of the Graph Apps pane and clicking the Install button. The hosted version of Halin hosts a manifest.json in the website’s root directory.
Additional Topics
Deep Links to your app
You can provide a deep link to your app using the
neo4j-desktop:// scheme and the name of your app from package.json.
For example, if the name of the app is
my-graph-app the link would be the following:
neo4j-desktop://graphapps/my-graph-app?key=value
You can pass parameters through to the graph app to help set the initial state of the app.
For example, in the URL above, the
?key=value will append a
key property with a value of
value to the graph app’s url.
The
neo4jDesktopApi has an
onArgumentsChange function that allows you to listen to changes in the applications arguments, for example when a new deep link has been clicked.
On load, and for each subsequent change of parameters, the callback function is called with two arguments; the original string and an object containing the decoded keys and values.
neo4jDesktopApi.onArgumentsChange((queryString, object) => { console.log(object.key) // "value" })
Deep links to Neo4j Browser
Your graph app can also link to Neo4j Browser using the
neo4j-desktop:// scheme and the Graph App name
neo4j-browser.
Additionally, you can specify a command and argument to automatically run as it loads. For example, if you wanted to run the
:play movies command to open the Movies Browser Guide, you could use the following link:
neo4j-desktop://graphapps/neo4j-browser?cmd=play&arg=movies
You can also start Neo4j Browser with a pre-populated cypher query by setting
cmd in the query string to edit and the
arg to the Cypher query in a URL encoded form.
neo4j-desktop://graphapps/neo4j-browser?cmd=edit&arg=MATCH%20%28n%29%20RETURN%20count%28n%29%20AS%20count
Linking to Bloom
You can link to Bloom by using the
neo4j-desktop:// scheme, and the Graph App name
neo4j-bloom. You can also add a
search parameter as a URL encoded string to auto-fill the search bar when bloom opens.
neo4j-desktop://graphapps/neo4j-bloom?search=URL%20Encoded%20String
Plugin Dependencies
You can specify any plugins that your Graph App depends on within
manifest.json file.
Any plugin with a valid coordinate from Maven Central will be will be automatically installed to all local databases within the current active project in Neo4j Desktop.
For example, if your Graph App requires APOC then your
manifest.json file may look something like this:
{ "name": "my-graph-app", "pluginDependencies": [ "org.neo4j.procedure/apoc" ] }
In order to specify your own plugins here, they must be published to Maven Central. Once published, the coordinates of the Maven Artifact can be added to the array.
Permissions
If a Graph App requires the use of a privileged API (for example executing Java or Node.js), these will need to be specified either in the
neo4jDesktop section of package.json or in
manifest.json.
Permissions can be defined as an array:
{ "name": "my-graph-app", "permissions": ["backgroundProcess", "allGraphs", "activeGraph"] }
Or alternatively, a map-like object can be provided with a short description of how the permission will be used.
{ "name": "my-graph-app", "permissions": [ "activeGraph", { "backgroundProcess": "Allow background processes to see output of demo Java class", "allGraphs": "Another usage description here" } ] }
Checking for Permission
When your graph app is installed, the user will have the option to grant or deny a permission and these permissions can also be revoked at any time from the Graph Apps pane.
Therefore, it is good practice to to check that the permission has been granted.
To do so, you can call the
checkPermission method on the injected API.
window.neo4jDesktopApi.checkPermission("backgroundProcess") .then(granted => { if ( granted === true ) { // Permission has been granted } });
Requesting Permission
If your graph app doesn’t already have the permission it needs, then it can be requested by calling the
requestPermission method on the injected API.
In order to request a permission, it must be listed in the graph app’s
manifest.json file.
The following example features the longform version of the permission declaration, describing how the
backgroundProcess permission will be used within the app.
{ "name": "my-graph-app", "permissions": { "backgroundProcess": "Allow this Graph App to create a CSV file on your hard drive" } }
The graph app can then request the permission. The user will be issued with a prompt which will allow them to Allow or Deny the permission to the Graph App.
window.neo4jDesktopApi.requestPermission("backgroundProcess") .then(granted => { if (granted) { // Permission has been granted } else { // The user has rejected the permission } });
Activation Keys
Activation Keys can be used to unlock functionality within your Graph App. An Activation Key is a JET token, similar to a JWT token but with specific fields that are used to grant access to protected resources and premium functionality. All users are required to enter an Activation Key when they first download desktop.
All keys are currently issued by Neo4j and are tied to the name from your
package.json file.
They hold the following keys:
Activation Keys are held as part of the context.
If you have requested the
activationKeys setting then it may be appropriate to filter the activation keys by their feature name.
const context = await neo4jDesktopApi.getContext() const activationKeys = context.activationKeys .filter(key => key.featureName == "my-graph-app")
If you are interested in using Activation Keys to unlock features in your app, please get in touch and we will see what we can do.
Files
Neo4j Desktop allows you to drag and drop files into a project for later use. For example, you could create a Browser Guide to explain your project to your coworkers or create set of Cypher scripts to seed a new database within the project or to hold commonly run queries. The Neo4j Desktop UI displays a link to these files so they can be quickly opened in Neo4j Browser.
You can also access these from your Graph App.
For example, a visualisation app may take a set of cypher queries and display them in a forced graph layout.
Each file can be accessed via HTTP through Neo4j Desktop’s API and therefore can be loaded through node’s
http module or a third party package like axios.
To get all cypher files from every, you could run a
.map and
.reduce on Neo4j Desktop’s context:
const axios = require('axios') const context = await neo4jDesktopApi.getContext() const cypherFiles = context.projects.map(project => project.files.filter(file => file.filename.endsWith('.cypher')) ) .reduce((files, projectFiles) => files.concat(projectFiles), []) axios.get(cypherFiles[0].url) .then(response => console.log(response.data)) // MATCH (n) ...
Framework Support
We do not recommend any specific front-end frameworks for developing apps. However, community members have built packages that will speed up your workflow.
React
The
use-neo4j library provides hooks for running Cypher queries against a Neo4j Database.
The
Neo4jProvider component will detect the Neo4j Desktop API and show a list of Projects and Graphs configured in Neo4j Desktop.
The library falls back to a generic login form which allows the user to enter their own credentials.
ReactDOM.render( <React.StrictMode> <Neo4jProvider> <App /> </Neo4jProvider> </React.StrictMode>, document.getElementById('root') );
Starter Kit
You can fork or clone the Graph App Starter kit for React to generate a basic Graph App. The example project uses Semantic UI for styling and
use-neo4j to interact with Neo4j.
Vue.js
The
vue-neo4j plugin provides a wrapper for the JavaScript driver in all Vue.js components via
this.$neo4j object.
There is also a set of helper functions for developing Graph Apps.
For more information, check out the Github repository for using Vue.js with Neo4j.
Community Forum
If you have any questions, comments, or would like to show off your own graph app, then there is a dedicated Graph Apps category on the Neo4j Community site.
Was this page helpful? | https://neo4j.com/developer/graph-apps/building-a-graph-app/ | CC-MAIN-2020-50 | refinedweb | 3,051 | 55.54 |
user=> (def x)
#'user/x
user=> x
java.lang.IllegalStateException: Var user/x is unbound.
user=> (def x 1)
#'user/x
user=> x
1
user=> (def ^:dynamic x 1)
user=> (def ^:dynamic y 1)
user=> (+ x y)
2
user=> (binding [x 2 y 3]
(+ x y))
5
user=> (+ x y)
2
You need to enable Javascript in your browser to edit pages.
help on how to format text
Table of Contents
Vars and the Global Environment
Clojure is a practical language that recognizes the occasional need to maintain a persistent reference to a changing value and provides 4 distinct mechanisms for doing so in a controlled manner - Vars, Refs, Agents and Atoms. Vars provide a mechanism to refer to a mutable storage location that can be dynamically rebound (to a new storage location) on a per-thread basis. Every Var can (but needn't) have a root binding, which is a binding that is shared by all threads that do not have a per-thread binding. Thus, the value of a Var is the value of its per-thread binding, or, if it is not bound in the thread requesting the value, the value of the root binding, if any.
The special form def creates (and interns) a Var. If the Var did not already exist and no initial value is supplied, the var is unbound:
Supplying an initial value binds the root (even if it was already bound).
By default Vars are static, but Vars can be marked as dynamic to allow per-thread bindings via the macro binding. Within each thread they obey a stack discipline:
Bindings created with binding cannot be seen by any other thread. Likewise, bindings created with binding can be assigned to, which provides a means for a nested context to communicate with code before it on the call stack. This capability is opt-in only by setting a metadata tag :dynamic to true as in the code block above. There are scenarios that one might wish to redefine static Vars within a context and Clojure (since version 1.3) provides the functions with-redefs and with-redefs-fn for such purposes.
Functions defined with defn are stored in Vars, allowing for the re-definition of functions in a running program. This also enables many of the possibilities of aspect- or context-oriented programming. For instance, you could wrap a function with logging behavior only in certain call contexts or threads.
(set! var-symbol expr)Assignment special form.
When the first operand is a symbol, it must resolve to a global var. The value of the var's current thread binding is set to the value of expr. Currently, it is an error to attempt to set the root binding of a var using set!, i.e. var assignments are thread-local.
In all cases the value of expr is returned.
Note - you cannot assign to function params or local bindings. Only Java fields, Vars, Refs and Agents are mutable in Clojure.
Using set for Java fields is documented in Java Interop.
InterningThe Namespace system maintains global maps of symbols to Var objects (see Namespaces). If a def expression does not find an interned entry in the current namespace for the symbol being def-ed, it creates one, otherwise it uses the existing Var. This find-or-create process is called interning. This means that, unless they have been unmap-ed, Var objects are stable references and need not be looked up every time. It also means that namespaces constitute a global environment in which, as described in Evaluation, the compiler attempts to resolve all free symbols as Vars.
The var special form or the #' reader macro (see Reader) can be used to get an interned Var object instead of its current value.
Non-interned VarsIt is possible to create vars that are not interned by using with-local-vars. These vars will not be found during free symbol resolution, and their values have to be accessed manually. But they can serve as useful thread-local mutable cells.
Related functions
Variants of def: defn defn- definline defmacro defmethod defmulti defonce defstruct
Working with interned Vars: declare intern binding find-var var
Working with Var objects: with-local-vars var-get var-set alter-var-root var? with-redefs with-redefs-fn
Var validators: set-validator get-validator
Common Var metadata: doc find-doc test | http://clojure.org/Vars?responseToken=0d5191493c4f654526a2cdc96e331e4f1 | CC-MAIN-2015-48 | refinedweb | 730 | 61.56 |
An Early Look at C# 7.1: Part 2
- |
-
-
-
-
-
-
Read later
Reading List
Yesterday we looked at Async Main and Default Expressions. Our tour of C# 7.1 continues with the proposals titled Infer Tuple Names and Pattern-matching with Generics.
Infer Tuple Names
Developers don’t often think about it, but anonymous types in C# include name inference. For example, if you write the below line then the object y will have properties named A and B.
var y = new { x.A, x.B };
Under the Infer Tuple Names proposal, value tuples would have roughly the same capabilities.
var z1 = (A: x.A, B: x.B); //explicit names var z2 = (x.A, x.B); //inferred names
There are some notable differences between anonymous types and value tuples:
- Anonymous types require property names, either explicit or inferred.
- Value tuples will label unnamed properties Item1, Item2, etc.
- Anonymous types with duplicate names result in a compiler error.
- Value tuples with duplicate explicit names result in a compiler error.
- Value tuples with duplicate inferred names will cause name inference to the skipped. For example (x.A, x.B, y.A) becomes (Item1, B, Item3).
- Value tuples cannot use the following reserved names: ToString, Rest, ItemN (where N > 0)
An interesting difference between C# and VB is that VB can infer anonymous property names from functions. For example:
var y = new { x.A, x.Bar() }; //compiler error Dim y = New With {x.A, x.Bar()} //anonymous type {A,Bar}
This capability will be extended to tuples in VB.
This feature can result in a breaking change if you happen to have an extension method with the same name as an inferred property. The proposal continues,
The compatibility council found this break acceptable, given that it is limited and the time window since tuples shipped (in C# 7.0) is short.
Tuple Names in Generic Constraints
While the compiler tries to warns the programmer about tuple name mismatches. For example,
public static (int A, int B) Test1((int A, int B) a) Test1((A: 1, B: 2)); Test1((X: 1, Y: 2)); //warning, tuple name mismatch
This doesn’t work when you start getting into generic constraints:
public static T Test2<T>(T a) where T : IEnumerable<(int A, int B)> Test2(new List<(int A, int B)>()); Test2(new List<(int X, int Y)>()); //no warning
The current word is that tuple names in generic constraints cases simply aren’t going to be checked by the compiler. Theoretically the compiler could catch stuff like this, but the performance cost would be too great compared to the benefit.
Pattern-matching with Generics
Pattern matching, new in C# 7.0, has a design flaw when it comes to generics. Consider this code submitted by Alex Wiese:
class Program { static void Main(string[] args) {} public void Send<T>(T packet) where T : Packet { if (packet is KeepalivePacket keepalive) { // Do stuff with keepalive } switch (packet) { case KeepalivePacket keepalivePacket: // Do stuff with keepalivePacket break; } } } public class Packet {} public class KeepalivePacket : Packet {}
This gives us the error: “An expression of type T cannot be handled by a pattern of type KeepalivePacket.” But if we change the parameter to be of type System.Object instead of T, it works as expected.
public void Send(object packet)
In C# 7.1 this has been corrected by slightly changing the rules under which pattern matching can occur,
We change the paragraph in the pattern-matching specification (the proposed addition is shown in bold):
Certain combinations of static type of the left-hand-side and the given type are considered incompatible and result in compile-time error. A value of static type E is said to be pattern compatible with the type T if there exists an identity conversion, an implicit reference conversion, a boxing conversion, an explicit reference conversion, or an unboxing conversion from E to T, or if either E or T is an open type. It is a compile-time error if an expression of type E is not pattern compatible with the type in a type pattern that it is matched with.
This is considered to be a bug fix, but since it will “introduce a forward incompatibility” you will have to set the compiler to C# 7.1 in order to take advantage of the change.
Rate this Article
- Editor Review
- Chief Editor Action | https://www.infoq.com/news/2017/06/CSharp-7.1-b?utm_source=news_about_c_sharp&utm_medium=link&utm_campaign=c_sharp | CC-MAIN-2018-51 | refinedweb | 726 | 62.68 |
So I'm trying to create a score system that goes up by 100 every second. I get this error: "Only assignment, call, increment, decrement, and new object expressions can be used as a statement"
This is my code so far:
using UnityEngine;
using System.Collections;
public class ScoreperSec : MonoBehaviour {
public int startingScore = 0;
public int currentScore = 0;
public GUIText scoregui;
private float time;
private int score;
void Update (){
time+=Time.deltaTime;
//currentScore += (int)time;
print ((int)time);
(int)time * 100 == score;
scoregui.text = "Score: "+ score;
}
}
(int)time 100 == score; may be error, i think you should like this if ((int)time 100 == score)
Answer by Kiwasi
·
Jan 23, 2015 at 03:14 AM
score = (int)time * 100;
You probably also need
scoregui.text = "Score: "+ score.ToString();
Shouldn't you use score = (int)(time * 100) otherwise your dropping the decimal values of time and multiplying that by 100?
@Drakenish
As written it will increase by 100 points at the end of every second.
If you want it to go from 0 to 100 over one second then your code should be used.
The OP was not overly clear on which effect he was after.
Answer by RalphTrickey
·
Jan 23, 2015 at 02:58 AM
Is it this statement?
(int)time * 100 == score;
== is a comparison and doesn't make any sense in this context. If you meant = then the left hand side is not a variable (lvalue).
I believe that is the issue, yeah. I'm not sure how I would fix it though.
score = (int)(time * 100); ? I believe this is what you are trying to do.
Ohhh I get what I did wrong now, coin score to multiplied value
2
Answers
Cannot implicitly convert type `float' to `int'. An explicit conversion exists (are you missing a cast?)
1
Answer
Error when checking if float is a whole number
2
Answers
C# Do something every 100 points?
1
Answer
float = int / int float value always 0
1
Answer | https://answers.unity.com/questions/883433/multiply-float-by-int.html | CC-MAIN-2019-51 | refinedweb | 329 | 73.47 |
Coingecko:.
Vegas has been issuing money since forever, and the various chips trade, they usually can be exchanged across casinos. Vegas has gambling pits, and hey got a cycle price, the ante, or the double zero. But they don;t compress bets, instead they give chips away then float customers back and sell them entertainment.
What does it take to set up a betting pit? Went through this with the numbers, The boss pays off according to the conditional probability of your bet against the number that came in. Betting against a NGDP announcement yields a distribution of 'estimates' We expect winner to form bell shaped distribution about the final number, wild guess would be anti symmetric and saddle shaped distributions,. Betters must have figured out the best algorithms for paying off by probability, I haven't.
But, making the pit is easy, just pay the python team their $1,000 license and its all:
import trading pit, and standard issue coin.
The pit organizes the bets the same, a nested probability graph. Betters can scan the graph, then bet. Or, the last verion of the graph is posted. So, better who see the current estimates, and have inside information, would pile on the bets at the speculated position. As time progressed, the NGDP numbers become firm, and the data collectors make increasingly accurate bets. The pit boss rules can be written to close the bets when the center estimate peaks beyng a limit, the boss can specify a mean to varianc limit at the start.
Hence, anytime some part of the economy bulges with something interesting, spawn a pit and quantize the flow.
1 comment:
Did you consider trading with the best Bitcoin exchange service - YoBit. | http://bettereconomics.blogspot.com/2016/12/gambling-chips.html | CC-MAIN-2017-43 | refinedweb | 287 | 61.87 |
NAME
device_ids, major, minor, umajor, uminor - calculate device ids
SYNOPSIS
#include <sys/types.h> #include <sys/systm.h> int major(struct cdev *dev); int minor(struct cdev *dev); int umajor(dev_t id); int uminor(dev_t id);
DESCRIPTION
The device_ids family of functions take either the raw device ID, id, or a pointer to the device structure, dev, and return the integer value that is the major or minor device ID as requested. The actual major and minor device IDs are values masked from of the raw device ID. For details on the actual calculations used to determine the major or minor IDs see the actual source in kern_conf.c.
RETURN VALUES
An integer greater than zero and less than NUMCDEVSW. major() and minor() will return NODEV if the device is invalid.
AUTHORS
This manual page was written by Chad David 〈davidc@acns.ab.ca〉. | http://manpages.ubuntu.com/manpages/hardy/man9/major.9.html | CC-MAIN-2014-35 | refinedweb | 144 | 54.73 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.