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
NDArray Indexing - Array indexing features¶ MXNet’s advanced indexing features are modeled after NumPy’s implementation and documentation. You will see direct adaptations of many NumPy indexing features and examples which are close, if not identical, so we borrow much from their documentation. NDArrays can be indexed using the standard Python x[obj] syntax, where x is the array and obj the selection. There are two kinds of indexing available: - basic slicing - advanced indexing In MXNet, we support both basic and advanced indexing following the convention of indexing NumPy’s ndarray. Basic Slicing and Indexing¶ Basic slicing extends Python’s basic concept of slicing to N dimensions. For a quick review: a[start:end] # items start through end-1 a[start:] # items start through the rest of the array a[:end] # items from the beginning through end-1 a[:] # a copy of the whole array from mxnet import nd For some working examples of basic slicing we’ll start simple. x = nd.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], dtype='int32') x[5:] [5 6 7 8 9] <NDArray 5 @cpu(0)> x = nd.array([0, 1, 2, 3]) print('1D complete array, x=', x) s = x[1:3] print('slicing the 2nd and 3rd elements, s=', s) 1D complete array, x= [ 0. 1. 2. 3.] <NDArray 4 @cpu(0)> slicing the 2nd and 3rd elements, s= [ 1. 2.] <NDArray 2 @cpu(0)> Now let’s try slicing the 2nd and 3rd elements of a multi-dimensional array. x = nd.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]) print('multi-D complete array, x=', x) s = x[1:3] print('slicing the 2nd and 3rd elements, s=', s) multi-D complete array, x= [[ 1. 2. 3. 4.] [ 5. 6. 7. 8.] [ 9. 10. 11. 12.]] <NDArray 3x4 @cpu(0)> slicing the 2nd and 3rd elements, s= [[ 5. 6. 7. 8.] [ 9. 10. 11. 12.]] <NDArray 2x4 @cpu(0)> Now let’s try writing to a specific element. We’ll write 9 to element 2 using x[2] = 9.0, which will update the whole row. print('original x, x=', x) x[2] = 9.0 print('replaced entire row with x[2] = 9.0, x=', x) original x, x= [[ 1. 2. 3. 4.] [ 5. 6. 7. 8.] [ 9. 10. 11. 12.]] <NDArray 3x4 @cpu(0)> replaced entire row with x[2] = 9.0, x= [[ 1. 2. 3. 4.] [ 5. 6. 7. 8.] [ 9. 9. 9. 9.]] <NDArray 3x4 @cpu(0)> We can target specific elements too. Let’s replace the number 3 in the first row with the number 9 using x[0, 2] = 9.0. print('original x, x=', x) x[0, 2] = 9.0 print('replaced specific element with x[0, 2] = 9.0, x=', x) original x, x= [[ 1. 2. 3. 4.] [ 5. 6. 7. 8.] [ 9. 9. 9. 9.]] <NDArray 3x4 @cpu(0)> replaced specific element with x[0, 2] = 9.0, x= [[ 1. 2. 9. 4.] [ 5. 6. 7. 8.] [ 9. 9. 9. 9.]] <NDArray 3x4 @cpu(0)> Now lets target even more by selecting a couple of targets at the same time. We’ll replace the 6 and the 7 with x[1:2, 1:3] = 5.0. print('original x, x=', x) x[1:2, 1:3] = 5.0 print('replaced range of elements with x[1:2, 1:3] = 5.0, x=', x) original x, x= [[ 1. 2. 9. 4.] [ 5. 6. 7. 8.] [ 9. 9. 9. 9.]] <NDArray 3x4 @cpu(0)> replaced range of elements with x[1:2, 1:3] = 5.0, x= [[ 1. 2. 9. 4.] [ 5. 5. 5. 8.] [ 9. 9. 9. 9.]] <NDArray 3x4 @cpu(0)> New Indexing Features in v1.0¶ Step¶ The basic slice syntax is i:j:k where i is the starting index, j is the stopping index, and k is the step (k must be nonzero). Note: Previously, MXNet supported basic slicing and indexing only with step=1. From release 1.0, arbitrary values of step are supported. x = nd.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], dtype='int32') # Select elements 1 through 7, and use a step of 2 x[1:7:2] [1 3 5] <NDArray 3 @cpu(0)> Negative Indices¶ Negative i and j are interpreted as n + i and n + j where n is the number of elements in the corresponding dimension. Negative k makes stepping go towards smaller indices. x[-2:10] [8 9] <NDArray 2 @cpu(0)> If the number of objects in the selection tuple is less than N , then : is assumed for any subsequent dimensions. x = nd.array([[[1],[2],[3]], [[4],[5],[6]]], dtype='int32') x[1:2] [[[4] [5] [6]]] <NDArray 1x3x1 @cpu(0)> You may use slicing to set values in the array, but (unlike lists) you can never grow the array. The size of the value to be set in x[obj] = value must be able to broadcast to the same shape as x[obj]. x = nd.arange(16, dtype='int32').reshape((4, 4)) print(x) [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11] [12 13 14 15]] <NDArray 4x4 @cpu(0)> print(x[1:4:2, 3:0:-1]) [[ 7 6 5] [15 14 13]] <NDArray 2x3 @cpu(0)> x[1:4:2, 3:0:-1] = [[16], [17]] print(x) [[ 0 1 2 3] [ 4 16 16 16] [ 8 9 10 11] [12 17 17 17]] <NDArray 4x4 @cpu(0)> New Advanced Indexing Features in v1.0¶ Advanced indexing is triggered when the selection object, obj, is a non-tuple sequence object (e.g. a Python list), a NumPy ndarray (of data type integer), an MXNet NDArray, or a tuple with at least one sequence object. Advanced indexing always returns a copy of the data. Note: - When the selection object is a Python list, it must be a list of integers. MXNet does not support the selection object being a nested list. That is, x[[1, 2]]is supported, while x[[1], [2]]is not. - When the selection object is a NumPy ndarrayor an MXNet NDArray, there is no dimension restrictions on the object. - When the selection object is a tuple containing Python list(s), both integer lists and nested lists are supported. That is, both x[1:4, [1, 2]]and x[1:4, [[1], [2]]are supported. Purely Integer Array Indexing¶ = nd.array([[1, 2], [3, 4], [5, 6]], dtype='int32') x[[0, 1, 2], [0, 1, 0]] [1 4 5] <NDArray 3 @cpu(0)> To achieve a behavior similar to the basic slicing above, broadcasting can be used. = nd.array([[ 0, 1, 2], [ 3, 4, 5], [ 6, 7, 8], [ 9, 10, 11]], dtype='int32') x[[[0, 0], [3, 3]], [[0, 2], [0, 2]]] [[ 0 2] [ 9 11]] <NDArray 2x2 @cpu(0)> However, since the indexing arrays above just repeat themselves, broadcasting can be used. x[[[0], [3]], [[0, 2]]] [[ 0 2] [ 9 11]] <NDArray 2x2 @cpu(0)> Combining Advanced and Basic Indexing¶ There are three situations we need to consider when mix advanced and basic indices in a single selection object. Let’s look at examples to understand each one’s behavior. - There is only one advanced index in the selection object. For example, xis an NDArraywith shape=(10, 20, 30, 40, 50)and result=x[:, :, ind]has one advanced index indwith shape=(2, 3, 4)on the third axis. The resultwill have shape=(10, 20, 2, 3, 4, 40, 50)because the subspace of xin the third dimension is replaced by the subspace of shape=(2, 3, 4). If we let i, j, k loop over the (2, 3, 4)-shaped subspace, it is equivalent to result[:, :, i, j, k, :, :] = x[:, :, ind[i, j, k], :, :]. import numpy as np shape = (10, 20, 30, 40, 50) x = nd.arange(np.prod(shape), dtype='int32').reshape(shape) ind = nd.arange(24).reshape((2, 3, 4)) print(x[:, :, ind].shape) (10, 20, 2, 3, 4, 40, 50) - There are at least two advanced indices in the selection object, and all the advanced indices are adjacent to each other. For example, xis an NDArraywith shape=(10, 20, 30, 40, 50)and result=x[:, :, ind1, ind2, :]has two advanced indices with shapes that are broadcastable to shape=(2, 3, 4). Then the resulthas shape=(10, 20, 2, 3, 4, 50)because (30, 40)-shaped subspace has been replaced with (2, 3, 4)-shaped subspace from the indices. ind1 = [0, 1, 2, 3] ind2 = [[[0], [1], [2]], [[3], [4], [5]]] print(x[:, :, ind1, ind2, :].shape) (10, 20, 2, 3, 4, 50) - There are at least two advanced indices in the selection object, and there is at least one advanced index separated from the others by basic indices. For example, xis an NDArraywith shape=(10, 20, 30, 40, 50)and result=x[:, :, ind1, :, ind2]has two advanced indices with shapes that are broadcastable to shape=(2, 3, 4). Then the resulthas shape=(2, 3, 4, 10, 20, 40)because there is no unambiguous place to place the indexing subspace, hence it is prepended to the beginning. print(x[:, :, ind1, :, ind2].shape) (2, 3, 4, 10, 20, 40)
https://mxnet.apache.org/versions/1.2.1/tutorials/basic/ndarray_indexing.html
CC-MAIN-2022-33
refinedweb
1,531
70.43
I was at the Global Azure Bootcamp recently concluded last week, one of the participant came and asked me, “Hey what is Cosmos DB” I casually responded “Well, that’s Microsoft’s globally distributed, massively scalable, horizontally partitioned, low latency, fully indexed, multi-model NoSQL database”. The immediate question came after that was whether it supports hybrid applications. In this blog I will be explaining how to leverage the features of cosmos db when you’re building hybrid applications. Ionic framework is an open source library of mobile-optimized components in JavaScript, HTML, and CSS. It provides developers with tools for building robust and optimized hybrid apps which works on Android,IOS and web. Ionic comes with very native-styled mobile UI elements and layouts that you’d get with a native SDK on iOS or Android. Let’s see how to build Hybrid application with Ionic and Cosmosdb PreRequisites: You need to have npm and node installed on your machine to get started with Ionic. Step 1: Make sure you’ve installed ionic in your machine with the following command, ionic -v Step 2: Install Ionic globally if it’s not installed, install it by using the command npm i -g ionic Step 3: Create a new ionic project Ionic start is a command to create a new ionic project. You pass in the directory name to create, and the template to use. The template can be a built-in one (tabs, blank) or can point to a GitHub URL. The aim is to create a simple ToDo application which displays lists of tasks, and user should be able to add new tasks. Lets create a blank project with the command ionic start cosmosdbApp tabs You will see a new project getting created. Step 4: Run the ionic app You can run the app with a simple command by navigating to the folder and then run Ionic serve This starts a local web server and opens your browser at the URL, showing the Ionic app in your desktop browser. Remember, ionic is just HTML, CSS and JavaScript! It will open the application in the default browser with the default app. If you’re stuck at any point you can refer to my slides on How to get started with Ionic and follow the steps. Step 5: Create the cosmosdb account on azure portal, We need to create an cosmosdb account and use the Endpoint and SecretKey in our application. You can follow the Blog on how to create it from the azure portal Create a database named “ToDoList” and containeras “Items“. Once created, lets go back to the application. Step 6: Lets add Cosmosdb SDK to the project To consume the Cosmosdb service in the application we need to add the Azure Cosmos Javascript SDK to the project. This can be done with the command npm i @azure/cosmos Step 7: You need to create an interface/model which will be used to save/retrieve the objects from the cosmosdb Step 8: You need to add two pages home and todo page , home to display the lists of items inside the containerand todo page to add a new item. These two pages can be generated insdie the module with the command, ionic g page home Ionic g page todo Step 9: We need to add a service to embed the logic to communicate with the cosmosdb you can create a new service inside the module as, ionic g service cosmos As we need to make use of the available methods inside the @azure/cosmos You can import cosmos with the line, import * as Cosmos from “@azure/cosmos”; Now make use of all the available functions in the SDK to add,delete,update items in the cosmosdb. Step 8: To make application compatible with android/ios , run the following command, Ionic cordova build ios/android If you want to make the development faster, you could try building your ionic application with capacitor as well. Now your hybrid application uses cosmosdb as a backend, with this demo you know how to use cosmosdb as a database for your hybrid application. I hope you should be able to create more applications in the future with cosmosdb and ionic. You can check the demo application source code from here.
https://sajeetharan.com/2019/06/12/build-hybrid-apps-with-cosmos-db-ionic/
CC-MAIN-2020-10
refinedweb
716
52.83
Hello all, I'm working with a custom RS485 adapter that I've connected to the following GPIO pins GPIO 14/8 - TX GPIO 15/10 - RX GPIO 18/12 - Direction My end goal to communicate via rs485-Modbus using Node. So far I've been able to send and receive messages via serial communications and manually flipping the 12 pin in user space. Example python code below[1] I'm stuck at getting modbus across the adapter. The golden egg would be to find an existing driver so I could use this device with minimalModbus , which I have working with a USB adapter. Short of that I need to either 1 - Write my own driver (scary) or 2 - Find a way to control the GPIO in Kernel space or 3 - Send modbus over serial and switch the GPIO in user space. This options seems like it would be the easiest to do, but would also have the worst performance. Any advice would be appreciated. This is my first real experience doing anything at this level on a Raspberry Pi or any other device so I wouldn't be shocked to find that I'm aiming in the wrong direction. [1] import time import serial import RPi.GPIO as GPIO GPIO.setmode(GPIO.BOARD) GPIO.setup(12, GPIO.OUT); ser = serial.Serial( port= '/dev/ttyS0', baudrate= 57600, parity= serial.PARITY_NONE, stopbits= serial.STOPBITS_ONE, bytesize= serial.EIGHTBITS, timeout=1 ) def write_add(): counter = 0; message = 0 while (True): print "writing", GPIO.output(12,1) #set high/transmit ser.write('%d \n'%(message)) time.sleep(0.005) #baud for 57600 #time.sleep(0.5) #baud for 9600 GPIO.output(12, 0) #pin set to low/receive loop_count = 0 res ="" while (res == ""): res =ser.readline(); if(res != ""): print "" print "Read Cycles: "+str(loop_count)+" Total: "+str(counter) print res message = int(res) + 1 counter = counter + 1 elif(loop_count > 10): res = "start over" else: print ".", loop_count = loop_count + 1 write_add()
https://www.raspberrypi.org/forums/viewtopic.php?t=213714&p=1316659
CC-MAIN-2019-04
refinedweb
323
67.15
glutSetWindowTitle man page glutSetWindowTitle — Request changing the title of the current window Library OpenGLUT - window Synopsis #include <openglut.h> void glutSetWindowTitle(const char* title); Parameters title New window title Description glutSetWindowTitle() requests that the window system change the title of the window. Normally a window system displays a title for every top-level window in the system. The initial title is set when you call glutCreateWindow(). By means of this function you can set the titles for your top-level OpenGLUT windows. Some window systems do not provide titles for windows, in which case this function may have no useful effect. Because the effect may be delayed or lost, you should not count on the effect of this function. However, it can be a nice touch to use the window title bar for a one-line status bar in some cases. Use discretion. If you just want one title for the window over the window's entire life, you should set it when you open the window with glutCreateWindow(). Caveats Only for managed, onscreen, top-level windows. Not all window systems display titles. May be ignored or delayed by window manager. See Also glutCreateWindow(3) glutSetIconTitle(3) Referenced By glutCreateWindow(3), glutSetIconTitle(3).
https://www.mankier.com/3/glutSetWindowTitle
CC-MAIN-2016-50
refinedweb
203
56.45
I have program i am trying to do. I was successful in checking to see if the file was created and if it was not created then creating it. Now I want to actually put data it the file and i am getting an exception error. Writing to a file should be very easy. Not sure where I am going wrong with this. Code java: import java.io.File; import java.io.*; import java.util.Formatter; import java.util.Scanner; /** * * @author Jamal */ public class Player { private int wonAGame; private int lostAGame; private int addMoney; private static String fPlayer; private Formatter x; Scanner sn = new Scanner(System.in); public String getPlayerinfo() { return fPlayer; } public void playerInfo(String fName) { System.out.println("Please enter your first name: "); String fname = sn.nextLine(); fPlayer = fname; Player pr = new Player(); pr.checkPlayer(fname); } public void checkPlayer(String fname) { File file = new File("C:\\test\\" + fPlayer + ".txt"); if (file.exists()) { System.out.println("Weclome back" + " " + fPlayer); } else { System.out.println("Sorry not there"); try { Formatter x = new Formatter("C:\\test\\" + fPlayer + ".txt"); System.out.println("File has been created"); } catch (Exception e) { System.out.println("didn't work"); } Player pr = new Player(); pr.writeFile(); } } public void writeFile() { x.format("%s,%s", "LastName, First Name"); } public void closeFile() { x.close(); } }
http://www.javaprogrammingforums.com/%20whats-wrong-my-code/17951-help-writing-file-getting-exception-error-printingthethread.html
CC-MAIN-2014-10
refinedweb
213
54.18
Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Learn Text Classification With Python and Keras. Choosing a Data Set. Extract the folder into a data folder and go ahead and load the data with Pandas: import pandas as pd filepath_dict = {'yelp': 'data/sentiment_analysis/yelp_labelled.txt', 'amazon': 'data/sentiment_analysis/amazon_cells_labelled.txt', 'imdb': 'data/sentiment_analysis/imdb_labelled.txt'} df_list = [] for source, filepath in filepath_dict.items(): df = pd.read_csv(filepath, names=['sentence', 'label'], sep='\t') df['source'] = source # Add another column filled with the source name df_list.append(df) df = pd.concat(df_list) print(df.iloc[0]) The result will be as follows: sentence Wow... Loved this place. label 1 source yelp Name: 0, dtype: object This looks about right. With this data set, you are able to train a model to predict the sentiment of a sentence. Take a quick moment to think about how you would go about predicting the data. One way you could do this is to count the frequency of each word in each sentence and tie this count back to the entire set of words in the data set. You would start by taking the data and creating a vocabulary from all the words in all sentences. The collection of texts is also called a corpus in NLP. The vocabulary in this case is a list of words that occurred in our text where each word has its own index. This enables you to create a vector for a sentence. You would then take the sentence you want to vectorize, and you count each occurrence in the vocabulary. The resulting vector will be with the length of the vocabulary and a count for each word in the vocabulary. The resulting vector is also called a feature vector. In a feature vector, each dimension can be a numeric or categorical feature, like for example the height of a building, the price of a stock, or, in our case, the count of a word in a vocabulary. These feature vectors are a crucial piece in data science and machine learning, as the model you want to train depends on them. Let’s quickly illustrate this. Imagine you have the following two sentences: >>> sentences = ['John likes ice cream', 'John hates chocolate.'] Next, you can use the CountVectorizer provided by the scikit-learn library to vectorize sentences. It takes the words of each sentence and creates a vocabulary of all the unique words in the sentences. This vocabulary can then be used to create a feature vector of the count of the words: >>> from sklearn.feature_extraction.text import CountVectorizer >>> vectorizer = CountVectorizer(min_df=0, lowercase=False) >>> vectorizer.fit(sentences) >>> vectorizer.vocabulary_ {'John': 0, 'chocolate': 1, 'cream': 2, 'hates': 3, 'ice': 4, 'likes': 5} This vocabulary serves also as an index of each word. Now, you can take each sentence and get the word occurrences of the words based on the previous vocabulary. The vocabulary consists of all five words in our sentences, each representing one word in the vocabulary. When you take the previous two sentences and transform them with the CountVectorizer you will get a vector representing the count of each word of the sentence: >>> vectorizer.transform(sentences).toarray() array([[1, 0, 1, 0, 1, 1], [1, 1, 0, 1, 0, 0]]) Now, you can see the resulting feature vectors for each sentence based on the previous vocabulary. For example, if you take a look at the first item, you can see that both vectors have a 1 there. This means that both sentences have one occurrence of John, which is in the first place in the vocabulary. This is considered a Bag-of-words (BOW) model, which is a common way in NLP to create vectors out of text. Each document is represented as a vector. You can use these vectors now as feature vectors for a machine learning model. This leads us to our next part, defining a baseline model. Defining a Baseline Model When you work with machine learning, one important step is to define a baseline model. This usually involves a simple model, which is then used as a comparison with the more advanced models that you want to test. In this case, you’ll use the baseline model to compare it to the more advanced methods involving (deep) neural networks, the meat and potatoes of this tutorial. First, you are going to split the data into a training and testing set which will allow you to evaluate the accuracy and see if your model generalizes well. This means whether the model is able to perform well on data it has not seen before. This is a way to see if the model is overfitting. Overfitting is when a model is trained too well on the training data. You want to avoid overfitting, as this would mean that the model mostly just memorized the training data. This would account for a large accuracy with the training data but a low accuracy in the testing data. We start by taking the Yelp data set which we extract from our concatenated data set. From there, we take the sentences and labels. The .values returns a NumPy array instead of a Pandas Series object which is in this context easier to work with: >>> from sklearn.model_selection import train_test_split >>> df_yelp = df[df['source'] == 'yelp'] >>> sentences = df_yelp['sentence'].values >>> y = df_yelp['label'].values >>> sentences_train, sentences_test, y_train, y_test = train_test_split( ... sentences, y, test_size=0.25, random_state=1000) Here we will use again on the previous BOW model to vectorize the sentences. You can use again the CountVectorizer for this task. Since you might not have the testing data available during training, you can create the vocabulary using only the training data. Using this vocabulary, you can create the feature vectors for each sentence of the training and testing set: >>> from sklearn.feature_extraction.text import CountVectorizer >>> vectorizer = CountVectorizer() >>> vectorizer.fit(sentences_train) >>> X_train = vectorizer.transform(sentences_train) >>> X_test = vectorizer.transform(sentences_test) >>> X_train <750x2505 sparse matrix of type '<class 'numpy.int64'>' with 7368 stored elements in Compressed Sparse Row format> You can see that the resulting feature vectors have 750 samples which are the number of training samples we have after the train-test split. Each sample has 2505 dimensions which is the size of the vocabulary. Also, you can see that we get a sparse matrix. This is a data type that is optimized for matrices with only a few non-zero elements, which only keeps track of the non-zero elements reducing the memory load. CountVectorizer performs tokenization which separates the sentences into a set of tokens as you saw previously in the vocabulary. It additionally removes punctuation and special characters and can apply other preprocessing to each word. If you want, you can use a custom tokenizer from the NLTK library with the CountVectorizer or use any number of the customizations which you can explore to improve the performance of your model. Note: There are a lot of additional parameters to CountVectorizer() that we forgo using here, such as adding ngrams, beacuse the goal at first is to build a simple baseline model. The token pattern itself defaults to token_pattern=’(?u)\b\w\w+\b’, which is a regex pattern that says, “a word is 2 or more Unicode word characters surrounded by word boundaries.”. The classification model we are going to use is the logistic regression which is a simple yet powerful linear model that is mathematically speaking in fact a form of regression between 0 and 1 based on the input feature vector. By specifying a cutoff value (by default 0.5), the regression model is used for classification. You can use again scikit-learn library which provides the LogisticRegression classifier: >>> from sklearn.linear_model import LogisticRegression >>> classifier = LogisticRegression() >>> classifier.fit(X_train, y_train) >>> score = classifier.score(X_test, y_test) >>> print("Accuracy:", score) Accuracy: 0.796 You can see that the logistic regression reached an impressive 79.6%, but let’s have a look how this model performs on the other data sets that we have. In this script, we perform and evaluate the whole process for each data set that we have: for source in df['source'].unique(): df_source = df[df['source'] == source] sentences = df_source['sentence'].values y = df_source['label'].values sentences_train, sentences_test, y_train, y_test = train_test_split( sentences, y, test_size=0.25, random_state=1000) vectorizer = CountVectorizer() vectorizer.fit(sentences_train) X_train = vectorizer.transform(sentences_train) X_test = vectorizer.transform(sentences_test) classifier = LogisticRegression() classifier.fit(X_train, y_train) score = classifier.score(X_test, y_test) print('Accuracy for {} data: {:.4f}'.format(source, score)) Here’s the result: Accuracy for yelp data: 0.7960 Accuracy for amazon data: 0.7960 Accuracy for imdb data: 0.7487 Great! You can see that this fairly simple model achieves a fairly good accuracy. It would be interesting to see whether we are able to outperform this model. In the next part, we will get familiar with (deep) neural networks and how to apply them to text classification. A Primer on (Deep) Neural Networks You might have experienced some of the excitement and fear related to artificial intelligence and deep learning. You might have stumbled across some confusing article or concerned TED talk about the approaching singularity or maybe you saw the backflipping robots and you wonder whether a life in the woods seems reasonable after all. On a lighter note, AI researchers all agreed that they did not agree with each other when AI will exceed Human-level performance. According to this paper we should still have some time left. So you might already be curious how neural networks work. If you already are familiar with neural networks, feel free to skip to the parts involving Keras. Also, there is the wonderful Deep Learning book by Ian Goodfellow which I highly recommend if you want to dig deeper into the math. You can read the whole book online for free. In this section you will get an overview of neural networks and their inner workings, and you will later see how to use neural networks with the outstanding Keras library. In this article, you don’t have to worry about the singularity, but (deep) neural networks play a crucial role in the latest developments in AI. It all started with a famous paper in 2012 by Geoffrey Hinton and his team, which outperformed all previous models in the famous ImageNet Challenge. The challenge could be considered the World Cup in computer vision which involves classifying a large set of images based on given labels. Geoffrey Hinton and his team managed to beat the previous models by using a convolutional neural network (CNN), which we will cover in this tutorial as well. Since then, neural networks have moved into several fields involving classification, regression and even generative models. The most prevalent fields include computer vision, voice recognition and natural language processing (NLP). Neural networks, or sometimes called artificial neural network (ANN) or feedforward neural network, are computational networks which were vaguely inspired by the neural networks in the human brain. They consist of neurons (also called nodes) which are connected like in the graph below. You start by having a layer of input neurons where you feed in your feature vectors and the values are then feeded forward to a hidden layer. At each connection, you are feeding the value forward, while the value is multiplied by a weight and a bias is added to the value. This happens at every connection and at the end you reach an output layer with one or more output nodes. If you want to have a binary classification you can use one node, but if you have multiple categories you should use multiple nodes for each category: You can have as many hidden layers as you wish. In fact, a neural network with more than one hidden layer is considered a deep neural network. Don’t worry: I won’t get here into the mathematical depths concerning neural networks. But if you want to get an intuitive visual understanding of the math involved, you can check out the YouTube Playlist by Grant Sanderson. The formula from one layer to the next is this short equation: Let’s slowly unpack what is happening here. You see, we are dealing here with only two layers. The layer with nodes a serves as input for the layer with nodes o. In order to calculate the values for each output node, we have to multiply each input node by a weight w and add a bias b. All of those have to be then summed and passed to a function f. This function is considered the activation function and there are various different functions that can be used depending on the layer or the problem. It is generally common to use a rectified linear unit (ReLU) for hidden layers, a sigmoid function for the output layer in a binary classification problem, or a softmax function for the output layer of multi-class classification problems. You might already wonder how the weights are calculated, and this is obviously the most important part of neural networks, but also the most difficult part. The algorithm starts by initializing the weights with random values and they are then trained with a method called backpropagation. This is done by using optimization methods (also called optimizer) like the gradient descent in order to reduce the error between the computed and the desired output (also called target output). The error is determined by a loss function whose loss we want to minimize with the optimizer. The whole process is too extensive to cover here, but I’ll refer again to the Grant Sanderson playlist and the Deep Learning book by Ian Goodfellow I mentioned before. What you have to know is that there are various optimization methods that you can use, but the most common optimizer currently used is called Adam which has a good performance in various problems. You can also use different loss functions, but in this tutorial you will only need the cross entropy loss function or more specifically binary cross entropy which is used for binary classification problems. Be sure to experiment with the various available methods and tools. Some researchers even claim in a recent article that the choice for the best performing methods borders on alchemy. The reason being that many methods are not well explained and consist of a lot of tweaking and testing. Introducing Keras Keras is a deep learning and neural networks API by François Chollet which is capable of running on top of Tensorflow (Google), Theano or CNTK (Microsoft). To quote the wonderful book by François Chollet, Deep Learning with Python: Keras is a model-level library, providing high-level building blocks for developing deep-learning models. It doesn’t handle low-level operations such as tensor manipulation and differentiation. Instead, it relies on a specialized, well-optimized tensor library to do so, serving as the backend engine of Keras (Source) It is a great way to start experimenting with neural networks without having to implement every layer and piece on your own. For example Tensorflow is a great machine learning library, but you have to implement a lot of boilerplate code to have a model running. Installing Keras Before installing Keras, you’ll need either Tensorflow, Theano, or CNTK. In this tutorial we will be using Tensorflow so check out their installation guide here, but feel free to use any of the frameworks that works best for you. Keras can be installed using PyPI with the following command: $ pip install keras You can choose the backend you want to have by opening the Keras configuration file which you can find here: $HOME/.keras/keras.json If you are a Windows user, you have to replace $HOME with %USERPROFILE%. The configuration file should look as follows: { "image_data_format": "channels_last", "epsilon": 1e-07, "floatx": "float32", "backend": "tensorflow" } You can change the backend field there to "theano", "tensorflow" or "cntk", given that you have installed the backend on your machine. For more details check out the Keras backends documentation. You might notice that we use float32 data in the configuration file. The reason for this is that neural networks are frequently used in GPUs, and the computational bottleneck is memory. By using 32 bit, we are able reduce the memory load and we do not lose too much information in the process. Your First Keras Model Now you are finally ready to experiment with Keras. Keras supports two main types of models. You have the Sequential model API which you are going to see in use in this tutorial and the functional API which can do everything of the Sequential model but it can be also used for advanced models with complex network architectures. The Sequential model is a linear stack of layers, where you can use the large variety of available layers in Keras. The most common layer is the Dense layer which is your regular densely connected neural network layer with all the weights and biases that you are already familiar with. Let’s see if we can achieve some improvement to our previous logistic regression model. You can use the X_train and X_test arrays that you built in our earlier example. Before we build our model, we need to know the input dimension of our feature vectors. This happens only in the first layer since the following layers can do automatic shape inference. In order to build the Sequential model, you can add layers one by one in order as follows: >>> from keras.models import Sequential >>> from keras import layers >>> input_dim = X_train.shape[1] # Number of features >>> model = Sequential() >>> model.add(layers.Dense(10, input_dim=input_dim, activation='relu')) >>> model.add(layers.Dense(1, activation='sigmoid')) Using TensorFlow backend. Before you can start with the training of the model, you need to configure the learning process. This is done with the .compile() method. This method specifies the optimizer and the loss function. Additionally, you can add a list of metrics which can be later used for evaluation, but they do not influence the training. In this case, we want to use the binary cross entropy and the Adam optimizer you saw in the primer mentioned before. Keras also includes a handy .summary() function to give an overview of the model and the number of parameters available for training: >>> model.compile(loss='binary_crossentropy', ... optimizer='adam', ... metrics=['accuracy']) >>> model.summary() _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= dense_1 (Dense) (None, 10) 25060 _________________________________________________________________ dense_2 (Dense) (None, 1) 11 ================================================================= Total params: 25,071 Trainable params: 25,071 Non-trainable params: 0 _________________________________________________________________ You might notice that we have 25060 parameters for the first layer and another 11 in the second one. Where did those come from? See, we have 2505 dimensions for each feature vector, and then we have 10 nodes. We need weights for each feature dimension and each node which accounts for 2505 * 10 = 25050 parameters, and then we have another 10 times an added bias for each node, which gets us the 25060 parameters. In the final node, we have another 10 weights and one bias, which gets us to 11 parameters. That’s a total of 25071 parameters for both layers. Neat! You are almost there. Now it is time to start your training with the .fit() function. Since the training in neural networks is an iterative process, the training won’t just stop after it is done. You have to specify the number of iterations you want the model to be training. Those completed iterations are commonly called epochs. We want to run it for 100 epochs to be able to see how the training loss and accuracy are changing after each epoch. Another parameter you have to your selection is the batch size. The batch size is responsible for how many samples we want to use in one epoch, which means how many samples are used in one forward/backward pass. This increases the speed of the computation as it need fewer epochs to run, but it also needs more memory, and the model may degrade with larger batch sizes. Since we have a small training set, we can leave this to a low batch size: >>> history = model.fit(X_train, y_train, ... epochs=100, ... verbose=False, ... validation_data=(X_test, y_test), ... batch_size=10) Now you can use the .evaluate() method to measure the accuracy of the model. You can do this both for the training data and testing data. We expect that the training data has a higher accuracy then for the testing data. Tee longer you would train a neural network, the more likely it is that it starts overfitting. Note that if you rerun the .fit() method, you’ll start off with the computed weights from the previous training. Make sure to call clear_session() before you start training the model again: >>> from keras.backend import clear_session >>> clear_session() Now let’s evaluate the accuracy of the model: >>> loss, accuracy = model.evaluate(X_train, y_train, verbose=False) >>> print("Training Accuracy: {:.4f}".format(accuracy)) >>> loss, accuracy = model.evaluate(X_test, y_test, verbose=False) >>> print("Testing Accuracy: {:.4f}".format(accuracy)) Training Accuracy: 1.0000 Testing Accuracy: 0.7754 You can already see that the model was overfitting since it reached 100% accuracy for the training set. But this was expected since the number of epochs was fairly large for this model. However, the accuracy of the testing set has already surpassed our previous logistic Regression with BOW model, which is a great step further in terms of our progress. To make your life easier, you can use this little helper function to visualize the loss and accuracy for the training and testing data based on the History callback. This callback, which is automatically applied to each Keras model, records the loss and additional metrics that can be added in the .fit() method. In this case, we are only interested in the accuracy. This helper function employs the matplotlib plotting library: import matplotlib.pyplot as plt plt.style.use('ggplot') def plot_history(history): acc = history.history['acc'] val_acc = history.history['val_acc'] loss = history.history['loss'] val_loss = history.history['val_loss'] x = range(1, len(acc) + 1) plt.figure(figsize=(12, 5)) plt.subplot(1, 2, 1) plt.plot(x, acc, 'b', label='Training acc') plt.plot(x, val_acc, 'r', label='Validation acc') plt.title('Training and validation accuracy') plt.legend() plt.subplot(1, 2, 2) plt.plot(x, loss, 'b', label='Training loss') plt.plot(x, val_loss, 'r', label='Validation loss') plt.title('Training and validation loss') plt.legend() To use this function, simply call plot_history() with the collected accuracy and loss inside the history dictionary: >>> plot_history(history) You can see that we have trained our model for too long since the training set reached 100% accuracy. A good way to see when the model starts overfitting is when the loss of the validation data starts rising again. This tends to be a good point to stop the model. You can see this around 20-40 epochs in this training. Note: When training neural networks, you should use a separate testing and validation set. What you would usually do is take the model with the highest validation accuracy and then test the model with the testing set. This makes sure that you don’t overfit the model. Using the validation set to choose the best model is a form of data leakage (or “cheating”) to get to pick the result that produced the best test score out of hundreds of them. Data leakage happens when information outside the training data set is used in the model. In this case, our testing and validation set are the same, since we have a smaller sample size. As we have covered before, (deep) neural networks perform best when you have a very large number of samples. In the next part, you’ll see a different way to represent words as vectors. This is a very exciting and powerful way to work with words where you’ll see how to represent words as dense vectors. What Is a Word Embedding? Text is considered a form of sequence data similar to time series data that you would have in weather data or financial data. In the previous BOW model, you have seen how to represent a whole sequence of words as a single feature vector. Now you will see how to represent each word as vectors. There are various ways to vectorize text, such as: - Words represented by each word as a vector - Characters represented by each character as a vector - N-grams of words/characters represented as a vector (N-grams are overlapping groups of multiple succeeding words/characters in the text) In this tutorial, you’ll see how to deal with representing words as vectors which is the common way to use text in neural networks. Two possible ways to represent a word as a vector are one-hot encoding and word embeddings. One-Hot Encoding The first way to represent a word as a vector is by creating a so-called one-hot encoding, which is simply done by taking a vector of the length of the vocabulary with an entry for each word in the corpus. In this way, you have for each word, given it has a spot in the vocabulary, a vector with zeros everywhere except for the corresponding spot for the word which is set to one. As you might imagine, this can become a fairly large vector for each word and it does not give any additional information like the relationship between words. Let’s say you have a list of cities as in the following example: >>> cities = ['London', 'Berlin', 'Berlin', 'New York', 'London'] >>> cities ['London', 'Berlin', 'Berlin', 'New York', 'London'] You can use scikit-learn and the LabelEncoder to encode the list of cities into categorical integer values like here: >>> from sklearn.preprocessing import LabelEncoder >>> encoder = LabelEncoder() >>> city_labels = encoder.fit_transform(cities) >>> city_labels array([1, 0, 0, 2, 1]) Using this representation, you can use the OneHotEncoder provided by scikit-learn to encode the categorical values we got before into a one-hot encoded numeric array. OneHotEncoder expects each categorical value to be in a separate row, so you’ll need to reshape the array, then you can apply the encoder: >>> from sklearn.preprocessing import OneHotEncoder >>> encoder = OneHotEncoder(sparse=False) >>> city_labels = city_labels.reshape((5, 1)) >>> encoder.fit_transform(city_labels) array([[0., 1., 0.], [1., 0., 0.], [1., 0., 0.], [0., 0., 1.], [0., 1., 0.]]) You can see that categorical integer value represents the position of the array which is 1 and the rest is 0. This is often used when you have a categorical feature which you cannot represent as a numeric value but you still want to be able to use it in machine learning. One use case for this encoding is of course words in a text but it is most prominently used for categories. Such categories can be for example city, department, or other categories. Word Embeddings This method represents words as dense word vectors (also called word embeddings) which are trained unlike the one-hot encoding which are hardcoded. This means that the word embeddings collect more information into fewer dimensions. Note that the word embeddings do not understand the text as a human would, but they rather map the statistical structure of the language used in the corpus. Their aim is to map semantic meaning into a geometric space. This geometric space is then called the embedding space. This would map semantically similar words close on the embedding space like numbers or colors. If the embedding captures the relationship between words well, things like vector arithmetic should become possible. A famous example in this field of study is the ability to map King - Man + Woman = Queen. How can you get such a word embedding? You have two options for this. One way is to train your word embeddings during the training of your neural network. The other way is by using pretrained word embeddings which you can directly use in your model. There you have the option to either leave these word embeddings unchanged during training or you train them also. Now you need to tokenize the data into a format that can be used by the word embeddings. Keras offers a couple of convenience methods for text preprocessing and sequence preprocessing which you can employ to prepare your text. You can start by using the Tokenizer utility class which can vectorize a text corpus into a list of integers. Each integer maps to a value in a dictionary that encodes the entire corpus, with the keys in the dictionary being the vocabulary terms themselves. You can add the parameter num_words, which is responsible for setting the size of the vocabulary. The most common num_words words will be then kept. I have the testing and training data prepared from the previous example: >>> from keras.preprocessing.text import Tokenizer >>> tokenizer = Tokenizer(num_words=5000) >>> tokenizer.fit_on_texts(sentences_train) >>> X_train = tokenizer.texts_to_sequences(sentences_train) >>> X_test = tokenizer.texts_to_sequences(sentences_test) >>> vocab_size = len(tokenizer.word_index) + 1 # Adding 1 because of reserved 0 index >>> print(sentences_train[2]) >>> print(X_train[2]) Of all the dishes, the salmon was the best, but all were great. [11, 43, 1, 171, 1, 283, 3, 1, 47, 26, 43, 24, 22] The indexing is ordered after the most common words in the text, which you can see by the word the having the index 1. It is important to note that the index 0 is reserved and is not assigned to any word. This zero index is used for padding, which I’ll introduce in a moment. Unknown words (words that are not in the vocabulary) are denoted in Keras with word_count + 1 since they can also hold some information. You can see the index of each word by taking a look at the word_index dictionary of the Tokenizer object: >>> for word in ['the', 'all', 'happy', 'sad']: ... print('{}: {}'.format(word, tokenizer.word_index[word])) the: 1 all: 43 happy: 320 sad: 450 Note: Pay close attention to the difference between this technique and the X_train that was produced by scikit-learn’s CountVectorizer. With CountVectorizer, we had stacked vectors of word counts, and each vector was the same length (the size of the total corpus vocabulary). With Tokenizer, the resulting vectors equal the length of each text, and the numbers don’t denote counts, but rather correspond to the word values from the dictionary tokenizer.word_index. One problem that we have is that each text sequence has in most cases different length of words. To counter this, you can use pad_sequence() which simply pads the sequence of words with zeros. By default, it prepends zeros but we want to append them. Typically it does not matter whether you prepend or append zeros. Additionally you would want to add a maxlen parameter to specify how long the sequences should be. This cuts sequences that exceed that number. In the following code, you can see how to pad sequences with Keras: >>> from keras.preprocessing.sequence import pad_sequences >>> maxlen = 100 >>> X_train = pad_sequences(X_train, padding='post', maxlen=maxlen) >>> X_test = pad_sequences(X_test, padding='post', maxlen=maxlen) >>> print(X_train[0, :]) [ 1 10 3 282 739 25 8 208 30 64 459 230 13 1 124 5 231 8 58 5 first values represent the index in the vocabulary as you have learned from the previous examples. You can also see that the resulting feature vector contains mostly zeros, since you have a fairly short sentence. In the next part you will see how to work with word embeddings in Keras. Keras Embedding Layer Notice that, at this point, our data is still hardcoded. We have not told Keras to learn a new embedding space through successive tasks. Now you can use the Embedding Layer of Keras which takes the previously calculated integers and maps them to a dense vector of the embedding. You will need the following parameters: input_dim: the size of the vocabulary output_dim: the size of the dense vector input_length: the length of the sequence With the Embedding layer we have now a couple of options. One way would be to take the output of the embedding layer and plug it into a Dense layer. In order to do this you have to add a Flatten layer in between that prepares the sequential input for the Dense layer: from keras.models import Sequential from keras import layers embedding_dim = 50 model = Sequential() model.add(layers.Embedding(input_dim=vocab_size, output_dim=embedding_dim, input_length=maxlen)) model.add(layers.Flatten()) model.add(layers.Dense(10, activation='relu')) model.add(layers.Dense(1, activation='sigmoid')) model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy']) model.summary() The result will be as follows: _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= embedding_8 (Embedding) (None, 100, 50) 87350 _________________________________________________________________ flatten_3 (Flatten) (None, 5000) 0 _________________________________________________________________ dense_13 (Dense) (None, 10) 50010 _________________________________________________________________ dense_14 (Dense) (None, 1) 11 ================================================================= Total params: 137,371 Trainable params: 137,371 Non-trainable params: 0 _________________________________________________________________ You can now see that we have 87350 new parameters to train. This number comes from vocab_size times the embedding_dim. These weights of the embedding layer are initialized with random weights and are then adjusted through backpropagation during training. This model takes the words as they come in the order of the sentences as input vectors. You can train it with the following: history = model.fit(X_train, y_train, epochs=20,.5100 Testing Accuracy: 0.4600 This is typically a not very reliable way to work with sequential data as you can see in the performance. When working with sequential data you want to focus on methods that look at local and sequential information instead of absolute positional information. Another way to work with embeddings is by using a MaxPooling1D/ AveragePooling1D or a GlobalMaxPooling1D/ GlobalAveragePooling1D layer after the embedding. You can think of the pooling layers as a way to downsample (a way to reduce the size of) the incoming feature vectors. In the case of max pooling you take the maximum value of all features in the pool for each feature dimension. In the case of average pooling you take the average, but max pooling seems to be more commonly used as it highlights large values. Global max/average pooling takes the maximum/average of all features whereas in the other case you have to define the pool size. Keras has again its own layer that you can add in the sequential model: from keras.models import Sequential from keras import layers embedding_dim = 50 model = Sequential() model.add(layers.Embedding(input_dim=vocab_size, output_dim=embedding_dim, input_length=maxlen))_9 (Embedding) (None, 100, 50) 87350 _________________________________________________________________ global_max_pooling1d_5 (Glob (None, 50) 0 _________________________________________________________________ dense_15 (Dense) (None, 10) 510 _________________________________________________________________ dense_16 (Dense) (None, 1) 11 ================================================================= Total params: 87,871 Trainable params: 87,871 Non-trainable params: 0 _________________________________________________________________ The procedure for training does not change:.8050 You can already see some improvements in our models. Next you’ll see how we can employ pretrained word embeddings and if they help us with our model. Using Pretrained Word Embeddings We just saw an example of jointly learning word embeddings incorporated into the larger model that we want to solve. An alternative is to use a precomputed embedding space that utilizes a much larger corpus. It is possible to precompute word embeddings by simply training them on a large corpus of text. Among the most popular methods are Word2Vec developed by Google and GloVe (Global Vectors for Word Representation) developed by the Stanford NLP Group. Note that those are different approaches with the same goal. Word2Vec achieves this by employing neural networks and GloVe achieves this with a co-occurrence matrix and by using matrix factorization. In both cases you are dealing with dimensionality reduction, but Word2Vec is more accurate and GloVe is faster to compute. In this tutorial, you’ll see how to work with the GloVe word embeddings from the Stanford NLP Group as their size is more manageable than the Word2Vec word embeddings provided by Google. Go ahead and download the 6B (trained on 6 billion words) word embeddings from here ( glove.6B.zip, 822 MB). You can find other word embeddings also on the main GloVe page. You can find the pretrained Word2Vec embeddings by Google here. If you want to train your own word embeddings, you can do so efficiently with the gensim Python package which uses Word2Vec for calculation. More details on how to do this here. Now that we got you covered, you can start using the word embeddings in your models. You can see in the next example how you can load the embedding matrix. Each line in the file starts with the word and is followed by the embedding vector for the particular word. This is a large file with 400000 lines, with each line representing a word followed by its vector as a stream of floats. For example, here are the first 50 characters of the first line: $ head -n 1 data/glove_word_embeddings/glove.6B.50d.txt | cut -c-50 the 0.418 0.24968 -0.41242 0.1217 0.34527 -0.04445 Since you don’t need all words, you can focus on only the words that we have in our vocabulary. Since we have only a limited number of words in our vocabulary, we can skip most of the 40000 words in the pretrained word embeddings: import numpy as np def create_embedding_matrix(filepath, word_index, embedding_dim): vocab_size = len(word_index) + 1 # Adding again 1 because of reserved 0 index embedding_matrix = np.zeros((vocab_size, embedding_dim)) with open(filepath) as f: for line in f: word, *vector = line.split() if word in word_index: idx = word_index[word] embedding_matrix[idx] = np.array( vector, dtype=np.float32)[:embedding_dim] return embedding_matrix You can use this function now to retrieve the embedding matrix: >>> embedding_dim = 50 >>> embedding_matrix = create_embedding_matrix( ... 'data/glove_word_embeddings/glove.6B.50d.txt', ... tokenizer.word_index, embedding_dim) Wonderful! Now you are ready to use the embedding matrix in training. Let’s go ahead and use the previous network with global max pooling and see if we can improve this model. When you use pretrained word embeddings you have the choice to either allow the embedding to be updated during training or only use the resulting embedding vectors as they are. First, let’s have a quick look how many of the embedding vectors are nonzero: >>> nonzero_elements = np.count_nonzero(np.count_nonzero(embedding_matrix, axis=1)) >>> nonzero_elements / vocab_size 0.9507727532913566 This means 95.1% of the vocabulary is covered by the pretrained model, which is a good coverage of our vocabulary. Let’s have a look at the performance when using the GlobalMaxPool1D layer: model = Sequential() model.add(layers.Embedding(vocab_size, embedding_dim, weights=[embedding_matrix], input_length=maxlen, trainable=False))_10 (Embedding) (None, 100, 50) 87350 _________________________________________________________________ global_max_pooling1d_6 (Glob (None, 50) 0 _________________________________________________________________ dense_17 (Dense) (None, 10) 510 _________________________________________________________________ dense_18 (Dense) (None, 1) 11 ================================================================= Total params: 87,871 Trainable params: 521 Non-trainable params: 87,350 _________________________________________________________________.7500 Testing Accuracy: 0.6950 Since the word embeddings are not additionally trained, it is expected to be lower. But let’s now see how this performs if we allow the embedding to be trained by using trainable=True: model = Sequential() model.add(layers.Embedding(vocab_size, embedding_dim, weights=[embedding_matrix], input_length=maxlen, trainable=True))_11 (Embedding) (None, 100, 50) 87350 _________________________________________________________________ global_max_pooling1d_7 (Glob (None, 50) 0 _________________________________________________________________ dense_19 (Dense) (None, 10) 510 _________________________________________________________________ dense_20 (Dense) (None, 1) 11 ================================================================= Total params: 87,871 Trainable params: 87,871 Non-trainable params: 0 _________________________________________________________________.8250 You can see that it is most effective to allow the embeddings to be trained. When dealing with large training sets it can boost the training process to be much faster than without. In our case it seemed to help but not by much. This does not have to be because of pretrained word embeddings. Now it is time to focus on a more advanced neural network model to see if it is possible to boost the model and give it the leading edge over the previous models. Convolutional Neural Networks (CNN) Convolutional neural networks or also called convnets are one of the most exciting developments in machine learning in recent years. They have revolutionized image classification and computer vision by being able to extract features from images and using them in neural networks. The properties that made them useful in image processing makes them also handy for sequence processing. You can imagine a CNN as a specialized neural network that is able to detect specific patterns. If it is just another neural network, what differentiates it from what you have previously learned? A CNN has hidden layers which are called convolutional layers. When you think of images, a computer has to deal with a two dimensional matrix of numbers and therefore you need some way to detect features in this matrix. These convolutional layers are able to detect edges, corners and other kinds of textures which makes them such a special tool. The convolutional layer consists of multiple filters which are slid across the image and are able to detect specific features. This is the very core of the technique, the mathematical process of convolution. With each convolutional layer the network is able to detect more complex patterns. In the Feature Visualization by Chris Olah you can get a good intuition what these features can look like. When you are working with sequential data, like text, you work with one dimensional convolutions, but the idea and the application stays the same. You still want to pick up on patterns in the sequence which become more complex with each added convolutional layer. In the next figure you can see how such a convolution works. It starts by taking a patch of input features with the size of the filter kernel. With this patch you take the dot product of the multiplied weights of the filter. The one dimensional convnet is invariant to translations, which means that certain sequences can be recognized at a different position. This can be helpful for certain patterns in the text: Now let’s have a look how you can use this network in Keras. Keras offers again various Convolutional layers which you can use for this task. The layer you’ll need is the Conv1D layer. This layer has again various parameters to choose from. The ones you are interested in for now are the number of filters, the kernel size, and the activation function. You can add this layer in between the Embedding layer and the GlobalMaxPool1D layer: embedding_dim = 100 model = Sequential() model.add(layers.Embedding(vocab_size, embedding_dim, input_length=maxlen)) model.add(layers.Conv1D(128, 5, activation='relu')) model.add(layers.GlobalMaxPooling1D()) model.add(layers.Dense(10, activation='relu')) model.add(layers.Dense(1, activation='sigmoid')) model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy']) model.summary() The result will be as follows: _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= embedding_13 (Embedding) (None, 100, 100) 174700 _________________________________________________________________ conv1d_2 (Conv1D) (None, 96, 128) 64128 _________________________________________________________________ global_max_pooling1d_9 (Glob (None, 128) 0 _________________________________________________________________ dense_23 (Dense) (None, 10) 1290 _________________________________________________________________ dense_24 (Dense) (None, 1) 11 ================================================================= Total params: 240,129 Trainable params: 240,129 Non-trainable params: 0 _________________________________________________________________ history = model.fit(X_train, y_train, epochs=10,.7700 You can see that 80% accuracy seems to be tough hurdle to overcome with this data set and a CNN might not be well equipped. The reason for such a plateau might be that: - There are not enough training samples - The data you have does not generalize well - Missing focus on tweaking the hyperparameters CNNs work best with large training sets where they are able to find generalizations where a simple model like logistic regression won’t be able. Hyperparameters Optimization One crucial steps of deep learning and working with neural networks is hyperparameter optimization. As you saw in the models that we have used so far, even with simpler ones, you had a large number of parameters to tweak and choose from. Those parameters are called hyperparameters. This is the most time consuming part of machine learning and sadly there are no one-fits-all solutions ready. When you have a look at the competitions on Kaggle, one of the largest places to compete against other fellow data scientists, you can see that many of the winning teams and models have gone through a lot of tweaking and experimenting until they reached their prime. So don’t get discouraged when it gets tough and you reach a plateau, but rather think about the ways you could optimize the model or the data. One popular method for hyperparameter optimization is grid search. What this method does is it takes lists of parameters and it runs the model with each parameter combination that it can find. It is the most thorough way but also the most computationally heavy way to do this. Another common way, random search, which you’ll see in action here, simply takes random combinations of parameters. In order to apply random search with Keras, you will need to use the KerasClassifier which serves as a wrapper for the scikit-learn API. With this wrapper you are able to use the various tools available with scikit-learn like cross-validation. The class that you need is RandomizedSearchCV which implements random search with cross-validation. Cross-validation is a way to validate the model and take the whole data set and separate it into multiple testing and training data sets. There are various types of cross-validation. One type is the k-fold cross-validation which you’ll see in this example. In this type the data set is partitioned into k equal sized sets where one set is used for testing and the rest of the partitions are used for training. This enables you to run k different runs, where each partition is once used as a testing set. So, the higher k is the more accurate the model evaluation is, but the smaller each testing set is. First step for KerasClassifier is to have a function that creates a Keras model. We will use the previous model, but we will allow various parameters to be set for the hyperparameter optimization: def create_model(num_filters, kernel_size, vocab_size, embedding_dim, maxlen): model = Sequential() model.add(layers.Embedding(vocab_size, embedding_dim, input_length=maxlen)) model.add(layers.Conv1D(num_filters, kernel_size, activation='relu')) model.add(layers.GlobalMaxPooling1D()) model.add(layers.Dense(10, activation='relu')) model.add(layers.Dense(1, activation='sigmoid')) model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy']) return model Next, you want to define the parameter grid that you want to use in training. This consists of a dictionary with each parameters named as in the previous function. The number of spaces on the grid is 3 * 3 * 1 * 1 * 1, where each of those numbers is the number of different choices for a given parameter. You can see how this could get computationally expensive very quickly, but luckily both grid search and random search are embarrassingly parallel, and the classes come with an n_jobs parameter that lets you test grid spaces in parallel. The parameter grid is initialized with the following dictionary: param_grid = dict(num_filters=[32, 64, 128], kernel_size=[3, 5, 7], vocab_size=[5000], embedding_dim=[50], maxlen=[100]) Now you are already ready to start running the random search. In this example we iterate over each data set and then you want to preprocess the data in the same way as previously. Afterwards you take the previous function and add it to the KerasClassifier wrapper class including the number of epochs. The resulting instance and the parameter grid are then used as the estimator in the RandomSearchCV class. Additionally, you can choose the number of folds in the k-folds cross-validation, which is in this case 4. You have seen most of the code in this snippet before in our previous examples. Besides the RandomSearchCV and KerasClassifier, I have added a little block of code handling the evaluation: from keras.wrappers.scikit_learn import KerasClassifier from sklearn.model_selection import RandomizedSearchCV # Main settings epochs = 20 embedding_dim = 50 maxlen = 100 output_file = 'data/output.txt' # Run grid search for each source (yelp, amazon, imdb) for source, frame in df.groupby('source'): print('Running grid search for data set :', source) sentences = df['sentence'].values y = df['label'].values # Train-test split sentences_train, sentences_test, y_train, y_test = train_test_split( sentences, y, test_size=0.25, random_state=1000) # Tokenize words tokenizer = Tokenizer(num_words=5000) tokenizer.fit_on_texts(sentences_train) X_train = tokenizer.texts_to_sequences(sentences_train) X_test = tokenizer.texts_to_sequences(sentences_test) # Adding 1 because of reserved 0 index vocab_size = len(tokenizer.word_index) + 1 # Pad sequences with zeros X_train = pad_sequences(X_train, padding='post', maxlen=maxlen) X_test = pad_sequences(X_test, padding='post', maxlen=maxlen) # Parameter grid for grid search param_grid = dict(num_filters=[32, 64, 128], kernel_size=[3, 5, 7], vocab_size=[vocab_size], embedding_dim=[embedding_dim], maxlen=[maxlen]) model = KerasClassifier(build_fn=create_model, epochs=epochs, batch_size=10, verbose=False) grid = RandomizedSearchCV(estimator=model, param_distributions=param_grid, cv=4, verbose=1, n_iter=5) grid_result = grid.fit(X_train, y_train) # Evaluate testing set test_accuracy = grid.score(X_test, y_test) # Save and evaluate results prompt = input(f'finished {source}; write to file and proceed? [y/n]') if prompt.lower() not in {'y', 'true', 'yes'}: break with open(output_file, 'a') as f: s = ('Running {} data set\nBest Accuracy : ' '{:.4f}\n{}\nTest Accuracy : {:.4f}\n\n') output_string = s.format( source, grid_result.best_score_, grid_result.best_params_, test_accuracy) print(output_string) f.write(output_string) This takes a while which is a perfect chance to go outside to get some fresh air or even go on a hike, depending on how many models you want to run. Let’s take a look what we have got: Running amazon data set Best Accuracy : 0.8122 {'vocab_size': 4603, 'num_filters': 64, 'maxlen': 100, 'kernel_size': 5, 'embedding_dim': 50} Test Accuracy : 0.8457 Running imdb data set Best Accuracy : 0.8161 {'vocab_size': 4603, 'num_filters': 128, 'maxlen': 100, 'kernel_size': 5, 'embedding_dim': 50} Test Accuracy : 0.8210 Running yelp data set Best Accuracy : 0.8127 {'vocab_size': 4603, 'num_filters': 64, 'maxlen': 100, 'kernel_size': 7, 'embedding_dim': 50} Test Accuracy : 0.8384 Interesting! For some reason the testing accuracy is higher than the training accuracy which might be because there is a large variance in the scores during cross-validation. We can see that we were still not able to break much through the dreaded 80%, which seems to be a natural limit for this data with its given size. Remember that we have a small data set and convolutional neural networks tend to perform the best with large data sets. Another method for CV is the nested cross-validation (shown here) which is used when the hyperparameters also need to be optimized. This is used because the resulting non-nested CV model has a bias toward the data set which can lead to an overly optimistic score. You see, when doing hyperparameter optimization as we did in the previous example, we are picking the best hyperparameters for that specific training set but this does not mean that these hyperparameters generalize the best. Conclusion There you have it: you have learned how to work with text classification with Keras, and we have gone from a bag-of-words model with logistic regression to increasingly more advanced methods leading to convolutional neural networks. You should be now familiar with word embeddings, why they are useful, and also how to use pretrained word embeddings for your training. You have also learned how to work with neural networks and how to use hyperparameter optimization to squeeze more performance out of your model. One big topic which we have not covered here left for another time was recurrent neural networks, more specifically LSTM and GRU. Those are other powerful and popular tools to work with sequential data like text or time series. Other interesting developments are currently in neural networks that employ attention which are under active research and seem to be a promising next step since LSTM tend to be heavy on the computation. You have now an understanding of a crucial cornerstone in natural language processing which you can use for text classification of all sorts. Sentiment analysis is the most prominent example for this, but this includes many other applications such as: - Spam detection in emails - Automatic tagging of texts - Categorization of news articles with predefined topics You can use this knowledge and the models that you have trained on an advanced project as in this tutorial to employ sentiment analysis on a continuous stream of twitter data with Kibana and Elasticsearch. You could also combine sentiment analysis or text classification with speech recognition like in this handy tutorial using the SpeechRecognition library in Python. Further Reading If you want to delve deeper into the various topics from this article you can take a look at these links: Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Learn Text Classification With Python and Keras
https://realpython.com/python-keras-text-classification/
CC-MAIN-2021-39
refinedweb
8,801
54.42
Hide Forgot Booting the latest Fedora Atomic Workstation Rawhide installer image on a VM here results in the network not coming up for some reason. Haven't figured out why yet, but there's a bug regardless of that: if the network is not connected, the hub will not allow you to progress to 'Begin Installation' (the 'NETWORK & HOST NAME' spoke is shown with the orange warning icon, the 'Beging Installation' button is greyed out, and the 'Please complete items marked with this icon before continuing to the next step' message is shown at the bottom of the hub), even though there shouldn't be any need for the network to be connected, AFAIK - the payload should be fully present on the media, just like the traditional DVD install media. Hi Adam, Could you please attach installation logs. Thank you. Created attachment 1420117 [details] anaconda.log Created attachment 1420118 [details] dbus.log Created attachment 1420119 [details] ifcfg.log Created attachment 1420120 [details] journalctl -b output Created attachment 1420121 [details] lvm.log Created attachment 1420122 [details] program.log Created attachment 1420123 [details] storage.log Created attachment 1420124 [details] X.log This is the case also in F28 Beta, Dusty do you care to have this fixed in F28? It would be nice to have this fixed for f28, but I don't necessarily think it's critical. Is it possible we can have someone do quick investigation to see if the solution is simple? It should be simple: Yeah, in that case I prefer F28 :) Offhand... NetworkSpoke.py: @property def completed(self): """ Check whether this spoke is complete or not. Do an additional check if we're installing from CD/DVD, since a network connection should not be required in this case. """ return (not can_touch_runtime_system("require network connection") or nm.nm_activated_devices()) I suspect Anaconda doesn't understand that we injected the ostree content in - it's a different process from the classical "DVD" model with RPMs that is generated by pungi. Proposed as a Freeze Exception for 28-final by Fedora user walters using the blocker tracking app because: Part of the installation experience for FAW. Not a blocker though. Are there any other Anaconda changes pending for F28? If not I'm happy to do a build/test for this. I do see but it's not clear that's going to be worked on soon. It's best to leave it to the anaconda team, there's a process and a schedule for doing the builds. This will still have time to get in. They usually build on Mondays, so there's a good chance it'll go in then. Discussed during the 2018-04-16 blocker review meeting: [1] The decision to classify this bug as an AcceptedFreezeException was made as it: "there's clearly a benefit to having the appstream data as up to date as possible with the packages included in Final, so updating it after freeze is a good idea" [1] Whoops, wrong decision... : Discussed during the 2018-04-16 blocker review meeting: [1] The decision to classify this bug as an AcceptedFreezeException was made as it: "this isn't a super important fix, but it is to the installer (so cannot be done post-install) and is pretty isolated and safe, so accepted as an FE issue so long as it lands soon" [1] anaconda-28.22.8-1.fc28 has been submitted as an update to Fedora 28. anaconda-28.22.8-1.fc28, initial-setup-0.3.58-1.fc28 has been pushed to the Fedora 28 testing repository. If problems still persist, please make note of it in this bug report. See for instructions on how to install test updates. You can provide feedback for this update here: anaconda-28.22.8-1.fc28, initial-setup-0.3.58-1.fc28 has been pushed to the Fedora 28 stable repository. If problems still persist, please make note of it in this bug report. can someone confirm this is fixed now? Just tested it with the ISO from today's F28 two-week Atomic nightly build, worked fine.
https://bugzilla.redhat.com/show_bug.cgi?id=1565369
CC-MAIN-2021-21
refinedweb
686
62.88
Python logging filters do not propagate like handlers and levels do Loggers are organized in a hierarchical fashion. A logger named 'foo.bar' is a child of a logger named 'foo'. ...... read more » Subdomain-based configuration for a Flask local development server This example shows how to set up a Flask local development server to use a different configuration based on the subdomain of the request. The project I work on has several environments (dev, qa, staging, etc). Each environment has different database and API hostnames. I use this to switch between database and API environments quickly while using my local development server. This assumes a create_app function is used to create the Flask application instance as described in the Application Factories Flask documentation. create_app¶ Modify the create_app function to take a configobj argument and use it to override the default configuration ... How to add a margin around markers in the Google Static Maps API using Python This example shows how to use Python to generate a Google Static Map URL for a map that contains markers within some dimensions which are smaller than the map image dimensions. This effectively allows for setting minimum X and Y margins around the markers in a map. This is useful for a "fluid" web design where a maximum map size is requested from Google and is then cut off at the edges for small browser windows. The bulk of this solution is based on the Javascript code here: import math def generate_map_url( min_map_width_px, max_map_width_px ... Do you have a lot of short, single-use, private functions in your Python code? Do you have a lot of short, single-use, private functions in your Python code? For example, below is some stubbed out authentication code I've been working on. It checks if a user's password is correct and updates the hash algorithm to use bcrypt. The 4 private functions with the leading underscore are from 1 to 10 lines long and are only used by the check_password function. These functions are part of a larger module with about 20 functions. I don't like that these 4 functions add clutter to the module and are not grouped with the function ... How ... When is the try-finally block used in Python? The finally block is used to define clean-up actions. Why is the finally block needed? Why can't the clean up actions be put after the try/except/else block? This works in some cases, but if there is a return, break, or continue, or an unhandled exception inside the try, except, or else clauses, that code will never be executed. The finally block executes even in these conditions. try: print 'Inside try' raise Exception finally: print 'Inside finally' print 'Never get here' Results: Inside try Inside finally Traceback (most recent call last): File "tmp.py", line 13, in... read more » raise ... Using ...... read more » How to start a long-running process in screen and detach from itHow to start a long-running process in screen, detach from it, and reattach to it later. Start a long running process in screen and detach¶ - Ssh to the remote host, myremote: eliot@mylocal:~$ ssh myremote - Start a new screen session eliot@myremote:~$ screen - Start a long running process, "sleep 3600": eliot@myremote:~$ sleep 3600 - Detach from the screen session:(Hit [CTRL-A], then type a colon character, then type "detach", then hit [ENTER]) eliot@myremote:~$ CTRL-A : detach ENTER - Exit your remote SSH session: eliot@myremote:~$ exit Reattach to the existing screen session¶ - Ssh to the remote host again: eliot@mylocal:~$ ssh ... How to use pip with crate.ioHere's how to use pip with crate.io (in case pypi.python.org goes down): $ pip install --index-url= yolk $ pip install --log=my-pip-debug.log --index-url= yolk See also¶ - - - - - How ...
http://www.saltycrane.com/blog/
CC-MAIN-2014-15
refinedweb
638
62.88
Chatlog 2012-02-03 From Provenance WG Wiki See original RRSAgent log or preview nicely formatted version. Please justify/explain all edits to this page, in your "edit summary" text. 08:12:31 <RRSAgent> RRSAgent has joined #prov 08:12:31 <RRSAgent> logging to 08:12:33 <trackbot> RRSAgent, make logs world 08:12:35 <trackbot> Zakim, this will be 08:12:35 <Zakim> I don't understand 'this will be', trackbot 08:12:36 <trackbot> Meeting: Provenance Working Group Teleconference 08:12:36 <trackbot> Date: 03 February 2012 08:12:40 <Stian> tlebo: we get the same 08:12:42 <Luc> Zakim, this will be PROV <pgroth> Guest: Ivan (ivan) Herman, W3C <pgroth> Guest: Guus (guus) Schreiber, W3C RDF WG Chair 08:12:42 <Zakim> ok, Luc, I see PROV_f2f()3:00AM already started 08:12:47 <GK> GK has joined #prov 08:13:10 <ivan> zakim, who is there? 08:13:10 <Zakim> I don't understand your question, ivan. 08:13:15 <kai> kai has joined #prov 08:13:17 <ivan> zakim, who is on the call 08:13:17 <Zakim> I don't understand 'who is on the call', ivan 08:13:23 <ivan> zakim, who is on the call? 08:13:23 <Zakim> On the phone I see ??P11 08:13:38 <ivan> is anybody on the call already? 08:13:40 <ivan> who is P11 08:13:42 <ivan> ? 08:13:46 <Luc> Agenda: 08:13:57 <tlebo> I don't know. 08:14:07 <Luc> Chair: Luc Moreau 08:14:12 <Luc> Scribe: dgarijo 08:14:27 <ivan> tlebo: you are not on zakim, right? 08:14:36 <Luc> rrsagent, make logs public 08:15:01 <tlebo> it's 3:15 here 08:16:25 <Zakim> disconnecting the lone participant, ??P11, in PROV_f2f()3:00AM 08:16:26 <Zakim> PROV_f2f()3:00AM has ended 08:16:26 <Zakim> Attendees were +1.315.724.aaaa, [VrijeUni], tlebo, [IPcaller], +1.781.899.aabb, Sandro, Satya_Sahoo, MacTed, Ivan 08:16:49 <dgarijo> Luc: session on prov-dm <pgroth> Topic: Prov-dm continued <pgroth> Summary: A discussion was had about had around ISSUE 207 on where start and end times should occur in the model. No decision was taken. 08:16:52 <ivan> zakim, this is prov 08:16:52 <Zakim> ivan, I see PROV_f2f()3:00AM in the schedule but not yet started. Perhaps you mean "this will be prov". 08:17:02 <khalidbelhajjame> khalidbelhajjame has joined #prov 08:17:03 <ivan> zakim, this will be prov 08:17:03 <Zakim> ok, ivan; I see PROV_f2f()3:00AM scheduled to start 17 minutes ago 08:17:16 <dgarijo> ... would like a clarification on the prov-o resolution yesterday 08:17:31 <Stian> Zakim, start prov 08:17:31 <Zakim> I don't understand 'start prov', Stian 08:17:37 <dgarijo> ... prov-o team will have to remember that there are "concepts at risk" 08:17:52 <dgarijo> ... there is an issue around wasAsociatedWith 08:18:08 <dgarijo> ... whether the agent should be optional or not 08:18:26 <dgarijo> ... those issues are inserted in the document 08:18:34 <tlebo> (Can I get onto a skyper that is NOT the scribe?) 08:18:48 <dgarijo> ... there is no point trying to encode this into prov-o 08:19:13 <tlebo> Thanks, Khalid. 08:19:33 <Stian> Zakim, this is PROV_f2f 08:19:33 <Zakim> Stian, I see PROV_f2f()3:00AM in the schedule but not yet started. Perhaps you mean "this will be PROV_f2f". 08:19:40 <Stian> Zakim, this is PROV_f2f()3:00AM 08:19:40 <Zakim> Stian, I see PROV_f2f()3:00AM in the schedule but not yet started. Perhaps you mean "this will be PROV_f2f()3:00AM". 08:19:48 <Stian> future of AI.. 08:19:51 <dgarijo> ... in this session we want to solve a number of issues flagged in the tracker 08:20:04 <dgarijo> ... in order to make some progress in the future version of the WD 08:20:07 <tlebo> (Tim hears now) 08:20:34 <dgarijo> 08:20:45 <dgarijo> ... issue 207 08:20:48 <Luc> 08:21:48 <dgarijo> ... when we talk about activities we say that there is a start event and an end event. The place holder with time is not with the event, but with the activity itself 08:21:57 <dgarijo> ... There is a bit of inconsistency 08:22:22 <dgarijo> ... can we move starttime with the start event 08:22:24 <GK> (This issue of start/end times is also alluded to in) 08:22:39 <dgarijo> ... can we move start/end away from the activity? 08:22:48 <dgarijo> ... feedback? 08:23:12 <Luc> q? 08:23:14 <tlebo> q+ 08:23:15 <dgarijo> ... prov-o team, is that a big change for the ontology? 08:23:15 <Stian> q+ 08:23:39 <pgroth> q? 08:23:56 <dgarijo> tlebo: I like the proposal to make it consitent. 08:24:31 <dgarijo> ... concerned about people wanting to add this directly to the activity. Would it be possible to have both? 08:24:50 <ivan> q+ to refer to a minor issue on time 08:25:20 <dgarijo> luc: another example on scruffy vs not scruffy. From a data model view is not useful to have many placeholders for the same info 08:25:25 <ivan> ack tlebo 08:25:31 <tlebo> +1 danger for inconsistency 08:25:37 <dgarijo> ... risk for inconsistency 08:26:04 <dgarijo> ... is it just sintactic sugar? 08:26:29 <dgarijo> tlebo: it reduces query time. You are running to a lot of practical reasons 08:26:39 <Luc> q? 08:26:43 <smiles> q+ 08:26:43 <tlebo> and bnodes don't consolidate across merges. 08:26:46 <Luc> ack stian 08:27:23 <dgarijo> stian: a destruction event would complete the cycle. 08:27:42 <dgarijo> ... activity and entity had start and end. 08:28:08 <dgarijo> ... it would be very good to relate these events 08:28:24 <dgarijo> ... without having necessarily to refer to time 08:28:38 <Luc> why not say id a Activity, aStartEvent ... 08:29:14 <GK> q+ to ask Can we separate the "proper" model from convenient "syntactic sugar"? I.e. formal model uses extra node, but "convenient" shortcut property used. This convenience property might be introduced only in the ontology. 08:29:38 <dgarijo> khalid: prov.dm has to be consistent. not having the notion of event would be a problem? 08:29:48 <Luc> q? 08:29:51 <dgarijo> ... it would be a simpler ontology 08:29:58 <tlebo> e.g. :activity prov:hasStart [ prov:inXSDDateTime "2012-02-03T03:27:09-05:00"^^xsd:dateTime ]; prov:hasEnd [ prov:inXSDDateTime "2012-02-03T03:37:09-05:00"^^xsd:dateTime ] 08:30:12 <pgroth> q+ 08:30:41 <Luc> q? 08:30:45 <dgarijo> stian: if you want to associate anything extra to the event (how the time was measured) then you are not able to do so. 08:32:20 <GK> Hmmm... I'm sure PatH will do a spendid job, but isn't doing time out of scope for RDF group? 08:32:31 <dgarijo> ivan: 2 things: 1) this has been a discussion on the rdf group. What they come up with may be useful for you, so it might be good to postpone the resolution and reuse what they decide. 08:33:21 <dgarijo> ... 2) Good to know that the ??? document is coming up. 08:33:41 <dgarijo> ... someone in the rdf working group was reviewing the changes 08:34:11 <khalidbelhajjame> q? 08:34:22 <dgarijo> luc: would it be useful to share this feedback to the group? 08:34:26 <Luc> ack iv 08:34:26 <Zakim> ivan, you wanted to refer to a minor issue on time 08:34:29 <dgarijo> ivan: no problem 08:34:52 <tlebo> e.g. 2 "scruff") :activity prov:hasStart "2012-02-03T03:27:09-05:00"^^xsd:dateTime; prov:hasEnd "2012-02-03T03:37:09-05:00"^^xsd:dateTime . 08:35:01 <kai> ivan: if you use xsd dates which you should, look at the new draft, not the old document. 08:35:04 <dgarijo> smiles: don't see a problem for having support for both types of provenance. 08:35:28 <Luc> q? 08:35:34 <Luc> ack sm 08:35:36 <GK> ack gk 08:35:36 <Zakim> GK, you wanted to ask Can we separate the "proper" model from convenient "syntactic sugar"? I.e. formal model uses extra node, but "convenient" shortcut property used. This 08:35:39 <Zakim> ... convenience property might be introduced only in the ontology. 08:35:44 <dgarijo> stian: having both makes interoperability difficult 08:35:55 <dgarijo> graham: +1 to simon's point 08:36:21 <ivan> -> Alex Hall's review of the XSD 1.1 and the influence on RDF 08:36:24 <Luc> ack gk 08:36:40 <dgarijo> ... having them in prov-o doesn't mean that they are in the dm 08:36:49 <Luc> q? 08:36:53 <Luc> ack pgr 08:36:57 <tlebo> +1 @pgroth, this truly does match our "qualified and unqualified" duality. "upgrade path" 08:37:17 <tlebo> I think that makes a lot of sense. 08:37:21 <dgarijo> paul: +1 to that: in the ontology you have qualified and unqualified properties. So it is essentially the same thing 08:38:09 <tlebo> it's how I wrote 08:38:15 <tlebo> (the "upgrade path") 08:38:29 <dgarijo> ivan: the separation between simple/complicated qualifications is not visible in the document 08:38:50 <dgarijo> ... it is not highlighted 08:38:57 <Luc> q? 08:38:57 <dgarijo> in the primer/prov-o 08:39:31 <Stian> but it's not that different from current syntax: :activity prov:startedAt [ time:inXSDDateTime "2012-02-03T03:27:09-05:00"^^xsd:dateTime; ] ; - as compared to upgrading to qualifiedX your shorthand does not add much 08:40:10 <ivan> q+ 08:40:20 <dgarijo> luc: so we keep start /end for activities but no events? 08:40:26 <jcheney> q+ 08:40:36 <dgarijo> activities can refer to time or to events 08:41:02 <Luc> q? 08:42:01 <tlebo> +1 paul - the duality stays out of the DM, prov-o adds the duality (i.e. syntactic sugar) 08:42:07 <GK> PGroth: duality only in the ontology, not in the DM 08:42:09 <dgarijo> paul: the prov-o has a duality that the dm doesn't have 08:42:12 <GK> +1 to paul 08:42:16 <pgroth> @tlebo agree 08:42:21 <tlebo> +1 @luc 08:42:29 <dgarijo> luc: for dm events have time and activities are related to events 08:43:45 <khalidbelhajjame> q? 08:44:09 <Luc> q? 08:44:24 <dgarijo> graham: give the basic voc and see how it evolves 08:44:33 <tlebo> @ivan, sorry, I meant prov:inXSDDateTime 08:44:34 <Luc> ack ivan 08:44:42 <khalidbelhajjame> do we need to have time at all in prov-dm, wouldn't the notion of event be enough? 08:44:45 <dgarijo> ivan: please don't use the 2006 WD of the ontology. 08:45:17 <dgarijo> @kahlid: the events (usage, for instance) have time.. 08:45:17 <GK> ^^ == time ontology (?) 08:45:19 <Stian> is a start/end event in the universe of discourse? 08:45:26 <Stian> we'll clone the few things from time: we're currently using 08:45:28 <Luc> q? 08:45:30 <tlebo> @ivan, thanks, will mirror them into prov namespace. 08:46:06 <tlebo> @stain, YOU were using the 2006 time >:-{ 08:46:20 <Stian> Yes! But it was a good placeholder! 08:46:24 <Stian> better than nothing at all 08:46:31 <dgarijo> jcheney: had some issues about events too. Would it be ok if we don't make any formal determinations until I solved those? 08:46:59 <Stian> @tlebo - will you do the job to update the OWL file? Should be almost just a search replace of &time; 08:47:13 <Luc> q? 08:47:13 <jcheney> jcheney has joined #prov 08:47:16 <Luc> ack jc 08:47:27 <tlebo> @stian sure 08:47:29 <dgarijo> luc: not enough resolution 08:47:30 <Stian> thanks :) 08:48:31 <Stian> That's 08:48:41 <tlebo> @stian 08:49:50 <dgarijo> luc: wasStartedBy as a subproperty of wasAssociatedWith. Woudln't it better to have a start/end event? 08:50:14 <GK> q+ to ask if start/end should be inherrent in an event or part of relation between event and some activity (or something)? 08:50:15 <Luc> q? 08:50:32 <Stian> this starts sounding like Tim's "events are a kind of activity" argument - if agents can be associated with a start event, etc 08:51:21 <dgarijo> GK: Is event the right place to make the association? Event is more like a timestamp 08:51:35 <khalidbelhajjame> +q 08:52:07 <dgarijo> we had 4 types of events 08:53:28 <Stian> is it now not just 2 events? Creation and Destruction 08:53:29 <Luc> ack gk 08:53:29 <Zakim> GK, you wanted to ask if start/end should be inherrent in an event or part of relation between event and some activity (or something)? 08:54:04 <dgarijo> khalid: disagrees with GK. The event type is the start of an activity. 08:54:21 <Luc> q? 08:54:23 <Paolo> Paolo has joined #prov 08:54:26 <Luc> ack khalid 08:54:29 <Stian> (far out there) if an activity was created (ie. started) - then that could have been caused by another activity (that of an agent) 08:54:41 <tlebo> q+ 08:55:15 <dgarijo> tim: disagrees with wasStartedBy being a specialization of association 08:55:42 <dgarijo> ... starting an activity is like being responsible for it 08:56:16 <smiles> q+ 08:56:32 <dgarijo> luc: we really don't have start and end of activities right now. 08:56:39 <Paolo> q+ 08:56:41 <dgarijo> ... responsability is another topic 08:56:59 <dgarijo> ... I just didn't want to go there now. 08:57:23 <Luc> q? 08:57:27 <dgarijo> ... coming back to the original proposal, those records represent events 08:57:48 <dgarijo> tim: are we talking about agents or events starting the activity 08:57:52 <khalidbelhajjame> I think that there are two points here that we need to reflect on separatly: i)- do we need to encode the start/end of activities as events? ii)- do we still need to have wasStartedBy to specify that an egent was responsible for startng an activity 08:57:56 <pgroth> q? 08:58:37 <dgarijo> pgroth: wasstartedBY vs wasStartedAT 08:58:56 <dgarijo> ... people are confused by both. 08:58:58 <jcheney> what about just "started" and "ended"? 08:59:21 <Stian> (also far out) if Generation/Usage/Started/Ended are activities, then agents can be associated/responsible just like with other activities 08:59:33 <jcheney> you can name the agent in a "started" record, or not. 08:59:42 <Luc> q? 08:59:44 <Stian> jcheney: make sense 08:59:45 <Paolo> q? 08:59:51 <tlebo> q- 09:00:01 <Luc> ack smil 09:00:08 <dgarijo> smiles: +1 to tim and gk 09:00:40 <dgarijo> ... you don't want to attach the agent to the event 09:01:11 <jcheney> perhaps could define "wasStartedBy" as "evt was a start event for activity" and "agent was associated with evt" 09:01:15 <Paolo> +1 for smiles, GK however that leaves wasGeneratedBy as an anomaly -- that /does/ require a generator to be expressed 09:01:21 <jcheney> i think this = simon's proposal too 09:01:25 <Luc> q? 09:01:39 <dgarijo> paolo: agrees with smiles 09:01:48 <GK> q+ to ask are "events" things that are referenced explicitly by records, are they implicit (and used in the explanation of) relationships between other things (e.f. entity wasGeneratedBy activity) 09:01:59 <dgarijo> ... generation doesn't stand for itself 09:02:06 <dgarijo> ... you just need a generator 09:02:20 <jcheney> could decompose generation into "event created" and "activity performed event" 09:02:25 <Stian> there was a seperate proposal to allow wasGenerated() without activity (to record entity start time) 09:03:06 <dgarijo> luc: would the agent be optional 09:03:22 <tlebo> +1 keep them separate, let one assert either or both. 09:03:38 <ivan_> ivan_ has joined #prov 09:03:43 <Stian> (assuming we have destruction) - can an agent die before the activity start event - but still be responsible for starting? 09:04:39 <Stian> (I would argue yes) 09:04:41 <dgarijo> ivan: why make it simple if you can make it complicated? 09:05:13 <khalidbelhajjame> ?q 09:05:19 <khalidbelhajjame> q? 09:05:19 <Stian> q? 09:05:24 <Paolo> q- 09:05:26 <dgarijo> luc: issue not entirely finished yet 09:05:29 <GK> ack gk 09:05:29 <Zakim> GK, you wanted to ask are "events" things that are referenced explicitly by records, are they implicit (and used in the explanation of) relationships between other things (e.f. 09:05:32 <Zakim> ... entity wasGeneratedBy activity) 09:06:08 <dgarijo> GK: there is a confusing about where the events are situated in the dm 09:06:22 <Paolo> q+ 09:06:42 <dgarijo> ... are events in the domain of discourse? or even the entities? 09:07:20 <Stian> diagram at 09:07:39 <Luc> q? 09:07:43 <Luc> ack pao 09:07:59 <dgarijo> paolo: start and end record and then the activity record 09:08:29 <dgarijo> ... you can't assert an activity record until the end of it 09:08:55 <pgroth> q? 09:08:59 <tlebo> q+ to say that adding all of the optionals will make it more difficult to map to prov-o (or anything) 09:08:59 <Stian> ig activities are entities, then start/end events are same for both. currently wasGeneratedBy can say who started it - but currently says that the starter/creator was an activity (which is currently disjoint from agent) 09:09:11 <Stian> but why can activities only be created by agents, and entities only by activities? 09:09:50 <GK> FWIW, CIDOC CRM uses events to mediate between other things, and events are considered to have duration, not be instantaneous. Just saying. 09:10:00 <Stian> If I create a document, as an agent I am (responsible for) generating it 09:10:20 <dgarijo> luc: we are talking about exchanging prov info, at the moment of exchange you know the traces. 09:10:44 <tlebo> -1 @paolo 09:11:12 <Luc> q? 09:11:40 <dgarijo> tim: problem with the optionals when doing the mappings to prov-o 09:11:49 <dgarijo> ... smaller constructs are easier 09:12:24 <GK> tlebo: for formal description, prefers more smaller constructs that can be linked together without optional bits. (was that right?) 09:12:24 <tlebo> q- 09:12:29 <khalidbelhajjame> +q 09:12:47 <Stian> +1 tlebo 09:13:02 <dgarijo> luc: your proposal paolo, is not addressing our current issue. 09:13:23 <dgarijo> ... it is mantaining the inconsistency 09:13:39 <GK> @tlebo I think your point argues for making events explicit in the model. Just saying. 09:13:41 <Stian> Stian: There are two kinds of optionals in DM - the "Don't know now" implied optional, and the "Not applicable" (null) optional - in mapping to OWL we would need to distinguish between these 09:14:12 <tlebo> @GK I'm ok with that. Generation and Usage are the events. 09:14:25 <dgarijo> luc: a start record is not a representation of an event 09:15:18 <dgarijo> ... something could argue about starting events not being on the data model 09:15:20 <pgroth> +q 09:15:25 <Stian> every entity has an (implied) generation event - but every activity does not (currently) have an implied started event 09:15:41 <dgarijo> ... geenration events are on de UoD and start events are not 09:15:53 <Luc> q? 09:15:54 <tlebo> q+ to propose startedAt(activity, time) + endedAt(activity, time) and wasStartedBy(activity, agent) 09:16:20 <Stian> tlebo: +1 - that's Simon's proposal 09:16:34 <dgarijo> jcheney: instead of startedBy say started 09:16:37 <tlebo> @stian, then +1 simon. 09:16:40 <Stian> if you say wasStartedBy - we know it was at startedAt 09:16:50 <Stian> tlebo: but do ask it :) 09:16:50 <dgarijo> ... combining the event and the agent 09:17:00 <Luc> q? 09:17:24 <Luc> ack kh 09:17:49 <dgarijo> khalid: what info should we attach to those events? 09:17:58 <Paolo> q? 09:18:02 <Paolo> q+ 09:18:45 <Stian> .. and role etc 09:19:09 <dgarijo> ... when expressing event we attach the info necessary in that event 09:19:22 <Luc> q? 09:19:25 <dgarijo> ... that would make the model complex 09:19:46 <tlebo> I see Khalid's argument for "inconsistent" treatment for the start/end and use/generation... 09:20:23 <Luc> q? 09:20:27 <GK> Good question, Khalid. Don't know. 09:20:29 <tlebo> wondering if the "upgrade path" duality is going to surface soon. 09:20:31 <dgarijo> ... is it worth decoupling things or simplifying the concept by attaching optional things to use/generation. 09:20:33 <khalidbelhajjame> ack kha 09:20:37 <Luc> ack pg 09:20:52 <dgarijo> pg: nice summary. 09:21:19 <dgarijo> ... events are good to express what we have in the model 09:22:00 <tlebo> activity hadQualifiedStart would parallel event hadQualifiedGeneration 09:22:03 <dgarijo> ... do we need constructs of events to express our provenance? 09:22:07 <smiles> q+ 09:22:08 <Stian> ie. are events in universal discourse or not 09:22:35 <tlebo> no construct with is ..... an event ? 09:22:40 <dgarijo> luc: currently there is no construct of an event. 09:22:53 <GK> q+ to respond to paul: we don't *need* new constructs - can can get by without them - but is it *easier* to describe/understand by introducing the extra concepts. 09:24:32 <Zakim> PROV_f2f()3:00AM has now started 09:24:38 <Luc> q? 09:24:39 <Zakim> +??P0 09:24:44 <Zakim> -??P0 09:24:45 <Zakim> PROV_f2f()3:00AM has ended 09:24:45 <Zakim> Attendees were 09:24:51 <Luc> q? 09:24:57 <dgarijo> luc: this issue is stil not finiched 09:24:58 <tlebo> hey! 09:25:07 <Stian> Evil zakim! 09:25:08 <GK> q+ to respond to paul: we don't *need* new constructs - can can get by without them - but is it *easier* to describe/understand by introducing the extra concepts. 09:25:24 <Stian> perhaps in that little minute we had our chance to call in to zakim 09:25:38 <tlebo> startedAt(activity, time) + endedAt(activity, time) and wasStartedBy(activity, agent) 09:25:49 <dgarijo> tlebo: higlight the distinction of wasstartedBy (agent), and wasStartedAt(time). 09:26:00 <dgarijo> ... this events are already modeled 09:26:11 <jcheney> And we were already considering renaming "QualifiedInvolvement" to "Event"... 09:26:11 <dgarijo> ... through the qualifiedInvolvement. 09:26:33 <dgarijo> ... by modeled is in the ontology. 09:26:50 <dgarijo> ... generation and usage are qualifiedInvolvement 09:27:19 <dgarijo> pgroth: notion of transforming qualifiedInvolvement to Event 09:27:47 <Zakim> PROV_f2f()3:00AM has now started 09:27:48 <dgarijo> smiles: disagreed with tim 09:27:53 <Zakim> +??P0 09:28:23 <dgarijo> ... it is just to describe the relationship, not the event. 09:28:44 <dgarijo> ... proposes to separate wasStartedAt and wasStartedBy 09:29:03 <dgarijo> khalid: would the agent be optional in wasStartedAt 09:29:28 <Stian> so say prov:hadRole on an event is a bit strange.. did the event play a role? I thought the event was what happened when someone assumed the role 09:29:29 <Luc> q? 09:29:37 <Stian> I think QualifiedInvolvement could have duration 09:29:41 <Stian> for instance Usage 09:29:52 <Stian> I used the encyclopedia entity from 14:45 to 15:15 09:30:02 <Stian> and at 15:00 I generated the report 09:30:42 <Luc> q? 09:30:42 <Stian> 1~but that took me from 14:50 till 15:00 09:30:45 <GK> ack gk 09:30:45 <Zakim> GK, you wanted to respond to paul: we don't *need* new constructs - can can get by without them - but is it *easier* to describe/understand by introducing the extra concepts. 09:30:55 <tlebo> zakim! 09:31:08 <Paolo> q? 09:31:11 <Paolo> q+ 09:31:23 <dgarijo> GK: do we need these new constructs? I don't think so 09:31:56 <stephenc> stephenc has joined #prov 09:32:02 <dgarijo> we shouldn't change the current model unless we do have a clear use case 09:32:18 <dgarijo> luc: but what is it in the dm? 09:32:46 <dgarijo> gk: events are not surfaced as part of the dm, just as an explanation 09:33:12 <Stian> formally the events have partial ordering which is defined in constraints - like usage time of entity >= generation time 09:34:01 <Luc> q? 09:34:01 <tlebo> over taken by Activities. 09:35:04 <jun> jun has joined #prov 09:35:06 <dgarijo> paolo: activities begin and end 09:35:15 <dgarijo> ... what do you say about entity? 09:36:05 <dgarijo> ... if you ad the generatedBy and generatedAt you restore part of the consistency 09:36:19 <Luc> q? 09:36:23 <Luc> ack paolo 09:37:14 <Paolo> hi Jun! 09:37:44 <Stian> jun: our zakim bridge has gone bad .. do you want to skype in? 09:37:50 <dgarijo> pgroth: the only issue is that we want some sort simetry/consistency across the model 09:37:55 <Luc> q? 09:38:18 <dgarijo> luc: last part of the issue 09:38:24 <pgroth> or jun are you on the bridge? 09:38:37 <Stian> Zakim, who is on the phone? 09:38:37 <Zakim> On the phone I see ??P0 09:38:47 <dgarijo> ... something was started by something which is not clearly an agent 09:39:01 <Zakim> -??P0 09:39:02 <Zakim> PROV_f2f()3:00AM has ended 09:39:02 <Zakim> Attendees were 09:39:02 <smiles> Just to say, I dont think my proposal implies any need for change in the ontology, as long as we dont interpret qualifiedinvolvement as an event 09:39:32 <Stian> Zakim, list conferences 09:39:32 <Zakim> I see no active conferences 09:39:34 <Zakim> scheduled at this time is PROV_f2f()3:00AM 09:39:40 <Stian> zakim, this is PROV_f2f 09:39:40 <Zakim> Stian, I see PROV_f2f()3:00AM in the schedule but not yet started. Perhaps you mean "this will be PROV_f2f". 09:39:53 <Stian> zakim, this is PROV 09:39:53 <Zakim> Stian, I see PROV_f2f()3:00AM in the schedule but not yet started. Perhaps you mean "this will be PROV". 09:39:54 <tlebo> @smiles, can QualifiedInvolvment be a superclass of event? 09:39:56 <Stian> zakim, this is bob 09:39:56 <Zakim> sorry, Stian, I do not see a conference named 'bob' in progress or scheduled at this time 09:40:10 <dgarijo> ... a coment that starts an activity 09:40:26 <dgarijo> ... the presence of an entity that started the activity 09:40:37 <dgarijo> ... we can't express that 09:40:44 <dgarijo> ... it is a limitation 09:41:00 <pgroth> zakim, this with be PROV_f2f() 09:41:00 <Zakim> I don't understand 'this with be PROV_f2f()', pgroth 09:41:17 <tlebo> #zakim #irc #prov #humor from @stian 09:41:22 <pgroth> Zakim, this will be PROV 09:41:22 <Zakim> ok, pgroth; I see PROV_f2f()3:00AM scheduled to start 101 minutes ago 09:41:38 <tlebo> entities cause activities 09:41:55 <tlebo> (luc think people will want to say it) 09:42:05 <smiles> @tlebo that doesnt seem intuitive to me. I would think the event is 'in' the relation between qualifiedinvolvement and timestamp, but not an explicit class 09:42:24 <dgarijo> +q 09:42:44 <Luc> q? 09:42:46 <tlebo> @smiles, the QualifiedInvolvement is the reification (shhh!), so the timestamp on that _is_ in the relation. 09:42:49 <Luc> ack dg 09:43:05 <Stian> moving many of these shortcuts away from formal model means that their granularity might disappear from the provenance exchange 09:43:13 <Stian> then something automatically becomes exapnded in DM 09:43:15 <khalidbelhajjame> +q 09:43:40 <Luc> q? 09:44:04 <tlebo> what are we converging to? 09:44:30 <jcheney> Can we identify some next actions and move on? 09:44:31 <dgarijo> dgarijo: agents are entities in the end, so we could see that the wasStartedBy allways as startedBy an entity 09:44:39 <smiles> @tlebo not sure i quite understand, but i think that matches what i was saying - we are reifying the relationship to say more about it, but the event is only one thing you might say about it... 09:45:01 <jcheney> We are arguing with phantoms, need concrete proposals first. 09:45:07 <GK> q+ to say this worries me a little because it seems to remove one of the core concepts from OPMV, which AFAICT is a fairly minimal provenance core based in real-world modelling experience 09:45:10 <Luc> q? 09:45:40 <dgarijo> khalid: we are using the same relationship for 2 different things 09:46:07 <dgarijo> ... control ordering, it is more like triggering the activity 09:46:16 <GK> Khalid: startedBy vs triggered? 09:46:35 <Luc> q? 09:46:42 <Luc> ack kha 09:46:55 <dgarijo> ... it would be less confusing if we had another relationship for this instead of the same 09:47:18 <tlebo> @smiles, I see what you're saying. 09:47:53 <tlebo> can anyone summarize what is going on? 09:47:56 <dgarijo> GK: It's a clever trick, but I'm a bit worried about. We might be losing some information. 09:48:30 <dgarijo> luc: in OPM you couldn't express the provenance of Agents. 09:48:46 <dgarijo> ... it was a fundamental shortcoming of that model 09:48:57 <tlebo> luc: important that Agents be Entities so we can describe them. 09:49:18 <tlebo> topic - Letting Entities make stuff happen (i.e., be Agents) 09:49:33 <dgarijo> pgroth: GK wants agents to have responsability 09:49:47 <dgarijo> ... or osmething 09:50:13 <tlebo> so we already have Entity wasDerivedFrom Entity. But we're now looking at Activities being caused by Entities? 09:50:41 <tlebo> e.g. "The" email that caused the flurry thread of email responses. 09:51:00 <dgarijo> ... wasStartedBy has a connotation of agency, and if we removed that we still have this connotation 09:51:12 <Stian> wasTriggeredBy or wasStartedBecauseOfThePresenceOf (ugggu) is more the passive started usecase we are talking about 09:51:32 <tlebo> are we just defining a subclass of Activity that are those that generate entities derived from the specified Entity? 09:51:39 <Luc> q? 09:51:40 <tlebo> q+ to ask are we just defining a subclass of Activity that are those that generate entities derived from the specified Entity? 09:51:50 <khalidbelhajjame> How about wasEventuallyStartedBy :-) 09:51:50 <GK> q- 09:51:55 <Luc> ack gk 09:53:22 <Stian> mmm... it's a kind of activity derivation, is it not.. "wasCausedBy" 09:53:28 <dgarijo> tim: clarification about the topic 09:53:51 <dgarijo> luc: maybe it is a corner case.. 09:54:29 <dgarijo> tim: you want to associate that entity to some the activities that used it? 09:54:37 <pgroth> signature is: wasStartedBy(Agent) 09:54:44 <dgarijo> luc: anything that started an activity is an agent 09:54:46 <Stian> and making an email an agent (and giving it responsibility) does sound quite far out 09:54:56 <pgroth> thus you infer the email as agent 09:55:03 <GK> Or - there exists an activity that used the email and was initiated by some agent 09:55:09 <dgarijo> ... so in this use case we would have the email as an agent 09:55:35 <jcheney> issue-207?? 09:56:19 <dgarijo> luc: issue: agent should be asserted and not inferred. 09:56:22 <jcheney> issue-206?? 09:56:40 <Stian> yes - is related 09:56:50 <GK> Hmmm... can we separate all the inference stuff from the basic data model definition? 09:57:05 <dgarijo> luc: wrap up: we don't have a proposal on the table right now. 09:57:31 <Stian> if we can't agree - we propose strip/remove. Removing the agent-constraint is a kind of removal. 09:57:39 <dgarijo> ... wasStartedBy between an activity and an Entity instead of an Agent, but there is not enough consensus. 09:57:48 <GK> @stian +1 09:58:11 <dgarijo> ... if we do it, it is not a specialization of an association 09:58:20 <dgarijo> ... it is not clear. 09:58:26 <Stian> @luc: +1 - wasAssociatedWith to stay as responsibility and agent 09:58:33 <GK> @stian I think this leads back to Paul's "trick", but keeping the notion of agency in the model. 09:58:41 <dgarijo> ... the other proposal is that we don't make any change. 09:59:24 <dgarijo> ... consequence: the email is regarded as an agent in the data model, which is not very "natural". 10:01:13 <Stian> @GK which 'this'..? :) 10:01:50 <GK> @stian this == "strip/remove" the bits we don't agree about 10:02:15 <GK> Why is this linked to startedBy not being a subproperty of wasAssociatedWith? 10:02:27 <Zakim> PROV_f2f()3:00AM has now started 10:02:34 <Zakim> PROV_f2f()3:00AM has ended 10:02:35 <Zakim> Attendees were 10:02:42 <Stian> @GK but is it not confusing if we have a semantic constrain in the DM, but don't reflect that in the PROV-O? Then you can express things n PROV-O that don't map (easily) to PROV-DM. 10:02:45 <Stian> zakim is drunk 10:04:04 <stephenc> (I think that outburst from zakim was caused by me connecting to voip, and being the 1st participant, and hanging up) 10:04:25 <tlebo> how long is this break? 10:04:32 <pgroth> 10 minutes 10:04:35 <tlebo> thx 10:04:39 <pgroth> maybe 15 minutes 10:05:31 <tlebo> what about causedBy ? 10:06:09 <tlebo> Event wasDerivedFrom Event 10:06:14 <tlebo> ack! 10:06:22 <tlebo> s/Event/Entity/ 10:06:23 <pgroth> no way 10:06:41 <tlebo> Activity wasCausedBy Email 10:06:54 <tlebo> Activity wasStartedBy EvilDoer 10:14:48 <tlebo> @sandro hi! 10:14:56 <tlebo> i'm no Skype now. 10:15:01 <tlebo> zakim didn't like me this morning. 10:16:24 <tlebo> zakim, why aren't you answering your phone? 10:16:24 <Zakim> I don't understand your question, tlebo. 10:20:44 <sandro> Zakim, what is the code? 10:20:44 <Zakim> the conference code is 77683 (tel:+1.617.761.6200 sip:zakim@voip.w3.org), sandro 10:20:50 <Zakim> PROV_f2f()3:00AM has now started 10:20:57 <Zakim> +Sandro 10:21:00 <tlebo> @jcheney, I can't open 10:21:29 <tlebo> page says application/zip, but .pdf which is it? 10:23:15 <ivan_> zakim, this is prov 10:23:15 <Zakim> ivan_, this was already PROV_f2f()3:00AM 10:23:17 <Zakim> ok, ivan_; that matches PROV_f2f()3:00AM 10:23:50 <sandro> ivan_, are you folks calling in to Zakim now? 10:23:51 <Zakim> +??P1 10:23:57 <Luc> q? 10:24:15 <Zakim> +tlebo 10:24:26 <jcheney> Oops, uploaded keynote source. Should work now. 10:24:35 <tlebo> Hi, zakim! 10:24:45 <tlebo> Zakim, did you miss us? 10:24:45 <Zakim> I don't understand your question, tlebo. 10:24:48 <Zakim> + +31.20.598.aaaa 10:24:56 <pgroth> we have moved to zakim 10:26:21 <Paolo> Jun are you on Zakim? 10:26:31 <Stian> zakim, who is on the phone? 10:26:31 <Zakim> On the phone I see Sandro, ??P1, tlebo, +31.20.598.aaaa 10:26:35 <Paolo> zakim, who is on the phone? 10:26:35 <Zakim> On the phone I see Sandro, ??P1, tlebo, +31.20.598.aaaa 10:26:51 <jcheney> slides at: 10:27:26 <khalidbelhajjame> Topic: prov-sem <pgroth> Summary: James presented a strawman proposal for a formal semantics of provenance. The group positively recieved the proposal and agreed to make it a deliverable of the project. The prov-sem was seen a mechanism to to encode proper provenance. Additionally, he presented the ProvRDF mappings page that provides a systematic means to map prov-dm to prov-o. 10:27:33 <Luc> q? 10:27:33 <pgroth> q? 10:27:36 <pgroth> slide 2 10:27:59 <tlebo> (btw, can't open the slides. Press on) 10:28:25 <Stian> works in chrome 10:29:01 <pgroth> slide 3 10:29:03 <khalidbelhajjame> jcheney: we need to be careful about the features that we include 10:29:19 <tlebo> thx, have it in chrome 10:29:40 <pgroth> slide 4 10:30:02 <Stian> sandro: ;') 10:30:39 <khalidbelhajjame> jcheney: we have high level contructs, that can be used by people, vs. complex (and risk) approach 10:30:48 <Stian> I like this comparison.. PROV-DM ~= CISC - PROV-O ~= RISC 10:31:08 <GK> I'm not sure the scruffy/proper axis is quite like CISC/RISC axis 10:31:22 <pgroth> slide 5 10:31:31 <tlebo> I would reverse the RISC analogy 10:32:27 <khalidbelhajjame> jcheney: approach: formally specifying the meaning of prov-dm, which can then facilitate the maping from prov-dm to prov-o 10:32:34 <Stian> @tlebo, elaborate (briefly!) 10:33:30 <tlebo> scruffies want fewer constructs for the common cases - RISC 10:33:37 <Stian> we've got many 'instructions' in DM, O has fewer instructions that can be used/combined to do (most of) what you do in DM 10:33:41 <Stian> I agree 10:33:46 <khalidbelhajjame> jcheney: the benefit is that we can systematically map prov-dm to prov-o 10:33:50 <GK> I see RDF vs PROV-DM like RISC vs CISC. Either can be scruffy or proper. IMHO 10:34:01 <pgroth> slide 6 10:34:24 <khalidbelhajjame> jcheney: what is the goal of the formal semantics? 10:34:39 <khalidbelhajjame> jcheney: What are the metrics? 10:34:45 <tlebo> test cases! 10:34:51 <khalidbelhajjame> jcheney: what process can be used for reconciling mismatches 10:35:35 <Luc> q? 10:35:54 <jcheney> 10:36:16 <khalidbelhajjame> jcheney: there has been some changes 10:36:40 <khalidbelhajjame> jcheney: prov-dm assertions are seen as formula 10:37:04 <khalidbelhajjame> jcheney: prov-dm instance is seen as conjunction of formula 10:38:00 <khalidbelhajjame> jcheney: terminology-wise, I use world as opposed to model to avoid confusion 10:38:36 <khalidbelhajjame> jcheney: I speak about identifiers as variables in a logical formula 10:39:09 <khalidbelhajjame> jcheney: I assume that there is a set of time instances that can be partially or totally ordered 10:39:11 <GK> @jcheyney re identifiers. Suggest s/(or blank nodes in RDF)/(or nodes in RDF)/ 10:39:33 <khalidbelhajjame> jcheney: I am also using intervals of time 10:40:14 <khalidbelhajjame> jcheney: I am agnostic about what values are and what attributes are 10:40:42 <pgroth> in section formulas 10:40:57 <khalidbelhajjame> jcheney: A subset of records in prov-dm are represented as formulas 10:41:19 <tlebo> 10:41:30 <khalidbelhajjame> jcheney: there are two kinds of formulas: element_ and relation_formula 10:41:48 <pgroth> section worlds 10:44:40 <khalidbelhajjame> jcheney: There are three layers: Things, Objects, Syntax 10:44:59 <pgroth> no khalidbelhajjame 10:45:07 <pgroth> Things, Social, Syntax 10:46:01 <tlebo> 10:46:40 <khalidbelhajjame> jcheney: Things have a life time and attributes that can change over time 10:46:52 <Stian> (jcheney just updated formula of #things to talk about Things rather than Objects) 10:47:50 <tlebo> ^^ rdf:type prov:Account . 10:48:07 <khalidbelhajjame> jcheney: example: thing can change color over tme, e.g., from blue to red 10:48:48 <khalidbelhajjame> jcheney: It is possible to have two things that have the same attributes and attribute values 10:49:03 <khalidbelhajjame> jcheney: and have the same lifetime 10:49:49 <khalidbelhajjame> Stian: are you distinguishing between known and unkniown attributes 10:50:04 <khalidbelhajjame> jcheney: I am not saying anything about that 10:50:58 <pgroth> q? 10:51:11 <khalidbelhajjame> jcheney: Things may not be distinguishable by anything other than their identity 10:51:45 <Stian> @jcheney: This is good stuff 10:51:46 <khalidbelhajjame> jcheney: Entities, Activities and Agenets are seen as Objects 10:52:12 <tlebo> ? 10:52:22 <pgroth> Objects 10:52:36 <khalidbelhajjame> jcheney: An entity is a representation of a thing during an interval 10:53:05 <Stian> (jcheney removed "of things" in "a set Objects of things" under #Objects) 10:53:41 <khalidbelhajjame> jcheney: The difference between things and entities is the time dependency 10:53:56 <pgroth> highlighting entities 10:54:21 <khalidbelhajjame> Ivan: what's the reason between the distinction between entities and objects? 10:54:34 <khalidbelhajjame> jcheney: That's what the DM says 10:54:41 <Stian> YESSSS 10:55:29 <khalidbelhajjame> luc: activities and entities are disjoint 10:55:53 <khalidbelhajjame> jcheney: the difference between the thing and object is there because it is in the DM 10:56:01 <GK> For the purpose of formalizing prov-dm (as is), is it important to have "lifetime : Things -> Intervals" ? 10:56:12 <Stian> the difference between *entity* and *object* 10:56:20 <khalidbelhajjame> jcheney: the grouping of entities, activities and agent under object is there for typing purposes 10:57:17 <pgroth> in section Activities 10:58:16 <khalidbelhajjame> luc: a given object does not necessarily have values for all attributes 10:58:26 <khalidbelhajjame> jcheney: some values stand for missing 10:58:45 <khalidbelhajjame> jcheney: I d rather go through the basics rather than trying to discuss everything 11:00:25 <khalidbelhajjame> jcheney: because we separate things that varies from entities that are (fixed), we have a function that map the two 11:01:07 <khalidbelhajjame> jcheney: examples: three entities can describe the same entity with possibly overlapping intervals 11:01:15 <khalidbelhajjame> jcheney: events 11:01:39 <Stian> Activity disjoint from Entity prevents an Activity using/generating/etc another Activity, etc (so you can't say :discussing a prov:Activity . :scribing a prov:Activity, prov:used :discussing ) - you will need to make the entity :discussion (which is... generated by :discussing?) 11:01:51 <khalidbelhajjame> jcheney: an activity is an object that comrises a set of events 11:02:29 <khalidbelhajjame> jcheney: an activity is related to a collection of events 11:02:52 <khalidbelhajjame> jcheney: Events is a subset of Objects 11:03:16 <khalidbelhajjame> jcheney: an event relates an activity to an entity 11:03:29 <dgarijo> @Stian: the phantom entity! 11:03:33 <khalidbelhajjame> jcheney: an event is associated with a time 11:04:09 <khalidbelhajjame> jcheney: events can be ordered based on the times associated with them 11:04:14 <tlebo> ? 11:04:23 <khalidbelhajjame> jcheney: start and end of activities are events 11:04:24 <GK> This makes me realize my earlier focus of (some) discussion on "domain of discourse" wasn't quite right... 11:05:09 <GK> @tlebo yes, I think so 11:05:18 <khalidbelhajjame> jcheney: Used relates an event to an entity 11:06:00 <khalidbelhajjame> jcheney: to keep track of the different uses, we are associating the entity with the event 11:06:11 <khalidbelhajjame> jcheney: the "use" event 11:13:14 <Stian> @Paolo +1 (and that's why perhaps 'destruction' is wrong term) 11:13:15 <khalidbelhajjame> Paolo: the disctuction of an entity does not means the disctuction of the tghing, but possibly thhe modification of the value of one of its attributes 11:13:16 <pgroth> Section Semantics 11:13:28 <Stian> it's more 'end of characterisation' - which in some cases could be end of the thing 11:13:44 <khalidbelhajjame> jcheney: the identifiers are interpreted as objects not as things 11:14:11 <khalidbelhajjame> jcheney: multiple identifiers may refer to the same object 11:14:16 <Stian> so the identifier is an activity, entity, event or perhaps something else 11:14:48 <khalidbelhajjame> Luc: the identifiers are identifiers of descriptions as opposed to identifiers of things? 11:14:58 <Stian> it's more like the identifier of objects in the universe of discourse 11:15:34 <khalidbelhajjame> jcheney: yes, but I am not super-comfortable with it ! 11:16:09 <khalidbelhajjame> Paul: would use of perspective instead of description 11:17:46 <pgroth> in section satisfaction 11:17:50 <khalidbelhajjame> jcheney: for each formula, we define relationships that says that a given formula is satisfied in a given world, given an interpretation 11:18:01 <GK> Interesting... I always read |= as "entails" (as opposed to "models") 11:18:16 <Stian> did Objects require there to be at least 1 attribute - or just that the function gives those attributes which "Don't change?". I think the second - then easily all things can be objects 11:18:29 <khalidbelhajjame> jcheney: a conjuctions of formulas holds if the constituent formulas holds individually 11:19:43 <tlebo> 11:19:55 <khalidbelhajjame> Entity Records section 11:20:55 <Stian> @GK - well our world here is within the view of one particular account 11:22:04 <Stian> and this means that entity records with the same ID (but different attribs) are mapped in the same space (which I think is intention of DM) 11:22:13 <tlebo> the scruffies tend to name (and reference) Things, not Entities. 11:22:33 <khalidbelhajjame> Activity Records section 11:23:28 <khalidbelhajjame> jcheney: an activity has a plan, and has a start and end times, which are literals 11:23:34 <tlebo> (or, the broadest Entity that mirrors the Thing to the largest interval....) 11:23:51 <GK> @stian ... er, yes, but I'm not sure of the motivation for this observation. I was just trying to point out that this semantics was enforcing a certain level of invariance. 11:24:13 <khalidbelhajjame> Generation section 11:25:01 <Stian> sorry - what is the obj here? 11:25:38 <Stian> ah -it should be in Entities - right 11:27:47 <khalidbelhajjame> Spezialization section 11:28:20 <tlebo> please don't collapse to owl:sameAs. 11:28:31 <Stian> @GK that's what our model says - if someone abuses the model then they can't expect the formal semantics to still work - in fact that they don't work should be a good hint to them that they've done something too scruffy 11:29:06 <GK> @stian indeed... 11:30:39 <stephenc> Is specializationOf reflexive? I think it needs to be stated whether or not (here and in prov-dm). 11:31:56 <pgroth> q? 11:32:00 <GK> IMO, this definition of specialization actually allows us to let the DM define a "scruffy" usage, and then sets out the conditions under which the provenance can be combined in ways that we might want/expect to do.... 11:32:26 <GK> ... i.e. we can eliminate the thing/entity distinction in DM, but still keep this semantic model. 11:33:17 <Stian> .... and in some cases the two physical things could be the same entity? ("The north-facing traffic light in StreetA crossing StreetB is red") 11:34:03 <Paolo> @ stephenc: I think it should be stated it is reflexive 11:35:50 <pgroth> q? 11:35:57 <Stian> @stephenc reflexive is allowed here and implied because if 'if and only if'. 11:36:04 <Stian> s/if/of/ 11:36:19 <khalidbelhajjame> Graham: we could made the chances to collapse the distinction between things and entities, we map the entities to the semantics. This may give us the (formal) behaviour taht we want 11:37:05 <khalidbelhajjame> jcheney: the objective is to see if prov-sem is a good, and to specify the kinds of interactions that prov-sem can have with other documents 11:37:10 <pgroth> last slide 11:37:11 <GK> I think DM can describe both PropP and ScrufP (proper and scruffy provenance), and the semantics then tells us when the expressions can be treated formally as PropP. 11:37:12 <khalidbelhajjame> jcheney: last slide 11:37:36 <khalidbelhajjame> jcheney: plan for next weeks, have something that we can show to other people, e.G., in Dagsthul 11:38:04 <GK> The upside for us... the DM can be radically simplified by deferring to this semantics for much of its formal content. 11:38:18 <ivan> q+ 11:38:28 <Stian> @GK +10 11:38:45 <pgroth> ack gk 11:38:49 <pgroth> ack ivan 11:40:05 <khalidbelhajjame> Ivan:the formal sem can be used to check if what is described (makes sense?) 11:40:47 <khalidbelhajjame> Ivan: OWL can be used to infer things (facts) 11:40:50 <Paolo> q+ 11:40:52 <Paolo> q? 11:41:10 <kai> q+ 11:41:12 <stephenc> @Stian, @Paolo It seems to depend on reflexivity of "contained in" in condition (3). In prov-dm, I think it is still ambiguous, although I think Paolo and GK discussed it on mailing list and agreed. 11:41:54 <GK> q+ to say... the DM can be radically simplified by deferring to this semantics for much of its formal content. 11:42:08 <khalidbelhajjame> jcheney: we may want to think about if prov-sem can hep in identifying inference rules in prov-dm or prov-o 11:42:20 <khalidbelhajjame> jcheney: I have not written that yet 11:42:50 <Luc> q? 11:42:53 <khalidbelhajjame> ivan: to the outside world we need to clarify that, and we need to use a different world than semantics 11:42:56 <pgroth> ace paolo 11:42:59 <pgroth> ack Paolo 11:43:08 <ivan> s/, and/, or/ 11:43:16 <khalidbelhajjame> Paolo: there are constraints in DM that can be used to generate new assertions 11:43:24 <pgroth> ack kai 11:43:45 <khalidbelhajjame> Kai: in the dublin work, we have a work on use of OWL to check 11:45:27 <pgroth> ack gk 11:45:27 <Zakim> GK, you wanted to say... the DM can be radically simplified by deferring to this semantics for much of its formal content. 11:45:48 <khalidbelhajjame> Graham: prov-sem can help us in simplifying the model 11:46:15 <Stian> ... but then we need to make it a REQ, right? 11:46:23 <khalidbelhajjame> Graham: and by having prov-sem, we can tell to people this is what it actuall means. In other words, use prov-dm as a tool 11:47:00 <pgroth> q+ guus 11:47:04 <tlebo> are we going to discuss ? 11:47:07 <khalidbelhajjame> luc: prov-sem is a tool that allow us to explore the possibilities 11:47:25 <Stian> (PROV-SM could be made into an appendix to PROV-DM) 11:47:36 <tlebo> q? 11:47:47 <khalidbelhajjame> Graham: it can also be used to avoid having things in prov-dm that can be clearly defined using prov-sem 11:47:59 <jcheney> @tlebo: I think we will look at ProvRDF after lunch, sorry 11:48:20 <dgarijo> grama? 11:48:25 <khalidbelhajjame> Paul: introduces guus, the chair of RDF working group 11:48:28 <tlebo> @jcheney, after lunch is fine. I just wanted to know if it was on the agenda. 11:49:01 <khalidbelhajjame> Guus: for the semantics, we only went for things that we actually are sure are used, and tried to keep is simple 11:49:55 <khalidbelhajjame> Guus: maybe you can take a look when at how we specified SKOS semantics, that can be helpful 11:50:20 <tlebo> 11:50:21 <khalidbelhajjame> Ivan: there are some issues that we are in prov wg are interested in having feedback from the rdf working group 11:50:28 <dgarijo> 11:50:50 <tlebo> 40 minute break? 11:52:02 <pgroth> yes 11:52:10 <pgroth> breaking until 1:30 our time 11:53:01 <Zakim> -Sandro 12:11:25 <kai> kai has joined #prov 12:30:11 <jcheney> jcheney has joined #prov 12:31:59 <sandro> it's time, yes? 12:32:31 <tlebo> I think so 12:33:24 <sandro> zakim, what is the code? 12:33:24 <Zakim> the conference code is 77683 (tel:+1.617.761.6200 sip:zakim@voip.w3.org), sandro 12:33:33 <Zakim> +Sandro 12:35:38 <kai> kai has joined #prov 12:36:03 <khalidbelhajjame> Topic: Interoperability <pgroth> Summary: The discussion focused on interoprability of implementations and how the group would demonstrate interoprability. Guus suggested we look at the skos approach to demonstrating interoprability. A survey was taken of the group about who was planning on implementing the spec. 8 people said they had plans or were already under way. It was agreed that we would take a dual approach to demonstrating interoprability. One would be a survey of implementations that shows that every concept is used in at least two different implementations (like skos). The second would be to identify pairs of implementations that can excahnge provenance. The implementation task force would be activated to begin building test harnesses based on the examples cataloged by Tim. 12:36:13 <Luc> q? 12:36:16 <GK> GK has joined #prov 12:36:18 <Luc> ack guus 12:36:39 <khalidbelhajjame> Luc: who is implementing the specs? 12:36:57 <khalidbelhajjame> Stian, smiles:, Paul, Luc 12:37:02 <jcheney> +0.5 12:37:08 <khalidbelhajjame> Graham also 12:37:52 <pgroth> export functionality from workflow systems 12:37:57 <khalidbelhajjame> Stian: workflow provenance export from Taverna 12:37:57 <pgroth> (wings, taverna) 12:38:06 <GK> (I'm expecting to implement code that reads and analyzes provenance information that is conformant with the model and semantics.) 12:38:07 <khalidbelhajjame> kai: Dublin 12:38:08 <khalidbelhajjame> core 12:38:28 <khalidbelhajjame> smiles: standalone library 12:38:53 <khalidbelhajjame> jcheney: implementing history of changes in wiki 12:39:21 <stephenc> We plan to use on open data projects - but initially at least it will be mapping from OPMV 12:39:49 <khalidbelhajjame> Paolo: datalog interpretation of prov-dm 12:40:17 <tlebo> My implementations: 1) switching from PML to prov-o for my tabular RDF converter, csv2rdf4lod 2) capturing provenance in a Linked Data evaluation framework, DataFAQs. 12:40:18 <khalidbelhajjame> Graham: I'm expecting to implement code that reads and analyzes provenance information that is conformant with the model and semantics in the context of workflows and data quality 12:40:43 <khalidbelhajjame> Luc: the use of prov in the context of smart energy management systems 12:41:07 <smiles> smiles has joined #prov 12:41:21 <khalidbelhajjame> luc: and scientific environment for editorial activities 12:41:51 <Luc> q? 12:42:15 <khalidbelhajjame> Paul: tracking data preparation procedures that are done on teh command line 12:43:34 <khalidbelhajjame> luc: two independent impelmentations that interoperatte? 12:43:40 <GK> Interop - one implementation generates/writes, another reads/uses 12:43:47 <khalidbelhajjame> luc: we need to talk about skos 12:44:40 <khalidbelhajjame> ivan: after recommendation, the next thing is to who that the 'thing' is implementable 12:44:58 <khalidbelhajjame> ivan: you have an API for javascript, and hope there are 2 or more implementations 12:45:24 <Stian> perhaps what we are weak on is *consuming* provenance 12:45:49 <khalidbelhajjame> ivan: for thinsg like provenance, it is not clear, and it is up to the group to decide what it means to have interoperable implementations 12:45:55 <ivan> -> SKOS implementation report 12:46:00 <khalidbelhajjame> ivan: in the case for skos for examples: 12:47:34 <khalidbelhajjame> ivan: the criteria themeselves are not subject to public review 12:48:52 <Stian> several terms here are not used by anything, collection, mappingRelation, member, memberList, xl:label, .. 12:49:32 <khalidbelhajjame> Paul: for every contruct in the vocabulary, they showed in skos, the implementations that made use of that construct 12:49:41 <sandro> q+ to ask how this passed with Collection not implemented 12:50:49 <tlebo> My implementations: 1) switching from PML to prov-o for my tabular RDF converter, csv2rdf4lod 2) capturing provenance in a Linked Data evaluation framework, DataFAQs. 12:51:06 <jcheney> q+ 12:51:18 <Stian> Taverna-PROV-O is using it as RDF/XML, but not really linked data as it generates new (non-dereferencable) URIs for pretty much everything (more like a file format) 12:51:40 <pgroth> +q 12:52:06 <tlebo> dereferencing all over my stuff :-) 12:52:39 <pgroth> ack sandro 12:52:39 <Zakim> sandro, you wanted to ask how this passed with Collection not implemented 12:52:40 <khalidbelhajjame> ivan: it is preferable to have people who are not part of the wg, who implemented the model 12:52:57 <Stian> no - the SKOS issues there are used to track what was posted about the implementations 12:53:22 <khalidbelhajjame> sandro: there are some contructs in skos that were not implenented by anybody, or very few 12:54:12 <khalidbelhajjame> jcheney: vocabularies? 12:54:16 <pgroth> ack jcheney 12:54:33 <tlebo> so, a "data application" 12:54:38 <Stian> Remember SKOS is meant to be used by/for vocabularies 12:54:45 <Stian> PROV is not 12:54:55 <tlebo> "Vocabulary": instance data using the skos vocab. 12:54:56 <khalidbelhajjame> jcheney: vocabularies: a pile of vocabulary somewhere, services ? 12:55:09 <khalidbelhajjame> ivan: for example, a service that check the quality 12:55:26 <khalidbelhajjame> jcheney: application is something used by people 12:56:37 <khalidbelhajjame> paul: what it mean to have interoperability? I can take prov xml and output prov rdf? 12:56:54 <sandro> producers and consumers, yes. 12:57:19 <khalidbelhajjame> graham: one impl generates statments, and another implementation that use and make sense of the thing output by the first impl 12:57:27 <tlebo> X out of Y functions that Tool T can do IS DONE based on the provenance provided by Tool S 12:57:55 <khalidbelhajjame> graham: not necessarily two impl from the same domain 12:58:03 <sandro> q+ 12:58:07 <pgroth> ack pgroth 12:58:19 <Luc> q? 12:58:23 <khalidbelhajjame> paolo: how do you ensure that the interpretation is doen correctly? 12:58:24 <ivan> ack sandro 12:59:22 <khalidbelhajjame> sandro: you can have test suite that is used seperatly with the consumer and producer for propvenance, you don't have to have direct interoperability between two implementations 12:59:48 <sandro> too quiet 13:00:00 <tlebo> khalid: ?? 13:00:06 <Stian> for instance - a REST service in Taverna could use PAQ to also ask for the provenance of the retrieved resource (which would need to come from a second implementation), and link retrieved entities to the workflow entities in its exported provenance. But how would that be measured? 13:00:42 <GK> I think the test suite approach works for features like inferences in consumers, but I'm not sure it applies to basic exchange. 13:01:02 <Stian> In Provenance Challenge there was a set of queries you should be able to answer 13:01:03 <khalidbelhajjame> paul: I don't understand how test suite can help in our case 13:01:22 <sandro> q+ 13:01:53 <Stian> say an implementation only exports wasDerivedFrom() records - then we need a derivation-query 13:02:28 <pgroth> q+ 13:02:43 <ivan> ack sandro 13:02:46 <GK> Sandro's test case matches my consumer case (above), but doesn't test the producer. 13:04:11 <khalidbelhajjame> paul: all they did in skos it show that the vocabulary is used and the applications that make use of it 13:04:20 <Stian> but how do you know the different implementations actually interpreted the standard in an interoperable way? 13:04:48 <Stian> +1 sandro 13:05:15 <GK> Trouble is, SKOS have a very weak notion of correctness. 13:05:17 <khalidbelhajjame> paul: what is the test suite for vocabulary 13:05:27 <tlebo> We could start with examples that cover the constructs.... 13:05:50 <GK> @Paul +1 13:05:52 <khalidbelhajjame> paul: if we have inferences, then it make sense to have test suite 13:06:11 <khalidbelhajjame> +q 13:06:15 <Paolo> q+ 13:06:17 <sandro> sandro: you probably cant test a vocab, so maybe build some scaffolding for each use case to test implementation of those use cases 13:06:26 <pgroth> q? 13:06:28 <tlebo> pointers to real-world instance data and services? 13:06:30 <pgroth> ack pgroth 13:07:04 <sandro> 13:07:06 <pgroth> ack khalidbelhajjame 13:07:13 <tlebo> interoperability - the minimal amount that you need to agree upon so that you don't need to agree to anything more. 13:07:42 <Luc> Interoperability is a property referring to the ability of diverse systems and organizations to work together (inter-operate). 13:07:44 <GK> "There is no requirement that a Working Draft have two independent and interoperable implementations to become a Candidate Recommendation" -- 13:07:49 <Luc> 13:08:10 <sandro> formally it's just "a sufficient level of implementation experience" , noting: "There is no requirement that a Candidate Recommendation have two independent and interoperable implementations to become a Proposed Recommendation. However, such experience is strongly encouraged and will generally strengthen its case before the Advisory Committee." 13:08:35 <Stian> but implementations are not required to perform queries? 13:08:46 <khalidbelhajjame> paolo: provenance is a graph, so we can check interoperability, by looking on how different impelementations will answer a set of queries, that are domain independant 13:09:03 <khalidbelhajjame> q+ 13:09:15 <Stian> I'm not going to implmenent any queries in Taverna-PROV - if you want to query, do a SPARQL 13:09:15 <ivan> ack Paolo 13:09:24 <khalidbelhajjame> Paul: but my application may not be able to answer any of those queries 13:10:19 <GK> q+ to say w.r.t. Paul's implementation that he be able to provide a credible, substatiatable report that other applicatios have successfully consumed the produced provenance and performed useful functions with it. 13:10:22 <khalidbelhajjame> smiles: there is an algorithm there that tries to match the queries and the answers given by the implementation? 13:11:00 <Stian> say a visualisation implementation - how do you 'query' that? You can say that you should be able to follow the derivation path, for instance. 13:11:09 <Luc> q+ 13:12:05 <GK> ack gk 13:12:05 <Zakim> GK, you wanted to say w.r.t. Paul's implementation that he be able to provide a credible, substatiatable report that other applicatios have successfully consumed the produced 13:12:08 <Zakim> ... provenance and performed useful functions with it. 13:12:13 <pgroth> ack khalidbelhajjame 13:12:43 <Stian> 'successful' and 'useful' difficult 13:12:54 <khalidbelhajjame> Graham: here are other applications that were able consume the provenance produced by a given application 13:13:49 <khalidbelhajjame> Luc: identify applications that generate and make use of provenance within the context of the same domain 13:14:12 <Paolo> q+ 13:14:14 <Paolo> q? 13:14:17 <pgroth> ack Luc 13:14:26 <khalidbelhajjame> Luc: if we can demonstrate that from within one of my applications that produced trust info, in teh context of a single application, can be used by other applications 13:14:40 <GK> (Single application != "interoperability", IMO) 13:14:59 <khalidbelhajjame> Luc: second: we have two deliverables that are going into that direction that are owl-specific 13:15:35 <GK> If it works for OWL/RDF, that validates the model, IMO. 13:15:42 <khalidbelhajjame> ivan: this is something that the group have to decide 13:15:52 <sandro> ( re how SKOS got out of CR .... they set the bar very very low, and no one objected. It looks like it helped that they then went so far over their bar. ) 13:16:02 <khalidbelhajjame> paul: follow the map of skos, and follow the use of prov 13:16:26 <khalidbelhajjame> paul: we can build soem test cases to read provenance information, and answer simple queries 13:16:27 <Stian> perhaps PROV-ODM is on the level of vocabulary in SKOS - PROV-O is more on the level of implementations/protocols (except for pure use in OWL imports) PROV-AQ is clearly implementation thing. PROV-SEM - I don't know. Papers? 13:16:51 <Paolo> q? 13:17:07 <GK> Paul: nice thought about test suite for checking provenance as a way to validate producers. 13:17:10 <sandro> sounds like a prov validator, not a test suite. useful, but different. 13:17:31 <GK> @sandro, yes, but it still validates the generator to some extent. 13:17:33 <khalidbelhajjame> Paolo: there are two levels, correctness and usefulness 13:17:38 <Luc> PROV-SEM is not at level of REC 13:17:53 <khalidbelhajjame> Paolo: usefulness is hard to show 13:18:09 <sandro> @gk, sure but it's not a test suite -- it's not input documents. 13:18:11 <GK> @Paolo: it's arguable that usefulness is more important than correctness... 13:18:45 <pgroth> +q 13:18:46 <smiles> I dont think it is validation. The provenance must be correct before the test suite discussed can run, and the provenance could be used without the test suite passing 13:18:50 <khalidbelhajjame> ack paolo 13:20:20 <khalidbelhajjame> paul: we can do two things: one we show a variety of implementations that produce or consume provenance, then a smaller case, we should identify different people that there are two impls that use and consume provenance based on some (test suite?) 13:21:00 <pgroth> ack pgroth 13:21:26 <pgroth> q? 13:21:48 <GK> @Paul: I think there's a useful middle ground - which is to demonstrate applications based on exchange between independent implementations. 13:22:31 <khalidbelhajjame> paul: we have a task force who have been keen on gatherfing info on implementations 13:22:53 <GK> q+ to suggest that the survey might be used as a basis for drawing success criteria 13:23:04 <pgroth> ack GK 13:23:04 <Zakim> GK, you wanted to suggest that the survey might be used as a basis for drawing success criteria 13:23:08 <sandro> q+ to ask if you're thinking about 100% coverage or not 13:23:23 <Luc> q+ cab we leverage Tim's suite of examples? 13:23:41 <khalidbelhajjame> Graham: maybe we can use the survey to draw the success criteria 13:23:43 <Luc> q+ to say can we leverage Tim's suite of examples? 13:24:09 <tlebo> 13:24:31 <khalidbelhajjame> Paul: in our survey of implementations, every concepts (rel) is used in at least 2 implementations 13:24:56 <khalidbelhajjame> Paul: and on exchange on provenance, we try to cover most (if not all), the constructs of prov 13:25:02 <pgroth> ack sandro 13:25:02 <Zakim> sandro, you wanted to ask if you're thinking about 100% coverage or not 13:25:04 <pgroth> ls 13:25:27 <Paolo> q+ 13:25:31 <pgroth> ack Luc 13:25:31 <Zakim> Luc, you wanted to say can we leverage Tim's suite of examples? 13:25:33 <pgroth> ack Luc 13:25:36 <khalidbelhajjame> Luc: If we can make use of Tim examples 13:26:12 <khalidbelhajjame> Paolo: a benchmark is an example, and a set of questions with known answers. 13:26:37 <khalidbelhajjame> smiles: not domain dependant 13:26:56 <khalidbelhajjame> Luc: not from the semantics, but rather the vocabulary 13:27:17 <khalidbelhajjame> smiles: tracedTo is an example 13:27:22 <khalidbelhajjame> luc:: that is the only example we have 13:29:23 <khalidbelhajjame> Luc: the way to use the constraint is not i nteh specification. In particular, we are not specifying what we can infer 13:29:23 <pgroth> q? 13:29:28 <pgroth> ack Paolo 13:30:02 <tlebo> a really bad draft at permitting tool makes to self-list their capabilities and quantifying the interoperabilities: 13:30:12 <tlebo> s/makes/makers/ 13:30:34 <khalidbelhajjame> Paul: ask Helena and Stephane to start this activity 13:31:13 <khalidbelhajjame> Luc: in other WGs, was there any test suite that were produced? 13:31:58 <khalidbelhajjame> Ivan: there is a language for text reporting, and there are tools out there who consume the text produced by the tool 13:32:19 <tlebo> 13:32:45 <pgroth> 13:32:48 <tlebo> @ivan, link to that RDF tester? 13:33:45 <ivan> tlebo: 13:33:50 <pgroth> Action: Engage implementation task force to begin developing of a test harness around examples (from tim or others) 13:33:50 <trackbot> Sorry, couldn't find user - Engage 13:33:52 <tlebo> thanks! 13:34:07 <pgroth> Action: pgroth Engage implementation task force to begin developing of a test harness around examples (from tim or others) 13:34:08 <trackbot> Created ACTION-54 - Engage implementation task force to begin developing of a test harness around examples (from tim or others) [on Paul Groth - due 2012-02-10]. 13:34:18 <ivan> tlebo: this is an RDFa tester, not RDF!! 13:34:32 <Stian> ( says now EXCESSIVE DELAYS ) 13:37:13 <pgroth> Proposed: For interoperability we catalogue existing implementations and which constructs of prov they use. Looking for at least two implementations of each construct. Furthermore, which pair of implementations can exchange prov (different pairs may exchange different constructs) 13:37:32 <pgroth> Accepted: For interoperability we catalogue existing implementations and which constructs of prov they use. Looking for at least two implementations of each construct. Furthermore, which pair of implementations can exchange prov (different pairs may exchange different constructs) 13:39:08 <khalidbelhajjame> Intero-session closed 13:51:49 <jcheney> jcheney has joined #prov 13:52:35 <jcheney> 13:52:37 <khalidbelhajjame> prov-sem session (cont.) 13:52:38 <Paolo> Paolo has joined #prov 13:53:54 <jun> jun has joined #prov 13:54:06 <tlebo> others have gone through the pain, too :-) 13:54:09 <khalidbelhajjame> jcheney: tried to systematize the translation prov-dm -> provo 13:54:44 <khalidbelhajjame> section Translating element formulas 13:56:04 <tlebo> I think this should be at the bottom of prov-o HTML 13:56:45 <dgarijo> @tim: not a bad idea. 13:56:57 <Stian> we talked about using OWL annotations for notes 13:57:27 <tlebo> owl annotations are on single instances? I thought just on a triple. 13:57:53 <GK> (I was minded to suggest removing the stuff about Annotations, as being used primarily for provenance of accounts by my reading.) 13:58:04 <khalidbelhajjame> paul: what is the role if this? 13:59:04 <GK> Luc: how do we take this forward? 13:59:45 <GK> (My answer to Luc might be that this is a matter for the editors.) 14:00:06 <tlebo> q+ 14:00:16 <khalidbelhajjame> Section Questions/Problems <pgroth> Topic: Planning <pgroth> Summary: The session focused on planning. To facilatate mapping of prov-o and prov-dm, the group agreed to adopt the use of the ProvRDF mappings page to synchronize the two documents after the ontology reached the level of prov-dm WD3. To facilate this usage, it was agreed to ensure that the ProvRDF mappings page was also aligned with prov wd3. It was agreed that the editors would draft an updated version of prov-aq to address all outstanding issues. Additionally, the group agreed to start producing an xml schema. The editors of the prov-dm agreed to draft an simplified introduction to it reflecting the groups desire for simplfication. Finally, Paul agreed to summarize the F2F for an email to the whole group as well as in a blog post. 14:00:57 <pgroth> q? 14:01:03 <Luc> q? 14:01:23 <GK> q+ to note This is uncontroversial as long s it's also uncontroversial that DM uses URIs to name entities, attributes, etc. 14:01:56 <Stian> tlebo: perhaps 14:02:03 <Luc> ack tle 14:02:34 <GK> ack gk 14:02:34 <Zakim> GK, you wanted to note This is uncontroversial as long s it's also uncontroversial that DM uses URIs to name entities, attributes, etc. 14:02:54 <khalidbelhajjame> Luc: tim? you are supportive of this effort? 14:03:39 <jcheney> Luc's question is how to integrate this into other things? 14:04:02 <khalidbelhajjame> Tim: this is explicit form that should be used by the rest of the prov-o team 14:04:10 <khalidbelhajjame> q+ 14:04:35 <khalidbelhajjame> luc: what process would you suggest Tim? 14:05:25 <khalidbelhajjame> Tim: the previous mappings can be translated just like James did 14:05:47 <tlebo> one step: DM editors ensure that all "left sides" are listed. 14:05:49 <Luc> q? 14:06:15 <tlebo> a second step: PROV-O team sets the "right sides" in this notation 14:06:41 <GK> It seems to me this is a very effective way of bridging the DM presentation to RDF cognoscenti 14:06:44 <dgarijo> some binary relationships are missing, like a used e, e wasGeneratedBy a. 14:06:56 <khalidbelhajjame> luc: translation rules, we should use each rule endorced by the wg 14:07:13 <Luc> ack k 14:07:17 <pgroth> q+ 14:07:30 <Stian> and while editing, having these in the end of PROV-O is also good as it sh/would show what mappings were used in that particular version 14:07:38 <tlebo> This is our status bar! 14:07:53 <GK> Khalid: James' rute of translation, rather than translation for every construct, try to come up with translation pattern? 14:08:04 <Luc> q? 14:08:09 <tlebo> remember the port of .... ? 14:08:18 <pgroth> quote of tony hoare 14:08:24 <tlebo> thx 14:09:25 <GK> proposes (among other things) factoring out attributes in the DM. 14:09:34 <khalidbelhajjame> Paul: we agreed on a proces on how the development of prov-o to first start with the ontology, do we need to add to that the additional effort to encode the rules that James illustrated? 14:09:59 <tlebo> +1 14:09:59 <Luc> q? 14:10:03 <pgroth> ack pgroth 14:10:03 <smiles> q+ 14:10:10 <dgarijo> +1 to the proposed process 14:10:12 <pgroth> ack smiles 14:10:15 <khalidbelhajjame> +1 14:10:25 <Stian> +1 14:11:00 <khalidbelhajjame> smiles: this can also be useful for the primer to understad what has been changed in prov-o and might affect the primer 14:11:43 <Luc> q? 14:12:20 <tlebo> q+ to ask DM'ers to ensure the "left side" list is complete and to add annotatiosn for "what out, this one is in danger of leaving" (at) 14:13:26 <khalidbelhajjame> luc: if there is a proposal for change, then it still should be raised as an issue 14:14:54 <khalidbelhajjame> paul: it should be up to the chairs of prov-dm and prov-o to raise change against the primer, when things change in either prov-dm or prov-o 14:14:54 <Luc> q? 14:15:09 <khalidbelhajjame> to raise issues not change :-) 14:15:11 <Luc> ack tl 14:15:11 <Zakim> tlebo, you wanted to ask DM'ers to ensure the "left side" list is complete and to add annotatiosn for "what out, this one is in danger of leaving" (at 14:15:14 <Zakim> ...) 14:15:20 <Stian> we have in the PROV-O document just kept a flat changelog as as well 14:15:31 <GK> (I woudn't raise a second issue on the primer, but I won't argue the case if the respective editors are OK with it.) 14:15:52 <khalidbelhajjame> jcheney: the translation rules specified is not complete yet 14:16:33 <GK> In line with other decisions, should we aim to align the rules with DM3, then let process track? 14:16:50 <khalidbelhajjame> luc: the issues that are raised in the tracker and in the prov-dm, and can be used by prov-o team to identify the constructs (relationships) at risk 14:17:00 <Paolo> Paolo has joined #prov 14:17:32 <tlebo> sounds great. 14:18:15 <Luc> q? 14:18:21 <tlebo> will get into sync with DM WD3 14:18:49 <khalidbelhajjame> luc: the translation rules seem to be a useful tool for synchronizing the updates 14:18:57 <tlebo> we can handle the various issues in PROV-O team. 14:19:24 <khalidbelhajjame> prov-sem ended 14:20:02 <Luc> q? 14:20:06 <tlebo> the timetable for is before I go to bed tonight :-) 14:21:08 <tlebo> two weeks from now, we have an OWL file for WD3 14:21:08 <tlebo> yes 14:21:10 <pgroth> 2 weeks for alignment of prov-o ontology to prov-dm wd3 14:21:54 <tlebo> :-) 14:21:58 <GK> I won't be available for the 17 Feb telecon. Just saying. 14:22:39 <tlebo> what about the owl file will we discusson the 16th? 14:22:46 <tlebo> s/son// 14:22:49 <MacTed> MacTed has joined #prov 14:22:58 <Paolo> . 14:23:09 <tlebo> ok 14:23:11 <Luc> q? 14:23:17 <stephenc> Very tempting to implement abstract syntax <=> rdf translation as prolog 14:23:32 <tlebo> so, the action is just due by the 17. 14:23:42 <pgroth> Action: Michael Lang - Prov-o team will produce an updated owl file reflecting prov-dm wd3 by 17 Feb telecon 14:23:42 <trackbot> Created ACTION-55 - Lang - Prov-o team will produce an updated owl file reflecting prov-dm wd3 by 17 Feb telecon [on Michael Lang - due 2012-02-10]. 14:24:17 <jcheney> @stephenc, yes, that's one of the next steps I had in mind. 14:28:15 <dgarijo> @tlebo, stian, khalid: are we supposed to include a complete example with the ontology? 14:28:37 <dgarijo> it would help the review. 14:29:05 <tlebo> satya doesn't want instance data in the owl file. 14:29:27 <dgarijo> :) well then an additional file.. 14:29:36 <tlebo> so we'll need a second file. But better, I want to use an annotation property to point from provo classes to examples that use them. 14:29:49 <khalidbelhajjame> @Daniel, not in the ontology. I understand that we will be focusing just on the ontology itself 14:29:51 <tlebo> (and properties) 14:29:51 <dgarijo> ahh ok. 14:29:58 <Luc> q? 14:30:17 <dgarijo> @khalid, I know, not in the final version of the ontology. I was referring just for the review. 14:31:10 <stephenc> @jcheney swi-prolog has direct rdf support. Abstract syntax is already "deviant prolog" - so no parsers to write. It would also be easy to generate a latex version for the wiki from a prolog version of the mapping rule. 14:31:16 <Stian> tlebo: feel free :) (annotation properties) 14:31:33 <jcheney> @stephenc What about sicstus :) 14:31:41 <tlebo> @ivan, do you have a handful of good vocab annotation vocabs? (like the ones Ian uses)? 14:31:56 <Stian> @khalidbelhajjame: I've checked in for our flight - seat 23F (window) - perhaps you want to check in as well 14:31:57 <stephenc> @jcheney It's not free! 14:32:07 <pgroth> action: jcheney to update the provrdf rules and align it with prov wd3 by 16 Feb telecon 14:32:07 <trackbot> Created ACTION-56 - Update the provrdf rules and align it with prov wd3 by 16 Feb telecon [on James Cheney - due 2012-02-10]. 14:32:19 <jcheney> True, but Edinburgh has a site license... 14:32:27 <Luc> q? 14:32:37 <ivan> problem is: there are more:-) 14:32:46 <ivan> the scientific community has some of those 14:32:53 <tlebo> @ivan, I'm always pleased when I run into them, but have never gathered up a list of them. 14:33:29 <tlebo> for example 14:33:51 <ivan> Tim, I do not have an exhaustive list. I think the best two are one coming form the Mass. General Hostpital (TIm Clark) and the other, I believe, from Lawrence LL. Will try to find a link 14:34:35 <ivan> s/Lawrence LL/Los Alamos/ 14:34:39 <ivan> that one is: 14:35:36 <ivan> look at as well, there is a group looking into this 14:35:57 <ivan> 14:36:03 <ivan> problem - none of these are stable 14:36:19 <pgroth> action: pgroth draft review of potential public wd2 addressing all outstanding issues 14:36:19 <trackbot> Created ACTION-57 - Draft review of potential public wd2 addressing all outstanding issues [on Paul Groth - due 2012-02-10]. 14:36:32 <tlebo> @ivan thanks! 14:40:02 <pgroth> action: pgroth write a summary email of f2f for the larger group 14:40:02 <trackbot> Created ACTION-58 - Write a summary email of f2f for the larger group [on Paul Groth - due 2012-02-10]. 14:40:21 <pgroth> action: pgroth write a blog post about current status on development 14:40:21 <trackbot> Created ACTION-59 - Write a blog post about current status on development [on Paul Groth - due 2012-02-10]. 14:43:59 <pgroth> action: luc kickstart discussion on xml schema 14:43:59 <trackbot> Created ACTION-60 - Kickstart discussion on xml schema [on Luc Moreau - due 2012-02-10]. 14:46:03 <tlebo> I'm interesting in helping the XML (to write a GRDDL to rescue the XML into RDF) (and perhaps to write some example xpaths that exercise the XML) no xml schema experience, tons of xslt experience. 14:47:17 <Luc> q? 14:52:34 <Luc> q? 14:52:47 <Zakim> -Sandro 14:54:22 <Stian> I've got XSD experience, but don't think I have the bandwith 14:54:30 <Stian> can pretend I'm 'expert' 14:55:29 <GK> Our charter calls for: D1. PIL Conceptual Model (REC), D2. PIL Formal Model (REC), D3. PIL Formal Semantics (NOTE), which are mapped to roughly: PROV-DM, PROV-O and semantics. But there' a lot of formal-ish material in PROV-DM which doesn't really belong in PROV-O. Should we try and factor away the inference/constraint material in PROV-DM from a basic and accessible description of the underlying model? 14:57:11 <pgroth> action: jcheney to update prov-sem to be compatible with wd3 14:57:11 <trackbot> Created ACTION-61 - Update prov-sem to be compatible with wd3 [on James Cheney - due 2012-02-10]. 14:57:18 <Stian> khalidbelhajjame: start your skype :) 14:59:22 <jcheney> That should be due February 23... 15:00:00 <pgroth> q+ 15:01:07 <tlebo> luc: if we don't have things, there is not specOf and altOf ? 15:01:18 <tlebo> did I get that right? 15:01:35 <Zakim> +Sandro 15:05:37 <kai2> kai2 has joined #prov 15:05:57 <smiles> smiles has joined #prov 15:06:48 <kai3> kai3 has joined #prov 15:07:59 <dgarijo> luc: are "objects" descriptions? 15:08:37 <dgarijo> jcheney: for description I'm not sure about the connotations 15:08:45 <tlebo> @sandro, you there? 15:08:58 <GK> I think "description" is part of the ;language, not what we are describing. 15:09:44 <dgarijo> luc: instead of objects should we talk about states of resources, or partial states of resources? 15:09:55 <GK> q+ to say I don't think we should be trying to describe this 15:10:03 <Luc> q? 15:10:22 <dgarijo> jcheney: objects are kind of a weird middle level 15:10:24 <GK> (this = how PROV-DM entoities relate to resources) 15:11:50 <tlebo> - awww:Resources are semiotic referents denoted and awww:identifiedBy URIs. Requesting the URI via HTTP will return a Resource Representation that describes the referent. 15:12:06 <Luc> q? 15:13:06 <dgarijo> pgroth: yesterday we said: let's do thing and just continue from there. What would the ramifications be for the semantics? 15:13:08 <GK> q+ to say I now think there are (1) things in the domain of discourse that may be identified in the semantic model, (2) things in domain of discourse that are referenced directly in the DM and (3) syntactic artifacts (and maybe other things) that are not referenced by any construct. The consequence of this is that DM can refer to entities (alone) without reference to things, which are still explained in the semantics by reference to things. 15:13:49 <dgarijo> ivan: the different between thing and objects dissapear 15:13:57 <dgarijo> s 15:15:59 <dgarijo> jcheney: in order to say that an attribute is true I have to measure the time of the assertion, that was part of the semantics 15:16:39 <dgarijo> luc: Remove things and then rename objects into thing 15:16:46 <tlebo> "scruffiness" means that asserters name and refer to less specialized Entities, while the "propers" would object to that modeling because they think more specialized Entities should be named and referred to. For example, scruffies describe when propers would want them to describe 15:18:09 <dgarijo> gk: the scruffiness is maybe isatisfaible 15:18:53 <satya> satya has joined #prov 15:19:03 <Zakim> +Satya_Sahoo 15:19:55 <Stian> I don't understand "over time" here 15:19:55 <dgarijo> khalid: when we have the things, then can they be mutable or not? 15:20:56 <tlebo> I hope people are not considering "web resources" to be exclusively computer files. I'm a web resource.... 15:21:33 <Stian> do you mean that someone says in a single graph: :car a owl:Thing; :colour :red . :ColourFinder a prov:Activity ; prov:used :car . :blue prov:wasGeneratedBy :ColourFinder; prov:wasDerivedFrom :car . 15:21:51 <Stian> (assuming that colourfinder found the :colour attribute) 15:22:32 <dgarijo> gk: this doesn't talk about attirbutes other than the others that vary with time 15:23:06 <Zakim> -Satya_Sahoo 15:23:36 <Luc> q? 15:23:39 <Luc> ack pg 15:23:40 <sandro> tlebo, I'm not sure I agree. I think "resource" can be anything, but if you're going to put the word "web" in there, it's short of "web-accessible". not quite sure if that covers non-IR resources or not, but it only covers things with working IRIs. 15:24:00 <sandro> (not sure if you have a working IRI or now) 15:24:06 <sandro> s/now/not/ 15:24:35 <dgarijo> paul: if we do what luc proposed, do we deal scruffiness? 15:24:47 <dgarijo> gk: what do you mean by scruffiness? 15:25:22 <dgarijo> pgroth: if you use the semantics, it will come up and barf: you're not doing it right ->structured guidance. 15:25:27 <tlebo> Web Resources disjointUnion ( non-Information-Resource InformationResource ) 15:25:38 <dgarijo> ... in RDF we do this all the time 15:26:04 <dgarijo> ... the intention is to make it easy to apply 15:27:20 <tlebo> Web Resource := anything denoted by a URI (though, happy to get corrected with a pointer to a doc) 15:29:02 <tlebo> :Web_Resource owl:equivalentClass awww:Resource . 15:29:43 <dgarijo> luc: maybe Paolo, james an luc should sit around the table, discuss and then come back 15:30:03 <Luc> q? 15:30:44 <dgarijo> paul: the semantics is how you should do provenance, but it is fine if you don't do it 15:31:39 <GK> ack gk 15:31:39 <Zakim> GK, you wanted to say I don't think we should be trying to describe this and to say I now think there are (1) things in the domain of discourse that may be identified in the 15:31:42 <dgarijo> luc: how can I map those assertions into the semantics. At the moment I don't see it, so it doesn't help 15:31:42 <Zakim> ... semantic model, (2) things in domain of discourse that are referenced directly in the DM and (3) syntactic artifacts (and maybe other things) that are not referenced by any 15:31:42 <Zakim> ... construct. The consequence of this is that DM can refer to entities (alone) without reference to things, which are still explained in the semantics by reference to things. 15:32:32 <dgarijo> gk: we can take out a layer from the model without necessarily having to take it from the semantics 15:34:18 <Stian> q? 15:34:18 <Luc> q? 15:34:25 <dgarijo> luc: instead of droping entities in the data model, we drop things in the data model and we map them to the semantics 15:34:38 <pgroth> q+ ivan 15:34:45 <pgroth> q- ivan 15:34:50 <Paolo> q? 15:35:21 <Paolo> q+ 15:35:29 <dgarijo> jcheney: there is no syntax for things (I don't think it is necessary). 15:36:00 <Luc> q? 15:36:34 <pgroth> ack Paolo 15:36:35 <dgarijo> paolo: makes perfect sense what gk said. 15:37:00 <dgarijo> paolo: I don't see the need for that in the DM 15:38:45 <dgarijo> luc: the scruffy version is objects/entities for which there is no lifetime defined? 15:39:12 <dgarijo> luc: so none of this machinery works! they don't have lifetime 15:39:33 <tlebo> scruffies assert among Entities that are higher in the specializationOf chain 15:39:45 <dgarijo> stian: how do you know it doesn't work? it is just not stated 15:40:35 <Stian> :blogPost prov:wasAuthoredBy :paul is fine as long as you don't also say :paul prov:wasDerivedFrom :blogPost 15:40:59 <dgarijo> paolo: we may not have inconsistencies, but we could have consequences. 15:41:47 <Stian> or say you use <> for both identifiers :) 15:41:54 <dgarijo> luc: action to prov-dm editors: write a separate document to no longer talk about things in prov dm, just entities. Things will be the mechanism by which we'll provide some semantics. 15:42:26 <dgarijo> ... we'l analyze the meaning of scruffy provenance vs more sofisticated and comlpete provenance 15:42:54 <dgarijo> paul: one conclusion is that people is keen on not having entities 15:43:02 <dgarijo> ... it simplifies the model 15:43:21 <dgarijo> ... avoid using intervals, freezing, etc. 15:43:25 <GK> @paul +lots! 15:43:31 <tlebo> :-) 15:43:57 <dgarijo> paul: please take that under consideration. 15:44:19 <dgarijo> smiles: in the primer that's our approach 15:44:41 <Stian> Satya Sahoo: "Attributes on an Entity SHOULD be consistent across all involvements of the entity in other provenance records" 15:44:52 <dgarijo> luc: we could tackle that after the second half of the dm, reduced to a minimum 15:45:16 <Stian> s/consistent/true/ or similar (people don't like 'consistent') 15:45:19 <dgarijo> pgroth: I really like the interaction between semantics and dm 15:45:38 <dgarijo> luc:it confirms that semantics should be a note. 15:46:22 <pgroth> q? 15:46:25 <dgarijo> luc: will go back to the working group in 2 weeks 15:46:49 <Stian> KL1093 16:20 to Manchester was cancelled 15:47:19 <dgarijo> @Stian :S 15:48:38 <Luc> q? 15:49:33 <pgroth> action: luc to provide a preliminary simplified introduction to the data model 16 Jan 15:49:34 <trackbot> Created ACTION-62 - Provide a preliminary simplified introduction to the data model 16 Jan [on Luc Moreau - due 2012-02-10]. 15:49:58 <GK> GK has joined #prov 15:49:58 <Luc> q? 15:50:24 <pgroth> luc: thanking everyone 15:50:37 <dgarijo> pgroth: thanks to ivan 15:50:49 <dgarijo> ... and to all. 15:51:03 <Stian> @dgarijo they seem to be recovering and flying out a few 14:00 flights now - me and Khalid are hopefully fine by 21 - but 15:51:52 <tlebo> bye bye :-) 15:52:02 <pgroth> tlebo awesomeness! 15:52:05 <satya> @Daniel: Thanks Daniel again for hosting us! 15:52:18 <Zakim> - +31.20.598.aaaa 15:52:19 <satya> bye 15:52:21 <Zakim> -tlebo 15:52:24 <Zakim> -Sandro 15:52:24 <tlebo> Thanks, @daniel! 15:52:28 <Zakim> -??P1 15:52:29 <Zakim> PROV_f2f()3:00AM has ended 15:52:29 <Zakim> Attendees were Sandro, tlebo, +31.20.598.aaaa, Satya_Sahoo 15:52:32 <GK> Done!!! 15:53:14 <dgarijo> bye all 15:53:39 <Stian> for 16:00 says pretty much everything cancelled - at 14:00 there are 3 flights that went out 15:55:51 <pgroth> zakim, end telecon 15:55:51 <Zakim> I don't understand 'end telecon', pgroth 15:55:59 <pgroth> trackbot, end telecon 15:55:59 <trackbot> Zakim, list attendees 15:55:59 <Zakim> sorry, trackbot, I don't know what conference this is 15:56:07 <trackbot> RRSAgent, please draft minutes 15:56:07 <RRSAgent> I have made the request to generate trackbot 15:56:08 <trackbot> RRSAgent, bye 15:56:08 <RRSAgent> I see 10 open action items saved in : 15:56:08 <RRSAgent> ACTION: Engage implementation task force to begin developing of a test harness around examples (from tim or others) [1] 15:56:08 <RRSAgent> recorded in 15:56:08 <RRSAgent> ACTION: pgroth Engage implementation task force to begin developing of a test harness around examples (from tim or others) [2] 15:56:08 <RRSAgent> recorded in 15:56:08 <RRSAgent> ACTION: Michael Lang - Prov-o team will produce an updated owl file reflecting prov-dm wd3 by 17 Feb telecon [3] 15:56:08 <RRSAgent> recorded in 15:56:08 <RRSAgent> ACTION: jcheney to update the provrdf rules and align it with prov wd3 by 16 Feb telecon [4] 15:56:08 <RRSAgent> recorded in 15:56:08 <RRSAgent> ACTION: pgroth draft review of potential public wd2 addressing all outstanding issues [5] 15:56:08 <RRSAgent> recorded in 15:56:08 <RRSAgent> ACTION: pgroth write a summary email of f2f for the larger group [6] 15:56:08 <RRSAgent> recorded in 15:56:08 <RRSAgent> ACTION: pgroth write a blog post about current status on development [7] 15:56:08 <RRSAgent> recorded in 15:56:08 <RRSAgent> ACTION: luc kickstart discussion on xml schema [8] 15:56:08 <RRSAgent> recorded in 15:56:08 <RRSAgent> ACTION: jcheney to update prov-sem to be compatible with wd3 [9] 15:56:08 <RRSAgent> recorded in 15:56:08 <RRSAgent> ACTION: luc to provide a preliminary simplified introduction to the data model 16 Jan [10] 15:56:08 <RRSAgent> recorded in # SPECIAL MARKER FOR CHATSYNC. DO NOT EDIT THIS LINE OR BELOW. SRCLINESUSED=00001180
http://www.w3.org/2011/prov/wiki/index.php?title=Chatlog_2012-02-03&oldid=5806
CC-MAIN-2014-42
refinedweb
16,029
58.62
Created on 2012-11-02 18:23 by pjenvey, last changed 2013-04-06 05:29 by serhiy.storchaka. This issue is now closed. #9396 replaced a few caches in the stdlib w/ lru_cache, this made the mako_v2 benchmark on Python 3 almost 3x slower than 2.7 The benchmark results are good now that Mako was changed to cache the re itself, but the problem still stands that lru_cache seems to hurt the perf of inline res compared to 2.7. The fix for Mako did not affect the 2.7 benchmark numbers See more info here: lru_cache() seems to use a complicated make_key() function, which is invoked on each cache hit. The LRU logic is probably on the slow side too, compared to a hand-coded logic which would favour lookup cost over insertion / eviction cost. Would be interesting to know what speed difference would occur if the statistics gathering was optional and turned off. As for _make_key(), I wonder if ``(args, tuple(sorted(kwd.items())))`` as a key would be any faster as a tuple's hash is derived from its contents and not the tuple itself (if I remember correctly). You could even special case when len(kwds) == 0 to skip the sorted(kwd.items()) overhead if it is worth it performance-wise. Ditching the statistics only sped up regex_compile by 2%. > Ditching the statistics only sped up regex_compile by 2%. Does explicit compiling even go through the cache? Regardless, the issue here is with performance of cache hits, not cache misses. By construction, you cache something which is costly to compute, so the overhead of a cache miss won't be very noticeable. re.compile() calls _compile() which has the lru_cache decorator so it will trigger it. But you make a good point, Antoine, that it's the hit overhead here that we care about as long as misses don't get worse as the calculation of is to be cached should overwhelm anything the LRU does. With a simplified _make_key() I can get regex_compile w/ cache clearing turned off to be 1.28x faster by making it be:: if not typed: if len(kwds) == 0: return args, () else: return args, tuple(sorted(kwds.items())) else: if len(kwds) == 0: return (tuple((type(arg), arg) for arg in args), ()) else: return (tuple((type(arg), arg) for arg in args), tuple((type(v), (k, v)) for k, v in kwds.items())) That might not be the fastest way to handle keyword arguments (since regex_compile w/ caching and leaving out the len(kwds) trick out becomes 1.13x slower), but at least for the common case of positional arguments it seems faster and the code is easier to read IMO. Did you try moving the existing single-argument fast path to before the main if statement in _make_key? That is: if not kwds and len(args) == 1: key = args[0] key_type = type(key) if key_type in fasttypes: if typed: return key, key_type return key Such a special case is already present, but it's *after* a lot of the other processing *and* it doesn't fire when typed==True. So instead of the simple 2-tuple creation above, you instead do the relatively wasteful: args + tuple(type(v) for v in args) > re.compile() calls _compile() which has the lru_cache decorator so it > will trigger it. What's the point of using the lru_cache for compiled regexes? Unless I'm missing something, re.compile() should just return the compiled regex without going though lru_cache and needlessly wasting time and cache's slots. in response to ezio, I poked around the source here, since I've never been sure if re.compile() cached its result or not. It seems to be the case in 2.7 and 3.2 also - 2.7 uses a local caching scheme and 3.2 uses functools.lru_cache, yet we don't see as much of a slowdown with 3.2. so it seems like the caching behavior is precedent here, but I would revert re.py's caching scheme to the one used in 2.7 if the functools.lru_cache can't be sped up very significantly. ideally lru_cache would be native. also does python include any kind of benchmarking unit tests ? over in SQLA we have an approach that fails if the call-counts of various functions, as measured by cProfile, fall outside of a known range. it's caught many issues like these for me. Now that Brett has a substantial portion of the benchmark suite running on Py3k, we should see a bit more progress on the PyPy-inspired speed.python.org project (which should make it much easier to catch this kind of regression before it hits a production release). In this case, as I noted in my earlier comment, I think the 3.3 changes to make_key broke an important single-argument fast path that the re module was previously relying on, thus the major degradation in performance on a cache hit. I haven't looked into setting up the benchmark suite on my own machine though, so we won't know for sure until either I get around to doing that, or someone with it already set up tries the change I suggested above. This is not only 3.3 regression, this is also 3.2 regression. 3.1, 3.2 and 3.3 have different caching implementation. Mikrobenchmark: $ ./python -m timeit -s "import re" "re.match('', '')" Results: 3.1: 2.61 usec per loop 3.2: 5.77 usec per loop 3.3: 11.8 usec per loop Here is a patch which reverts 3.1 implementation (and adds some optimization). Microbenchmark: $ ./python -m timeit -s "import re" "re._compile('', 0)" Results: 3.1: 1.45 usec per loop 3.2: 4.45 usec per loop 3.3: 9.91 usec per loop 3.4patched: 0.89 usec per loop Attached a proof of concept that removes the caching for re.compile, as suggested in msg174599. Ezio, I agree with you, but I think this should be a separate issue. I think the lru_cache should be kept if possible (i.e. I'm -0.5 on your patch). If this result in a slowdown (as the mako_v2 benchmark indicates), then there are two options: 1) optimize lru_cache; 2) avoid using it for regular expressions compiled with re.compile; Both the changes should improve the performances. This issue is about the re module, so I think it's ok to cover any changes to the re module here, and improvements to lru_cache (e.g. a faster make_key) should be moved to a new issue. If this is not enough to restore the performances we might decide to go back to a custom cache instead of using lru_cache. > I think the lru_cache should be kept if possible (i.e. I'm -0.5 on your patch). This patch is only to show the upper level to which should be sought. I tried to optimize lru_cache(), but got only 15%. I'm afraid that serious optimization is impossible without rewriting lru_cache() on C. > 2) avoid using it for regular expressions compiled with re.compile; I do not see how it can significantly affect performance. Maybe lru_cache() should have a key argument so you can specify a specialized key function. So you might have def _compile_key(args, kwds, typed): return args @functools.lru_cache(maxsize=500, key=_compile_key) def _compile(pattern, flags): ... > Maybe lru_cache() should have a key argument so you can specify a specialized key function. It would be interesting to look at the microbenchmarking results. Since switching from a simple custom cache to the generalized lru cache made a major slowdown, I think the change should be reverted. A dict + either occasional clearing or a circular queue and a first-in, first-out discipline is quite sufficient. There is no need for the extra complexity of a last-used, first out discipline. For 3.4 #14373 might solve the issue. A few thoughts: * The LRU cache was originally intended for IO bound calls not for tight, frequently computationally bound calls like re.compile. * The Py3.3 version of lru_cache() favors size optimizations (i.e. it uses only one dictionary instead of the two used by OrderedDict and keyword arguments are flattened into a single list instead of a nested structure). Also, the 3.3 version assures that __hash__ is not called more than one for a given key (this change helps objects that have a slow hash function and it helps solve a reentrancy problem with recursive cached function calls). The cost of these changes is that _make_key is slower than it was before. * I had hoped to get in a C version of _make_key before Py3.3 went out but I didn't have time. Going forward, the lru_cache() will likely have a C-implementation that is blindingly fast. * For the re module, it might make sense to return to custom logic in the re modue that implements size limited caching without the overhead of 1) LRU logic, 2) general purpose argument handling, 3) reentrancy or locking logic, and 4) without statistics tracking. Until the lru_cache can be sped-up significantly, I recommend just accepting Serhiy's patch to go back to 3.2 logic in the regex module. In the meantime, I'll continue to work on improving speed of _make_key(). Raymond's plan sounds good to me. We may also want to tweak the 3.3 lru_cache docs to note the trade-offs involved in using it. Perhaps something like: "As a general purpose cache, lru_cache needs to be quite pessimistic in deriving non-conflicting keys from the supplied arguments. When caching the results of CPU-bound calculations, the cost of deriving non-conflicting keys may need be assessed against the typical cost of the underlying calculation." Which does give me a thought - perhaps lru_cache in 3.4 could accept a "key" argument that is called as "key(*args, **kwds)" to derive the cache key? (that would be a separate issue, of course) Serhiy, please go ahead an apply your patch. Be sure to restore the re cache tests that existed in Py3.2 as well. Thank you. Raymond, actually my patch reverts 3.1 logic. lru_cache used since 3.2. There are no any additional re cache tests in 3.2 or 3.1. > Which does give me a thought - perhaps lru_cache in 3.4 could accept a > "key" argument that is called as "key(*args, **kwds)" to derive the cache > key? (that would be a separate issue, of course) Agreed. I suggested the same in an earlier post. New changeset 6951d7b8d3ad by Serhiy Storchaka in branch '3.2': Issue #16389: Fixed an issue number in previos commit. New changeset 7b737011d822 by Serhiy Storchaka in branch '3.3': Issue #16389: Fixed an issue number in previos commit. New changeset 6898e1afc216 by Serhiy Storchaka in branch 'default': Issue #16389: Fixed an issue number in previos commit.
http://bugs.python.org/issue16389
CC-MAIN-2016-18
refinedweb
1,831
75.2
When developing a library, designing an easy to use API while hiding unnecessary implementation details from clients is fundamental. Today I'd like to show you some API design choices we've made for our library Krate, an Android SharedPreferences wrapper. Delegates 101 Delegates (or to be completely precise, delegated properties) let you take functionality you'd write in a property's custom getter or setter and extract it into a class, making that logic easily reusable. The standard library provides some handy delegates, for example lazy, which you initialize with a lambda that can produce the value to be returned by your property. lazy will only execute this lambda when the property is first read, and then cache its value: val pi: Double by lazy { print("Calculating... ") val sum = (1..50_000).sumByDouble { 1.0 / (it * it) } sqrt(sum * 6.0) } println(pi) // Calculating... 3.1415702709353357 println(pi) // 3.1415702709353357 println(pi) // 3.1415702709353357 Now, this looks rather magical at first, as if it was a special language feature. However, as with many "built-in" features in Kotlin, this is merely clever use of language features that are available to everyone - we can create our own delegates very simply. We won't look at how lazy is implemented, although you can check it out by looking at its implementation in the standard library's source. Instead, we'll take a look at a simplified version of one of the delegates that our library, Krate includes. internal class IntDelegate( private val sharedPreferences: SharedPreferences, private val key: String ) { operator fun getValue(thisRef: Any?, property: KProperty<*>): Int { return sharedPreferences.getInt(key, 0) } operator fun setValue(thisRef: Any?, property: KProperty<*>, value: Int) { sharedPreferences.edit().putInt(key, value).apply() } } As you can see, we wrote a regular class, and conformed to the requirements of delegates, which is to implement the getValue and setValue operators with the given signatures. Note that the latter of these is optional: you only need it if you want your delegate to be applicable for a var, and not just a val. These requirements are an example of the many conventions around operators in Kotlin. This delegate can be used very similarly to the built-in one we've seen before, using the by keyword to delegate the property's implementation to an instance of our class: var score: Int by IntDelegate(sharedPreferences, "score") println(score) // 0 score = 34 println(score) // 34 The behaviour we see here isn't particularly impressive at first, as a simple Int would behave the same way. However, this property will keep its value persistently through application restarts! Hiding the details We could provide the delegate class above as-is for our clients, but there's no reason for them to know about or use this concrete implementation directly, which is why we've marked it as internal. For this next part, you'll have to be familiar with the library's Krate interface. This is extremely simple - anything can be a Krate as long as it contains a SharedPreferences instance: public interface Krate { public val sharedPreferences: SharedPreferences } With that, what we can do instead of making our delegate implementation public is to create a factory function for it, which can also provide nicer API (not unlike lazy): public fun Krate.intPref(key: String): IntDelegate { return IntDelegate(sharedPreferences, key) } Using this method in a Krate implementation would look like this (we're using the SimpleKrate base class, which implements Krate by opening the default SharedPreferences using the provided Context): class MyKrate(context: Context) : SimpleKrate(context) { var score: Int by intPref("score") } Let's summarize what we've achieved here: - This function isn't available globally, only within Krateinstances, due to being an extension on Krate. This is sensible scoping, as we always want these delegates to be within a Krate, because... - This way clients no longer have to provide a SharedPreferencesinstance for every delegate they declare, as this extension can access the sharedPreferencesproperty of the Krateit was called on. - We've made our public API explicitly public, as recommended by the official Kotlin coding conventions. As great as the code above seems, it won't compile: earlier we've marked our IntDelegate class internal, and a public function can't return an internal type. The compiler won't allow it, as it wouldn't make sense to expect our clients to use the returned value without knowing its type. And of course, the whole idea for creating this function was that clients aren't supposed to know about our concrete class! We could create an interface for our class to implement and use that as our function's return type, but the good news is that two very handy interfaces for delegates are already provided for us in the standard library: ReadOnlyProperty and ReadWriteProperty. While we've seen that we can create delegates without them, using them makes the whole process better. Our class allows both reading and writing the stored value, so we'll implement ReadWriteProperty: internal class IntDelegate( private val key: String ) : ReadWriteProperty<Krate, Int> { override operator fun getValue(thisRef: Krate, property: KProperty<*>): Int { return thisRef.sharedPreferences.getInt(key, 0) } override operator fun setValue(thisRef: Krate, property: KProperty<*>, value: Int) { thisRef.sharedPreferences.edit().putInt(key, value).apply() } } Again, let's look at what we've gained: - We don't have to know the signatures of the operators by heart anymore. We can just implement the interface, and then generate the methods to override! - The first type parameter of ReadWritePropertylets us constrain the type of class that this delegate can be used in. In our case, we can state that this property can only be in a Krate. - We'll still keep our factory methods as extensions on Krate, this way they won't pollute the global namespace. If they weren't extensions, they'd still show up in autocompletion everywhere, they'd just produce an error when not used in a Krate. - The thisRefparameter of our methods finally makes sense: it refers to the Krateinstance that our property is in, should we need to access it. And we actually have a use for it here: we no longer have to pass in a SharedPreferencesinstance to the delegate class, as we can access it via thisRef. To fix our previous visibility issue, we can now make our factory function return a ReadWriteProperty<Krate, Int>: public fun Krate.intPref(key: String): ReadWriteProperty<Krate, Int> { return IntDelegate(key) } This is perfect for us: we're returning a well known type from the standard library instead of a custom one. This return type contains the information that the returned delegate can only be a property of a Krate, that it can both be read and written (e.g. it may be a var), and that it's of type Int. Generics trouble With the basics out of the way, let's get to the hard part. The method shown above covered the primitive types, but there comes a time when you need to store more complex data, and you want to do it quickly - without a database. We've decided to add support for this in Krate, and for our new Gson based delegate, things got a bit more complicated. This delegate needed to be generic, since its purpose is to store any arbitrary type by serializing it into a String (and back). We'll need to provide the generic parameter to Gson when deserializing a value, which we can do so by passing in a Type instance to the fromJson method. Since we can't get this from a T directly, we'll resort to the trick of using a TypeToken, usually used to get proper Type representation for nested types. To simplify this example, we'll use a ReadOnlyProperty in the snippets, as the getter's implementation is what's in the spotlight here. internal class GsonDelegate<T : Any>( private val key: String ) : ReadOnlyProperty<Krate, T?> { override operator fun getValue(thisRef: Krate, property: KProperty<*>): T? { val string = thisRef.sharedPreferences.getString(key, null) return Gson().fromJson(string, object : TypeToken<T>() {}.type) } } We'll also create a wrapper function, using what we've learnt with our IntDelegate: public fun <T : Any> Krate.gsonPref( key: String ): ReadOnlyProperty<Krate, T?> { return GsonDelegate(key) } This looks pretty good on first look, and it even compiles! We'll have plenty of trouble at runtime though, in the form of ClassCastExceptions. What went wrong here? The type being passed in is generic, but on the JVM generic types are really only checked at compilation time. At runtime, anything that's generic will essentially be an Object (or in Kotlin terms, Any). This yields good compilation time and runtime performance compared to some other approaches of handling generic types, but it also happens to be the source of our issues in this case. The reason this causes trouble is that Gson makes heavy use of runtime reflection. When it inspects the type we pass in, it sees that it's the type "T", but since generic types are erased at runtime, it doesn't know what T stood for in the case of any given call to fromJson. All it knows is that it needs to create an Object, which it will do so by mapping the JSON string to a completely general JSON representation using nested ArrayLists and LinkedTreeMaps instead of our specific model objects that we'd expect to get. You can read more about the effects of type erasure in these materials I've prepared for a conference workshop last year. Reifying Kotlin provides us with the reified keyword for situations just like this, when a type parameter's concrete value needs to be made available at runtime. A type parameter for a class can't be reified, so we'll need to create our Type instance outside of the class, and receive it as a parameter: internal class GsonDelegate<T : Any>( private val key: String, private val type: Type // the type to use for deserialization ) : ReadOnlyProperty<Krate, T?> { // ... } The good news is that we've been creating wrapper functions around our delegates anyway, so we can reify the type parameter in the function that creates our GsonDelegate: inline fun <reified T : Any> Krate.gsonPref( key: String ): ReadWriteProperty<Krate, T?> { return GsonDelegate(key, object : TypeToken<T>() {}.type) } Unfortunately, reified type parameters are only available to functions that are also inline, which wasn't required of our delegate functions before. With the addition of inline, this function won't compile, because just like our other delegate implementation, GsonDelegate is an internal class. Using internal declarations in an inline function isn't allowed, as the process of inlining will essentially copy the function's body to the call site, where our internal declarations wouldn't be accessible from (this is explained in more detail in the official documentation). Boundaries There's yet another Kotlin feature we can make use of to circumvent this issue, @PublishedApi. Using this annotation on an internal declaration - such as our class - will make it available for inlining while maintaining its internal visibility. @PublishedApi internal class GsonDelegate<T : Any>( // ... ) : ReadOnlyProperty<Krate, T?> { /* ... */ } This way, client code can include it indirectly via the inline function and it will be there in the compiled client code, but it still can't be referenced directly from client source code. Since compiled client code might now refer to our internal declaration, it should be treated as public API in terms of introducing any changes to it. Even though client source code can't reference it, already compiled client code will still refer to it, which raises concerns of binary compatibility. You can read about what binary compatibility is and why it matters, even in the context of Android in this article. In the actual library code, you'll see that we've added an extra layer of indirection for these reified functions. This way, only some helper functions needed to be marked with @PublishedApi, and our actual GsonDelegate class remained entirely internal. This means we can swap out this class freely as long as the helper functions' signatures are untouched. What's next? If you're developing Android apps and you're looking for an easy to use SharedPreferences solution, please do check out Krate! We've just released 0.1.0, which brings Gson support to the library (in a separate artifact). Want to know how importing libraries carelessly can cause security problems with Gradle? Read our article telling the story of a jcenter issue we've encountered. For more about Kotlin API design, you can read my article about designing DSLs, containing lots of example code, with implementations available in a repository as well. Finally, continuing on the topic of how to create great Kotlin libraries, this article by Adam Arold lays out several important things to keep in mind. That's it for now, thanks for reading!
https://blog.autsoft.hu/delightful-delegate-design/
CC-MAIN-2019-30
refinedweb
2,147
50.97
Jensen Harris: An Office User Interface Blog Server2006-09-14T14:00:00ZThe Story of the Ribbon<P>I was reading through commentary from people who attended last week's MIX conference in Las Vegas. Running across <A href="" mce_href="">Miguel de Icaza's kind words</A> reminded me that I hadn't posted a follow-up about my MIX talk yet.</P> <P.</P> <P!</P> <P align=center><A href="" mce_href="">Download "The Story of the Ribbon"</A><BR><I>(Windows Media, 146 MB)</I></P> <P align=center><B>Alternate Formats:</B></P> <P align=center><A href="" mce_href="">Download for iPod</A><BR><I>(.mp4, 121 MB)</I></P> <P align=center><A href="" mce_href="">Download the PowerPoint slides only</A><BR><I>(.pptx, 20 MB)</I></P> <P align=center><A class="" href="" mce_href="">Dowload the slides only as a PDF</A><BR><EM>(.pdf, 19 MB)</EM></P> <P align=left.</P> <P align=left>Here are photos of the beginning and the end of the talk courtesy of <A href="" mce_href="">Long Zheng</A>. (You'll have to watch the presentation to see what's in-between!)</P> <P align=center><IMG src="" mce_src=""> </P> <P align=center><IMG src="" mce_src=""> </P> <P align=left>Over the last few days, the screenshots of the evolution of Word from version 1.0 to 2003 have been lifted from this presentation and subsequently posted and reposted all over the web.</P> <P align=left>That's OK, but if you want to see the full, original screenshots along with the commentary and discussion, please <A href="" mce_href="">read parts 2, 3, and 4 of the Why the UI? series of posts</A>.</P> <P>While at MIX, I also participated in a panel discussion called "What's the Secret Formula?" along with <A href="" mce_href="">Mike Schroepfer</A> from Mozilla, <A href="" mce_href="">Dan Harrelson</A> from Adaptive Path, and Daniel Makoski from the Surface team at Microsoft. This was an interesting discussion about some of the challenges inherent in delivering on great user experiences.</P> <P align=center><A href="" mce_href="">Watch "What's the Secret Formula?"</A></P> <P align=left>Thanks to everyone who came up and introduced themselves after the session and throughout MIX. I enjoyed talking to you and meeting so many of you face-to-face!</P><img src="" width="1" height="1">jensenh's MIX it up!<p>Just a short note to let you know that I'll be presenting a new session during <a href="" mce_href="">MIX in Las Vegas</a> on Friday, March 7 at 10:00 entitled <a href="" mce_href="">"The Story of the Ribbon."</a></p> <p align="center"><img src="" mce_src=""> </p> <p.</p> <p. </p> <p>The session is part of <a href="" mce_href="">MIX UX</a>, a three-day user experience track which is new to MIX08.</p> <p.</p> <p>If you're at MIX, I'd love to chat, so please feel free to come by and introduce yourself. I hope to meet some of you in person either at my sessions or elsewhere at MIX!</p> <p>More information about all the great MIX content is <a href="" mce_href="">on the MIX08 web site</a>.</p><img src="" width="1" height="1">jensenh Gone<p>It's been a while since I last wrote in this space.</p> <p?</p> <p>Nah. The truth is less interesting than any of the theories.</p> <p>A couple of things, both work-related and personal, have conspired to monopolize my time over the last few months and leave me little time for blogging.</p> <p.</p> <p...</p> <p.</p> <p>Whether it will be interesting or not, that remains to be seen... but I'm officially Not Gone.</p><img src="" width="1" height="1">jensenh RibbonX with C++ and ATL<H3>Today's Guest Writer: Eric Faller</H3> <P><I>Eric is a Software Design Engineer on the Office User Experience team focused on user interface extensibility for Office developers.</I> </P> <P. </P> <P. </P> <P><B>IRibbonExtensibility </B></P> <P. </P> <P. </P> <P. </P> <P. </P> <P><B>IDispatch </B></P> <P>If you're unfamiliar with IDispatch-based interfaces, you may be curious how it is that Office can call arbitrary C++ functions in an add-in, given only their names. For example, consider a button specified with this XML: </P><CODE> <P style="TEXT-ALIGN: center"><button id="MyButton" onAction="ButtonClicked"/> </P></CODE> <P. </P> <P>IDispatch is a COM interface used for "dispatching" function calls to objects when their types are unknown or need to be late-bound. It's the reason that this VBA code works even though the "word" variable is not strongly typed: </P><CODE> <P>Dim word<BR>Set word = Application <BR>word.CheckSpelling ("misspellled") </P></CODE> <P>The IDispatch interface contains a whole bunch of methods which you can read all about in the <A href="" mce_href="">documentation</A>, but the main two to be concerned with are GetIDsOfNames() and Invoke(). </P> <P." </P> <P." </P> <P>Parameters and return values are passed around in <A href="" mce_href="">VARIANT</A>. </P> <P>That pretty much sums up the high-level overview of how IDispatch works, so let's see it in action and build a simple RibbonX add-in in C++ with ATL. </P> <P><B>Building a simple C++/ATL RibbonX add-in </B></P> <P>The steps for creating a C++ RibbonX add-in start off pretty much the same as for a C# add-in: </P> <OL> <LI>Open up Visual Studio </LI> <LI>Click "New Project" </LI> <LI>Select "Extensibility" under "Project types" and choose "Shared Add-in" </LI> <LI>Give it a name and click OK: </LI> <P align=center><A href=""><IMG src=""></A><BR><I>Click to view full picture</I></P> <LI>Click through the wizard that shows up, making sure to check "Create an Add-in using Visual C++/ATL" and "I would like my Add-in to load when the host application loads." </LI></OL> <P>Now you have an empty C++ add-in. Click "Build Solution" just to make sure that it all compiles OK with no problem. </P> <P>Next, open up Class View, right-click on your CConnect class and select "Add -> Implement Interface…" In the dialog that pops up, select the "Microsoft Office 12.0 Object Library <2.4>" type library and add the "IRibbonExtensibility" interface from it: </P> <P align=center><IMG src=""></P> . </P> <P>Once you're done with that, Visual Studio should have auto-generated your GetCustomUI() function for you. Delete its "return E_NOTIMPL;" and paste in some valid code, like this: </P><PRE><P>STDMETHOD(GetCustomUI)(BSTR RibbonID, BSTR * RibbonXml)<BR>{<BR> if (!RibbonXml)<BR> return E_POINTER; </P><BR><P> *RibbonXml = SysAllocString(</P><P> L"<customUI xmlns=\"\">"<BR> L" <ribbon>"<BR> L" <tabs>"<BR> L" <tab id=\"CustomTab\"" <BR> L" label=\"Custom Tab\">" <BR> L" <group id=\"CustomGroup\"" <BR> L" label=\"Custom Group\">" <BR> L" <button id=\"CustomButton\"" <BR> L" imageMso=\"HappyFace\""<BR> L" size=\"large\"" <BR> L" label=\"Click me!\"" <BR> L" onAction=\"ButtonClicked\"/>" <BR> L" </group>" <BR> L" </tab>" <BR> L" </tabs>" <BR> L" </ribbon>" <BR> L"</customUI>" </P><P> ); </P><BR><P> return (*RibbonXml ? S_OK : E_OUTOFMEMORY); <BR>} </P></PRE> <P>Now, a real add-in would obviously not hard-code its XML like this (embedding it as a resource in the DLL would be much better), but this suffices for our simple demo. Don't do this at home! </P> <P: </P> <OL> <LI>Open up "stdafx.h" and move the #import statement for MSO.dll from the bottom of the file up next to the #import statement for the Extensibility library inside the #pragma blocks (remove any 'no_namespace' annotations from that line as well) </LI> <LI>Add "using namespace Office;" to the top of the Connect.h file. </LI></OL> <P>Now we can build successfully and see our button: </P> <P align=center><IMG src=""></P> <P>If we click it we get an error saying "The callback function 'ButtonClicked' was not found," which makes sense since we haven't written that function or implemented it via IDispatch yet. Let's use ATL to do that now. </P> <P. </P> <P. </P> <P>Back in Class View, right-click on ICallbackInterface and select "Add -> Add Method…" In the Add Method Wizard, add a method named "ButtonClicked" with one [in] parameter of type IDispatch* called RibbonControl: </P> <P align=center><IMG src=""></P> <P. </P> : </P><CODE> <P>STDMETHOD(ButtonClicked)( IDispatch * RibbonControl)<BR>{ <BR> // Add your function implementation here. </P> <P> MessageBoxW(NULL,<BR> L"The button was clicked!", <BR> L"Message from ExampleATLAddIn", <BR> MB_OK | MB_ICONINFORMATION); </P></CODE> <P> return S_OK; <BR>} </P> <P <I>and</I>". </P> <P: </P><CODE> <P>BEGIN_COM_MAP(CConnect) <BR> COM_INTERFACE_ENTRY2(IDispatch, ICallbackInterface) <BR> COM_INTERFACE_ENTRY(AddInDesignerObjects::IDTExtensibility2) <BR> COM_INTERFACE_ENTRY(IRibbonExtensibility) <BR> COM_INTERFACE_ENTRY(ICallbackInterface) <BR>END_COM_MAP() </P></CODE> <P>Once that's all built, try out the add-in and see that it works! </P> <P align=center><IMG src=""></P> <P <A href="" mce_href="">RibbonX documentation</A>. A "getLabel" callback, for example, would have the same parameters, except it would have an additional "[out, retval] BSTR *Label" parameter for returning the label. </P> <P>For more info about RibbonX, check out the documentation mentioned above, the <A href="" mce_href="">Developer category</A> on this blog, or the <A href="" mce_href="">Office Discussion Groups</A> if you have other questions not specifically related to the topics of this article.</P> <P><I>Update: Eric has made the <A href="" mce_href="">resulting Visual Studio 2005 project available for download</A>.</I><BR></P><img src="" width="1" height="1">jensenh, Office, and Exchange Business Launch <p>Today is the <a href="" mce_href="">official business launch</a> of Windows Vista, the 2007 Office system, and Exchange Server 2007. </p> <p>This means that as of today, businesses can get these products and start deploying them within their organization. </p> <p align="center"><img src="" mce_src="" height="43" width="446"></p> <p>The consumer launch is scheduled for January 30—that's when you'll be able to go into retail stores and buy shrink-wrapped copies of Office and Windows. </p> <p>You can read all about the business launch, see videos, and participate in the forums here: <a href="" mce_href=""></a> </p> <p>Steve Ballmer sent out mail to everyone at Microsoft commemorating today's business launch. Here's in part what he wrote: </p> <p><i>"Eleven years ago, Microsoft launched Windows 95 and Office 95 and introduced an era of unprecedented opportunity, transforming the way people do business, share information, and communicate. Today, in New York I announced the business availability of Windows Vista, the 2007 Office System, and Exchange Server 2007. This announcement marks the beginning of the most significant launch in company history, with more than 1 billion people expected to use these products in the next decade. </i></p> <p><i>"The launch of Windows Vista, the 2007 Office System, and Exchange Server 2007 is an important milestone in our company's history. The result of incredibly hard work, phenomenal perseverance, and remarkable innovation, they are the most advanced work that Microsoft has ever done. For the last three decades, Microsoft has delivered technologies that embody our belief in the power of software to change the world. Windows Vista, the 2007 Office system, and Exchange Server 2007 continue this great tradition and I want to congratulate everyone who worked on these products—thank you for your dedication and commitment to making today possible."</i> </p> <p>You can also read the <a href="" mce_href="">external version of the mail</a> that was posted on Microsoft.com. </p> <p>Want to experience Office 2007 for yourself? Today might be a great day to try <a href="" mce_href="">taking the new Office for a test drive</a>. </p> <p>Or, if you want to download a fully-functional trial version, those will be posted online tomorrow, December 1.</p> <img src="" width="1" height="1">jensenh Image FAQ<p><i>Today I'm delighted to present a new guest writer to the blog: Eric Faller, Software Design Engineer on the Office User Experience Team. </i></p> <p><i>Eric is one of the developers on our team who helped to design and implement RibbonX, the user interface extensibility model for Office developers.<br></i></p> <h3>Today's Guest Writer: Eric Faller</h3> <p <a href="" mce_href="">official documentation</a> or the <a href="" mce_href="">Developer category</a> on this blog. </p> <p><b>Alpha channels, masks, color keys, oh my! </b></p> <p? </p> <p>The problem at hand is: how do we specify which parts of our images are transparent and should let the background color of the Ribbon show through? Before tackling that question, we should look at why it's even necessary to do this in the first place. </p> <p: </p> <p align="center"><img src=""> </p> <p>As we can see, in order for an add-in to look professional, it's going to need to pay attention to transparency. Let's look at what features previous releases of Office offered to solve this problem. </p> <p><b>Color keys </b></p> <p: </p> <p align="center"><img src=""> </p> <p. </p> <p><b>Picture & Mask </b></p> <p: </p> <p align="center"><img src=""> </p> <p>The most obvious drawback with this system is that you need to draw and keep track of <i>two</i> images per icon. </p> <p. </p> <p><b>Alpha channels </b></p> <p. </p> <p>For example, here's what our "A" image looks like when it's drawn in the Ribbon with an alpha channel: </p> <p align="center"><img src=""> </p> <p <a href="" mce_href="">Paint.NET</a>) to draw them. </p> <p><b>File formats </b></p> <p>Another hurdle to using alpha channels is that common file formats do not support them uniformly:<br></p> <table align="center" border="1" cellpadding="0" cellspacing="0" height="275" width="392"> <tbody> <tr> <td valign="top" width="144"> <p align="center"><b>Format</b></p> </td> <td valign="top" width="162"> <p align="center"><b>Supports Transparency?</b></p> </td> </tr> <tr> <td valign="top" width="144"> <p align="center">BMP</p> </td> <td valign="top" width="162"> <p align="center">No (technically Yes, but most libraries don't load it properly) </p> </td> </tr> <tr> <td valign="top" width="144"> <p align="center">JPEG</p> </td> <td valign="top" width="162"> <p align="center">No</p> </td> </tr> <tr> <td valign="top" width="144"> <p align="center">GIF</p> </td> <td valign="top" width="162"> <p align="center">Single level only (no semi-transparency)</p> </td> </tr> <tr> <td valign="top" width="144"> <p align="center">PNG</p> </td> <td valign="top" width="162"> <p align="center">Yes - full support</p> </td> </tr> </tbody></table> <p>PNG is the only common file format with full alpha channel support and widespread tool support. It's the recommended format for storing RibbonX images. </p> <p>So, you might be wondering "Which file formats does RibbonX support?" </p> <p>RibbonX operates on <i>bitmap objects</i> in code, not on <i>files</i> on the disk. It's the add-in which actually loads the files and returns the bitmap objects to RibbonX. Thus, an add-in can use whatever file format it wants when it is loading its images. </p> <p. </p> <p.) </p> <p><b>16-bit vs. 32-bit </b></p> <p>Several things can go wrong in an add-in while it's loading its images before it passes them off to RibbonX. These usually involve the in-memory format used to store the image. </p> <p. </p> </p> <p>So, if the file format you're using (PNG, for example) includes the full 32-bit pixel data, why would the image become compacted to only 16 bits when loading into memory? Unfortunately this happens more than one might expect. </p> <p><b>DIB vs. DDB </b></p> <p. </p> <p. </p> <p. </p> <p. </p> <p>Fortunately, if you are writing a .NET managed add-in and are using GDI+ to load your images, you don't have to worry about this because GDI+ uses DIBs internally. </p> <p><b>IPictureDisp vs. System.Drawing.Bitmap </b></p> <p: </p> <ol> <li>IPictureDisp objects </li> <li>System.Drawing.Bitmap objects </li> <li>Strings (equal to the "imageMso" value of a built-in icon to use) </li> </ol> <p>The 3rd option can be used if you want to re-use a built-in image. The first two require loading your own image and are more complicated. </p> <p>The type of value you should return depends on the language you are using to write your add-in: </p> <ol> <li><b>VB6/VBA:</b> IPictureDisp is the "COM name" of Picture, which is the native VB image type. You can just take the return value from the VB LoadPicture() function and return it (LoadPicture does not support PNG files, though, see the discussion above).<br><br> </li> <li><b>C/C++ and other native code:</b>. <br><br></li> <li><b>C#/VB.NET and other managed code:</b>. </li> </ol> . </p> <p. </p> <p><b>Bitmaps vs. Icons </b></p> <p>Some add-in writers store their UI icons in .ICO files and load them into HICON or System.Drawing.Icon objects. </p> <p>RibbonX can load .ICO files from Open XML format files, and it will accept HICON-based IPictureDisps, but its icon support is somewhat limited and it doesn't accept System.Drawing.Icon objects at all. </p> . </p> <p><b>getImage vs. loadImage </b></p> <p>Another common question is "Why are there both getImage and loadImage functions? Which should I use?" </p> <p>The answer is that you should almost always use loadImage, except when you need to dynamically change your controls' images at runtime, in which case you should use getImage on those controls. </p> <p>loadImage provides these advantages over getImage: </p> <ul><li>If multiple controls use the same image, loadImage is called only once, saving time and space.<br><br> </li><li>If a control is invalidated (for example, in order to change its enabled state), loadImage is not uselessly called again. <br><br></li><li>Arbitrary strings can be specified in the "image" property and passed to loadImage (for example, a resource ID or filename), but with getImage you're stuck with the ID of the specific control you're interested in. </li></ul><ul style="margin-left: 37pt;"> </ul> <p>The main advantage of getImage is that its return value can be invalidated using IRibbonUI.InvalidateControl() and changed dynamically at runtime. Once an image is set with loadImage, it's permanent. </p> <p><b>Further reading </b></p> <p>For more information, check out the official <a href="" mce_href="">RibbonX documentation</a>. </p> <p>If you have specific support questions unrelated to this article, try the <a href="" mce_href="">Office Discussion Groups</a>.</p> <img src="" width="1" height="1">jensenh the 2007 Microsoft Office User Interface<p>For the last year or so, one of the questions I've been asked again and again has been: "Can I use the new Office user interface in my own product?" </p> <p. </p> <p>On the other hand, the new Office user interface was a huge investment by Microsoft and the resulting intellectual property belongs to Microsoft. </p> <p>As a result, I've never been totally comfortable answering questions about whether people can use the new UI or not publicly because, honestly, I didn't really know the answer. You might have noticed I've been pretty quiet on the subject. </p> <p>Internally, though, more than a year ago we started talking about how we could share the design work we've done more broadly in a way that also protects the value of Microsoft's investment in this research and development. </p> <p>Well, I'm pleased to finally be able to definitively answer the question. Today, <a href="" mce_href="">we're announcing a licensing program for the 2007 Microsoft Office system user interface</a> which allows virtually anyone to obtain a royalty-free license to use the new Office UI in a software product, including the Ribbon, galleries, the Mini Toolbar, and the rest of the user interface. </p> <p>Last week, I recorded a video along with Judy Jennison, the lawyer who has been spearheading the licensing effort, to chat about the UI license in detail. Take a look, or keep reading to learn more. </p> <p><i>(If you ever wondered what my office looks like, here's your chance!) </i></p> <p style="text-align: center;"><a href="" class="" target="_blank" mce_href="">Watch the Channel 9 video about the Office 2007 UI License</a> </p> <p><b>How does the license work?</b> </p> <p>It's pretty simple really. First, you visit the <a href="" mce_href="">Office UI Licensing web site</a>. On this page, you'll find some information about the licensing program, a downloadable copy of the license to peruse at your leisure, and further contact information. </p> . </p> <p>This should give you the confidence you need to build a business or product on top of the Office UI platform, secure in the knowledge that you've licensed the technology and research you're using in your product. </p> <p><b>You must follow the guidelines, though.</b> </p> <p. </p> <p>To stay within the terms of the license, you must follow these guidelines. </p> <p>We want to ensure that when someone implements the Ribbon (for example) that they do so the right way… and in a way consistent with how it works in Office. </p> <p>There's tremendous value in making sure that we all use these models in a consistent way, because it helps to ensure that people have predictable user experiences moving between Office-style user interfaces. </p> <p>In the guidelines you'll find REQUIRED sections and OPTIONAL sections. The REQUIRED sections are exactly that—sections that you must implement in order to stay within the letter of the license. </p> <p. </p> <p>The 120+ page guidelines document is confidential, so you'll need to visit the licensing site and agree to a short evaluation license before downloading it. But we created a little preview version of one of the sections to give you a flavor of what the guidelines are like. </p> <p>The particular section we excerpted for the preview is Ribbon Resizing, which details the way in which the Ribbon must scale up and down to adjust to varying horizontal resolutions. The actual guidelines document contains similar information for the entire UI. </p> <p style="text-align: center;"><a href="" mce_href="">Download the 2007 Microsoft Office System UI Guidelines Preview</a> <i>(1.39 MB)</i> </p> <p. </p> <p><b>What's the catch?</b> </p> <p>For almost everyone, there's no catch at all. Just sign up for the license, and follow the guidelines. That's all there is to it. </p> .</p> <p>There's only one limitation: if you are building a program which directly competes with Word, Excel, PowerPoint, Outlook, or Access (the Microsoft applications with the new UI), you can't obtain the royalty-free license. </p> <p>Why this exclusion? </p> <p>Microsoft spent hundreds of millions of dollars on the research, design, and development of the new Office user interface. </p> <p>We're allowing developers to license this intellectual property and take advantage of these advances in user interface design without any fee whatsoever. </p> <p>But we want to preserve the innovation for Microsoft's productivity applications that are already using the new UI. </p> <p><b>Summary</b> </p> <p. </p> <p>I think the license strikes the right balance between allowing developers to use the new Office UI and protecting Microsoft's rights as the company who paid all of us to work on it. </p> <p><b>For More Information</b> </p> <ul> <li><a href="" mce_href="">2007 Microsoft Office System User Interface Licensing web site</a> </li> <li><a href="" mce_href="">User Interface Guidelines Preview</a> <i>(A short excerpt of the actual guidelines) </i></li> <li><a href="" class="" mce_href="">Channel 9 video discussion with more about the UI and the UI license</a> </li> <li><a href="" mce_href="">Press release and Q & A about the licensing announcement</a> </li> <li><a href="" mce_href="">Frequently asked questions</a></li></ul><img src="" width="1" height="1">jensenh Resources for Office 2007 RTM<p>Now that we've released Office 2007 to manufacturing, developers can get started modifying their solutions so that they're ready to test with the released version of Office. </p><p>Final versions of the RibbonX schema and Control ID list will be published on MSDN soon, but that can take a while—so I'll continue to publish developer resources here first so that you don't have to wait. </p><p>First, the entire set of Office 2007 Control ID lists. I'm putting these up in two different formats: .xls (97-2003 format) and .xlsx (2007 format.) </p><p>You only need one of these files; the contents of them are the same aside from the different format of the files. </p><p style="text-align: center;"><a href="" mce_href=""><b>Download Office 2007 RTM Control ID List</b><b> </b><i>(Excel 97-2003 Format)</i></a><b> </b></p><p style="text-align: center;"><a href="" mce_href=""><b>Download Office 2007 RTM Control ID List</b><b> </b><i>(Excel 2007 Format)</i></a><b> </b></p><p. </p><p style="text-align: center;"><a href="" mce_href=""><b>Download List of Control ID List Changes between B2TR and RTM</b></a> </p><p>The Control ID lists can be useful even if you aren't a developer. For example, we added a column for Group Policy ID in each of the lists; this ID number is the ID you need to disable Office commands via group policy. </p><p>Finally, it's worth mentioning again: a few weeks ago we released the RTM customUI schema for RibbonX. If you didn't catch it then, you might want to download it now: </p><p style="text-align: center;"><a href="" mce_href=""><b>Download Office 2007 RTM customUI Schema</b></a></p><img src="" width="1" height="1">jensenh Office 2007 UI Bible<p>I've published over 200 posts on this blog since I started it last September. </p> <p>With all of those posts, it can be hard to remember what you've read and what you haven't… and it can be hard for new people to jump in and figure out where to start reading. </p> <p>I've been meaning to sit down and create a kind of table of contents for all of the posts here—a starting point for people to read about the Office 2007 UI. </p> <p>But then, I found out that someone already did the work for me. <a href="" mce_href="">Patrick Schmid</a>, a OneNote MVP and friend of the Office 2007 UI, put together what he called the <a href="" mce_href="">Office UI Bible</a> on his blog—a fully organized catalog of many of my posts. </p> <p>And so with Patrick's kind permission I reprint here the catalog of Office 2007 UI posts (so far.) </p> <p>I hope you find it useful—and thanks, Patrick! </p> <p><b>Why a New UI for Office 2007?<br> </b></p> <ul> <li><a href="" mce_href="">The Why of the New UI (Part 1)</a><span style="font-family: Times New Roman; font-size: 12pt;"> </span></li> <li><a href="" mce_href="">Ye Olde Museum Of Office Past (Why the UI, Part 2)</a> </li> <li><a href="" mce_href="">Combating the Perception of Bloat (Why the UI, Part 3)</a> </li> <li><a href="" mce_href="">New Rectangles to the Rescue? (Why the UI, Part 4)</a> </li> <li><a href="" mce_href="">Tipping the Scale (Why the UI, Part 5)</a> </li> <li><a href="" mce_href="">Inside Deep Thought (Why the UI, Part 6)</a> </li> <li><a href="" mce_href="">No Distaste for Paste (Why the UI, Part 7)</a> </li> <li><div><a href="" mce_href="">Grading On the Curve (Why the UI, Part 8)</a> </div></li> </ul> <p><b>Overview of the New UI </b></p> <ul> <li><a href="" mce_href="">Enter the Ribbon</a><span style="font-family: Times New Roman; font-size: 12pt;"> </span></li> <li><a href="" mce_href="">What programs get the new Office UI?</a> </li> <li><a href="" mce_href="">Mythbusters: The Office 12 New UI</a> </li> <li><a href="" mce_href="">Office 12 New UI: The Cat's Out</a> </li> <li><a href="" mce_href="">Why is it called the Ribbon?</a> </li> <li><a href="" mce_href="">Outlook and the Ribbon</a> </li> <li><a href="" mce_href="">Need Some Help with That?</a> </li> <li><a href="" mce_href="">Through the Looking Glass</a> </li> <li><a href="" mce_href="">Where Did That Feature Go?</a> </li> <li><a href="" mce_href="">Running With the Popular Crowd</a> </li> <li><div><a href="" mce_href="">Accessibility Begets Usability</a> </div></li> </ul> <p><b>Ribbon UI Elements<br> </b></p> <ul> <li><a href="" mce_href="">I'm In Louvre! (Galleries: Part 1 of 3)</a> </li> <li><a href="" mce_href="">Visualize Whirled Peas (Galleries: Part 2 of 3)</a> </li> <li><a href="" mce_href="">Results-Oriented Design (Galleries: Part 3 of 3)</a> </li> <li><a href="" mce_href="">It's All About Context</a> </li> <li><a href="" mce_href="">Saddle Up to the MiniBar</a> </li> <li><a href="" mce_href="">You'll Know It When You See It</a> </li> <li><a href="" mce_href="">Super Tooltips</a> </li> <li><a href="" mce_href="">Dialog Launchers</a> </li> <li><a href="" mce_href="">A Separate Piece</a> </li> <li><a href="" mce_href="">Rich Menus</a> </li> <li><a href="" mce_href="">The Future of Task Panes</a> </li> <li><a href="" mce_href="">Adding Groups to the Quick Access Toolbar</a> </li> <li><a href="" mce_href="">Lingering Around</a> </li> <li><a href="" mce_href="">Obscure Options, Meet Super Tooltips</a> </li> <li><a href="" mce_href="">About About</a> </li> <li><a href="" mce_href="">You Windows 3.1 Lovers!</a> </li> <li><a href="" mce_href="">Introducing the Command Well</a> </li> <li><a href="" mce_href="">Dipping Into the Well</a> </li> <li><a href="" mce_href="">Recently Used Documents</a> </li> <li><a href="" mce_href="">The Quick Customize Menu</a> </li> <li><a href="" mce_href="">A Brief History of the Status Bar</a> </li> <li><a href="" mce_href="">Status Bar Update</a> </li> <li><div><a href="" mce_href="">Zoom, Zoom, Zoom</a> </div></li> </ul> <p><b>The Size of the Ribbon, Screen Real-Estate, Ribbon Scaling, and Minimization<br> </b></p> <ul> <li><a href="" mce_href="">For Sale By Owner</a><span style="font-family: Times New Roman; font-size: 12pt;"> </span></li> <li><a href="" mce_href="">Scaling Up, Scaling Down</a> </li> <li><a href="" mce_href="">A Disappearing Act</a> </li> <li><a href="" mce_href="">The Biggest Loser</a> </li> <li><a href="" mce_href="">The Size Of Things</a> </li> <li><a href="" mce_href="">Taking the Minimized Ribbon to the Max</a> </li> <li><div><a href="" mce_href="">Nice for Mice: Menu Tabs</a> </div></li> </ul> <p><b>Migrating to Office 2007<br> </b></p> <ul> <li><a href="" mce_href="">Tools for the Transition</a><span style="font-family: Times New Roman; font-size: 12pt;"> </span></li> <li><a href="" mce_href="">Welcome to the New User Interface</a> </li> <li><div><a href="" mce_href="">You Mean I Don't Need To Retrain Everybody? (Real People Study, Part 2)</a> </div></li> </ul> <p><b>UI Themes and Visuals<br> </b></p> <ul> <li><a href="" mce_href="">Beauty and the Geek</a><span style="font-family: Times New Roman; font-size: 12pt;"> </span></li> <li><a href="" mce_href="">Black and Blue</a> </li> <li><a href="" mce_href="">March Madness</a> </li> <li><a href="" mce_href="">Silver Bullet</a> </li> <li><a href="" mce_href="">Office 2007 Silver on Windows XP Silver</a> </li> <li><a href="" mce_href="">Which Color When? (Part 1)</a> </li> <li><div><a href="" mce_href="">Which Color When? (Part 2)</a> </div></li> </ul> <p><b>Keyboard Control of the Ribbon<br> </b></p> <ul> <li><a href="" mce_href="">Stroking the Keys in Office 12</a><span style="font-family: Times New Roman; font-size: 12pt;"> </span></li> <li><a href="" mce_href="">The Keyboard At Your Command</a> </li> <li><a href="" mce_href="">Which Letter Is Better?</a> </li> <li><a href="" mce_href="">Odds, Ends, Shortcuts, and Accelerators</a> </li> <li><a href="" mce_href="">An Unintentional Week of Keyboard</a> </li> <li><a href="" mce_href="">Verklärte Macht: Keyboard Revisited</a> </li> <li><div><a href="" mce_href="">A Numbers Game</a> </div></li> </ul> <p><b>New Fonts for Office 2007<br> </b></p> <ul> <li><a href="" mce_href="">Making the Letters Better</a><span style="font-family: Times New Roman; font-size: 12pt;"> </span></li> <li><a href="" mce_href="">I Guess No One Cares About Fonts</a> </li> <li><div><a href="" mce_href="">New Fonts For Documents</a> </div></li> </ul> <p><b>Customizing Office 2007 (Add-ins, RibbonX) </b></p> <p><i>Note that most examples shown in the following posts need to be updated for use with the RTM version.<br> </i></p> <ul> <li><a href="" mce_href="">Let's Talk About Customization</a><span style="font-family: Times New Roman; font-size: 12pt;"> </span></li> <li><a href="" mce_href="">It All Adds Up</a> </li> <li><a href="" mce_href="">Because You Want To, Not Because You Have To</a> </li> <li><a href="" mce_href="">Hello World, For Real</a> </li> <li><a href="" mce_href="">Good Service for Add-ins</a> </li> <li><a href="" mce_href="">Hollywood Meets Office Add-ins</a> </li> <li><a href="" mce_href="">RibbonX Control Type Tour, Part 1</a> </li> <li><a href="" mce_href="">RibbonX Control Type Tour, Part 2</a> </li> <li><a href="" mce_href="">Finding a New Purpose</a> </li> <li><a href="" mce_href="">RibbonX Control Type Tour, Part 3</a> </li> <li><a href="" mce_href="">RibbonX Resources</a> </li> <li><a href="" mce_href="">Ribbon Extensibility: A VBA Sample</a> </li> <li><a href="" mce_href="">RibbonX Updates for B2TR</a> </li> <li><div><a href="" mce_href="">Final Schema for RibbonX-based Solutions</a> </div></li> </ul> <p><b>From First Sketches to the Final Design<br> </b></p> <ul> <li><a href="" mce_href="">Be Willing To Be Wrong</a><span style="font-family: Times New Roman; font-size: 12pt;"> </span></li> <li><a href="" mce_href="">Formatting: An Act In Three Plays</a> </li> <li><a href="" mce_href="">Thrown For a Loop</a> </li> <li><a href="" mce_href="">Beta 1-derful: The 'Top 30' List</a> </li> <li><a href="" mce_href="">Fast At Any Speed</a> </li> <li><a href="" mce_href="">The Feature Bob Invented</a> </li> <li><a href="" mce_href="">The Expert Mode Misadventure</a> </li> <li><a href="" mce_href="">The Long Road to Contextual Tabs</a> </li> <li><a href="" mce_href="">Picture This: A New Look For Office</a> </li> <li><a href="" mce_href="">There's No Place Like Home</a> </li> <li><a href="" mce_href="">Drawn Together</a> </li> <li><a href="" mce_href="">Choosing the Contextual Colors</a> </li> <li><a href="" mce_href="">The Printer is Being Electrocuted!</a> </li> <li><a href="" mce_href="">Get Your Office 2007 Beta 2 Today!</a> </li> <li><a href="" mce_href="">Are We There Yet?</a> </li> <li><a href="" mce_href="">The Spelling Check is Complete</a> </li> <li><a href="" mce_href="">Iterative Design Process Applied to Charting</a> </li> <li><a href="" mce_href="">Evolution of the PowerPoint Home Tab</a> </li> <li><a href="" mce_href="">Reality Check</a> </li> <li><a href="" mce_href="">Beta 2 Technical Refresh Available Tomorrow</a> </li> <li><a href="" mce_href="">Beta 2 Technical Refresh Available Now</a> </li> <li><div><a href="" mce_href="">Office 2007 Released to Manufacturing</a> </div></li> </ul> <p><b>Design Tenets <br> </b></p> <ul> <li><a href="" mce_href="">Most People Are Not Trained In Geology</a><span style="font-family: Times New Roman; font-size: 12pt;"> </span></li> <li><a href="" mce_href="">I Am Your Density</a> </li> <li><a href="" mce_href="">The End of Personalized Menus</a> </li> <li><a href="" mce_href="">The Myth of Ideal Organization</a> </li> <li><a href="" mce_href="">Flea Market of Functionality</a> </li> <li><a href="" mce_href="">Going Gray</a> </li> <li><a href="" mce_href="">Set In Our Ways?</a> </li> <li><a href="" mce_href="">Not So Set In Our Ways After All</a> </li> <li><a href="" mce_href="">Which menu items get icons?</a> </li> <li><a href="" mce_href="">Breathing New Life Into Old Features</a> </li> <li><div><a href="" mce_href="">Catching the Plane</a> </div></li> </ul> <p><b>Design Ponderings<br> </b></p> <ul> <li><a href="" mce_href="">The Importance Of Labels</a><span style="font-family: Times New Roman; font-size: 12pt;"> </span></li> <li><a href="" mce_href="">Help Is For Experts</a> </li> <li><a href="" mce_href="">The 50/50 Rule</a> </li> <li><a href="" mce_href="">Designing Against a Degrading Experience</a> </li> <li><div><a href="" mce_href="">Giving You Fitts</a> </div></li> </ul> <p><b>An Inside Look Into UI Design, Usability, Development and Testing at Microsoft<br> </b></p> <ul> <li><a href="" mce_href="">More Than Just the Two-Way Mirror</a><span style="font-family: Times New Roman; font-size: 12pt;"> </span></li> <li><a href="" mce_href="">Usability Redux</a> </li> <li><a href="" mce_href="">1000 Card Pick-Up</a> </li> <li><a href="" mce_href="">Paper Prototypes</a> </li> <li><a href="" mce_href="">The Myth of the Orange Dot</a> </li> <li><a href="" mce_href="">Quality Is Usability</a> </li> <li><a href="" mce_href="">Obsession to Detail</a> </li> <li><a href="" mce_href="">Measuring Results</a> </li> <li><a href="" mce_href="">Prototyping With PowerPoint</a> </li> <li><a href="" mce_href="">Usability Stockholm Syndrome</a> </li> <li><a href="" mce_href="">The Wall of Ribbons</a> </li> <li><a href="" mce_href="">Tell Us What You Think About Office 2007 Beta 2</a> </li> <li><a href="" mce_href="">Where do the Smiles go?</a> </li> <li><a href="" mce_href="">Usability: Art and Science</a> </li> <li><a href="" mce_href="">Real People Doing Real Work with Office 2007 (Part 1)</a> </li> <li><a href="" mce_href="">You Mean I Don't Need To Retrain Everybody? (Real People Study, Part 2)</a> </li> <li><a href="" mce_href="">Putting the Feedback to Work (Real People Study, Part 3)</a> </li> <li><div><a href="" mce_href="">Computers Can Do That? (Real People Study, Part 4)</a> </div></li> </ul> <p><b>Office Themes<br> </b></p> <ul> <li><a href="" mce_href="">Office Themes: Getting Documents To Sing One (Beautiful) Song</a><span style="font-family: Times New Roman; font-size: 12pt;"> </span></li> <li><a href="" mce_href="">The Elements of Office Style</a> </li> <li><div><a href="" mce_href="">Variations on a Theme by Office</a> </div></li> </ul> <p><b>New Features in Office 2007 Involving the New UI<br> </b></p> <ul> <li><a href="" mce_href="">Cover Pages: Cool Things In Office 12 (Part 1)</a><span style="font-family: Times New Roman; font-size: 12pt;"> </span></li> <li><a href="" mce_href="">For Trembling Hands (Office 12 Coolness, Part 2)</a> </li> <li><a href="" mce_href="">Know Your ABC's (Office 12 Coolness, Part 3)</a> </li> <li><a href="" mce_href="">Math On Demand (Office 12 Coolness, Part 4)</a> </li> <li><a href="" mce_href="">Symbolism (Office 12 Coolness, Part 5)</a> </li> <li><a href="" mce_href="">A Better Box Of Crayons</a> </li> <li><a href="" mce_href="">Drop Me A Line (Office 12 Coolness, Part 6)</a> </li> <li><a href="" mce_href="">It's Gonna Be A Hot Summer</a> </li> <li><a href="" mce_href="">Don't Forget To Check Your Filters</a> </li> <li><a href="" mce_href="">Double Feature</a> </li> <li><a href="" mce_href="">Every Which Way But Loose</a> </li> <li><a href="" mce_href="">No Longer Spellbound</a> </li> <li><a href="" mce_href="">The 96,000 New PowerPoint Slide Designs</a> </li> <li><div><a href="" mce_href="">Things of Beauty</a> </div></li> </ul> <p><b>Miscellaneous<br> </b></p> <ul> <li><a href="" mce_href="">Learning From the MVPs</a><span style="font-family: Times New Roman; font-size: 12pt;"> </span></li> <li><a href="" mce_href="">Decoding Office Build Numbers</a> </li> <li><a href="" mce_href="">Thanksgiving on a Wednesday</a> </li> <li><a href="" mce_href="">Introducing the 2007 Microsoft Office System</a> </li> <li><a href="" mce_href="">Icon Explosion</a> </li> <li><a href="" mce_href="">Try Office 2007 Without Installing It</a> </li> <li><div><a href="" mce_href="">New Product Icons for Office 2007</a> </div></li> </ul> <p><b>The Office 2007 UI team<br> </b></p> <ul> <li><a href="" mce_href="">Hello World</a><span style="font-family: Times New Roman; font-size: 12pt;"> </span></li> <li><a href="" mce_href="">It Takes a Village</a> </li> <li><a href="" mce_href="">It's the Reason for Being</a></li> </ul> <img src="" width="1" height="1">jensenh 2007 Released to Manufacturing<p>I'm proud to announce that last Friday, November 3 at approximately 2:30 PM, we signed off on build 4518.1014 as the 2007 Microsoft Office system and released it to manufacturing. </p> <p>This was followed by a ship party for everyone in Office including a few minutes of speeches, the traditional sounding of the RTM siren, and plenty of champagne (much of which I ended up wearing.) The rain even stopped for a few hours!</p><p>You can <a href="" mce_href="">read the official press release here</a>. </p> <p align="center"><a href="" mce_href=""><img src="" mce_src=""></a></p> <p>This release has been such a great pleasure to work on. It was more than three years ago when <a href="" mce_href="">Julie<!</p> <p>Three years later and we've shipped a product that I'm so proud of.</p> . </p> <p>To those of you who have been active in the beta program and here on the blog, and to everyone who sent feedback on the betas, <b>thank you</b>. Your feedback truly made the product better than it ever could have been without you. </p> <p>To the app teams and partner teams around Office and at Microsoft who helped make this release possible, <b>thank you</b>. This couldn't have happened without your ideas and support. </p> <p>And to those of you on the UEX team, whose ingenuity, consummate engineering, missed weekends, and tireless attention to detail made it all possible—<b>thank you!</b> We did it! </p> <p align="center"><img src=""></p> <p><b>How to get it? </b></p> <p>Office 2007 products will be available at retail early in 2007, so you'll be able to get your hands on them soon. Business customers will be able to get Office 2007 through the volume licensing program before the end of the year. </p> <p>If you're running the Beta 2 Technical Refresh, the good news is that you can keep using that build for quite some time: the client build expires on March 31, 2007, and the server products expire on May 15, 2007. </p> <p><b>What's Next?</b> </p> <p>Between now and retail availability, I'm going to do a series of posts documenting the creation of the Office 2007 user interface from the earliest prototypes all the way to the final product.</p><img src="" width="1" height="1">jensenh Schema for RibbonX-based Solutions<p>This morning, I posted the final customUI XML schema for creating Office 2007 RibbonX-based solutions. </p><p.) </p><p style="text-align: center;"><a href="" mce_href="">Download the RTM customUI Schema</a> </p><p>This updated version will also find its way onto MSDN in the coming weeks, but I wanted you guys to have access to it first.</p><img src="" width="1" height="1">jensenh Have I Gone?<p>I know in my last post I said that I'd be gone for a few days… and now those few days have stretched into a few weeks. </p><p. </p><p. </p><p>Now I'm finally back in Seattle for a while, so I will be writing regularly again. </p><p. </p><img src="" width="1" height="1">jensenh a Few Days Off<p>You may have noticed that I haven't posted for the last week.<br> </p><p>I wish I could say that I've been on a fabulous vacation, but in reality, I spent two weeks on the road, talking to people about the Office 2007 UI.</p><p>That trip, combined with an extremely busy time trying to help finish up Office and getting it ready to ship, means that I've had less time to write as of late. So, I decided to take a little break after the flurry of posts around the <a href="">release of Beta 2 Technical Refresh</a>. </p><p>I'll be back posting regularly in a few days. </p><p>In the meantime, if you're looking for some reading material, <a href="">check out the new Word team blog</a>. They've posted six articles over the last two weeks; hopefully they'll keep up that pace and write much more about one of Office's most-used programs. </p><p>Many of you have also written to me asking where you can get support for Office 2007 Beta 2 TR. The best place to ask a question or get help with a problem is in the <a href="">Office Discussion Groups on microsoft.com</a>. There's a group for just about every program and area in Office, so give it a try if you're having a problem. </p><p>Probably the most common problem I've seen reported is a known issue in B2TR: a dialog box on the launch of Word stating that "Building Blocks.dotx" is corrupt, followed by many of the Word galleries being empty. </p><p>Fortunately, it's easy to fix this. Close Word, navigate to the "%appdata%\Microsoft\Document Building Blocks" folder and delete "Building Blocks.dotx." You can find the solution to this and many other common problems <a href="">on Patrick Schmid's blog</a>.</p><img src="" width="1" height="1">jensenh Updates for B2TR<H3>Today's Guest Writer: Savraj Dhanjal</H3><EM>Savraj is a Program Manager on the Office User Experience team focused on user interface extensibility for Office developers.</EM> <P>As you may have discovered, we made a few tweaks to the UI developer story in Beta 2 Technical Refresh. </P> <P. </P> <P>We do not expect to change these IDs again for RTM, so (cross our fingers) this is the final list for Office 2007. We hope you find the new Excel-based lists easier to use and more flexible than the text files released with Beta 2. </P> <P style="TEXT-ALIGN: center"><A href=""><STRONG>Download Office 2007 B2TR Control ID List</STRONG></A></P> <P. </P> <P style="TEXT-ALIGN: center"><A href=""><STRONG>Download UpdateIdMso Tool</STRONG></A></P> <P>We also have a new customUI schema for B2TR. The schema has only a couple of notable changes. We renamed the <EM>fileMenu</EM> tag to <EM>officeMenu</EM> and also changed <EM>advanced</EM> to <EM>dialogBoxLauncher</EM>. We made these changes to ensure that the developer model matches the final feature names in the product. </P> <P style="TEXT-ALIGN: center"><A href=""><STRONG>Download B2TR customUI Schema</STRONG></A></P> <P>Along with the control ID list, another reference we've created is the Office 2007 Icons Gallery. Open this file and you'll get a new group on the Developer tab in Excel, filled with galleries of the icons you can reuse in your Office 2007 solutions. Just click an icon, and you'll learn its control ID. Use this ID with the imageMso attribute to copy our icons to your controls. </P> <P style="TEXT-ALIGN: center"><A href=""><STRONG>Download Office 2007 Icons Gallery</STRONG></A></P> <P>Perhaps the most interesting functionality we added in B2TR is the ability to execute built-in controls by control ID, and the ability to query control properties by control ID. </P> <P>For example, if you want to find out if the Save button is enabled, just call: </P> <P><SPAN style="FONT-FAMILY: Courier New">application.CommandBars.GetEnabledMso("FileSave") </SPAN></P> <P>and we'll return a boolean with the answer. And if you want to programmatically execute an obscure command that has no object model equivalent, just fire off: </P> <P><SPAN style="FONT-FAMILY: Courier New">application.CommandBars.ExecuteMso("MyObscureControlID") </SPAN></P> <P>The other functions are GetImageMso, GetLabelMso, GetPressedMso, GetScreentipMso, GetSupertipMso, and GetVisibleMso. </P> <P>The VBA object browser lists the function parameters and return values, which will also be detailed <A href="">on our MSDN site</A> when it is updated in the coming weeks. </P> <P>Thanks and let us know if you have questions. Happy solution-building!</P><img src="" width="1" height="1">jensenh 2 Technical Refresh Available Now<P>This morning, the Beta 2 Technical Refresh of the 2007 Microsoft Office system became available for download. </P> <P>You can <A href="">download it now from the Microsoft Download Center</A>. </P> <P><EM>(The download link above is the main download link. You also view the list of all available Beta 2 Technical Refresh updates for client and server by <A href="">clicking the Beta 2 Technical Refresh link on this page</A>.) </EM></P> <P>You must have Beta 2 installed in order to patch it to Beta 2 Technical Refresh, so don't uninstall Beta 2. </P> . </P> <P>Please also consider downloading the Send a Smile Feedback Tool to <A href="">tell us what you think about Office 2007</A>. If you already had it installed from Beta 2, you can continue to use it in B2TR. </P> <P>In my post yesterday, I <A href="">posted a list of the most substantive changes to the user interface in the new build</A>. Consider this by no means a full list of changes in B2TR—just those in the UI. </P> <P>I've also <A href="">posted a list of Ribbon Control IDs for use with B2TR</A> for RibbonX developers. These should also show up on MSDN sometime in the next few weeks. It's a 1.3 MB download (.zip file) if you need to grab it now.</P> <P><EM>Note: </EM>If you're having trouble installing the patch, try <A href="">following the instructions in this article</A>.</P> <P><EM>Note 2: </em>Patrick Schmid is <A href="">keeping a great log of solutions to issues people are encountering with B2TR</A>.</P><img src="" width="1" height="1">jensenh
http://blogs.msdn.com/jensenh/atom.xml
crawl-002
refinedweb
8,650
55.98
zc.customdoctests 1.0.1 ===================================================== doctest (and recently manuel) provide hooks for using custom doctest parsers. zc.customdoctests helps to leverage this to support other languages, such as JavaScript: js> function double (x) { ... return x*2; ... } js> double(2) 4 And with manuel, it facilitates doctests that mix multiple languages, such as Python, JavaScript, and sh. Contents Detailed documentation Custom doctest parsers zc.customdoctests provides a little bit of help with creating custom doctest parsers that work pretty muct like regular doctests, but that use an alternate means of evaluating examples. To use it, you call zc.customdoctests.DocTestParser and pass any of the following options: - ps1 The first-line prompt, which defaultd to '>>>'. This must be a regular expression that matches exactly 3 characters. (Note that you can’t override the second-line prompt.) - comment_prefix - The comment prefix regular expression, which defaults to ‘#’. - transform - A function used to transform example source, which defaults to a no-operation function. The js module provides support for using JavaScript in doctests using python-spidermonkey. It provides some examples of defining custom doctest parsers. Javascript and Python-Spidermonkey support To wire this up, you’d use something like: import doctest, zc.customdoctests.js test_suite = doctest.DocTestSuite( parser=zc.customdoctests.js.parser, setUp=zc.customdoctests.js.spidermonkeySetUp) Or, with manuel: test_suite = manuel.testing.TestSuite( manuel.doctest.Manuel(parser=zc.customdoctests.js.parser) + manuel.doctest.Manuel(parser=zc.customdoctests.js.eq_parser) + manuel.doctest.Manuel() + manuel.capture.Manuel(), 'spidermonkey.txt', setUp=zc.customdoctests.js.spidermonkeySetUp) Note that zc.customdoctests doesn’t require spidermonkey, so you need to install spidermonkey seperately if you want to use it. An advantage of using manuel is that you can use multiple parsers in the same document. In the example, above, 2 javascript example syntaxes (described below) as well as the standard doctest syntax are supported. This document is run with manuel to allow all 3 syntaxes. For the rest of this document, we’ll show examples of JavaScript doctests as well as helper APIs used to support JavaScript and to integrate JavaScript and Python. Javascript doctests use a “js>” prompt (as used in rhino and the spidermonkey interpreter): js> 2 + ... 'Hi world' // doctest: +ELLIPSIS u'2Hi... Assignments return values. This can generate annoying output in doctests: js> ob = {a: 1, b: 2} [object Object] If you’re using manuel, you can avoid this by using js!: js! x = 3 which suppresses expression values. load and print functions (similar to those found in rhino) are provided. For example, given a javascript file, double.js: function double (x) { return x*2; } We can load the file: js> load('double.js') js> double(10) 20 We can print values: js> print('Hi') Hi A python object provides access to the open function and the os module: js> python.os.path.exists('double.js') True js! f = python.open('double.js') js> print(f.read()) function double (x) { return x*2; } <BLANKLINE> js> f.close() If you’re using manuel, you can intermix Python and and JavaScript examples and there are a number of APIs to facilitate using Python and JavaScript together. There’s an add_js_global function to copy data from Python: >>> add_js_global('y', 1) js> y 1 There’s also a js object that provides attribute access to js globals: >>> js.x 3 >>> js.z = 4 js> z 4 You can also call this to run JS code without returning the resulting value: >>> js('a = x + y') js> a 4 Changelog 1.0.1 (2013-02-14) - Fixed ReStructuredText errors on the PyPI page. 1.0.0 (2013-02-13) - Added Python 3.3 support. - Cleanup setup.py, add tox.ini and manifest. 0.1.0 (2011-05-19) - Initial release - Author: Jim Fulton - License: ZPL 2.1 - Categories - Development Status :: 4 - Beta - :: Software Development - Package Index Owner: J1m, srichter, mgedmin - DOAP record: zc.customdoctests-1.0.1.xml
https://pypi.python.org/pypi/zc.customdoctests
CC-MAIN-2017-34
refinedweb
646
50.53
Thread Pooling Thread pooling is the process of creating a collection of threads during the initialization of a multithreaded application, and then reusing those threads for new tasks as and when required, instead of creating new threads. Then every process has some fixed number of threads depending on the amount of memory available, those threads are the need of the application but we have freedom to increase the number of threads. Every thread in the pool has a specific given task. The thread returns to the pool and waits for the next assignment when the given task is completed. Usually, the thread pool is required when we have number of threads are created to perform a number of tasks, in this organized in a queue. Typically, we have more tasks than threads. As soon as a thread completes its task, it will request the next task from the queue until all tasks have been completed. The thread can then terminate, or sleep until there are new tasks available. Creating thread pooling The .Net framework library included the "System.Threading.ThreadPool" class. it was so easy to use.You need not create the pool of threads, nor do you have to specify how many consuming threads you require in the pool. The ThreadPool class handles the creation of new threads and the distribution of the wares to consume amongst those threads. There are a number of ways to create the thread pool: Via the Task Parallel Library (from Framework 4.0). By calling ThreadPool.QueueUserWorkItem. Via asynchronous delegates. Via BackgroundWorker. Entering the Thread Pool via TPL The task parallel library provide the task class for enter the thread pool easy. The task class is the part of .Net Framework 4.0 .if you're familiar with the older constructs, consider the nongeneric Task class a replacement for ThreadPool.QueueUserWorkItem, and the generic Task<TResult> a replacement for asynchronous delegates. The newer constructs are faster, more convenient, and more flexible than the old. To use the nongeneric Task class, call Task.Factory.StartNew, passing in a delegate of the target method: using System.Threading.Tasks; using System.Threading; using System.Diagnostics; using System; class Akshay { static void Run() { Console.WriteLine("Welcome to the C# corner thread pool!"); } static void Main() // The Task class is in System.Threading.Tasks { Task.Factory.StartNew(Run); Console.Read(); } } Output : Task.Factory.StartNew returns a Task object, which you can then use to monitor the task-for instance, you can wait for it to complete by calling its Wait method. The generic Task<TResult> class is a subclass of the nongeneric Task. It lets you get a return value back from the task after it finishes executing. In the following example, we download a web page using Task<TResult>: class Akshay { static void Main() { // Start the task executing: Task<string> task = Task.Factory.StartNew<string> (() => DownloadString("")); // We can do other work here and it will execute in parallel: //RunSomeOtherMethod(); // When we need the task's return value, we query its Result property: // If it's still executing, the current thread will now block (wait) // until the task finishes: string result = task.Result; } static string DownloadString(string uri) { using (var wc = new System.Net.WebClient()) return wc.DownloadString(uri); Console.Read(); } } Entering the Thread Pool Without TPL using ThreadPool.QueueUserWorkItem You can't use the Task Parallel Library if you're targeting an earlier version of the .NET Framework (prior to 4.0). Instead, you must use one of the older constructs for entering the thread pool: ThreadPool.QueueUserWorkItem and asynchronous delegates. The ThreadPool.QueueUserWorkItem method allows us to launch the execution of a function on the system thread pool. Its declaration is as follows: ThreadPool.QueueUserWorkItem(new WaitCallback(Consume), ware); The first parameter specifies the function that we want to execute on the pool. Its signature must match the delegate WaitCallback. public delegate void WaitCallback (object state); Again, the simplicity of C# and the dotNet framework shine through. In just a few lines of code, I've recreated a multithreaded consumer-producer application. using System; using System.Threading; using System.Diagnostics; public class Akshay { public int id; public Akshay(int _id) { id = _id; } }class Class1{ public int QueueLength; public Class1() { QueueLength = 0; } public void Produce(Akshay ware) { ThreadPool.QueueUserWorkItem( new WaitCallback(Consume), ware); QueueLength++; } public void Consume(Object obj) { Console.WriteLine("Thread {0} consumes {1}", Thread.CurrentThread.GetHashCode(), //{0} ((Akshay)obj).id); //{1} Thread.Sleep(100); QueueLength--; } public static void Main(String[] args) { Class1 obj = new Class1(); for (int i = 0; i < 100; i++) { obj.Produce(new Akshay(i)); } Console.WriteLine("Thread {0}", Thread.CurrentThread.GetHashCode() ); //{0} while (obj.QueueLength != 0) { Thread.Sleep(1000); } Console.Read(); } } Ouput : Synchronization Objects The previous code contains some rather inefficient coding when the main thread cleans up. I repeatedly test the queue length every second until the queue length reaches zero. This may mean that the process will continue executing for up to a full second after the queues are finally drained. I can't have that. The following example uses a ManualResetEvent Event object that will signal the main thread to exit. using System; using System.Threading; using System.Diagnostics; public class Akshay { private bool WaitForComplete; private ManualResetEvent Event; public int QueueLength; public int id; public Akshay(int _id) { id = _id; } public void Wait() { if (QueueLength == 0) { return; } Event = new ManualResetEvent(false); WaitForComplete = true; Event.WaitOne(); } public void Consume(Object obj) { Console.WriteLine("Thread {0} consumes {1}", Thread.CurrentThread.GetHashCode(), //{0} ((Akshay)obj).id); //{1} Thread.Sleep(100); QueueLength--; if (WaitForComplete) { if (QueueLength == 0) { Event.Set(); } }; } } When the consuming thread finishes consuming a ware and detects that the WaitForComplete is true, it will trigger the Event when the queue length is zero. Instead of calling the while block when it wants to exit, the main thread calls the Wait instance method. This method sets the WaitForComplete flag and waits on the Event object. Why we need thread pooling? Thread pooling is essential in multithreaded applications for the following reasons. Thread pooling improves the response time of an application as threads are already available in the thread pool waiting for their next assignment and do not need to be created from scratch. Thread pooling saves the CLR from the overhead of creating an entirely new thread for every short-lived task and reclaiming its resources once it dies. Thread pooling optimizes the thread time slices according to the current process running in the system. Thread pooling enables us to start several tasks without having to set the properties for each thread. Thread pooling enables us to pass state information as an object to the procedure arguments of the task that is being executed. Thread pooling can be employed to fix the maximum number of threads for processing a particular request. Thread Pooling in C# Deadlock in C# Threading
http://www.c-sharpcorner.com/UploadFile/1d42da/threading-pooling-in-C-Sharp/
crawl-003
refinedweb
1,137
58.89
/* * Collector.java December.Iterator; import java.util.LinkedHashMap; /** * The <code>Collector</code> object is used to store variables for * a deserialized object. Each variable contains the label and value * for a field or method. The <code>Composite</code> object uses * this to store deserialized values before committing them to the * objects methods and fields. * * @author Niall Gallagher * @see org.simpleframework.xml.core.Composite class Collector implements Criteria { /** * This is the registry containing all the variables collected. */ private final Registry registry; * This is the registry that contains variables mapped to paths. private final Registry alias; * Constructor for the <code>Collector</code> object. This is * used to store variables for an objects fields and methods. * Each variable is stored using the name of the label. public Collector() { this.registry = new Registry(); this.alias = new Registry(); } * This is used to get the <code>Variable</code> that represents * a deserialized object. The variable contains all the meta * data for the field or method and the value that is to be set * on the method or field. * * @param key this is the key of the variable to be acquired * @return this returns the keyed variable if it exists public Variable get(Object key) { return registry.get(key); } * @param label this is the label to resolve the variable with * @return this returns the variable associated with the label public Variable get(Label label) throws Exception { if(label != null) { Object key = label.getKey(); return registry.get(key); } return null; * This is used to resolve the <code>Variable</code> by using * the union names of a label. This will also acquire variables * based on the actual name of the variable. * @param path this is the path of the variable to be acquired * @return this returns the variable mapped to the path public Variable resolve(String path) { return alias.get(path); * This is used to remove the <code>Variable</code> from this * criteria object. When removed, the variable will no longer be * used to set the method or field when the <code>commit</code> * method is invoked. * @param key this is the key associated with the variable public Variable remove(Object key) throws Exception{ return registry.remove(key); * This is used to acquire an iterator over the named variables. * Providing an <code>Iterator</code> allows the criteria to be * used in a for each loop. This is primarily for convenience. * @return this returns an iterator of all the variable names public Iterator<Object> iterator() { return registry.iterator(); * This is used to create a <code>Variable</code> and set it for * this criteria. The variable can be retrieved at a later stage * using the name of the label. This allows for repeat reads as * the variable can be used to acquire the labels converter. * @param label this is the label used to create the variable * @param value this is the value of the object to be read public void set(Label label, Object value) throws Exception { Variable variable = new Variable(label, value); String[] paths = label.getPaths(); for(String path : paths) { alias.put(path, variable); } registry.put(key, variable); * This is used to set the values for the methods and fields of * the specified object. Invoking this performs the population * of an object being deserialized. It ensures that each value * is set after the XML element has been fully read. * @param source this is the object that is to be populated public void commit(Object source) throws Exception { Collection<Variable> set = registry.values(); for(Variable entry : set) { Contact contact = entry.getContact(); Object value = entry.getValue(); contact.set(source, value); } * The <code>Registry</code> object is used to store variables * for the collector. All variables are stored under its name so * that they can be later retrieved and used to populate the * object when deserialization of all variables has finished. * @author Niall Gallagher private static class Registry extends LinkedHashMap<Object, Variable> { /** * This is used to iterate over the names of the variables * in the registry. This is primarily used for convenience * so that the variables can be acquired in a for each loop. * * @return an iterator containing the names of the variables */ public Iterator<Object> iterator() { return keySet().iterator(); }
http://simple.sourceforge.net/download/stream/report/cobertura/org.simpleframework.xml.core.Collector.html
CC-MAIN-2017-13
refinedweb
687
57.47
Investors in Johnson Controls International plc (Symbol: JCI) saw new options begin trading today, for the December 6th expiration. At Stock Options Channel, our YieldBoost formula has looked up and down the JCI options chain for the new December 6th contracts and identified one put and one call contract of particular interest. The put contract at the $42.00 strike price has a current bid of 62 cents. If an investor was to sell-to-open that put contract, they are committing to purchase the stock at $42.00, but will also collect the premium, putting the cost basis of the shares at $41.38 (before broker commissions). To an investor already interested in purchasing shares of JCI, that could represent an attractive alternative to paying $42.26/share today. Because the 1.48% return on the cash commitment, or 12.52% annualized — at Stock Options Channel we call this the YieldBoost. Below is a chart showing the trailing twelve month trading history for Johnson Controls International plc, and highlighting in green where the $42.00 strike is located relative to that history: Turning to the calls side of the option chain, the call contract at the $43.00 strike price has a current bid of 53 cents. If an investor was to purchase shares of JCI stock at the current price level of $42.26/share, and then sell-to-open that call contract as a "covered call," they are committing to sell the stock at $43.00. Considering the call seller will also collect the premium, that would drive a total return (excluding dividends, if any) of 3.01% if the stock gets called away at the December 6th expiration (before broker commissions). Of course, a lot of upside could potentially be left on the table if JCI shares really soar, which is why looking at the trailing twelve month trading history for Johnson Controls International plc, as well as studying the business fundamentals becomes important. Below is a chart showing JCI's trailing twelve month trading history, with the $43.00 strike highlighted in red: Considering the fact that the .25% boost of extra return to the investor, or 10.64% $42.26) to be.
https://www.nasdaq.com/articles/jci-december-6th-options-begin-trading-2019-10-24
CC-MAIN-2022-40
refinedweb
368
64.61
Abstract: Whenever we have thread pools in our system, we need to make their size configurable. In this follow-up, we continue looking at some issues with the common fork/join pool that is used in Java 8. A quick follow-up to the previous newsletter on Runtime.getRuntime().availableProcessors(). The parallelism of the common pool is typically calculated as availableProcessors() - 1, unless we specify it differently as a system property. However, if you run Java on a single-core machine, it sets the common pool parallelism to 1, whereas the more correct value would be zero. You might wonder whether anybody on this planet still has single-core machines? Actually, it has become vogue to give developers shared virtual development environments, where they are allocated a single core but oodles of memory. With virtualized boxes, it is quite likely that you will have just one core. The problem comes in when code such as the parallelSort algorithm tries to make a decision whether to run in parallel or to default to the old sort mechanism. In the Arrays.parallelSort() method, they look at the value of ForkJoinPool.getCommonPoolParallelism(). Since the value for a single-core and dual-core system is the same (1), it calls the default Arrays.sort() method. I thus stand by my assertion that the 30% performance boost claim on a dual-core machine is at best thumb sucked. However, for streams it works a little bit better. Since for a dual-core system, we have a Fork/Join pool of size 1, we actually will have two threads working: 1. The thread in the pool and 2. the submitting thread. I made the typical mistake where you are asked to count all the people in the room and you forget to include yourself in the total :-) So parallel() does work - sort of. It has the correct number of workers based on the value that is returned by availableProcessors(). Except of course if you have a single-core machine, in which case parallel() will use two threads instead of just the one that is mapped to a physical core. Pierre-yves Saumont kindly sent me a piece of code that proves that parallel() defaults to the availableProcessors() value (with some slight modifications by me - any mistakes are my fault :-)) import java.util.*; import java.util.concurrent.*; import java.util.stream.*; public class CountThreads { private static Map<String, Integer> map = new ConcurrentHashMap<>(); public static void main(String... args) { System.out.println(IntStream.range(1, 1_000_000). parallel().filter(CountThreads::isPrime).count()); map.forEach((k, v) -> System.out.println(k + ": " + v)); } public static boolean isPrime(int n) { map.compute(Thread.currentThread().getName(), (k, v) -> v == null ? 1 : v + 1); if (n % 2 == 0) return false; for (int i = 3; i * i <= n; i += 2) { if (n % i == 0) { return false; } } return true; } } On a dual-core and single-core systems, you'd see the following output: 78498 ForkJoinPool.commonPool-worker-1: 499999 main: 500000 On my 1-4-2 machine, with 8 hyperthreads, we see that 8 threads were part of the work: 78498 ForkJoinPool.commonPool-worker-7: 125000 ForkJoinPool.commonPool-worker-1: 125000 ForkJoinPool.commonPool-worker-2: 125000 main: 125000 ForkJoinPool.commonPool-worker-5: 125000 ForkJoinPool.commonPool-worker-6: 156249 ForkJoinPool.commonPool-worker-3: 125000 ForkJoinPool.commonPool-worker-4: 93750 If you measure the performance of something like parallel sort, which requires lots of memory access, you might find that your hyperthreads will give you close to linear speedup. This is because the biggest bottleneck is the speed at which the cache lines can be filled. Hyperthreading allows some of that to happen in parallel. Finding prime numbers is less dependent on memory and thus you would not see as much of a speedup beyond your physical cores. In addition, the sorting algorithm for parallelSort() is different. For some of the data sets that I tried, a single-threaded Arrays.sort() was much faster than an 8-threaded Arrays.parallelSort(), especially if the data set was already sorted. Lastly, I tried writing the CountThreads code with the Fork/Join framework. It came out looking like this: import java.util.concurrent.*; public class CountThreadsForkJoin { public static void main(String... args) { System.out.println(ForkJoinPool.commonPool().invoke( new PrimeSearcher(1, 1_000_000))); } private static class PrimeSearcher extends RecursiveTask<Integer> { private static final int THRESHOLD = 10000; private final int from; private final int to; public PrimeSearcher(int from, int to) { this.from = from; this.to = to; } protected Integer compute() { if (to - from < THRESHOLD) { return serialCount(); } int from0 = from; int to0 = from + (to - from) / 2; int from1 = to0 + 1; int to1 = to; PrimeSearcher ps0 = new PrimeSearcher(from0, to0); PrimeSearcher ps1 = new PrimeSearcher(from1, to1); ps0.fork(); return ps1.invoke() + ps0.join(); } private Integer serialCount() { int count = 0; for (int i = from; i < to; i++) { if (CountThreads.isPrime(i)) count++; } return count; } } } I would like to meet the person who thinks that Java 8 streams are not an improvement over the pain of manually coding Fork/Join: import java.util.stream.*; public class CountThreadsStream { public static void main(String... args) { System.out.println(IntStream.range(1, 1_000_000). parallel().filter(CountThreads::isPrime).count()); } } But time will tell how many use cases we can find for parallel() in the real world....
https://www.javaspecialists.eu/archive/Issue220b-Runtime.getRuntime.availableProcessors-Follow-Up.html
CC-MAIN-2020-45
refinedweb
875
56.55
Angelo zerr <angelo.zerr@gmail.com> wrote on 2011-08-11 21:22:08: > From: Angelo zerr <angelo.zerr@gmail.com> > To: dev@odfdom.odftoolkit.org > Cc: dev@simple.odftoolkit.org, dev@odftoolkit.odftoolkit.org, > general@incubator.apache.org > Date: 2011-08-11 21:22 > Subject: Re: [odfdom-dev] Status of the Simple Java API for ODF and > ODFDOM - 08/10/2011 > > Hi Biao, > > Thank a lot to mention XDocReport in your mail. I would like give > some information about it. You can find XDocReport at http:// > code.google.com/p/xdocreport/. By default XDocReport generate report > source 2 source (odt 2 odt, docx 2 docx...). At this step ODFDOM IS > NOT Used. ODFDOM is used for convert ODT 2 XHTM or PDF that we have called > ODFDOMConverter > > THe ODFDOMConverter is Java implementation to convert ODT 2 PDF > (with itext) and XHTML. This project is used by XDocReport (if you > wish convert your generated report 2 XHTML, PDF) BUT you can use > ODFDOMConverter without XDocReport (package is org.odftoolkit.odfdom.converter > ) > > My idea was to give to ODFDOM Team the sources of the > ODFDOMConverter project. But since you wish gives the project 2 > Apache, I'm not sure that ODFDOM Converter will interest Apacahe. > Why? Because we are using iText for PDF and not FOP. I believe that > Apache Fondation don't want use iText. > > We have the same proble with our DOCX converter http:// > code.google.com/p/xdocreport/wiki/XWPFConverter > > If you think iText is not a problem for Apache Fondation, we will > happy to give your the ODFDOMConverter project. Thanks for your contribution intention. But we found iText uses the AGPL license: So it would be difficult to use that in an Apache 2.0 licensed project. Do you have plan to supply a version using PDFBox pr FOP? Both of them will be OK for Apache 2.0 license. And as far as I know, PDFBox may be easier. Its API is similar with iText. Whatever, thank you for your eager contribution intention! > > Regards Angelo > > 2011/8/10 Biao Han <hanbiao@cn.ibm.com> > (We should send this to project mailing list, but we don't have one > yet. so sorry for interrupt those guys in incubator general mailing list) > > ODF Toolkit move to Apache > 1. SVN account has been created and is now available for use. We > will discuss and start the code move after mail lists are ready; > 2. The first board meeting is scheduled for Wed, 17 August 2011, 10 > am Pacific. We have submitted a quarterly board report to here. > 3. As we have been an Apache incubator project, so we will discuss > and release ODF Toolkit in the new community. The original release > plan have to be cancelled. > > Simple ODF > 1. Reviewed and pushed a bug about TextProperties (#bug 357). > 2. Reviewed and pushed three unit test coverage enhancement patches > (#bug 241) . > 3. The downloads of Simple ODF 0.6.5 has been to 204. This number > equals with Simple ODF 0.4. But version 0.4 uses more 6 months get > it, while version 0.6.5 uses only 40 days. > > ODFDOM > 1. Working on data signature. There are two issues caused by > OpenOffice block the process. > (1) OpenOffice.org generate a Namespace unaware signature document. > ODFDOM loads it fails. > (2) OpenOffice.org creates multiple X509Certificates instead of the > correct certification chain under ds:KeyInfo. > see also: > (ds namespace in > LibreOffice) > (ds namespace in OOo) > (multiple > X509Certificate in OOo) > > We have to supply two modes to fix it. One follows ODF > specification, the other follows Open Office. The question is which > is the default? > 2. A new user: XDocReport uses ODFDOM to load and manipulate ODF > document. It's Java API to merge XML document created with MS Office > (docx) or OpenOffice (odt), LibreOffice (odt) with a Java model to > generate report and convert it if you need to another format (PDF, XHTML...). >
http://mail-archives.eu.apache.org/mod_mbox/incubator-general/201108.mbox/%3COF9C4B89FA.F2EC03D3-ON482578EA.002F31EC-482578EA.00303427@cn.ibm.com%3E
CC-MAIN-2020-34
refinedweb
653
68.57
Defining Views¶ A view callable functions, then wire them into Pyramid using some view configuration. Declaring Dependencies in Our setup.py File¶ The view code in our application will depend on a package which is not a dependency of the original "tutorial" application. The original "tutorial" application was generated by the cookiecutter; it doesn't know about our custom application requirements. We need to add a dependency on the docutils package to our tutorial package's setup.py file by assigning this dependency to the requires parameter in the setup() function. Open setup.py and edit it to look like the following: Only the highlighted line needs to be added. Running pip install -e .¶ Since a new software dependency was added, you will need to run pip install -e . again inside the root of the tutorial package to obtain and register the newly added dependency distribution. Make sure your current working directory is the root of the project (the directory in which setup.py lives) and execute the following command. On UNIX: $ cd tutorial $ $VENV/bin/pip install -e . On Windows: c:\> cd tutorial c:\tutorial> %VENV%\Scripts\pip install -e . Success executing this command will end with a line to the console something like: Successfully installed docutils-0.13.1 tutorial Adding view functions in views.py¶ It's time for a major change. Open tutorial/views.py and edit it to look like the following: We added some imports and created a regular expression to find "WikiWords". We got rid of the my_view view function and its decorator that was added when we originally rendered the zodb cookiecutter. It was only an example and isn't relevant to our application. Then we added four view callable functions to our views.py module: view_wiki()- Displays the wiki itself. It will answer on the root URL. view_page()- Displays an individual page. add_page()- Allows the user to add a page. edit_page()- Allows the user to edit a page. We'll describe each one briefly in the following sections.. The view_wiki view function¶ Following is the code for the view_wiki view function and its decorator: Note In our code, we use an import that is relative to our package named tutorial, meaning we can omit the name of the package in the import and context statements. In our narrative, however, we refer to a class and thus we use the absolute form, meaning that the name of the package is included. view_wiki() is the default view that gets called when a request is made to the root URL of our wiki. It always redirects to an URL which represents the path to our "FrontPage". We provide it with a @view_config decorator which names the class tutorial.models.Wiki as its context. This means that when a Wiki resource is the context and no view name exists in the request, then). It uses the pyramid.request.Request.route_url() API to construct an URL to the FrontPage page resource (i.e.,), and uses it as the "location" of the HTTPFound response, forming an HTTP redirect. The view_page view function¶ Here is the code for the view_page view function and its decorator: The view_page function is configured to respond as the default view of a Page resource. We view function¶ Here is the code for the add_page view function and its decorator: The add_page function is configured to respond when the context resource is a Wiki and the view name is add_page. We uses grab view function¶ Here is the code for the edit_page view function and its decorator: The edit_page function is configured to respond when the context is a Page resource and the view name is edit_page. We. Adding templates¶. The view.pt template¶ Rename tutorial/templates/mytemplate.pt to tutorial/templates/view.pt and edit the emphasized lines to look like the following: This template is used by view_page() for displaying a single wiki page. It includes: - A divelement that is replaced with the contentvalue provided by the view (lines 37-39). contentcontains HTML, so the structurekeyword is used to prevent escaping it (i.e., changing ">" to ">", etc.) - A link that points at the "edit" URL which invokes the edit_pageview for the page being viewed (lines 41-43). The edit.pt template¶ Copy tutorial/templates/view.pt to tutorial/templates/edit.pt and edit the emphasized lines to look like the following: 46). - A submit button that has the name form.submitted(line 49). The form POSTs back to the save_url argument supplied by the view (line 44). The view will use the body and form.submitted values.. - invokes the view_pageview of the front page resource. This is because it's the default view (a view without a name) for Page resources. - invokes the edit view for the FrontPagePage resource. - invokes the add view for a Page. - To generate an error, visit which will generate an IndexError: tuple index out of rangeerror. You'll see an interactive traceback facility provided by pyramid_debugtoolbar.
http://docs.pylonsproject.org/projects/pyramid/en/master/tutorials/wiki/definingviews.html
CC-MAIN-2017-09
refinedweb
830
58.08
Red Hat Bugzilla – Bug 59851 rpmInstallSourcePackage() API seg fault Last modified: 2008-05-01 11:38:01 EDT From Bugzilla Helper: User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0) Description of problem: I have created a small C++ exe using the RPM API rpmInstallSourcePackage(). However, when running the program it seg faults on rpmInstallSourcePackage(). It is seg. faulting on the function rpmInstallSourcePackage() in Fileno() from /usr/lib/librpmio. The debugger shows me that before it seg faults, the program will trace through the lib's rpmInstallSourcePackage(), queryArgCallback (), rpmInstallSourcePackage(), rpmreadPackageHeader(),readPackageHeaders() and finally choke on some Fileno(). my usage of the function is as follows ... rpmInstallSourcePackage(rootDir, fd, specFilePtr,0,0,0) where rootDir is a const char * = "to/some/path" where fd = Fopen(argv[1]) where specFilePtr is a const char **="to/some/path" and I substitute null for the rest. My program is very simple and only calls two functions from the API. The Fopen and rpmInstallSourcePackage(). Version-Release number of selected component (if applicable): How reproducible: Always Steps to Reproduce: 1.run the program e.g.- # ./instllpkg /development/RPMS/i386/somepkg.rpm 2. 3. Actual Results: Segmentation fault in the function call in Fileno() from /usr/lib/librpmio 4.0.3.so Expected Results: The program should execute without segmentation faults, install package as specified and write output that it has installed package. Additional info: I'm not sure that this is a bug of rpm. Given my lack of knowledge to the rpm API I could be giving it bad params or giving it null when it is expecting a param. If your program is small, can you attach here? I can probably tell you what's up even though I'm not a C++ programmer. Jeff, I made some progress with my bug. I ended up using rpmInstall() vs. rpmInstallSource(). However, I now get another seg fault that says Error: no db path set. The source is as follows. #include <rpm/rpmlib.h> void main() { const char * rootdir = "/development" char * str[]={"/development/RPMS/i386/IM-0.1-1.i386.rpm"}; str[1]='/0'; const char ** temp = const_cast<const char**>(str); rpmInstall(rootdir,temp,RPMTRANS_FLAG_NONE,INSTALL_HASH,RPMPR0B_FILTER_NONE,0); } All programs that link against rpmlib need to do if (rpmReadConfigFiles(rcfile, NULL)) exit(EXIT_FAILURE); early on. ok, something is weird with rpm and its files. My rpmrc file resides in /usr/lib. It's visible to ls and when I do rpm --showrc it shows the contents of that file. However, when I use the command # more /usr/lib/rpmrc, it says no such file or dir. This error also happens when I supply this file to rpmReadConfigFiles("/usr/lib/rpmrc", NULL). Another weird thing is that I went to view /usr/include/rpmlib.h with the more command and it says that that file dn exist, but it does! I must be doing something wrong???? There may be a /usr/lib/rpmrc symlink, but the file(s) you want/need are /usr/lib/rpm/rpmrc /usr/lib/rpm/macros and (possibly) /usr/lib/rpm/<arch>-linux/macros This is what is read by rpmReadConfigFiles(NULL, NULL); (Yes, NULL will use defaults). If you need more help, please reopen this bug. Meanwhile I'm gonna close.
https://bugzilla.redhat.com/show_bug.cgi?id=59851
CC-MAIN-2017-09
refinedweb
543
50.53
README scikit.jsscikit.js JavaScript package for predictive data analysis and machine learning. Aims to be a Typescript port of the scikit-learn python library. This library is for users who wish to train or deploy their models to JS environments (browser, mobile) but with a familiar API. Generic math operations are powered by Tensorflow.js core layer for faster calculation. Documentation site: InstallationInstallation Backend UsersBackend Users For Node.js users who wish to bind to the Tensorflow C++ library, simply yarn add scikitjs-node Simple ExampleSimple Example import { LinearRegression } from 'scikitjs-node' const lr = LinearRegression({ fitIntercept: false }) const X = [[1], [2]] // 2D Matrix with a single column vector const y = [10, 20] await lr.fit(X, y) lr.predict([[3, 4]]) // roughly [30, 40] console.log(lr.coef) console.log(lr.intercept) Coming from python?Coming from python? This library aims to be a drop-in replacement for scikit-learn but for JS environments. There are some differences in deploy environment and underlying libraries that make for a slightly different experience. Here are the 3 main differences. 1. Class constructors take in objects. Every other function takes in positional arguments.1. Class constructors take in objects. Every other function takes in positional arguments. While I would have liked to make every function identical to the python equivalent, it wasn't possible. In python, one has named arguments, meaning that all of these are valid function calls. pythonpython def myAdd(a=0, b=100): return a+b print(myAdd()) # 100 print(myAdd(a=10)) # 110 print(myAdd(b=10)) # 10 print(myAdd(b=20, a=20)) # 40 (order doesn't matter) print(myAdd(50,50)) # 100 Javascript doesn't have named parameters, so one must choose between positional arguments, or passing in a single object with all the parameters. For many classes in scikit-learn, the constructors take in a ton of arguments with sane defaults, and the user usually only specifies which one they'd like to change. This rules out the positional approach. After a class is created most function calls really only take in 1 or 2 arguments (think fit, predict, etc). In that case, I'd rather simply pass them positionally. So to recap. pythonpython from sklearn.linear_model import LinearRegression X, y = [[1],[2]], [10, 20] lr = LinearRegression(fit_intercept = False) lr.fit(X, y) Turns into javascriptjavascript import { LinearRegression } from 'scikitjs-node' let X = [[1], [2]] let y = [10, 20] let lr = new LinearRegression({ fitIntercept: false }) await lr.fit(X, y) You'll also notice in the code above, these are actual classes in JS, so you'll need to new them. 2. underscore_case turns into camelCase2. underscore_case turns into camelCase Not a huge change, but every function call and variable name that is underscore_case in python will simply be camelCase in JS. In cases where there is an underscore but no word after, it is removed. pythonpython from sklearn.linear_model import LinearRegression X, y = [[1],[2]], [10, 20] lr = LinearRegression(fit_intercept = False) lr.fit(X, y) print(lr.coef_) Turns into javascriptjavascript import { LinearRegression } from 'scikitjs-node' let X = [[1], [2]] let y = [10, 20] let lr = new LinearRegression({ fitIntercept: false }) await lr.fit(X, y) console.log(lr.coef) In the code sample above, we see that fit_intercept turns into fitIntercept (and it's an object). And coef_ turns into coef. 3. Always await calls to .fit or .fitPredict3. Always await calls to .fit or .fitPredict It's common practice in Javascript to not tie up the main thread. Many libraries, including tensorflow.js only give an async "fit" function. So if we build on top of them our fit functions will be asynchronous. But what happens if we make our own estimator that has a synchronous fit function? Should we burden the user with finding out if their fit function is async or not, and then "awaiting" the proper one? I think not. I think we should simply await all calls to fit. If you await a synchronous function, it resolves immediately and you are on your merry way. So I literally await all calls to .fit and you should too. pythonpython from sklearn.linear_model import LogisticRegression X, y = [[1],[-1]], [1, 0] lr = LogisticRegression(fit_intercept = False) lr.fit(X, y) print(lr.coef_) Turns into javascriptjavascript import { LogisticRegression } from 'scikitjs-node' let X = [[1], [-1]] let y = [1, 0] let lr = new LogisticRegression({ fitIntercept: false }) await lr.fit(X, y) console.log(lr.coef)
https://www.skypack.dev/view/scikitjs-node
CC-MAIN-2022-21
refinedweb
742
60.01
The cs_project1 project skeleton was set up with the different commands in different classes, keeping related things together. On the other hand they had high level structure in common. Similar names were consciously used for methods: The corresponding names made it somewhat easier to follow the part of the Game constructor with the additions to the helpDetails Dictionary. Also there is repetitive logic in the crucial proccessCommand method. In a game with more possible commands, the code would only get more repetitious! You would like to think of having a loop to replace the repetitious code. A major use of a C# interface will allow this all to work in neat loops. For the first time we define our own interface, and use that interface as a type in a declaration. While we are at this we can refactor our code further: classes that give a response to a command all obviously have their Execute and Help methods. They also have a command word to call them. We can further encapsulate all data for the response by having the classes themselves be able to announce the command that calls them. We add a string property CommandWord to each of them. We will add an extra convenience feature of C# here. Thus far we have used private instance variables and public getter methods. We can use a public instance variable declaration with a similar effect as in: public string CommandName {get; private set;} The extra syntax in braces says that users in a another class may freely get (read) the variable, but setting the variable is still private: it may only be done inside the class. This is more concise than using a getter method: No getter needs to be declared; referencing the data is shorter too, since it is a property, no method parentheses are needed. Note the unusual syntax: the declaration does not end with a semicolon. The only semicolons are inside the braces. You will not be required to code with this notation, but it surely is neater than using a getter method! Now we can define our own interface taking all of these common features together. Since each is a response to a command, we will call our interface Response: namespace IntroCS { /// Object that responds to a command public interface Response { /// Execute cmd. /// Return true if the game is over; false otherwise bool Execute(Command cmd); /// Return a Help string for the command string Help(); string CommandName { get; } } } Things to note: interfaceinstead of class. We are going to need a collection if we want to simplify the code with loops. We could use code like the following, assuming we already declared the objects helper, goer, and quitter: Response[] resp = {helper, goer, quitter}; See how we use Response as a declaration type! Each of the objects in the declaration list is in fact a Response. Now that we can process with this collection and foreach loops, we do not need the object names we gave at all: We can just put new objects in the initialization sequence! Now that we can think of these different objects as being of the same type, we can see the processCommand logic, with its repetitive if statement syntax is just trying to match a command word with the proper Response, so a Dictionary is what makes sense! In fact all the logic for combining the various Responses is now moved into CommandMapper, and the the CommandMapper constructor creates the Dictionary used to look up the Response that goes with each command word. Here is the whole code for ResponseMapper, taking advantage of the Dictionary in other methods, too. using System; using System.Collections.Generic; namespace IntroCS { /// Map commands names to commands. public class CommandMapper { public string AllCommands { get; private set; } private Dictionary<string, Response> responses; //responses to commands /// Initialize the command response mapping /// game The game being played. public CommandMapper(Game game) { responses = new Dictionary<string, Response>(); Response[] resp = { new Quitter(), new Goer(game), new Helper(responses, this) // add new Responses here! }; AllCommands = ""; foreach (Response r in resp) { responses[r.CommandName] = r; AllCommands += r.CommandName + " "; } } /// Check whether aString is a valid command word. /// Return true if it is, false if it isn't. public bool isCommand(string aString) { return responses.ContainsKey(aString); } /// Return the command associated with a command word. /// cmdWord The command word. /// Return the Response for the command. public Response getResponse(string cmdWord) { return responses[cmdWord]; } } } There is even more to recommend this setup: The old setup had references in multiple places to various details about the collection of Responses. That made it harder to follow and definitely harder to update if you want to add a new command. Now after writing the new class to respond to a new command, the only thing you need to do is add a new instance of that class to the array initializer in the CommandMapper constructor! Note Interfaces never say anything about constructors. Classes satisfying an interface can have totally different constructors. In the code above, Quitter has a very simple constructor. (A Quitter has no individualized data, and only has an instance because an interface can only work with an instance, not with a static class.) On the other hand the Goer and Helper objects need to reference more data to work properly, so they have parameters. The revised Xamarin Studio project is csproject_stub (no 1 this time). See how the Game class is simplified, too. Talking about adding commands - these classes could be the basis of a game project for a small group. Have any ideas? See Group Project. Note that there is a data file in the project directory. Make sure your project, like this stub, sets the Output Path to the project folder. There are further examples of defining and using Interfaces in the starting code for the exercises at the end of the next section. This section is motivated by the revisions to the project, not specifically about Interfaces, though good use of them helps. There are three important ideas in organizing your code into classes and methods: Cohesion of code is how focused a portion of code is on a unified purpose. This applies to both individual methods and to a class. The higher the cohesion, the easier it is for you to understand a method or a class. Also a cohesive method is easy to reuse in combination with other cohesive methods. A method that does several things is not useful to you if you only want to do one of the things later. Separation of concerns allows most things related to a class to take place in the class where they are easy to track, separated from other classes. Data most used by one class should probably reside in that class. Cohesion is related to separation of concerns: The data and methods most used by one class should probably reside in that class, so you do not need to go looking elsewhere for important parts. Also, if you need to change something, where concerns are separated into cohesive classes, with the data and logic in one place, it is easier to see what to change, and the changes are likely to be able to be kept internal to the class, affecting only its internal implementation, not its public interface. Some methods are totally related to the connection between classes, and there may not be a clear candidate for a class to maximize the separation of concerns. One thing to look at is the number of references to different classes. It is likely that the most referred to class is the one where the method should reside. Coupling is the connections between classes. If there were no connections to a class, no public interface, it would be useless except all by itself. The must be some coupling between classes, where one class uses another, but with increased cohesion and strong separation of concerns you are likely to be able to have looser coupling. Limiting coupling makes it easier to follow your code. There is less jumping around. More important, it is easier to modify the code. There will be less interfacing between classes, so if you need to change the public interface of a class, there are fewer places in other classes that need to be changed to keep in sync. Aim for strong cohesion, clear separation of concerns, and loose coupling. Together they make your code clearer, easier to modify, and easier to debug. On a much smaller scale than the project, this exercise offers you experience writing classes implementing and using an interface. Copy project stub igame_stub to your own project, and modify it as discussed below. Look at the IGame interface in i_game.cs. Then look at addition_game.cs, that implements the interface. See how a new AdditionGame can be added to list of IGame‘s. Run play_games.cs. Randomly choosing a game when there is only one to choose from is pretty silly, but it gives you a start on a more elaborate list of games. The PopRandom method is a good general model for choosing, removing, and returning a random element. Write several very simple classes implementing the IGame interface, and modify Main in play_games.cs to create and add a new game of each type. (Test adding one at a time.) One such game to create with little more work would be a variation on instance based Guessing Game instance_version/guess_game.cs. You need to make slight modifications. You could make Play return the opposite of the number of guesses, so more guesses does generate a worse score. Note that you could not use the original static game version: Only objects can satisfy an interface. See bisection_method/bisection_method.cs. Identify the interface. See how two new classes satisfy the interface, while the rest of the code in these classes is quite different: One has an instance variable and an explicit constructor, while the other does not. See that the Bisection function now has a parameter for an object containing the mathematical function to use for root finding: Bisection is now a generally useful method, not just tied to one hard-coded function that might have a root. Add a new class satisfying the Function interface; add a test in Main. Try a function with multiple roots in the original interval and see what happens. Then, using distinct intervals in different tests, find different roots of the same function.
http://books.cs.luc.edu/introcs-csharp/interfaces/csproj-revisited.html
CC-MAIN-2019-09
refinedweb
1,739
62.58
TreeS = Collections.synchronizedSortedSet(new TreeSet(...)); In this tutorial we are going to see TreeSet example and the difference between TreeSet and other similar collection classes. TreeSet Example: In this example we have two TreeSet ( TreeSet<String> & TreeSet<Integer>). We have added the values to both of them randomly however the result we got is sorted in ascending order. import java.util.TreeSet; public class TreeSetExample { public static void main(String args[]) { // TreeSet of String Type TreeSet<String> tset = new TreeSet<String>(); // Adding elements to TreeSet<String> tset.add("ABC"); tset.add("String"); tset.add("Test"); tset.add("Pen"); tset.add("Ink"); tset.add("Jack"); //Displaying TreeSet System.out.println(tset); // TreeSet of Integer Type TreeSet<Integer> tset2 = new TreeSet<Integer>(); // Adding elements to TreeSet<Integer> tset2.add(88); tset2.add(7); tset2.add(101); tset2.add(0); tset2.add(3); tset2.add(222); System.out.println(tset2); } } Output: You can see both the TreeSet have been sorted in ascending order implicitly. [ABC, Ink, Jack, Pen, String, Test] [0, 3, 7, 88, 101, 222] Hello Chaitanya, I think one point to be corrected here. In your previous HashSet section you have mentioned, HashSet accepts null element and in this TreeSet section you have mentioned HashSet doesn’t allow null element and TreeSet does. I think TreeSet does not allow and HashSet does. Please correct it if I am right. Thanks. Yes I think you are right. TreeSet does not allow null value and HashSet allows but only once. Hey Chaitanya! Thank you for the information you are providing. It’s been useful many times. I have a question: if in my HashSet I keep objects that have different variables, how will it organize them? Can I choose a variable, so that the HashSet is organized according to that? Thank’s again
https://beginnersbook.com/2013/12/treeset-class-in-java-with-example/
CC-MAIN-2019-13
refinedweb
300
56.35
By: Charlie Calvert Abstract: This is the first part of a three part article on Event Handling in JBuilder. The text is an excerpt from my book, Charlie Calvert's Learn JBuilder, from WordWare publishing. Go to Part I Go to Part II Go to Part III Get the source for the whole book. In this chapter and the next you are going to learn the basic facts about handling events. The text will cover four major topics, the first two in this chapter, the last two in the next: Basic Event Handling: Learn the mechanism that JBuilder employs to allow you to handle the most basic events generated by a particular class. For instance, you will learn how to respond to a click on a JButton. More importantly, you learn how the code that supports this kind of simple event handler is constructed, and the various options you will have when implementing it. In particular, you will have a chance to examine the syntax for both anonymous and standard adapter classes. Supporting Listener Interfaces: Learn to create a class that supports an interface such as MouseListener, KeyListener, or the JDK 1.4 class called MouseWheelListener. These interfaces can enable a class to respond to a wide range of events. Generating Events: Create a class that can not only receive events, but also fire events. This technology can be used as a form of loosely coupled communication between the classes in your program. Loose coupling of this kind is highly respected in the OOP programming world because it promotes reuse and helps develop robust architectures. Custom Events: Look at how to create custom events that are tailor-made to convey a particular type of information. JBuilder provides easy to use mechanisms for handling most of these technologies. This chapter will explore these techniques, and give you some tips on how to expedite event-based development. Java events are not always an easy subject, especially for people new to the Java language. The level of complexity involved is significant, but not mind-boggling. A modest level of effort in this area will yield big results in the long run. Furthermore, JBuilder makes this topic much simpler than it would be were you trying to write event-handling code by hand. NOTE: Not all of the techniques shown in this chapter are supported in the Personal version of JBuilder. However, I will show all the code that the JBuilder wizards generate. If necessary, you can simply type the code in by hand. The MouseWheelListener class is found only in JDK 1.4. You already know the simplest way to handle events in JBuilder. However, we should go over it one more time just to be sure that we understand exactly how this code is structured. NOTE: In this chapter you are going to learn how to make a JButton object respond to events. You will also learn about the ActionEvent object. I will not, however, include descriptions of how to make a JButton respond to key presses, or how to make it respond to a key combination, such as Alt-X. I will also not talk about changing the text of the button, using HTML with the button, or adding icons to the button. All of these latter subjects are discussed later in this section of the book. In particular, see Chapter 18, called "The Art of the Button." Create a new project and place inside it a new application that includes a JMenuBar. The ability to create a menu bar as part of the application is built into the JBuilder Application wizard, which was described in the "Default Applications and Applets" chapter back in the Getting Started section of this book. Make sure Frame1 has its layout set to the default BorderLayout. Drop a JButton down on Frame1. Make sure the constraints for the button are set to Center. At this stage, your application is all button. When you run it, it should look like the application shown in Figure 1. Figure 1: A default JBuilder project with a button dropped down onto Frame1. We now want to create a simple event that can be associated with this button. More specifically, when the user presses this button, we want our event to be called and some associated action to take place. For instance, we might pop up a dialog that will allow the user to choose a new application. In JBuilder, there are two ways to associate an event with the button: Double click on the button. This will automatically take you to the source for your program and create a method handler stub for you. Turn to the Events page of the inspector and click on the actionPerformed property. A single click should give you an editable suggested name for your property. Use this single click technology to specify the name for the event handler you are about to create. You can go with the default if you want, but you can use this opportunity to give your event handler a more meaningful name. A double click or a press of the enter key will take you to source view and create the method stub for you. Regardless of which course you take, the method stub that was created should look something like this, though the actual name of the method will vary: void JButton1_actionPerformed(ActionEvent e) { } Fill in the method with some simple code so that you can see it in action: void JButton1_actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(this, "Hate is not conquered by hate, hate is conquered by love!"); } The JButton1_actionPerformed method will be called automatically when JButton1 is selected by the user. NOTE: The JOptionPane class is designed to help you build pop up dialogs of various types. It has methods such as showMessageDialog, showInputDialog, showConfirmDialog and so on. This book is about JBuilder, and not about the JDK, so I will ask that you read the help or visit Sun's web site if you want to learn more about this class. There are many examples of using the class in the source code for this book, so you can grep through that code if you want to see the class in action. NOTE: Before moving on to the next subject, I should perhaps mention that there are occasions when you will get error messages when trying to create an event handler. For instance, you might double click on JButton1 and receive a seemingly nonsensical error saying that a parenthesis was not found. If something like this happens to you, try closing the file you are working on, and then opening it again from the recently used files list. This usually fixes the problem for me. The JButton1_actionPerformed method in the previous section is not called directly by the JDK. Instead, it is called by a class embedded inside of Frame1. It is now time to spend a moment thinking about that class. The class that calls JButton1_actionPerformed can appear in one of two places in your source code. Which of the places it resides depends on the settings you selected in the Project Properties dialog reached by selecting Project | Project Properties | Code Style from the JBuilder menu. The dialog, which was mentioned in the "Product Overview" chapter, is shown in Figure 2. Figure 2: Selecting the style for event-handling adapters in the Project Properties dialog. To understand exactly what is happening now, you need to take a look at two copies of the complete source code for a JFrame with a button on it and one response method. The first version is found in Listing 1, the second in Listing 2. Listing 1: The source for Frame1 as it appears when you use standard adapters. package untitled32; import java.awt.*; import javax.swing.*; import java.awt.event.*; Frame2_JButton1_actionAdapter(this)); this.getContentPane().add(JButton1, BorderLayout.CENTER); } void JButton1_actionPerformed(ActionEvent e) { } }); } } Listing 2: The source for Frame1 as it appears when you use anonymous adapters. package untitled32; import java.awt.*; import javax.swing.*; import java.awt.event.*; /** * <p>Title: </p> * <p>Description: </p> * <p>Copyright: Copyright (c) 2002</p> * <p>Company: </p> * @author unascribed * @version 1.0 */ java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { JButton1_actionPerformed(e); } }); this.getContentPane().add(JButton1, BorderLayout.CENTER); } void JButton1_actionPerformed(ActionEvent e) { } } I created these two source files by first choosing File | New from the JBuilder menu. In the General page of the Object Browser, I then chose Frame, which created a new instance of the JFrame class. In Listing 1, the Code Style for Event Handling in the project was set to Standard Adapters, and in Listing 2, it was set to Anonymous Adapters. I then dropped a button on each frame and created a handler for it. The reason I created new JFrame descendants rather than working with a Frame1 instance was so that these examples would not include irrelevant code such as the processWindowEvent method. This code is stripped down so that it shows little detail other than the code we want to focus on. In Listing 1, notice that there is a class called Frame2_JButton1_actionAdapter:); } } Look further and you will see that this class calls the JButton1_actionPerformed method that we had created earlier: adaptee.JButton1_actionPerformed(e); What we have established so far is that there is a class called an adapter included in your source code that calls the button handler. The button handler is where you place the code you want to have called when the button is pressed. So how does the JDK know to call your adapter when the button is pressed? The following code in jbInit supplies part of the answer to that question: JButton1.addActionListener(new Frame2_JButton1_actionAdapter(this)); The addActionListener method exists deep inside the JDK. This method calls it, and assigns the Frame2_JButton1_actionAdapter class to this instance of the JButton class. The JButton1 class maintains a list of all the actionAdapters that have been registered with it. When the button itself is pressed, it looks at that list and calls the actionPerformed method of that class: public void actionPerformed(ActionEvent e) { adaptee.JButton1_actionPerformed(e); } So now the mystery has been resolved. We have established that the JDK knows to call the adapter class because you called addActionListener, and we have seen that the adapter class calls our JButton1_actionPerformed method. So far so good. NOTE: You will, in fact, learn more about this process in the next chapter. There you will -- with the help of JBuilder -- create your own custom instances of the addActionListener method. But for now, you have enough information to see how the system works. You might also be interested in viewing the first method of the adapter: Frame2 adaptee; Frame2_JButton1_actionAdapter(Frame2 adaptee) { this.adaptee = adaptee; } This method is the constructor. It is passed an instance of the main frame for your application back in jbInit: The word this is the reference to Frame2 that gets passed to the adapter's constructor. The frame is then assigned to the variable adaptee. The adaptee variable is used in the actionPerformed method to call JButton1_actionPerformed. NOTE: In case you are curious, I believe that adaptee is not an English word. It is, however, a proper French word. I'm sure that the multicultural and very sophisticated JBuilder developers were in fact thinking in French when they came up with this variable name! At this stage, you now know the whole story of how events work when you use Standard Adapters in a JBuilder application. I believe that all of the code in this book, unless explicitly marked otherwise, uses standard adapters. Anonymous Adapters, shown in Listing two, use an anonymous class instead of standard Java class. The anonymous class is created in jbInit: JButton1.addActionListener ( new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { JButton1_actionPerformed(e); } } ); Anonymous classes are created, declared and implemented inside the parameter of another method. The method in this case looks like this: JButton1.addActionListener(-- class inserted here --) These are standard parenthesis, as if you were simply passing a parameter to a method. The class that has been inserted into the parameter for this method looks like this: new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { JButton1_actionPerformed(e); } } Note the existence of the word new before the class declaration, and note that the code uses curly braces rather than parens, and note further that the ancestor class name is given, but the class itself has no name: it is anonymous. The class is derived from ActionListener, but the child class has no name. As you can see, this class is very similar to the adapter class from Listing 1. It has no constructor and no Francophile adaptee variable. Nevertheless, its structure should be very familiar. The adaptee variable is not needed, since this class lives inside the scope of Frame2, and hence can call its methods directly. In fact, this class has an actionPerformed method that directly calls JButton1_actionPerformed: public void actionPerformed(ActionEvent e) { JButton1_actionPerformed(e); } Once again, the JButton1.addActionListener method inserts a handle to this anonymous class into a list maintained by JButton1. When JButton1 is pressed, all the classes in that list have their actionPerformed method called. What happens inside that method is up to us. In this case, we have that method call JButton1_actionPerformed. Or rather, JBuilder automatically generates code that will call JButton1_actionPerformed. When writing this book, and when developing the example programs, I had to decide whether I wanted to use anonymous adapters or standard adapters. As you already know, I chose to use standard adapters. Why did I make that decision? Simply because to me Standard Adapters are easier to parse visually than anonymous adapters. Furthermore, the use of Standard Adapters helps to keep my jbInit methods free of clutter. I make absolutely no claim that my choice here is better than its opposite. To my mind, this is simply a matter of taste, and my taste tends toward standard adapters. You should examine your own mind, and use the technique that you prefer. In the long run, it is all pretty much six of one, half dozen of the other. You should just pick your favorite technology and go along with it as happily as possible. Server Response from: SC4
http://edn.embarcadero.com/article/29424
crawl-002
refinedweb
2,375
71.44
Making applications using Visual Studio 2005 As part of my PhD I needed to build some quick and dirty Windows GUI applets, and Visual Studio 2005, which was already being used seemed a logical choice. One advantage is the ease of building GUIs. The disadvantage is that the Visual Studio is oriented around producing .NET style C++ with object instances being created in managed memory. Much of the code I wanted to interface with was unmanaged code, eg open source libraries. I needed to produce code which was partly .NET code and partly classic C++, and the documentation was unhelpful, so here are a few observations and code snippets. Debugging mixed .NET and conventional code The 'debugging' section of the Visual C++ projects property pages includes a 'Debugger type' with a default setting of auto. This is not the right setting for code that is a mix of managed and unmanaged code and 'mixed' should be used instead. Auto means that it can debug (ie add breakpoints, single step, view variable values) when the code is of the same style as the top level application (which might be .NET/managed or unmanaged), but cannot for the other code type. Mixed ensures it can do both. Conversion between managed and unmanaged data There is no problem for simple ints and bools. The problems start with strings, where in .NET the string is held in managed memory. Some code examples on the internet do not work, so beware!. I ended up using the following pieces of template code successfully. .NET string to std::string This is particularly useful if a simple .NET dialogue box is being used to return strings to a conventional C++ core application. Note that the 'Marshal' function returns a pointer to memory that must be freed. using namespace System::Runtime::InteropServices; std::string ConvToString(System::Object^ L) { if (L == nullptr) return ""; IntPtr v = Marshal::StringToHGlobalAnsi(L->ToString()); std::string retvalue((char*)v.ToPointer()); Marshal::FreeHGlobal (v); return retvalue; } Getting data in and out of the registry While the windows API can be used directly for doing this, using .NET allowed the code to be kept to a simple mix of classic and managed C++ using namespace System::Runtime::InteropServices; using namespace Microsoft::Win32; void SaveInRegistry(const char * name,const std::string value) { RegistryKey^ regKey = Registry::CurrentUser->OpenSubKey(KEY,true); if (regKey == nullptr) regKey = Registry::CurrentUser->CreateSubKey(KEY); regKey->SetValue(gcnew String(name),gcnew String(value.c_str())); regKey->Close(); } std::string GetFromRegistry(const char * name) { RegistryKey^ regKey = Registry::CurrentUser->OpenSubKey(KEY); if (regKey == nullptr) return ""; System::Object^ L = regKey->GetValue(gcnew String(name)); std::string value(ConvToString(L)); regKey->Close(); return value; } Problems with the OpenFileDialog box and Vista I created a .NET dll which included an OpenFileDialog box, and while it ran correctly on XP, would hang on Vista when an attempt was made to use the dialog box. I was not alone in finding this problem: It looks as if the problem can arise if the dialog box is called from a console application, or when it is a dll that is called from an old application. I suspect that it is the lack of manifest information in the top level application that is at the root of the problem. Fortunately, there is a simple solution: In the 'properties' for the dialog box object switch 'AutoUpgradeEnabled' to false.
https://warwick.ac.uk/fac/sci/moac/people/students/2007/nigel_dyer/phd/software/visualcpp/
CC-MAIN-2018-09
refinedweb
561
52.9
We are about to switch to a new forum software. Until then we have removed the registration on this forum. Hello, there is a program I would like to make with a face detector using OpenCV. So basically you would have an image A (could be a video) that when a face is close enough to the camera, slowly morphs into an image B. So far, I got to make the program change the images whether or not the face is recognized but now I would like to : 1) tell the face detector to detect the face only when it's around 3feet (1meter) away so the image can change only in that moment. 2) make the "image changing" really smooth and progressive (maybe if the two images merge together using opacity or something ?) I am new to Processing and even more to OpenCv that's why I would be so gload if someone has the solution or can help me ! I quoted my code if it helps… The images can be replaced (btw, they are scaled up when the program runs and I don't understand why… that's another problem but not the most important one) import gab.opencv.*; import processing.video.*; import java.awt.Rectangle; PImage image; PImage flou; PImage nette; Capture cam; OpenCV opencv; Rectangle[] faces; void setup() { fullScreen(); background (0, 0, 0); cam = new Capture( this, 640, 480, 30); cam.start(); opencv = new OpenCV(this, cam.width, cam.height); opencv.loadCascade(OpenCV.CASCADE_FRONTALFACE); image=loadImage("image.jpg"); nette=loadImage("nette.jpg"); flou=loadImage("flou.jpg"); } void draw() { opencv.loadImage(cam); faces = opencv.detect(); image(cam, 0, 0); if (faces!=null) { for (int i=0; i< faces.length; i++) { image(nette,0,0); noFill(); stroke(255, 255, 0); strokeWeight(10); rect(faces[i].x, faces[i].y, faces[i].width, faces[i].height); } } if (faces.length<=0) { textAlign(CENTER); fill(255, 0, 0); textSize(56); println("no faces"); image(flou,0,0); text("UNDETECTED", 200, 100); } } void captureEvent(Capture cam) { cam.read();} Thank you so much !! Answers
https://forum.processing.org/two/discussion/25470/interactive-image-using-face-detection-opencv
CC-MAIN-2019-43
refinedweb
341
63.9
A pivot table is a table that displays grouped data from a larger data set, running a function to get a summary for a set of variables in a column. A popular feature in Excel, Python makes it easy to create the same with your dataframes. This Extra Time tutorial shows how to create pivot tables, with the example of a dataset of matches from a full season. Import your modules, inspect the data and let’s go! import pandas as pd import numpy as np df = pd.read_csv("1617.csv") len(df) 380 As you’ll see below, we have a record for each game of the season. The columns contain lots of data points, including goals, cards and fouls. df.head() 5 rows × 22 columns We create a pivot table through pandas’ ‘.pivot_table’ function. It takes two arguments at its most basic: - The dataframe to pivot – df in this case - Index – the column that we will pivot around Let’s pivot around HomeTeam and see what happens: pd.pivot_table(df,index=["HomeTeam"]) This pivot table gives us the mean for each team in each of their home games – for every variable. Useful, but difficult to read. Let’s choose a couple of columns to look at more closely. We do this by passing a list of columns into the values argument: pd.pivot_table(df,index=["HomeTeam"], values=["FTHG","FTAG"]) Much easier – we can now spot the teams scoring and conceding the most at home really really easily – great job! By default, we get the average in our pivots – but we can pass an ‘aggfunc’ argument to change this. Pass one function to apply it to all columns, or a list of functions to return multiple calculations in your pivot table. Here are some common functions that you might pass: - np.sum – Add the figures - len – Give a count of values - np.std – Find the standard deviation Let’s look at a couple of examples: pd.pivot_table(df,index=["HomeTeam"], values=["FTHG","FTAG"], aggfunc=np.sum) pd.pivot_table(df,index=["HomeTeam"], values=["FTHG","FTHG"], aggfunc=[np.sum,len]) There we go, an intro to pivots in 5 minutes! For further information, read the docs. Give it a go, and if you’re looking to add more skills to your data analysis toolbox, check out our crash course!
https://fcpython.com/extra-time/pivot-tables-python
CC-MAIN-2018-51
refinedweb
388
65.22
Question: I'm building an emailing system for a framework I'm developing. Thus far, I've got a generic MailMessage interface that every different type of email message will implement, something along the lines of public interface MailMessage { public String[] getTo(); public void setTo(String[] to); public String getFrom(); public void setFrom(String from); ... // you can guess the setters/getters here ... } I've then got a SimpleMailMessage that's exactly what you would expect as a simple implementation of the interface (no encryption or encoding, just plain text). I've created an MailMessageFactory interface that's used as an abstract factory. I've got a SimpleMailMessageFactory that implements the factory to produce instances of SimpleMailMessage. One type of email I'd like to the framework to send is an Alert mail message, that is essentially a regular mail message except with "[Alert]" prefixed to the subject line (Another might be a email containing a "list" of order items, but I'm not sure of where the responsibility falls for converting the list to a String for an email lies). I can either subclass the SimpleMailMessage and override the setSubject(String subject) method to something like public class AlertMailMessage { ... public void setSuject(String subject) { this.to = "[Alert]" + to; } ... } Or I can create a decorator: public abstract class EmailDecorator implements MailMessage { protected MailMessage email; ... // delegate all implemented methods to email ... } public class AlertEmailDecorator extends EmailDecorator { public void setSubject(String subject) { email.setSubject("[Alert]" + subject); } } Or I can just delegate adding the "[Alert]" string in the SimpleMailMessageFactory. Thoughts on what I have? I think the problem is that I might be too thoughtful and forward-thinking, but I want the perfect design. Solution:1 A decorator seems a better option to me. I am thinking of, may be you need to append your subject line with, Fwd: or Re: as well, or may be you need to support signature where you will be adding a signature to the email body. Solution:2 The decorator seems like the better option. However, why are you writing your own email framework for Java? Why not just use the JavaMail API? Solution:3 Sounds just like the Spring's support for JavaMail. Don't reinvent the wheel, use already existing, proven solutions, and build on top of that. Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com EmoticonEmoticon
http://www.toontricks.com/2018/05/tutorial-design-emailing-system-in-java.html
CC-MAIN-2018-43
refinedweb
402
55.64
Lightweight LanguagesLightweight Languages What happens if you get a bunch of academic computer scientists and implementors of languages such as Perl, Python, Smalltalk and Curl, and lock them into a room for a day? Bringing together the academic and commercial sides of language design and implementation was the interesting premise behind last weekend's Lightweight Languages Workshop, LL1, at the AI Lab at MIT, and I'm happy to say that it wasn't the great flame-fest you might imagine. While there were the occasional jibes from all sides, (and mainly in our direction) it was a good-natured and enjoyable event. The one-day workshop began with a keynote by Olin Shivers, associate professor of computing at Georgia Tech, on how "Lambda" was the ultimate little language. He was, of course, teaching us about the Joys of Scheme. Olin showed us how we could use Scheme as a basis for implementing domain-specific languages, such as awk, and by embedding these languages in Scheme, one would have not just the power of the original language, but also the implementation language available as well. The alert reader will remember that this is something Larry spoke about in the State of the Onion this year with regard to Perl 6, and something that Damian Conway and Leon Brocard have been working on in Perl 5. Olin demonstrated the power of his "embedding" technique by calling from Scheme to Awk and from Awk back into Scheme in the same routine. He's even written a Scheme shell along the same lines, but there was some disagreement as to whether or not being able to do shell-like things with Scheme syntax means you have a Scheme shell. Olin also brushed aside suggestions that writing Awk, Scheme and Shell in the same syntax in the same function might be potentially confusing, saying that it had never tripped him up. Next came an enlightening panel discussion on the merits of the Worse-Is-Better philosophy; that is, the idea, that doing it right is not as important as doing it right now. I spoke first, explaining how Parrot development has to strike a balance between being correct, maintainable and fast, and ended by asking why doing the right thing is almost always the opposite of doing the fast thing; Jeremy Hylton, one of the Python developers and a really nice guy, replied that Python did not have this problem - for them, correctness and maintainability were more important than performance, giving them more flexibility in terms of doing it Right. Dan Weinreb piped up with the idea that programming implementation tends to be driven by managerial paranoia; thankfully, this is something that both the open-source language implementation community and the academic community are pretty much immune from. Nevertheless, the pressure to release can have adverse affects on future performance, as illustrated by Guy Steele, one of the designers on Java, who told us a sad story about the dangers of Worse Is Better - by putting some vital component of Java (I think it was tail recursion, but it might have been something else) off in order to get release 1.0 out of the door, it made it much harder to implement later on. This resonated with the experience that Python implementors had adding lexical scoping. This rapidly caused a degeneration into whether a language without lexical scoping or the lambda operator can be said to be properly thought out. Joe Marshall gave a short talk on one element of the initial implementation of the Rebol programming language. Rebol 1.0 was slightly different from the "network programming language" that Rebol is today - it was essentially Scheme with the brackets filed off. He explained that in his original Scheme implementation, he used a terribly complicated trick to avoid outgrowing the stack; something that was completely rewritten in the next implementation. Again we found that maintainability was more important in the long run. Jeremy Hylton then gave his presentation, on the design and implementation of Python. It was amusing but, at least to me, not entirely surprising, that Jeremy was the one developer at the conference that Dan Sugalski and I had most in common with. The implementation teams of Perl and Python are facing very much the same problems and approaching them in only very slightly different ways. That is, compared with many of the other approaches we saw presented, at least. Then it was our turn. We were running very late by this point, so I skipped over most of my talk; Dan explained what a lightweight language usually needed from its interpreter, and how Parrot was planning to provide that. David Simmons, one of the developers of SmallScript, a "scripting" Smalltalk implementation, challenged us on the viability of JIT compiling Parrot code, something we were interested in after looking at the Mono project's JIT compiler. We had been intrigued all day by the title of Shriram Krishnamurthi's talk, "The Swine Before Perl." We didn't know whether that referred to us or to Jeremy, who was talking before us. In the event, Shriram delivered a wonderfully interesting presentation about Scheme, and how he could apply "laziness, impatience and hubris" to Scheme programming. He mentioned a Scheme Web server that served dynamic pages many times faster than Apache/mod_perl, and a way of manipulating Scheme macros to provide a pre-compiled state-machine generator. He countered criticisms that Scheme is just lots of insane silly parentheses by demonstrating how XML was just lots of insane silly angle brackets. A fair point well made. Waldemar Horwat lead us through some of the more important design decisions involved in JavaScript version 2.0. No, don't laugh, it's a much more fully featured language than you'd think. His main point was, unsurpisingly, something else that Larry had picked up on in his State of the Onion talk; that modules need to provide ways of encoding the version of their API so as to protect their namespace from subclasses. That's to say, if there's a Perl module Foo and you subclass it to Foo::Advanced by adding a frobnitz method, then what happens when the original author of Foo produces the next version of Foo that already has a frobnitz method? Waldemar's solution was to use version-specific namespaces that only expose certain subsets of the whole API if a particular version number is asked for. This allows dependent modules to be future-proofed. Christopher Barber gave a talk on Curl, a bizarre little language that fills the same sort of niche as Flash. David Simmons spoke about SmallScript and his work porting Smalltalk to the Microsoft CLR; he had high hopes for the way Microsoft .NET was panning out. Jonathan Bachrach, one of the AI Labs researchers gave a clever talk, which I missed due to being out in the corridors debating the finer points of threading and continuations with a Scheme hacker. I returned to see him explain a efficient but highly difficult to follow method of determining whether two classes are the same; he also said that his language compiles down to C and the C compiler is executed on the fly, since it's faster to call GCC than to start up your own virtual machine. Paul Graham rounded off the talks by talking about his new dialect of Lisp, which he called Arc. Arc is designed to be a language for "good programmers" only, and gets away without taking the shortcuts and safeguards that you need if you're trying to be accessible. His presentation was very entertaining, and I have high hopes for his little language. As I've indicated, the interest of the workshop was as much what was going on outside the talks as well; Dan and I got to meet a load of interesting and clever people, and it was challenging for us to discuss our ideas with them - especially since we didn't always see eye to eye with our academic counterparts. Sadly, few people seemed to have heard much about Ruby, something they will probably come to regret in time. Dan seemed to have picked up a few more interesting technical tips, such as a way to collect reference count loops without walking all of the objects in a heap. Oh, and we found that you should pour liquid nitrogen into containers first rather than trying to make ice cream by directly pouring it into a mix of milk and butter. And that the ice-cream so produced is exceptionally tasty. But seriously, what did we learn? I think we learned that many problems that we're facing in terms of Perl implementation right now have already been thoroughly researched and dealt with as many as 30 years ago; but we also learned that if we want to get at this research, then we need to do a lot of digging. The academic community is good at solving tricky problems like threading, continuations, despatch and the like, but not very interested in working out all the implications. To bring an academic success to commercial fruition requires one, as Olin Shivers puts it, "to become Larry Wall for a year" - to take care of all the gritty implementation details, and that's not the sort of thing that gets a PhD. So the impetus is on us as serious language implementors to take the time to look into and understand the current state of the art in VM research to avoid re-inventing the wheel. Conferences such as LL1, and the mailing list that has been established as a result of it, are a useful way for us to find out what's going on and exchange experience with the academic community, and I look forward intently to the next one! O'Reilly & Associates was proud to be a co-sponsor of the Lightweight Languages Workshop. Perl.com Compilation Copyright © 1998-2006 O'Reilly Media, Inc.
http://www.perl.com/lpt/a/2001/11/21/lightweight.html
crawl-002
refinedweb
1,668
52.94
La plume légère, vers Sun, Jun 13, 2004 at 05:04:18PM +0100, heure d'inspiration, Eric Heintzmann écrivait en ces mots: > >But well, their point of view is nonetheless understandable, it's > >also normal > >that they want to reserve general names like terminal or preferences > >for > >meta-packages. And if they want to rename theses packages as > >backbone-preferences or backbone-terminal, I don't find it shocking, > >as > >preferences, terminal or textedit are parts of backbone. Personnally, one idea that comes to my mind is to not rename those packages but to keep them organized in a GNUstep category, the same way there is now a GNOME and a KDE category. Of course it does not solve the namespace "pollution" problem, but otoh, if for example the package Terminal.app cannot use the name "terminal", why would another package be allowed to... so why condemn the use of such names at all. > >A better solution imho would be to add ".app" to GNUstep apps names > >rather > >than prefixing with gnustep- . > > Well, this solution doen't satisfy everyone and doesn't solve the > naming problem on frameworks (like netclasses) and libs. netclasse.framework_version.deb ? Wolfgang pgpB1bmiuy212.pgp Description: PGP signature
http://lists.gnu.org/archive/html/discuss-gnustep/2004-06/msg00299.html
CC-MAIN-2015-48
refinedweb
201
60.95
QGeoBoundingArea Since: 1.1 #include <QtLocationSubset/QGeoBoundingArea> The QGeoBoundingArea class defines a geographic area. This class is the base class for classes which specify a geographic area. For the sake of consistency, subclasses should describe the specific details of the associated areas in terms of QGeoCoordinate instances and distances in metres. Overview Inheritance Public Types Index Public Functions Index Public Types Describes the type of a bounding area. BoxType A box shaped bounding area. CircleType A circular bounding area. - BoxType - - CircleType - Public Functions virtual Destructor. bool Returns whether the coordinate coordinate is contained within this area. bool Returns whether this bounding area is empty. An empty area is a region which has a geometrical area of 0. bool Returns whether this bounding area is valid. An area is considered to be invalid if some of the data that is required to unambiguously describe the area has not been set or has been set to an unsuitable value.
https://developer.blackberry.com/native/reference/cascades/qtmobilitysubset__qgeoboundingarea.html
CC-MAIN-2015-18
refinedweb
157
50.94
In this post we’ll cover a few packages for doing robotic process automation with Python. Robotic process automation, or RPA, is the process of automating mouse clicks and keyboard presses – i.e. simulating what a human user would do. RPA is used in a variety of applications, including data entry, accounting, finance, and more. We’ll be covering pynput, pyautogui, and pywinauto. Each of these three packages can be used as a starting point for building your own RPA application, as well as building UI testing apps. pynput The first package we’ll discuss is pynput. One of the advantages of pynput is that is works on both Windows and macOS. Another nice feature is that it has functionality to monitor keyboard and mouse input. Let’s get started with pynput by installing it with pip: pip install pynput Once you have it installed, you can get started by importing the Controller and Button classes. Then, we’ll create an instance of the Controller class, which we’ll call mouse. This will simulate your computer’s mouse to allow you to programmatically click buttons and move the mouse around on the screen. from pynput.mouse import Button, Controller mouse = Controller() Next, let’s look at a couple simple commands. To right or left-click, we can use the Button class imported above. # left-click mouse.press(Button.left) # right-click mouse.press(Button.right) To double click, you just need to add the number two as the second parameter. mouse.press(Button.left, 2) We can also move the mouse pointer to a different position by using the move method. mouse.move(50, -50) mouse.move(100, -200) pynput can control the keyboard, as well. To do that, we need to import the Key class from pynput.keyboard import Key To make your keyboard type, you can use the aptly-named keyboard.type method. keyboard.type("this is a test") As mentioned above, pynput can also monitor mouse movements and keyboard presses. To learn more about that functionality and pynput, check out this link. pyautogui Perhaps the most commonly known package for simulating mouse clicks and keyboard entries is the pyautogui library. pyautogui works on Windows, Linux, and macOS. If you don’t have it installed, you can get it using pip: pip install pyautogui pyautogui is also straightforward to use. For example, if you want to simulate typing a string of text, just use the typewrite method: pyautogui.typewrite("test pyautogui!") To left-click your mouse, you can use the click method. To right-click, you can use the rightClick method. # left-click pyautogui.click(100, 200) # right-click pyautogui.rightClick(100, 200) Searching for an image on the screen One of the coolest features of pyautogui is that it can search for an image on the computer screen. This is really helpful if you need to find a particular button to click. You can search for an image by inputting the image file name into the locateOnScreen method. The function returns the topleft coordinate along with the height and width of the identified image. location = pyautogui.locateOnScreen("random_image.png") To get the center of identified image, use the center method. Then, you can use the click method to click on the center of the identified image – in this case, a button on the screen. center = pyautogui.center(location) pyautogui.click(center) Sometimes an image may not be found exactly on a screen. In this case, you can add the confidence parameter to locateOnScreen to give Python a confidence level of identifying the image. pyautogui.locateOnScreen("random_image.png", confidence = 0.95) Taking a screenshot You can take a screenshot with pyautogui using the screenshot method. Passing a filename will save the screenshot out to that file. s = pyautogui.screenshot("sample_screenshot.png") It’s also possible to take a screenshot of a specific region, rather than the full screen: pyautogui.screenshot(region = c(0, 0, 100, 200)) pywinauto On Windows, another option we can look into is the pywinauto library. The main disadvantage of this library is that it does not work on macOS or Linux. However, it also offers a couple of nice advantages for Windows users. One, it’s syntax is object-oriented – it’s made to be more Pythonic. Secondly, because of its design, the library can make it easier to perform certain tasks, like clicking on specific buttons or finding menu items in an application. For example, let’s start by launching Notepad, typing some text, and saving the file. We can do that using the code snippet below. Here, we start Notepad by using the Application class. Then, we refer to the Notepad file we just opened by “UnitledNotepad”. We can use the Edit.type_keys to start typing text. from pywinauto.application import Application app = Application(backend="uia").start("notepad.exe") app.UntitledNotepad.Edit.type_keys("Starting notepad...") app.UntitledNotepad.menu_select("File->SaveAs") sub_app=app.UntitledNotepad.child_window(title_re = "Save As") sub_app.FileNameCombo.type_keys("test_file.txt") sub_app.Save.click() Learn more about pywinauto by checking out this link. Conclusion That’s it for this post! We covered three packages for doing robotic process automation with Python. Check out my other Python posts here. Visit TheAutomatic.net.
https://www.tradersinsight.news/ibkr-quant-news/3-ways-to-do-rpa-with-python/
CC-MAIN-2022-27
refinedweb
870
58.08
Illustrator SVG can't be opened by Illustrator after inkscape touches them Bug Description If you resave an illustrator SVG in Inkscape, it means it can't be opened in Illustrator again. Inkscape 0.46dev Dec.29 build, Windows Vista [Saving an Illustrator file with layers as SVG and opening it in Inkscape, not only doesn't Inkscape recognise the Layers (which simply use <g id="Layername"> , where Inkscape use proprietary Inkscape tags), it opens up as having no layer at all, not even a Default one. It is problematic recreating the Layers, as layers will automatically go above all the non-layered objects. When importing Illustrator SVGs, Inkscape should be able to recognise Illustrator's layers. ] [This part of the bug is a dupe of bug 179680 - Tom Davidson] I don't normally use SVGs in Illustrator (they seem to use their own nonstandard filters to go with their browser plugin), but I was wondering about how the layers were enoded, though I'm not a coder. I just did another test using the Inkscape logo, opening it in illustrator CS2, resaving a copy, and opening it in Inkscape again, and resaving a 3rd copy, and comparing the 3 files in a text editor. the final 3rd file, saved from Inkscape, silently fails to open in Illustrator. The 3 files are radically different. I will attach them. Illustrator is doing something funky, attaching a huge CDATA field <i:pgf id="adobe_ <![CDATA[ Inkscape rewrites the file, the header looks very different, and it removes the CDATA tag: <i:pgf id=" each followed by a large block of encoded data. I'm sure Inkscape shouldn't remove the CDATA tag, whatever that junk is. It is probably why Illustrator fails to reopen it. As for layers, all I ask is that the import/open recognise it as an illustrator file and use its Layers format. Considering how radically different the formats are, that should be easy. Incidentally, the inkscape formatting is harder to read than Illustrator's. I expect XML formatting conventions are similar to HTML. not that the SVG is meant to be read by people. Compare the following 2 attachments to share/clipart/ The original logo file was only 2kb, the illustratore SVG is blown out to 24kb becaus eof the CDATA, and the resaved Inkscape file is slightly larger again. I just confirmed the removed CDATA tag was the problem. I manually removed the large block of data in the <i:pgf id="adobe_ Maybe it's a preview icon or something for the Mac, which Windows can't make use of anyway. I'd say simply remove the whole block when encountered, it doesn't seem to affect the file. Obviously the problem is only encountered when an Illustrator SVG is opened and resaved in Inkscape. This is getting off-topic, but I did some research and found out what the CDATA is: http:// Quote: "If you save an SVG file from Illustrator with the "Preserve Illustrator Editing Capabilities" checkbox selected, Illustrator writes out what amounts to an embedded native .ai file in the SVG. When Illustrator reads the SVG file back in, it sees this embedded information and reads it instead of the SVG content. You can see the embedded editing information by opening the SVG file in a text editor and scrolling to the end of the file while looking for "<i:pgf". If you delete the entire <i:pgf ...> node, Illustrator will read the SVG data and you'll see the Adobe Server changes. (The ... represents the enclosed .ai info.) This also makes the file smaller making it process faster in Adobe Server." Hence you break AI compatibility by leaving the <i:pgf tag but removing the CDATA tag around the binary data. Compare the attached file with the 1st file attachment above (2 inkscape logo-illustrator test.svg). The only difference is I unticked the default option to preserve editing capability. Sorry, I haven't checked if there's a bug report relating to the <i:pgf and CDATA tag, or Illustrator compatibility. I will open one if you wish. Since you also filed bug 179680 to report the specific issue that Illustrator's layers are not recognized, I've renamed this bug to reflect the problem of Illustrator SVG files not being re-openable by Illustrator after being saved by Inkscape. From my analysis above, the bug only occurs when AI's default "Preserve Illustrator Editing Capabilities" option is left checked. As such, I'd say most AI SVGs would be affected, as it sounds like a good idea to retain editability, and like most, if you're not sure, you leave it at its defaults. An AI SVG saved without this option will not contain the encoded binary .ai file in the CDATA, which is what it actually opens when present, so all's well. I guess there's nothing else I can add. Thanks for Inkscape, it's important as the only dedicated SVG drawing program, and from this I've learnt how Illustrator, and probably others, can fill them with nonstandard proprietary filler. I'd like to add my two cents to this conversation. As Martin Andersen pointed out Illustrator reads the binary data if present. To amplify my point - Illustrator ignores the svg file as anything but a weird wrapper for an illustrator file if that block exists. If any changes are made in Inkscape, they will be unavailable in Illustrator unless the block is deleted. I propose a warning dialog that defaults to deleting the block with the wording Warning, this file contains an embedded illustrator element that will prevent your changes being seen in Adobe products. To make your changes visible in Adobe products you must delete this element (keep) (delete)[]always do this Where () represents a button and [] represents a checkbox Thanks for listening. Does this situation occurs when you save your SVG file as "Optimized SVG" or as "Plain SVG"? I'm saying this because one time I had to follow a tutorial on SVG animation using CSS techniques and only one of the SVG options Inkscape saves files as worked. Just trying to help here as well. I've added a prune in r15141 which will remove the i:pgf tag when found, the method can later be expanded to strip out any other problematic tags. The new prune works for both inkscape and plain svg files. I confirmed that trunk inkscape does not remove CDATA tags any more, so that part of the bug is already fixed. I won't backport this addition to 0.92 as I believe it won't be that useful now the cdata issue is fixed. But at least we can clear up the "I changed the file and Illustrator doesn't show the changes" bug. It cant be opened in illustrator again? Does it give an error or anything? That actually sounds like a bigger bug than the layers thing. As that is just we dont support their fudge for layers, whereas the not opening breaks the "we write standard svg that should open anywhere" philosophy. May just be AI has rubbish SVG import and cant cope with non svg namespace tags or something in which case its not our issue, but thats something we need to resolve.
https://bugs.launchpad.net/inkscape/+bug/179679
CC-MAIN-2017-34
refinedweb
1,223
61.06
Red Hat Bugzilla – Bug 516909 KSM breaks encryption 157 > kernel > 139 - KSM support now disabled Last modified: 2009-08-27 09:24:48 EDT 1) Upgrade to grubby-7.0.2-1.fc12.x86_64 2) Install grubby-7.0.2-1.fc12.x86_64 title Fedora (2.6.31-0.145.rc5.git3.fc12.x86_64) root (hd0,0) kernel /vmlinuz-2.6.31-0.145.rc5.git3.fc12.x86_64 ro root=/dev/mapper/vg0-rootfs rhgb quiet usbcore.autosuspend=1 SYSFONT=latarcyrheb-sun16 LANG=en_US.UTF-8 KEYTABLE=us rd_plytheme=charge initrd /initrd-generic-2.6.31-0.145.rc5.git3.fc12.x86_64.img This stanza was written by new-kernel-pkg. Note that it is booting the initrd-generic shipped within the kernel RPM. 3) Attempt boot. My LVM vg is encrypted, with rootfs on a lv within that vg. I type my passphrase, it successfully unlocks it, but then sits there forever. key slot 0 unlocked. Command successful. oops, step #2 is install kernel-2.6.31-0.145.rc5.git3.fc12.x86_64 This is with dracut-0.8-1.fc12.noarch. I tried to create a new initrd image with dracut, but that image exhibits the same problem as initrd-generic. dracut on kernel-2.6.31-0.125.rc5.git2.fc12.x86_64 works. This seems to be a problem with kernel-2.6.31-0.145.rc5.git3.fc12.x86_64. Reassigning. kernel-2.6.31-0.145.2.1.rc5.git3.fc12.x86_64 is broken in the same manner. Same here. The last kernel that is working for me is kernel-2.6.31-0.139.rc5.git3.fc12.x86_64 kernel-2.6.31-0.149.rc5.git3.fc12.x86_64 mkinitrd FAIL kernel-2.6.31-0.149.rc5.git3.fc12.x86_64 dracut FAIL I built a LiveCD with kernel-2.6.31-0.149.rc5.git3.fc12.x86_6 + dracut. It gets stuck forever without any error messages and just fails to boot. It seems this has nothing to do with encrypted root. GOOD kernel-2.6.31-0.139.rc5.git3.fc12.x86_64 mkinitrd GOOD kernel-2.6.31-0.139.rc5.git3.fc12.x86_64 dracut FAIL kernel-2.6.31-0.142.rc5.git3.fc12.x86_64 mkinitrd FAIL kernel-2.6.31-0.142.rc5.git3.fc12.x86_64 dracut Confirmed, it broke somewhere between 139 and 142. kernel-2.6.31-0.149.rc5.git3.fc12.sparc64 works just fine here. im using unencrypted lvm dracut-0.7-4.fc12 was used in the kernel build I'm confused. The very same livecd of Comment #6 works today, but the kernel installed on my laptop silently gets stuck after unlocking the encrypted disk. Sven, are you using encryption? enrypted LVM vg specifically? SysRQ-p after it gets stuck. It appears to be stuck in a loop. I am using encryption. I can reproduce those hangs on two machines - both using full vg encryption. If I'm not mistaken F12Alpha is going to ship with a kernel >139 and that would mean full disk encrytion is broken for alpha. As this is a rather important feature I think blocking on F12Alpha is warranted. This seems to be the "non-boot-side" of the same bug: Yeah, believe I can reproduce a similar issue by plugging in a USB hard drive with a Luks encrypted file system: As reported there, works for 0.139, fails for later kernels up to and including kernel-2.6.31-0.156.rc6.fc12.x86_64. All these kernels boot fine on my unencrypted LVM, but exhibit "cryptsetup won't die and consumes available cpu cycles". I've posted SysRQ-p traces there.... Same issue? It works with Linus' kernel, patches which introduced problem in Fedora: Kernel Samepage Merging (KSM). linux-2.6-ksm.patch linux-2.6-ksm-updates.patch Quite serious bug, probably all encrypted system are not bootable now. *** Bug 517545 has been marked as a duplicate of this bug. *** Both my rawhide machines are back to working state with kernel -157 (which disables the ksm-patches). From the included KSM series, probmlematic is this patch Subject: [PATCH 9/12] ksm: fix oom deadlock (fixes one deadlock...and introduces another one:-) -157 fixes my "plugging in a USB hard drive with encrypted FS" issue. FS now mounts and cryptsetup has properly exited. The F12 Alpha kernel is kernel-2.6.31-0.125.4.2.rc5.git2.fc12, so removing this from the alpha blocker Summary: - '[PATCH 9/12] ksm: fix oom deadlock' appears to cause deadlock with an encrypted root volume - This was added in 2.6.31-0.141.rc5.git3 by the addition of this set of KSM patches: - the KSM patches have since been disabled since 2.6.31-0.157.rc6 pending a fix for this > - '[PATCH 9/12] ksm: fix oom deadlock' appears to cause deadlock with an > encrypted root volume FYI: no need to have encrypted root volume, any "cryptsetup luksOpen" on x86_64 will cause deadlock, for process backtrace see bug 517545. Andrea suggests checking whether these programs are calling madvise() with bogus flags (In reply to comment #23) > Andrea suggests checking whether these programs are calling madvise() with > bogus flags Not explicitly, but probably forgot to unlock memory - try this code: #include <sys/mman.h> int main (int argc, char *argv[]) { mlockall(MCL_CURRENT | MCL_FUTURE); // munlockall(); return 0; } Investingating why those troublesome checks that deadlocks mlocked programs are added to page fault path... at first glance they look unnecessary, so asking just in case... Date: Tue, 25 Aug 2009 16:58:32 +0200 From: Andrea Arcangeli <aarcange@redhat.com> To: Hugh Dickins <hugh.dickins@tiscali.co.uk> Cc: Izik Eidus <ieidus@redhat.com>, Rik van Riel <riel@redhat.com>, Chris Wright <chrisw@redhat.com>, Nick Piggin <nickpiggin@yahoo.com.au>, Andrew Morton <akpm@linux-foundation.org>, linux-kernel@vger.kernel.org, linux-mm@kvack.org Subject: Re: [PATCH 9/12] ksm: fix oom deadlock On Mon, Aug 03, 2009 at 01:18:16PM +0100, Hugh Dickins wrote: > tables which have been freed for reuse; and even do_anonymous_page > and __do_fault need to check they're not being called by break_ksm > to reinstate a pte after zap_pte_range has zapped that page table. This deadlocks exit_mmap in an infinite loop when there's some region locked. mlock calls gup and pretends to page fault successfully if there's a vma existing on the region, but it doesn't page fault anymore because of the mm_count being 0 already, so follow_page fails and gup retries the page fault forever. And generally I don't like to add those checks to page fault fast path. Given we check mm_users == 0 (ksm_test_exit) after taking mmap_sem in unmerge_and_remove_all_rmap_items, why do we actually need to care that a page fault happens? We hold mmap_sem so we're guaranteed to see mm_users == 0 and we won't ever break COW on that mm with mm_users == 0 so I think those troublesome checks from page fault can be simply removed. Created attachment 358588 [details] attempted fix (last one was wrong diff) Created attachment 358624 [details] new proposed patch this is actually making ksm_exit simpler and it already contains down_write(mmap_sem) (also this time I checked which workstation I'm running firefox on, before picking a random file from /tmp ;) discussion is going live on linux-mm with Hugh Hugh acked my attachment 358624 [details] so please apply it and then we can close this bug. We've still some issue to discuss on oom handling with ksm on linux-mm but those aren't crtical issues and once we solve them, patches will flow in rawhide. thanks! Already applied and should be in kernel-2.6.31-0.180.rc7.git4.fc12 today. KSM has been re-enabled.
https://bugzilla.redhat.com/show_bug.cgi?id=516909
CC-MAIN-2016-22
refinedweb
1,296
66.44
May 3, 2012 PUBLISH Elisabeth A. Shumaker Clerk of Court No. 10-1263 THOMAS BADER, Defendant-Appellant. knowingly facilitating the sale of HGH brought into the United States contrary to law, and conspiracy to possess with intent to distribute a controlled substance (testosterone cypionate). He asks this court to reverse his convictions or, at a minimum, to grant him a new trial. Mr. Bader also challenges the district courts forfeiture order requiring him to remit the $4.8 million in proceeds that he allegedly derived from his unlawful activity. Exercising jurisdiction pursuant to 28 U.S.C. 1291, we affirm Mr. Baders convictions for distribution of HGH and conspiracy to possess with intent to distribute testosterone cypionate, but reverse based upon instructional error his convictions for knowingly facilitating the sale of HGH imported into the United States contrary to law, and conspiring to do so. Further, in light of our reversals, we conclude that the forfeiture judgment cannot rest on its current statutory basis, but we leave to the district court in the first instance the task of determining the precise amount (if any) of the forfeiture judgment authorized by the remaining, upheld convictions. We remand the case to the district court with instructions to vacate the judgment and sentence and for further proceedings consistent with this opinion. I. BACKGROUND Mr. Bader, a licensed pharmacist in the State of Colorado, owned and operated College Pharmacy, a compounding pharmacy located in Colorado Springs, Colorado. In the context of this case, the precise definition of drug compounding remains in dispute. Nevertheless, the parties agree that College -2- pursuant to which the district court entered a judgment of acquittal on twentythree of the HGH distribution counts; they involved prescriptions to minors, which had been validly issued by licensed physicians. Mr. Bader was subsequently sentenced to a below-Guidelines term of imprisonment of forty months and exempted from any payment of a criminal fine, the court having concluded that the forfeiture of $4.8 million and the pharmacy-building constituted an adequate financial penalty. This appeal followed. II. DISCUSSION Mr. Bader challenges on appeal each of his convictions and attacks the district courts forfeiture order. More specifically, Mr. Bader raises an array of arguments contesting the legal propriety of the jury instructions and the sufficiency of the evidence; alleges prosecutorial misconduct and entrapment by estoppel; and asserts violations of his Sixth Amendment rights and federal evidentiary rules. Mr. Bader asks us to reverse his convictions or, in the alternative, to grant him a new trial. We address below each of his challenges. A. Alleged Instructional Errors Mr. Bader alleges that the district court erroneously instructed the jury in three ways: (1) by including an alternative prong on uncharged API [active pharmaceutical ingredient] importation when it issued instructions regarding the charges of knowingly facilitating the sale of HGH imported contrary to law and conspiring to do so, Aplt. Opening Br. at 51; (2) by telling the jury [that] all [of -6- the] evidence about compounding was irrelevant, id. at 47; and (3) by refusing to instruct the jury on applicable state pharmacy laws and his First Amendment right to advertise. The government contends that any error in the courts alternative prong instruction was harmless, that the district court was correct to reject Mr. Baders compounding definition, and that the court properly refused to instruct the jury regarding state pharmacy dispensing regulations and Mr. Baders First Amendment rights. 1. Finished HGH versus API Mr. Baders first argument pertains to two of his convictionsspecifically, his convictions for knowingly facilitating the sale of HGH imported into the United States contrary to law and conspiring to do so (Counts Seventeen and One of the Second Superseding Indictment, respectively). These convictions implicate 18 U.S.C. 545, which prohibits the smuggling of illegal goods into the United States by providing, in relevant part, that [w]hoever fraudulently or knowingly imports or brings into the United States, any merchandise contrary to law, or receives . . . buys, [or] sells such merchandise, knowing the same to have been imported or brought into the United States contrary to law shall be fined or imprisoned for a maximum of twenty years. 18 U.S.C. 545. In the present case, Mr. Bader was charged in Count One with conspiring to knowingly facilitate the sale of HGH after importation knowing the same to have been imported into the United States contrary to several identified federal -7- Under the Federal Food, Drug, and Cosmetic Act (FDCA), a drug manufacturer may not market a new drug before first submitting a new drug application (NDA) to the FDA and receiving the agencys approval. Wyeth v. Levine, 129 S. Ct. 1187, 1219 (2009) (Breyer, J., concurring) (citing 21 U.S.C. 355(a)). (continued...) -8- (...continued) An NDA must contain, among other things, the labeling proposed to be used for such drug, full reports of investigations which have been made to show whether or not such drug is safe for use and whether such drug is effective in use, and a discussion of why the benefits exceed the risks [of the drug] under the conditions stated in the labeling. As the court later explained in its order partially granting Mr. Baders motion for judgment of acquittal, its instruction on Count Oneoutlined in jury instruction number twenty (Jury Instruction No. 20)[d]istilled to its essence, . . . directed the jury to resolve the imported contrary to law question by first determining whether the HGH being imported was a finished drug or an ingredient. Aplee. App., Vol. IV, at 1258 (Op. & Order Granting, in Part, Mot. for J. of Acquittal and Den. Remaining Mots., filed Apr. 29, 2010). The court further instructed that [t]here is no definition under the law for the term finished drug but that in determining whether the [HGH] was a finished drug, [the jury could] consider whether it was in a finished dosage form; for example, a tablet, capsule, or solution. Aplt. Trial Tr. App., Vol. VIII, at 2169 (Jury Instruction No. 20). In the event that the jury determined that the Chinese HGH was in finished form, they were instructed that a finished drug must have NDA approval in order to be legally imported, and because it was undisputed at trial that the HGH here did not have such approval, a finding that the HGH was a finished drug compelled the conclusion that it was imported contrary to law. Aplee. App., Vol. IV, at 125859; see Aplt. App., Vol. VIII, Tr. at 271516. However, significantly, the district court further instructed the jury, in the alternative, that if the jury f[ound] that the [HGH] was not a finished drug but instead an active pharmaceutical ingredient, then it still was authorized to find that the HGH was -10- Terrazas, 477 F.3d 1196, 1199 (10th Cir. 2007)) (internal quotation marks omitted). In undertaking the threshold error inquiry, we must determine whether, as a whole, the instructions correctly state the governing law and provide the jury with an ample understanding of the issues and the applicable standards. United States v. Visinaiz, 428 F.3d 1300, 1308 (10th Cir. 2005) (quoting United States v. Smith, 413 F.3d 1253, 1273 (10th Cir. 2005)) (internal quotation marks omitted). Regarding the second prong, we have recognized that error is plain if it is clear or obvious under current law. United States v. Cooper, 654 F.3d 1104, 1117 (10th Cir. 2011) (quoting United States v. Goode, 483 F.3d 676, 681 (10th Cir. 2007)) (internal quotation marks omitted). As for the third prong of the test, [i]n the ordinary case, to have the requisite affect on substantial rights, an error must be prejudicial, which means that there must be a reasonable probability that the error affected the outcome of the trial. United States v. Marcus, --- U.S. ----, 130 S. Ct. 2159, 2164 (2010) (internal quotation marks omitted); accord United States v. Thornburgh, 645 F.3d 1197, 1212 (10th Cir. 2011); United States v. Fishman, 645 F.3d 1175, 1196 (10th Cir. 2011). Lastly, as to the fourth prong, it is notable that there is a relationship between that prong and the third: [I]n most circumstances, an error that does not affect the jurys verdict [i.e., the third prong] does not significantly impugn the fairness, integrity, or public reputation of the judicial process [i.e., the fourth prong]. Marcus, 130 S. Ct. at -13- 2166 (quoting Johnson v. United States, 520 U.S. 461, 467 (1997)). We are constrained to conclude that, in propounding Instruction No. 20 to the jury, the district court committed clear or obvious error; that there is a reasonable probability that the error affected the outcome of the trial; and that, under the circumstances presented here, this error significantly impugned the fairness, integrity, and public reputation of the trial. In denying Mr. Baders posttrial motion for a judgment of acquittal, the district court concluded that the final sentence of Instruction No. 20 was unnecessary, but that any potential error was harmless. 3 Aplee. App., Vol. IV, at 126061. We conclude, however, that the final paragraph of the instruction was more than unnecessary; it effectively allowed the jury to convict Mr. Bader under a theory upon which he was never chargedviz., illegal importation of an API, as opposed to illegal importation of a finished drug product. See id. at 102450. Under Instruction No. 20, the jury was allowed to convict Mr. Bader of illegally importing HGH if either: (1) the imported HGH was a finished drug that The district courts error may have partially derived from its misplaced reliance upon Hedgpeth v. Pulido, 555 U.S. 57 (2008) (per curiam). While the district court was correct that Hedgpeth directs courts to consider whether [a] flaw in the [jury] instructions had substantial and injurious effect or influence in determining the jurys verdict, id. at 58 (quoting Brecht v. Abrahamson, 507 U.S. 619, 623 (1993)), its holding pertains to whether purported instructional errors are structural in nature for purposes of collateral review in a habeas proceeding. As Mr. Baders case involves neither a claim of structural error nor a collateral attack in a habeas proceeding, Hedgpeth is inapposite. -14- did not receive new drug approval from the FDA; or (2) the imported product was an API that was manufactured by a foreign entity that was not registered with the FDA. Aplt. Trial Tr. App., Vol. VIII, at 2170. This effectively rendered the finished drug versus API distinctionupon which the governments entire case was baseda nullity, allowing the jury to convict Mr. Bader regardless of the imported HGHs form. In particular, the instruction permitted the jury to convict Mr. Bader of a charge for which he was never indicted. 4 Therefore, in propounding Instruction No. 20 to the jury, the district court committed clear or obvious error. We also are convinced that there is a reasonable probability that this error affected the outcomei.e., that there is a reasonable probability that the jury would not have convicted Mr. Bader of the 545-related counts but for this error. See United States v. Marcus, 628 F.3d 36, 42 (2d Cir. 2010) ([T]he overall effect of the due process [instruction-related] error must have been sufficiently great such that there is a reasonable probability that the jury would not have convicted him absent the error.). The probable prejudicial impact of Instruction No. 20 is evident when we examine it within the context of the entire trial. See Visinaiz, 428 F.3d at 1308. In his closing argument, the prosecutor invited the jury to consider several email exchanges between Mr. Bader, Mr. Henry, and Genescience representatives that reflect[ed] a concern about whether [the Genescience facilities] [were] even registered facilities. Aplt. App., Vol. IX, Tr. at 2760. In one of those email chains, Mr. Henry asked a Genescience representative whether Genescience was FDA registered yet, to which the representative responded that Genescience ha[d]nt got registered in FDA yet. Id. at 2767 (Govt Ex. 34). In another, Mr. Henry informed Mr. Bader that a representative from Mediscaapparently an API supply companywould be sending a letter with information on the FDA[-]registered facility that their HGH comes from, explaining that the representative was totally convinced that Medisca is the only place in the country that is bringing in [HGH] legally. Id. at 2771 (Govt Ex. 44). In conclusion, Mr. Henry noted, College Pharmacy need[ed] to . . . find out if anybody [was] telling the truth or if they[ were] all doing it illegally. Id. Dr. Jason Woo, Associate Director for Medical and Scientific Affairs with the Center for Drug Evaluation Research, testified at trial. When questioned about the FDA approval of foreign-produced HGH, Dr. Woo explained that [t]here are no approved Chinese facilitiesmore specifically, there are not any facilities in China that are approved to make any components of the approved human growth hormone products. Aplee. App., Vol. I, Tr. at 18 (emphasis -16- And we discern nothing in the circumstances of this case that would indicate that such a prejudicial effect would not significantly impugn the fairness, integrity, and public reputation of Mr. Baders trial. Thus, we conclude that the fourth prong of the plain-error test also is satisfied. See Marcus, 628 F.3d at 44 (concluding that there was a reasonable probability that the erroneous jury charge affected the outcome of the trial and affected the fairness, integrity or public reputation of the proceedings). This plain-error analysis indicates that because of Jury Instruction No. 20s inclusion of an erroneous theory of liabilityviz., a theory that permitted Mr. Baders conviction for having imported an API, as opposed to a finished drug, so long as that API was manufactured by a foreign entity that was not registered with the FDA, Aplt. Trial Tr. App., Vol. VIII, at 2170 (Jury Instruction No. 20)we must reverse and remand. Specifically, we reverse Mr. Baders conviction on Count Seventeen, for knowingly facilitating the sale of HGH imported into the United States contrary to law, and on Count One, for conspiracy to do so. Both counts rely on the erroneous liability theory set forth in Jury Instruction 20. 6 (...continued) API distinction. The district court was correct when it represented to the jury that [t]here is no definition under the law for the term finished drug, Aplt. Trial Tr. App., Vol. VIII, at 2169; however, we do not operate on a blank slate. While the law is far from clear, we endeavor to outline here the relevant precedent to which the parties and the court should look in defining these terms upon remand. As the Supreme Court has explained, [t]he active ingredients in most prescription drugs constitute less than 10% of the product; inactive excipients (such as coatings, binders, and capsules) constitute the rest. United States v. Generix Drug Corp., 460 U.S. 453, 454 (1983). A complete product[], therefore, consists of active ingredients and excipients together. Id. at 461. Thus, the district court was correct when it instructed the jury that a finished drug productas opposed to an APIis often in finished dosage form; for example, a tablet, capsule, or solution. Aplt. Trial Tr. App., Vol. VIII, at 2169. Much of the law concerning the finished-drug versus API distinction is grounded in the recent methamphetamine epidemic. Pursuant to 21 U.S.C. 971(c)(1), for example, the DEA may order the suspension of any importation or exportation of a listed chemical . . . on the ground that the chemical may be diverted to the clandestine manufacture of a controlled substance. PDK Labs., Inc. v. DEA, 438 F.3d 1184, 1186 (D.C. Cir. 2006) (quoting Pub. L. No. 100-690, tit. VI, 6053(a), 102 Stat. 4312 (1988)) (internal quotation marks omitted). One of these listed chemical[s]ephedrineis an active ingredient in over-thecounter medications for the treatment of asthma and nasal congestion. Ephedrine is also used in the illicit production of methamphetamine, a controlled substance. PDK Labs., Inc. v. DEA, 362 F.3d 786, 789 (D.C. Cir. 2004). It has therefore fallen upon the courts to determine whether the DEA can act pursuant to 971(c)(1) in order to divert a pharmacys finished drugas opposed to the raw API that it importsfrom the hands of methamphetamine producers who seek to buy (or purchase) the medication from retail stores. In so doing, courts have offered at least a cursory explanation of the production process: pharmacies purchase[] raw, bulk ephedrine from foreign companies, combine[] the chemical with other active agents, and produce[] a finished product in tablet form, packaged in bottles or blister packs. Id. (emphases added). Thus, at least in the methamphetamine context, an API is a raw product that is combined with other active ingredients to produce a finished drug product that is ready for public (continued...) -19- 2. (...continued) consumption. In other words, a finished drug is a final, patient-ready drug that consists of one or more APIs and, most likely, one or more excipients. See Generix, 460 U.S. at 461. Indeed, this Court has also weighed in on the API/finished-drug distinction. In Pharmanex, Inc. v. Shalala, 221 F.3d 1151 (10th Cir. 2000), the FDA challenged the district courts decision to enjoin an FDA administrative decision that concluded that Cholestina product intended to promote healthy cholesterol levelswas not a dietary supplement that was exempt from FDA regulation. The district court, we explained, based its decision on the determination that [the relevant statute] refer[ed] unambiguously to finished drug products, rather than their individual constituents. Id. at 1153 (emphases added). On appeal, the FDA argued that the applicable statute was properly understood to contemplate active ingredients as well as finished drug products. Id. at 1154 (footnotes omitted). Our role, therefore, was to determine whether Congress unambiguously manifested its intent to exclude only finished drug products (rather than ingredients) from the definition of dietary supplement. Id. In so doing, we noted that the term [a]ctive ingredient means any component that is intended to furnish pharmacological activity or other direct effect. Id. at 1154 n.3 (emphasis added) (quoting 21 C.F.R. 210.3(b)(7)), while a [d]rug producta term that we analogized to finished drug productis defined as a finished dosage form . . . that contains a drug substance, generally, but not necessarily, in association with one or more drug ingredients. Id. at 1154 n.4 (emphases added) (quoting 21 C.F.R. 314.3(b)). These definitionspromulgated by the FDA itselfare certainly less than clear. At the very least, however, they provide a rudimentary foundation regarding the interrelation between the two terms: an API is a medicinally active component that is associated with additional drug substance[s] to form a finished product available in individual doses. See id. at 1154 n.34. These definitions, in conjunction with the aforementioned case law, should inform the district courts jury instructions in the event that Mr. Bader is retried. -20- Mr. Bader presented this argument for the first time in his post-trial motion for judgment of acquittal. See Aplee. App., Vol. IV, at 1257. His objection at trial, in contrast, merely sought to include a definition of the term prescription in Instruction No. 12. See Aplt. App., Vol. VIII, Tr. at 2699. -21- Consequently, we need not (and do not) consider whether the district courts characterization of compounding law as irrelevant obliges us to reverse Mr. Baders 545-related convictions; we have already determined that those convictions cannot stand. 3. Rejection of State Pharmacy and First Amendment Instructions Finally, Mr. Bader argues that the district court erred with respect to the jury instructions that it did not givei.e., in refusing to inform the jury of Colorados pharmacy-dispensing laws, see Aplt. Opening Br. at 5254, and in failing to instruct the jury that Mr. Bader had a Supreme Court-recognized right to advertise under the First Amendment, id. at 55. We review the district courts refusal to issue these instructions for an abuse of discretion. See United States v. Crockett, 435 F.3d 1305, 1314 (10th Cir. 2006). However, in determining whether the district court exercised its discretion properly, we review the jury instructions de novo to determine whether, as a whole, they accurately state the governing law and provide the jury with an accurate understanding of the relevant legal standards and factual issues in the case. Id. Applying this standard to the present case, it is patent that the district court appropriately exercised its discretion when it rejected Mr. Baders proposed instructions. Mr. Bader first contends that the district court erred in refusing to issue several relevant state pharmacy instructions regarding: (1) Colorado requirements that pharmacies maintain adequate drug inventories and provide -22- adequate services, Aplt. Opening Br. at 52; (2) [s]tate laws governing ordering, dispensing[,] and requirements for valid prescriptions, id. at 53; (3) [s]tate laws clarifying that pharmacists who prepare, compound, package, repackage, or dispense drug[s] are not drug wholesalers or manufacturers, id.; and (4) a Colorado law providing that pharmacists may rely on a physicians professional judgment in ordering a drug for a patient, id. at 54. However, Mr. Bader fails to identify to which of the forty-three charged counts these state laws pertain, let alone explain how they are relevant to the charges upon which he was convicted. Indeed, it is clear from the record that the district court was more than generous in including some language [from the proffered instructions] . . . where it [was] relevant to [the] explanation of a particular element of a particular count, despite its determination that Colorados pharmacy laws generally had no bearing upon Mr. Baders charges. See Aplee. App., Vol. III, Tr. at 634. As Mr. Bader offers no support for his bald allegation that this determination was somehow erroneous, we are constrained to conclude that his first argument is meritless. Mr. Baders undeveloped First Amendment claim, which he seeks to assert throughout his opening brief, is even less persuasive. As we discuss infra, the government introduced evidence of College Pharmacy advertisements in order to prove that Mr. Bader purposefully marketed HGH and testosterone cypionate for impermissible purposes. At no point, however, did the government contest, as a -23- appeal. Mr. Bader principally argues that his conviction cannot stand because the government failed to present proof that he knowingly filled a prescription for an unauthorized use[i]llegal distribution, he contends, requires proof of a prescription sale for an unapproved use and that a pharmacist knowingly filled it. Aplt. Opening Br. at 31. This is simply incorrect. Under 21 U.S.C. 333(e)(1), whoever knowingly distributes, or possesses with intent to distribute, human growth hormone for any use in humans other than the treatment of a disease or other recognized medical condition, where such use has been authorized by the Secretary of Health and Human Services under section 355 of this title and pursuant to the order of a physician, is guilty of an offense punishable by not more than 5 years in prison, such fines as are authorized by Title 18, or both. 21 U.S.C. 333(e)(1) (emphasis added). Thus, the plain terms of the statute belie Mr. Baders argumentspecifically, his contention that there is only one means to violate the statute involving knowingly filling a prescription for an unauthorized use. Indeed, Jury Instruction No. 38the instruction that outlined the elements of the unlawful distribution charge and to which Mr. Bader has offered no objectionwas phrased in the disjunctive. According to that instruction, proof of the filling of an improper physician prescription was but one of three ways that the government could satisfy its burden. The government could demonstrate -26- either: (1) that Mr. Bader knew that the [HGH] was not being distributed for a[] use authorized by the Secretary of Health and Human Services; or [(2)] that Mr. Bader knew that the [HGH] was not being distributed pursuant to the order of a physician; or [(3) that Mr. Bader knew that the HGH that he possessed] was not being prescribed for a valid medical purpose. Aplt. Trial Tr. App., Vol. VIII, at 2181 (emphases added). 8 Throughout Mr. Baders trial, the government introduced a series of exhibits consisting of College Pharmacy advertisements that extolled the antiaging and muscle-building benefits of HGH, as well as related statements from Mr. Blum and various College Pharmacy employees. Several of the witnesses who testified recalled that Mr. Bader had promoted HGH at A4M trade shows as an anti-aging and body-building drug. And their testimony was corroborated by photographs depicting Mr. Bader and his advertisements at one of these trade shows. Mr. Bader apparently argues that this evidence is insufficient because it merely demonstrates promotion, as opposed to actual distribution, of HGH. However, under the plain language of the statuteas well as Mr. Baders counts of convictionproscribed is not only the actual distribution of HGH but also Mr. Bader also avers that the governments reliance upon these advertisements runs afoul of the First Amendment in light of the Supreme Courts decision in Western States. In Western States, the Court invalidated several restrictions of the Food and Drug Administration Modernization Act of 1997 (FDAMA) on advertising of compounded drugs on the ground that they constituted unconstitutional restrictions on commercial speech. See 535 U.S. at 360. As the government points out, however, Mr. Baders First Amendment rights were not at issue in the instant case, and there is absolutely nothing in Western States that bars the government from relying upon a defendants commercial advertisements as evidence that he sought to distribute HGH or any other compounded drug for an unauthorized use in violation of 21 U.S.C. 333(e). Thus, any First Amendment argument by Mr. Bader predicated on Western States is without merit. 10 testified that body-building and anti-aging were not FDA-approved uses for HGH. On the basis of this evidence, a reasonable jury could have logically deduced that the College Pharmacy anti-aging and body-building advertisements introduced at trial were aimed at distributing HGH for those usesuses which had yet to be authorized by the Secretary of Health and Human Services or recognized as valid medical conditions warranting HGH prescriptions. Accordingly, a reasonable jury could have construed this evidence as satisfying the third element of 21 U.S.C. 333(e). 2. (...continued) conditions. Any use of the drug other than that in the approved labeling is considered an off-label use of the drug. Aplee. App., Vol. I, Tr. at 2021. For most drugs, these off-label uses are entirely legal, and physicians may proceed to prescribe the drug for other purposes. As Dr. Woo explained, however, this is not the case with HGH; due to congressional concerns with HGH abuse, off-label prescriptions of HGH are uniformly illegal. Id. This is evident from the plain language of 333(e), which holds a party liable for any use of HGH that has not been expressly authorized by the Secretary of Health and Human Services. 21 U.S.C. 333(e)(1). -29- could support [his] conviction. United States v. Holly, 488 F.3d 1298, 1311 n.11 (10th Cir. 2007); accord United States v. Pearl, 324 F.3d 1210, 1214 (10th Cir. 2003) (Our conclusion that [defendants] convictions on counts 2 through 5 must be reversed does not, however, preclude retrial of [defendant] on these counts . . . .); cf. Level 3 Commcns v. Liebert Corp., 535 F.3d 1146, 1150 (vacating the jurys verdict and remanding for a new trial where the court erroneously instructed the jury). This principle is grounded in the Double Jeopardy Clause. In contrast to a second trial following an acquittal, which would present an unacceptably high risk that the [g]overnment, with its vastly superior resources, might wear down the defendant so that even though innocent, he may be found guilty, United States v. Scott, 437 U.S. 82, 91 (1978) (quoting Green v. United States, 355 U.S. 184, 188 (1957)), the Supreme Court has held that the successful appeal of a judgment of conviction, on any ground other than the insufficiency of the evidence to support the verdict . . . poses no bar to further prosecution on the same charge because to require a criminal defendant to stand trial again after he has successfully invoked a statutory right of appeal to upset his first conviction is not an act of governmental oppression of the sort against which the Double Jeopardy Clause was intended to protect, id. at 9091. Accordingly, this circuit has established a distinction between trial error deriving from an erroneous jury instruction and pure insufficiency of evidence -30- such that, in the former case, a defendant may be retried without violating double jeopardy. Pearl, 324 F.3d at 1214; accord United States v. Wacker, 72 F.3d 1453, 1465 (10th Cir. 1995). Thus, Mr. Bader may be re-tried following remand to the district court if his case falls within this trial error categoryin other words, so long as the government presented legally sufficient evidence. See United States v. Nacchio, 519 F.3d 1140, 1157 (10th Cir. 2008) (Although we have concluded that Mr. Nacchios conviction must be reversed on account of trial error, we cannot leave it at that. He also claims that the government failed to introduce evidence sufficient for him to be convicted. If he is right, he was entitled to a judgment of acquittal and cannot be retried without violating the Double Jeopardy Clause.), vacated in part on other grounds, 555 F.3d 1234, 1236 (10th Cir. 2009). Perhaps because he is aware of this fact, Mr. Bader devotes a substantial portion of his briefs to challenging the sufficiency of the evidence supporting his 545-related convictions. Specifically, he avers that: (1) his convictions cannot stand because they were premised upon the importation of an API rather than a finished drugi.e., that a reasonable jury could not have concluded that the imported HGH was a finished drug on the basis of the evidence that the government produced at trial; (2) the record contains no evidence that Mr. Bader possessed the requisite mens rea to be convicted of the importation of HGH contrary to law; and (3) the government failed to prove that Mr. Bader knowingly -31- (i) Mr. Bader insists that a reasonable jury could not have convicted him of the 545-related charges because the government failed to sufficiently demonstrate that the imported HGH was a finished drug product rather than an API. Though as noted we find error with the dual avenues that Jury Instruction No. 20 provided for conviction, there was ample evidence upon which a reasonable jury could have convicted Mr. Bader on the proper ground specified in this instruction: that is, the imported HGH was a finished drug that was illegally imported on account of Mr. Baders failure to garner NDA approval. 12 11 (...continued) opportunity to demonstrate that the record does not support an appellants . . . assertions . . . .). However, even if we were to do so, we would conclude that it is without merit. Specifically, the jurys decision to acquit Mr. Bader of receiving stolen goods under Count Sixteen of the Second Superseding Indictment had no bearing upon his 545-related convictions. Count Sixteen primarily turned upon 18 U.S.C. 542, which relates to the entry of merchandise into the United States by means of false statements. Aplee. App., Vol. IV, at 103839; see Aplt. Trial Tr. App., Vol. VIII, at 2173 (Jury Instruction No. 26). A reasonable jury could have found that Mr. Bader was not guilty of having knowingly facilitated the importation of HGH into the United States through false statements to the FDA (i.e., statements indicating that the HGH was an API in order to gain import approval), yet simultaneously concluded that Mr. Bader was nevertheless guilty of knowingly facilitating the sale of an illegally imported finished drugeven if the importation of this finished drug was not facilitated through false representations . 12 12 (...continued) Genescience [HGH] into smaller vials labeled with College Pharmacy boxes and information for sale as Somatropin, without ever add[ing] ingredients to, or remov[ing] anything from, the product itself, Aplee. Br. at 2122, it fails to point to any excerpts from the record that support these sweeping statements. We remind counsel that is not this Courts job to sift through the record to find support for the governments arguments, and its failure to direct us to the location in the voluminous record where we [might] find support for their [arguments] has resulted in the unnecessary expenditure of valuable judicial resources. Phillips v. James, 422 F.3d 1075, 1081 (10th Cir. 2005). -34- took the Somatropin from the large bottles and put it into small vials, id. at 134, and confirmed that College Pharmacy got Somatropin from Genescience, id. at 131. John Ruth, a College Pharmacy national sales representative, also told the jury that, at least initially, College Pharmacy did no more than simply repackag[e] the imported HGH. Id., Vol. II, Tr. at 296 (Test. of John Ruth). Mr. Ruth explained that College Pharmacy employees were told via Mr. Bader to repackage the imported HGH, and that the College Pharmacy sales team, in turn, told all of [its] clients and prospective clients the same thing: College Pharmacy was bringing in a drug, importing it from another country, and . . . repackaging [it] into [College Pharmacys] own package and selling it to them. Id. Then, in early 2005, after [College Pharmacy] had been selling the Somatropin for several months and had done well, [the sales team was] told . . . that [it was] not repackaging [the HGH] because [it] could not get a license to repackage from the . . . FDA. Id. The College Pharmacy sales team then simply began to inform customers that the HGH was compounded; that it was no longer repackaged. Id. Any change in College Pharmacys Genescience processesfrom repackaging to compoundingwas therefore illusory, and was aimed at avoiding FDA oversight rather than actually compounding imported ingredients. The testimony of Ms. Griffin and Mr. Ruth was corroborated by the -35- testimony of Mr. Blum, who stated that he was not aware of anything being added or taken out of the bottled version [of HGH] that [Genescience] provided [College Pharmacy] [as juxtaposed with] the vials that [College Pharmacy was] putting out. Id., Vol. I, Tr. at 182 (Test. of Brad Blum). Mr. Blum consistently referred to the Genescience HGH product that he sold to Mr. Bader as Somatropin, and even testified that he personal[ly] use[d] Somatropin after purchasing it directly from Genescience. Id. at 16869. Upon receiving the Genescience shipment from China, Mr. Blum explained, he mixed the imported vial of HGH powder with a vial of water and injected himself with the hormone at his home, noting that HGH enables one to recover faster from injury and that he found it to improve his general well being. Id. at 170. On the basis of testimony from the man who actually imported and dealt directly with Genescience, it would have been entirely reasonable for a jury to conclude that Genesciences HGH, to which nothing was being added or taken out, was essentially (in substance) identical to the smaller Somatropin doses that College Pharmacy later marketedparticularly in light of Mr. Blums testimony that he was able to personally use (as well as distribute to his friends) the finished HGH that he received directly from Genescience. See id. at 172, 182. Having learned (1) that the imported Genescience HGH was merely repackaged into smaller vials as Somatropin, (2) that College Pharmacy employees themselves told clients they were merely repackaging the imported -36- HGH, and (3) that the imported Genescience HGH wasat least in certain significant instances (e.g., the use of Mr. Blum)patient-ready even prior to College Pharmacys processing, a reasonable jury could have easily inferred that the imported Genescience HGH was already in its finished form when it arrived at College Pharmacy for repackaging and distribution. In sum, Mr. Baders conviction was supported by a wealth of evidence. (ii) Mens Rea Mr. Bader also argues that the government failed to present sufficient evidence that he possessed the necessary mens rea to be convicted under 18 U.S.C. 545. See Aplt. Opening Br. at 28. Neither party does a good job of developing this issue. And, in particular, the governments conclusory assertion that [i]t was uncontroverted that [Mr. Bader] knew the [HGH] in question was not the subject of an approved NDA, Aplee. Br. at 23with no citations to the record that support this statementis unhelpful. Our independent review of the record, however, confirms that the government is correct: a reasonable jury could have easily concluded that Mr. Bader knew the illicit nature of his transactions on the basis of the evidence adduced at trial. Admittedly, our own circuit has offered little in the way of guidance regarding the mens-rea requirement of 545. Our sister circuits, however, have observed that the word knowinglyas it appears in 545modifies imports or brings into the United States, any merchandise contrary to law. -37- United States v. Garcia-Paz, 282 F.3d 1212, 1217 (9th Cir. 2002) (quoting 18 U.S.C. 545); accord United States v. Molt, 615 F.2d 141, 146 (3d Cir. 1980) (An essential element of a section 545 offense is . . . a knowing importation of merchandise contrary to law.); see also Roseman v. United States, 364 F.2d 18, 23 (9th Cir. 1966) (noting that an appellants charge under 18 U.S.C. 545 for the sale of LSD required proof (1) that the appellants sold the LSD; (2) that [the] appellants had knowingly brought this LSD into the United States contrary to law; and (3) that the LSD . . . was a new drug . . . for which there was no effective new drug application (emphasis added)). Under 545, [i]t is not a requirement of the offense that the defendant know the type of merchandise he is importing. He need only know that he is importing or bringing in merchandise contrary to law. Garcia-Paz, 282 F.3d at 1217 (quoting 18 U.S.C. 545). In the present case, therefore, the government could satisfy 545s mens-rea requirement so long as it could demonstrate that Mr. Bader knew that he was importing a drug from Genescience illegally. As proof that Mr. Bader possessed the requisite mens rea to be convicted of a 545-related offense, the government first presented the testimony of Chris Strong, College Pharmacys managing pharmacist at the time that Mr. Bader began importing the Chinese HGH. Mr. Strong testified that he had expressed his concerns about the importation of Chinese HGH to Mr. Bader and other College Pharmacy pharmacists at a meeting in 2004. He explained that the meeting had -38- centered upon whether or not College Pharmacy was going to operate the pharmacy with the compliance policy guidelines of the FDA, and he recalled that Mr. Baders opinion [had been] that [the FDAs policy] was a guidelinenot a rule or a regulation that College Pharmacy was obligated to follow. Aplee. App., Vol. I, Tr. at 113 (Test. of Chris Strong); see also id., Vol. II, Tr. at 29394 ([T]he FDA wanted in, and [Mr. Bader] wanted them out. . . . [T]hey were known as Big Pharma. They were the big enemy, and we were the good guys.). Mr. Strong further testified that he and Mr. Bader had quarreled over appropriate College Pharmacy protocol, usually in relation to Mr. Baders continuous attempts to increase College Pharmacys profit. Not long after Mr. Strong attempted to institute a new policy at College Pharmacypursuant to which pharmacists would be asked to verify that any new physician who sought to fill a prescription with College Pharmacy was adequately certifiedhe was fired from his position at the pharmacy. Mr. Baders knowing disregard of the FDAs regulatory scheme was directly confirmed by the testimony of Mr. Blum, who admitted that both he and Mr. Bader had known that the Genescience HGH was not an FDA-approved product and had also known that it was being imported from China. Mr. Ruth also told the jury that Mr. Bader had known that the imported HGH was subject to FDA approval, and recounted how Mr. Bader had directed his sales staff to inform College Pharmacy customers that the pharmacy was compound[ing] rather than -39- Conspiracy Finally, Mr. Bader contends that the government failed to prove that he conspired with Mr. Blum and others to illegally import HGH, alleging that (1) the [g]overnment failed to prove anything other than an equipoise buyer-seller relationship between [Mr.] Blum and the purchasing pharmacies, and (2) that the government failed to prove that he knowingly participated in the alleged conspiracy. Aplt. Opening Br. at 29. The district court here instructed the jury that, in order to convict Mr. Bader of conspiring to violate 18 U.S.C. 545, the government was obligated to prove, beyond a reasonable doubt, that (1) Mr. Bader entered into an agreement or understanding with one or more others to import [HGH] into the United States contrary to federal law and thereafter to sell or distribute that [HGH] within the United States; (2) [t]here was an -40- interdependence among Mr. Bader and the others involved in [the] agreement; (3) Mr. Bader knew that the purpose of the agreement was to import the [HGH] contrary to federal law[,] to sell it thereafter, and that he voluntarily entered into that agreement; and (4) [o]ne or more of the people who entered into the agreement performed one or more overt actsthat is, actions that constituted a substantial step towards achieving the purpose of the illegal importation scheme. 13 Aplt. Trial Tr. App., Vol. VIII, at 2168 (Jury Instruction No. 18); see 13 also Molt, 615 F.2d at 146 (discussing elements of crime of conspiring to violate 545). Mr. Bader arguments implicate only the first and third elements. The government, however, presented ample evidence to support the jurys findings as to these elements. First, on redirect, Mr. Blum clearly and unequivocally testified that he illegally imported and distributed HGH, and that he did so with Mr. Baders knowledge and assistance. Mr. Blum acknowledged that he had agree[d] to violate the law when he agreed to do business with Tom Bader, and he further admitted that this agreement amounted to a conspiracy involving importation of [HGH] and delivery to Mr. Bader, that the essential objective of the conspiracy was to distribute [HGH], and that the members of that conspiracy were [him]self and Tom [Bader]. Aplee. App., Vol. I, Tr. at 252. Mr. Blum also confirmed that Mr. Bader had knowingly and voluntarily participated in that agreement. Id.; see id. at 189 (agreeing that Mr. Bader . . . kn[e]w that this was not FDA[-]approved product). Mr. Blums statements were corroborated by the testimony of Mr. Strong, who told the jury that Mr. Bader was aware of the fact that his importation of 13 (...continued) States v. Williams, 376 F.3d 1048, 1051 (10th Cir. 2004) (The law of the case is applied to hold the government to the burden of proving each element of a crime as set out in a jury instruction to which it failed to object, even if the unchallenged jury instruction goes beyond the criminal statutes requirements.). In any event, given the nature of Mr. Baders specific challenges, we have no need to address this matter further. -42- Genescience HGH violated FDA protocol, as well as the testimony of Mr. Ruth, who confirmed that College Pharmacy was purchasing HGH from Mr. Blum and from Genescience in China at the direction of Mr. Bader. On the basis of this testimony, a reasonable jury could have concluded that Mr. Bader knowingly entered into an agreement with Mr. Blum to import and distribute HGH in a manner that Mr. Bader knew was contrary to lawi.e., in a way that he knew ran afoul of FDA rules and regulations. Accordingly, we conclude that the government presented sufficient evidence of Mr. Baders involvement in a conspiracy relating to the 545 charge. 4. Conspiracy to Distribute or Possess with Intent to Distribute Testosterone Cypionate Finally, Mr. Bader challenges the sufficiency of the evidence that the government presented to prove Count Nineteen of the Superseding Indictmentconspiracy to distribute and to possess with the intent to distribute testosterone cypionate (an anabolic steroid), in violation of 21 U.S.C. 841(a)(1), (b)(1)(D), and 21 U.S.C. 846. Mr. Bader argues that, of the nearly four thousand doctors that College Pharmacy serviced, only two admitted that they had secretly prescribed testosterone through College Pharmacy for unlawful uses. Aplt. Opening Br. at 56. He also avers that he was unaware of these unlawful prescriptions. As the jury was instructed at trial, the government bore the burden of proving, beyond a reasonable doubt, that: (1) Mr. Bader entered into an -43- 14 one aspect of the abundant evidence that the government presented to demonstrate that Mr. Bader knowingly agreed with other College Pharmacy sales and advertising staff to illegally distribute and to possess with the intent to distribute testosterone cypionate. First, to prove that an agreement existed, the government presented testimony from one of Mr. Baders co-conspirators. Specifically, Mr. Ruth testified that he always got instruction from Thomas Bader regarding how he and fellow College Pharmacy employee, Kevin Henry, should prepare for and present information at the A4M anti-aging conferences at which College Pharmacy marketed testosterone cypionate, Aplee. App., Vol. II, Tr. at 298despite the fact that anti-aging is not a lawful, approved use for this drug. Sometimes Mr. Bader even attended these conferences himself and, when he did, Mr. Bader was the one running the show. Id., Vol. I, Tr. at 191. Mr. Ruth also explained that College Pharmacy had enjoyed a lucrative relationship with Peak Physique, a large anti-aging clinic that purchased large volumes of prescriptions from College Pharmacy, and that Mr. Bader had supervised the Peak Physique account. Additionally, the government introduced a series of College Pharmacys 14 (...continued) College Pharmacy computer advances the governments cause. Nonetheless, as noted above, the evidence concerning the two physicians was only a small part of the inculpatory picture painted by the government concerning the charge of conspiracy to unlawfully distribute and possess with the intent to distribute testosterone cypionate. -45- 15 [a]nti-[a]ging clinics all over the United States [were] coming to College Pharmacy for solutions to their age[-]management questions. Id., Vol. III, at 645 (Govt Ex. 13). Mr. Ruth explained that Tracy Crawford, College Pharmacys managing director of sales, had affixed a post-it note to this advertisement asking Mr. Bader whether he would like to include it as an insert in the registration bags that College Pharmacy distributed to anti-aging trade show attendees. Indeed, Mr. Ruth confirmed that all of College Pharmacy marketing materials and major decisions were subject to Mr. Baders approval. His testimony, combined with these College Pharmacy advertisements, provided more than sufficient evidence upon which a reasonable jury could have concluded that Mr. Bader entered into an agreement with Mr. Ruth and other members of the sales department to unlawfully distribute testosterone cypionatein other words, the government met its burden of proof concerning element one of Count Nineteen under Jury Instruction No. 34. See Aplt. Trial Tr. App., Vol. VIII, at 2178; see id. at 216869 (Jury Instruction No. 19) (In determining whether the [g]overnment has shown that Mr. Bader entered into an agreement or understanding with others, you are instructed that the [g]overnment need not show that the people involved had any formal or written agreement nor that they specifically discussed among themselves what the purpose or details of the agreement would be or the means by which it would be accomplished.). (ii) Knowingly Unlawful Distribution -47- The government also established that Mr. Bader knew that the purpose of the agreement was to unlawfully distribute testosterone cypionate. Id. at 2178 (emphasis added). At trial, the jury was instructed that [w]ith regard to whether any distribution or possession with intent to distribute testosterone cypionate by Mr. Bader was unlawful, it was to consider whether the government had shown that Mr. Bader either knew that he was distributing or possessing with intent to distribute the testosterone cypionate without a valid prescription by a medical practitioner or knew that the prescription he was filling was issued without a valid medical purpose. Id. at 217879. As Mr. Ruth and others testified, Mr. Bader knew that he was distributing testosterone to Peak Physique and other clinics for anti-aging and body-building purposes. Furthermore, particularly in light of Mr. Ruths concession that he knew that anti-aging was not a valid medical purpose, id. at 2179, a reasonable jury could have easily inferred that a reasonable pharmacist acting in good faith, id. at 2173, would have known that these were unlawful uses. Thus, the government also satisfied its burden of proof regarding element two of the testosterone-conspiracy charge. Accordingly, construing the evidence in the light most favorable to the government, a reasonable jury could have convicted Mr. Bader of conspiracy to distribute and to possess with the intent to distribute testosterone cypionate. C. Prosecutorial Misconduct Mr. Bader claims that the government committed prosecutorial misconduct -48- when it prosecuted him for importation of HGH contrary to law in spite of the district courts purported pretrial ruling that the imported Genescience HGH was an API as opposed to a finished drug. In so doing, he argues that the prosecution intentionally misled th[e] jury to convict on an unfounded legal basisthat is, he was prosecuted on the basis of no legally cognizable evidence. Aplt. Reply Br. at 15 (emphasis removed); see United States v. Farinella, 558 F.3d 695, 70001 (7th Cir. 2009) (reversing a defendants conviction where the prosecutor committed egregious misconduct in failing to present any evidence that the defendant violated any federal law or FDA regulation). 17 Because he raises it for the first time on appeal, we review Mr. Baders prosecutorial-misconduct 17 contention for plain error. See, e.g., United States v. Sands, 968 F.2d 1058, 1063 (10th Cir. 1992). We use a two-step process when evaluating claims of prosecutorial misconduct. First, we examine whether the conduct was, in fact, improper. If we answer that question in the affirmative, we must then determine whether it warrants reversal. United States v. Oberle, 136 F.3d 1414, 1421 (10th Cir. 1998). When evaluating allegedly inappropriate remarks of counsel for plain error, we must view the remarks in the context of the entire trial. Id. (quoting Sands, 968 F.2d at 106364) (internal quotation marks omitted). Thus, [t]he relevant question is whether the prosecutors)). Applying these standards to the facts before us here, it is patent that Mr. Baders allegations fall short. Mr. Baders argument fails, in part, because it is premised upon a misreading of the record. Though Mr. Bader insists that the district court concluded pretrial that the imported [HGH] undisputedly was API, Aplt. Opening Br. at 19, actually the court made no such determination. As discussed above, the government alleged that Mr. Bader had represented to FDA officials that the Genescience HGH was an ingredient in order to successfully (but unlawfully) smuggle it into the United States. Aplt. App., Vol. VI, Tr. at 1778 -50- implicates due process concerns under the Fifth and Fourteenth Amendments. United States v. Nichols, 21 F.3d 1016, 1018 (10th Cir. 1994). In order to establish an entrapment-by-estoppel defense, a defendant must prove: (1) that there was an active misleading by a government agent; (2) that the defendant actually relied upon the agents representation, which was reasonable in light of the identity of the agent, the point of law misrepresented, and the substance of the misrepresentation; and (3) that the government agent is one who is responsible for interpreting, administering, or enforcing the law defining the offense. United States v. Apperson, 441 F.3d 1162, 120405 (10th Cir. 2006) (quoting United States v. Hardridge, 379 F.3d 1188, 1192 (10th Cir. 2004)) (internal quotation marks omitted). To the extent that Mr. Bader premises his estoppel claim upon federal court decisions, it fails at the outset. While this circuit has yet to explicitly address whether a courts ruling can give rise to a claim of estoppel, 19 the law is clear that 19 19 (...continued) conviction under federal law); United States v. Etheridge, 932 F.2d 318, 321 (4th Cir. 1991) (noting that no defense of entrapment by estoppel could be established where the government that advises and the government that prosecutes are not the same) (quoting United States v. Bruscantini, 761 F.2d 640, 64142 (11th Cir. 1985)) (internal quotation marks omitted)); see also Bruscantini, 761 F.2d at 64142 (explaining that the entrapment problem is different where state officials provided the legal interpretation upon which the defendant relied, but his conviction was based upon federal law), abrogated on other grounds by United States v. Fernandez, 234 F.3d 1345, 1347 n.2 (11th Cir. 2000). As Mr. Bader asserts no such reliance upon a state court decision, these cases do not provide an answer for the question posed by Mr. Baders argument. -54- one of the Apperson inquiry. See Apperson, 441 F.3d at 1204. Mr. Bader presents no evidence that any government official made any sort of active[ly] misleading statement with regard to the FDAMA; even if he had, his argument would be based upon a faulty premise. As the district court explained in its order denying Mr. Baders motion to dismiss, the FDAMA is material to this case only as a defense belonging to Mr. Bader. Aplee. App., Vol. IV, at 1060 (emphasis removed). Under the FDAMA, 21 U.S.C. 353a(a), a licensed pharmacist is exempt from federal liability where he compounds a drug product for an identified individual patient based on the unsolicited receipt of a valid prescription order or a notation, provided that certain conditions are met, id. The FDAMA therefore presents an affirmative defense that Mr. Bader might have asserted, not a charge that the government impermissibly sought. Thus, if anything, the FDAMA could have worked to Mr. Baders advantagean advantage that was precluded by Mr. Baders repeated averments that the FDAMA had no bearing upon his case. See Aplee. App., Vol. I, Tr. at 12. As Mr. Bader offers no evidence of active misleadinglet alone evidence of such conduct that might have prejudiced him at trialhis entrapment-by-estoppel claim is without merit. As for Mr. Baders argument that due process confusion precluded [his] conviction, Aplt. Opening Br. at 39, although it is not entirely clear, Mr. Bader appears to argue that the confusion rendered in the wake of Western States and -55- Medical Center Pharmacy failed to place him on notice that his compounding of HGH was subject to FDA oversight. In this regard, Mr. Bader asserts that [t]he courts told him [that] his pharmacy was compounding legally, id. at 37, and, based upon his survey of the legal landscape, he followed State law, the only law he knew to be applicable, id. at 39. This argument is misguided. With regard to Western States, by its terms, the Courts decision merely invalidated the FDAMAs speech-related provisions as they related to advertising; it did not address the FDAMAs substantive exemptions and accompanying restrictions with respect to compounding. See 535 U.S. at 366, 377. Therefore, Mr. Bader could not have divined from the text of Western States that his compounding activities were free from substantive FDA regulation. 20 20 20 (...continued) compounding both before Western Statesas ultimately defined and restricted by the FDAMA, cf. Food and Drug, supra, 13.74, at 194 (noting that no FDAMAdescribed safe harbor would have been necessary if the FDA indeed [previously] lacked the power to regulate compounded drugs)and after Western States. However, following Western States the agency recognize[d] the need for immediate guidance on what types of compounding might be subject to enforcement action under current law, and it indicated that its principal focus would be on the situation when the scope and nature of a pharmacys activities raise the kinds of concerns normally associated with a drug manufacturer. CPG 460.200 (emphasis added). In that regard, among other things, the FDA would consider whether the pharmacy was involved in [c]ompounding of drugs in anticipation of receiving prescriptions, except in very limited quantities in relation to the amounts of drugs compounded after receiving valid prescriptions. Id. (emphasis added). As the Third Circuit noted: [W]e agree that the FDAs reliance on the apparent volume of compounding is a reasonable means of determining whether that pharmacy is compounding in the regular course of its business of dispensing or selling drugs or devices at retail. Indeed, were we to adopt Wedgewoods. Wedgewood Vill. Pharmacy, Inc. v. United States, 421 F.3d 263, 274 (3d Cir. 2005) (internal quotation marks omitted); accord Food and Drug, supra, 13:74, at 13-95 (3d ed. 2007). As we further explicate infra, Mr. Bader and College Pharmacy were involved in the large-scale preparation and marketing of dosages of HGH. Consequently, even taking into account the FDAs arguably broad reading of the substantive impact of Western States, Mr. Bader still would have had fair warningas it related at least to his pharmacy businessof the possibility of FDA regulatory oversight. Moreover, viewed from another perspective, Mr. Bader has repeatedly discounted the effect of this specific policy provisionCPG 460.200noting that it is nonbinding and not law or proper for instruction. Aplt. Opening Br. (continued...) -57- 20 (...continued) at 7 n.11; see id. at 38 (noting that the [compliance policy guidance] CPG admittedly is not law and may not be instructed). In this regard, he has cited Professionals and Patients for Customized Care v. Shalala, 56 F.3d 592, 597, 602 (5th Cir. 1995) (holding that Compliance Guidance Manual provision relating to whether pharmacies were engaged in drug manufacturing did not establish binding norms). As a consequence, Mr. Bader is not well-situated now to contend that this policy guidance had placed a gloss on Western States that muddied the waters concerning the FDAs substantive regulatory authority over compounding. Furthermore, insofar as Mr. Baders argument focuses on whether the FDAMAs specific substantive provisions related to compounding remained viable after Western States, Mr. Bader would be hard-pressed to claim prejudice resulting from any lack of notice concerning the state of the law because he has expressly declined to avail himself of a statutory FDAMA defense to justify his compounding activities. See, e.g., Aplee. Supp. App., Vol. I, at 12. In light of his large-scale preparation and marketing of HGH doses this declination is not entirely surprising. See 21 U.S.C. 353a(a)(2); Aplee Br. at 40 (Defendants waiver [of a FDAMA compounding defense] is consistent with the knowledge that, even if the FDAMA was viable, the evidence did not support its applicability to the instant case.). -58- implicates new drug approval under the FDA and, as discussed above, those charges concern only the imported Genescience HGH as it existed before it was compounded by College Pharmacy. Consequently, Medical Center Pharmacy is inapposite. Moreover, as the district court correctly concluded, Mr. Bader misreads Medical Center Pharmacys actual holding. In Medical Center Pharmacy, the court found that subsections (a) and (c) of the FDAMA, 21 U.S.C. 353a, were severable from the remainder of 353a; consequently, pharmacies were still obligated to comply with subsection (b)s requirements for compounded drugs. 451 F. Supp. 2d at 863. In other words, the courts decision can be read as concluding that only drugs compounded in compliance with the restrictions set forth in [the] FDAMA fall outside [of] FDA regulation and the NDA process. Aplt. App., Vol. II, at 559 (emphasis removed). Furthermore, this exemption for compounded drugs from the new drug definition [was] limited to compounds which are made in reasonable quantities upon receipt of a valid prescription for an individual patient from a licensed practitioner. 451 F. Supp. 2d. at 863 (emphases added). Indeed, the Medical Center Pharmacy court clarified that [d]rugs that are compounded in large quantities before a prescription is received from a doctor do not fall within [this] narrow exemption. Id. It is clear from the record that Mr. Baders large-scale HGH compilation method fell outside the protective scope of this exemption. -59- obligated to completely disregard evidence that the defendant had a good faith misunderstanding of the applicable tax laws. Id. Here, in contrast, the district court merely (and permissibly) limited the scope of defense counsels questioning on account of counsels repeated attempts to surreptitiously introduce a legal definition of compounding that would favor Mr. Bader. See Aplt. Trial Tr. App., Vol. IV, at 962 (Im . . . going to instruct the jury that this witness[s] understanding of what compounding is[,] is not a legal definition of compounding and therefore they should not understand it as such.). This in no way ran afoul of the Sixth Amendment, nor did it prevent Mr. Bader from otherwise attempting to introduce a defense as to his understanding of the law at the time of the allegedly illegal conduct. Accordingly, we conclude that Cheek is inapposite, and that Mr. Baders unsupported second claim is entirely without merit. E. Alleged Evidentiary Errors Alternatively, Mr. Bader alleges that he should at least be afforded a new trial on account of various evidentiary objections that the government made and that the district court ruled upon. First, Mr. Bader asserts that the government impermissibly and excessively objected to much of the evidence that the defense offered, particularly that relating to the FDAs approval of the HGH shipments as an API, College Pharmacy employees understanding of the meaning of compounding, FDA import alerts distinguishing between API and finished HGH, and test results regarding the HGH that was seized from College Pharmacy. -62- Mr. Bader apparently claims that the governments frequent objections somehow amounted to prosecutorial misconduct. Because he failed to challenge these objections at trial, we review for plain error. Sands, 968 F.2d at 1063. It is clear that there was nothing improper about the governments objections, nor has Mr. Bader fashioned any argument as to how we might construe them as such. See Oberle, 136 F.3d at 1421. Each of the objections that Mr. Bader contests was grounded in the Federal Rules of Evidence, and each was entirely consistent with the governments overarching theory of the caseviz., that the imported HGH was a finished drug, not an API. In raising these objections, the government merely upheld its obligation to zealously advocate for its position, and the district court certainly did not clearly or obviously err by permitting the objections. 21 Accordingly, we need not further consider Mr. Baders unsubstantiated allegations regarding this matter. Second, Mr. Bader argues that the district court erred in sustaining the 21 gutted with regard to Mr. Baders HGH claims if the court were to adopt the compounding definition that he proffered. 22 Aplt. App., Vol. VIII, Tr. at 2570. The government, in opposing Mr. Baders request, argued that its prior admission should be excluded under Federal Rule of Evidence 403, particularly 22 Prior to trial, the government filed a motion asking the district court to reconsider its decision to issue a jury instruction on the Colorado definition of compounding and, in the alternative, to dismiss counts one through fifteen, seventeen, and twenty through forty-three of the Second Superseding Indictmenti.e., those counts related to conspiracy to facilitate the sale of illegally imported HGH, distribution of HGH, facilitating the sale of illegally imported HGH, possession with intent to distribute HGH, and distribution of HGH to minors. In that motion, the government conceded that the [c]ourts proposed definition of compounding substantially undermine[d] the [g]overnments theory of criminal liability in the [HGH] related counts, and therefore asked that, in the interest of judicial economy, the HGH counts be dismissed in the event that the court still planned to instruct the jury as to the definition of compounding under Colorado law. Aplt. App., Vol. II, at 495 (Govts Mot. to Reconsider & in the Alternative Mot. to Dismiss, dated Apr. 14, 2009) (emphasis added). In disposing of that motion, the court confirmed that it would instruct the jury according to Colorado law, but amended that instruction slightly such that the jury would be instructed in two phases: (i) that compounding is defined according to the terms of Colorado law as set forth in [Colo. Rev. Stat.] 1222102(6); and (ii) that a drug that is otherwise compounded according to that definition may still be subject to NDA requirements and other regulatory burdens if it runs afoul of the terms of the [FDAs 2002] CPG/FDAMA. Id. at 566. Observing that the governments position might be different on the basis of the courts conclusion that both the state definition of compounding and the provisions of the CPG/FDAMA can apply simultaneously, the court declined to assume that its (re-)adoption of the Colorado definition of compounding compel[led] dismissal of any Counts at that time. Id. at 567. Of course, these determinations were voided by the courts subsequent conclusion that the definition of compoundingunder Colorado lawhad no bearing upon Mr. Baders case. See Aplee. App., Vol. IV, at 1256 (With the benefit of hindsight and a full trial record, the Court now recognizes that nearly all of the briefing, discussion and analysis of compounding was an unnecessary digression.). -65- since the alleged admission arose out of the governments pretrial motion to dismissa motion that it had no occasion to pursue because the district court favorably shifted its position on the need to instruct the jury concerning Colorados compounding laws. Id. at 2571. Mr. Bader presents no argument as to how the district courts decision to deny Mr. Baders request to admit the governments statement constitutes an abuse of discretion; indeed, it was entirely possibleand, in fact, probablethat the admission of the statement would have confused the jury and proved to be unfairly prejudicial to the government. Accordingly, because Mr. Bader has provided no persuasive argument pertaining to any of the alleged evidentiary errors, he has presented no basis upon which we might grant him a new trial. F. Forfeiture Finally, Mr. Bader challenges the district courts $4.8 million forfeiture order, renewing his argument that the calculated amount was improperly based upon aggregated [HGH] sales rather than properly limit[ed] . . . to proceeds constitut[ing] or derived from a crime. Aplt. Opening Br. at 67 (third alteration in original). Additionally, Mr. Bader argues that the court erroneously failed to reduce the forfeiture amount to account for (1) the HGH seized and retained by the government, and (2) the HGH attributable to the counts for which -66- 24 that this $4.8 million figure excluded College Pharmacys lawful sales of commercially-produced, NDA[-]approved HGH, such as Saizen and Norditropin. Id., Vol. IV, at 1275 (emphasis altered); see id., Vol. II, at 440 (SA Hermsen testifying about a separate log that exclusively recorded the sales of the illegally imported HGH). To be sure, the district court correctly suggested that the Second Superseding Indictment charged Mr. Bader with violating other statutes that, in appropriate circumstances, may support a forfeiture judgment. 25 See id., Vol. IV, at 1273 (noting that [e]ach of the counts of conviction in this case give[s] rise to a claim for forfeiture, albeit through varying statutory routes). Furthermore, the district courts instructions and verdict formto which Mr. Bader did not lodge an objectiondid not ask the jury to attach its forfeiture finding to any particular counts of the Second Superseding Indictment. Instead, these documents only obliged the jury to determine whether Mr. Bader had obtained [as proceeds] 25 directly or indirectly as a result of the crime(s) for which [it] found [him] guilty the sum of $4.8 million. Aplt. App., Vol. IV, at 1196. (Jury Verdict Form, dated Feb. 2, 2010) (emphasis added); accord id., Vol. VIII, at 274950 (Jury Instruction No. 41); cf. Aplee. App., Vol. IV, at 1040 (seeking [a] sum of money equal to $4,800,000 in United States Currency, representing the amount of proceeds obtained as a result of the offenses in Counts One through Seventeen, and Nineteenviz., proceeds obtained pursuant to the charges of knowing facilitation of the sale of illegally imported HGH, conspiracy to do so, mail fraud, distribution of HGH, and conspiracy to distribute and to possess with the intent to distribute testosterone cypionate (emphasis added)). Yet, given the current posture of this caseinvolving our reversal of the 545-related HGH countswe are reluctant to speak definitively regarding the precise amount (if any) of proceeds that properly may be attributed to the other (i.e., non- 545) counts of the Second Superseding Indictment for purposes of adjudging the forfeiture amount. 26 Cf. Asset Forfeiture Law, supra, 15-3(a), at 47677 ([A] defendant may be acquitted on one offense and yet be convicted on 26 another that gives rise to the forfeiture of the same property. In that case, the forfeiture would survive the acquittal (or the reversal of the conviction) on the first offense because it would have an independent basis.). First, our analysis might be rendered of little or no effect, if the government elects upon remand to retry Mr. Bader on Counts One and Seventeen (i.e., the 545-related counts) and he is convicted again. Then, 545 would again be a viable basis on which to rest a forfeiture award. And, second, we do not have the benefit of the parties briefing on the implications of our reversal of the 545-related counts with regard to the precise amount of the forfeiture judgment that is legally authorized based on the remaining convictions. Of course, that is not surprising because it is only through this opinion that we effectuate our reversals. However, the reversals do raise serious questions. As noted, the district court relied in its forfeiture analysis on the testimony of SA Hermsen concerning the aggregate amount of the HGH sales during a time period beginning shortly after the start of the charged 545-related conspiracy and concluding at the end of the conspiracy. Agent Hermsen testified that those sales totaled $4.8 million. Let us assume, however, that Mr. Bader only may be held accountable in monetary forfeiture under the Second Superseding Indictment for all of the unlawful HGH sales identified by the government, because of his 545-related conspiracy charge, which sweeps broadly enough to encompasses those sales. -75- See, e.g., Capoccia, 503 F.3d at 11718 (Where the conviction itself is for executing a scheme, engaging in a conspiracy, or conducting a racketeering enterprise, the government need only establish that the forfeited assets have the requisite nexus to that scheme, conspiracy, or enterprise. (emphasis added) (citation omitted) (quoting Fed. R. Crim. P. 32.2(b)(1))); Asset Forfeiture Law, supra, 15-3(a), at 477 ([I]f the defendant is convicted of an over-arching conspiracy offense, he may be ordered to forfeit all property involved in the conspiracy, including property involved in substantive conduct that is not charged in the indictment or on which the defendant was acquitted. (emphasis added)). Put another way, let us assume that proceeds from uncharged discrete acts of facilitating the sale of illegally imported HGH may not be considered in determining the total monetary proceeds subject to forfeiture. See Asset Forfeiture Law, supra, 15-3(b), at 478 (Because forfeiture is part of the defendants sentence for committing a given offense, the criminal forfeiture is limited to the property involved in that offense. (emphases added)). In this event, even assuming that some of the remaining counts of conviction (e.g., involving 21 U.S.C. 333(e) or 21 U.S.C. 846) would yield forfeitable proceeds, what would be the proper amount of those proceeds? The district courts analysis does not offer an answer, nor have the parties addressed the matter before us. We are disinclined to answer such complex questions without input from -76- the parties or the district court. The district court is better equipped to entertain the parties arguments; if necessary, consider additional evidence; and to resolve such questions in the first instance. In sum, given our reversal of Mr. Baders 545-related convictions, we think it the prudent course to allow the district court in the first instance to speak to the precise amount (if any) of the forfeiture judgment that is legally authorized in this case. III. CONCLUSION For the foregoing reasons, we AFFIRM Mr. Baders convictions for discrete distributions of HGH (Counts Twelve through Fifteen, and Count Twenty), and conspiracy to distribute and to possess with intent to distribute testosterone cypionate, i.e., anabolic steroids (Count Nineteen); REVERSE his convictions for knowingly facilitating the sale of illegally imported HGH and for conspiring to do so (Counts Seventeen and One, respectively); and REMAND Mr. Baders case to the district court with instructions to VACATE its judgment and sentence, and to conduct further proceedings consistent with this opinion. -77-
https://it.scribd.com/document/317655348/United-States-v-Bader-678-F-3d-858-10th-Cir-2012
CC-MAIN-2021-04
refinedweb
12,247
55.13
snitfaq man page snitfaq — Snit Frequently Asked Questions Description Overview What is This Document?. What is Snit? Snit is a framework for defining abstract data types and megawidgets in pure Tcl. The name "Snit".. What Version of Tcl Does Snit Require? Snit 1.3 requires Tcl 8.3 or later; Snit 2.2 requires Tcl 8.5 or later. See Snit Versions for the differences between Snit 1.3 and Snit 2.2. Where Can I Download Snit? Snit is part of Tcllib, the standard Tcl library, so you might already have it. It's also available at the Snit Home Page,. What Are Snit's Goals? -. How is Snit Different from Other Oo Frameworks?. What Can I Do with Snit? Using Snit, a programmer can: -. Snit Versions Which Version of Snit Should I Use?. How Do I Select the Version of Snit I Want to Use?. How Are Snit 1.3 and Snit 2.2 Incompatible?. Are There Other Differences Between Snit 1.X and Snit 2.2?. Objects What is an Object?. What is an Abstract Data Type? In computer science terms, an abstract data type is a complex data structure along with a set of operations--a stack, a queue, a binary tree, etc--that is to say, in modern terms, an object. In systems that: #. What Kinds of Abstract Data Types Does Snit Provide? Snit allows you to define three kinds of abstract data type: - snit::type - snit::widget - snit::widgetadaptor What is a Snit::Type?. % snit::type dog { # ... } ::dog % This definition defines a new command (::dog, in this case) that can be used to define dog objects. An instance of a snit::type can have Instance Methods, Instance Variables, Options, and Components. The type itself can have Type Methods, Type Variables, Type Components, and Procs. What is a Snit::Widget?, the Short Story A snit::widget is a Tk megawidget built using Snit; it is very similar to a snit::type. See Widgets. What is a Snit::Widgetadaptor?, the Short Story A snit::widgetadaptor uses Snit to wrap an existing widget type (e.g., a Tk label), modifying its interface to a lesser or greater extent. It is very similar to a snit::widget. See Widget Adaptors. How Do I Create an Instance of a Snit::Type? You create an instance of a snit::type by passing the new instance's name to the type's create method. In the following example, we create a dog object called spot. %. % How Do I Refer to an Object Indirectly?. How Can I Generate the Object. % Can Types Be Renamed?. Can Objects Be Renamed?: -. How Do I Destroy a Snit Object?" % Instance Methods What is an Instance Method? An instance method is a procedure associated with a specific object and called as a subcommand of the object's command. It is given free access to all of the object's type variables, instance variables, and so forth. How Do I Define an Instance Method? Instance methods are defined in the type definition using the method statement. Consider the following code that might be used to add dogs to a computer simulation: % snit::type dog { method bark {} { return "$self barks." } method chase {thing} { return "$self chases $thing." } } ::dog %.) How Does a Client Call an Instance Method? The method name becomes a subcommand of the object. For example, let's put a simulated dog through its paces: % dog spot ::spot % spot bark ::spot barks. % spot chase cat ::spot chases cat. % How Does an Instance Method Call Another Instance Method?: % snit::type dog { method bark {} { return "$self barks." } method chase {thing} { return "$self chases $thing. [$self bark]" } } ::dog % dog spot ::spot % spot bark ::spot barks. % spot chase cat ::spot chases cat. ::spot barks. % Are There Any Limitations on Instance Method Names? Not really, so long as you avoid the standard instance method names: configure, configurelist, cget, destroy, and info. Also, method names consisting of multiple words define hierarchical methods. What is a Hierarchical Method?. How Do I Define a Hierarchical Method?. How Do I Call Hierarchical Methods? As subcommands of subcommands. % mytext .text .text % .text tag configure redtext -foreground red -background black % .text tag cget redtext -foreground red % How Do I Make an Instance Method Private?: % snit::type dog { # Private by convention: begins with uppercase letter. method Bark {} { return "$self barks." } method chase {thing} { return "$self chases $thing. [$self Bark]" } } ::dog % dog fido ::fido % fido chase cat ::fido chases cat. ::fido barks. % Are There Any Limitations on Instance Method Arguments?. What Implicit Arguments Are Passed to Each Instance Method? The arguments implicitly passed to every method are type, selfns, win, and self. What is $Type? The implicit argument type contains the fully qualified name of the object's type: % snit::type thing { method mytype {} { return $type } } ::thing % thing something ::something % something mytype ::thing % What is $Self? % What is $Selfns? % The above example reveals how Snit names an instance's private namespace; however, you should not write code that depends on the specific naming convention, as it might change in future releases. What is $Win?. How Do I Pass an Instance Method As a Callback? It depends on the context. Suppose in my application I have a dog object named fido, and I want fido to bark when a Tk button called .bark is pressed. In this case, I create the callback command in the usual way, using list:. How Do I Delegate Instance Methods to a Component? See Delegation. Instance Variables What is an Instance Variable? An instance variable is a private variable associated with some particular Snit object. Instance variables can be scalars or arrays. How is a Scalar Instance Variable Defined? Scalar instance variables are defined in the type definition using the variable statement. You can simply name it, or you can initialize it with a value: snit::type mytype { # Define variable "greeting" and initialize it with "Howdy!" variable greeting "Howdy!" } How is an Array Instance Variable Defined? Array instance variables are also defined in the type definition using the variable command. You can initialize them at the same time by specifying the -array option: snit::type mytype { # Define array variable "greetings" variable greetings -array { formal "Good Evening" casual "Howdy!" } } What Happens if I Don't Initialize an Instance Variable? Variables do not really exist until they are given values. If you do not initialize a variable when you define it, then you must be sure to assign a value to it (in the constructor, say, or in some method) before you reference it. Are There Any Limitations on Instance Variable Names?. Do I Need to Declare My Instance Variables in My Methods?.. How Do I Pass an Instance: snit::widget mywidget { variable labeltext "" constructor {args} { # ... label $win.label -textvariable [myvar labeltext] # ... } } How Do I Make an Instance Variable Public? Practically speaking, you don't. Instead, you'll implement public variables as Options. Alternatively, you can write Instance Methods to set and get the variable's value. Options What is an Option?. How Do I Define an Option? Options are defined in the type definition using the option statement. Consider the following type, to be used in an application that manages a list of dogs for a pet store: snit::type dog { option -breed -default mongrel option -color -default brown option -akc -default 0 option -shots -default 0 }: snit::type dog { option -breed mongrel option -color brown option -akc 0 option -shots 0 } If no -default value is specified, the option's default value will be the empty string (but see The TK Option Database). The Snit man page refers to options like these as "locally defined" options. How Can a Client Set Options at Object Creation?. % dog spot -breed beagle -color "mottled" -akc 1 -shots 1 ::spot % dog fido -shots 1 ::fido %. How Can a Client Retrieve an Option's Value? Retrieve option values using the cget method: % spot cget -color mottled % fido cget -breed mongrel % How Can a Client Set Options After Object Creation?. How Should an Instance Method Access an Option Value?. How Can I Make an Option Read-Only?, % How Can I Catch Accesses to an Option's Value? Define a -cgetmethod for the option. What is a -cgetmethod?: snit::type dog { option -color -default brown -cgetmethod GetOption method GetOption {option} { return $options($option) } } Any instance method can be used, provided that it takes one argument, the name of the option whose value is to be retrieved. How Can I Catch Changes to an Option's Value? Define a -configuremethod for the option. What is a -configuremethod?: snit::type dog { option -color -default brown -configuremethod SetOption method SetOption {option value} { set options($option) $value } } Any instance method can be used, provided that it takes two arguments, the name of the option and the new value. Note that if your method doesn't store the value in the options array, the options array won't get updated. How Can I Validate an Option's Value? Define a -validatemethod. What is: %" % Note that the same -validatemethod can be used to validate any number of boolean options. Any method can be a -validatemethod provided that it takes two arguments, the option name and the new option value. Type Variables What is a Type Variable? A type variable is a private variable associated with a Snit type rather than with a particular instance of the type. In C++ and Java, the term static member variable is used for the same notion. Type variables can be scalars or arrays. How is a Scalar Type Variable Defined? Scalar type variables are defined in the type definition using the typevariable statement. You can simply name it, or you can initialize it with a value: snit::type mytype { # Define variable "greeting" and initialize it with "Howdy!" typevariable greeting "Howdy!" } Every object of type mytype now has access to a single variable called greeting. How is an Array-Valued Type Variable Defined? Array-valued type variables are also defined using the typevariable command; to initialize them, include the -array option: snit::type mytype { # Define typearray variable "greetings" typevariable greetings -array { formal "Good Evening" casual "Howdy!" } } What Happens if I Don't Initialize a Type Variable? Variables do not really exist until they are given values. If you do not initialize a variable when you define it, then you must be sure to assign a value to it (in the type constructor, say) before you reference it. Are There Any Limitations on Type Variable Names? Type variable names have the same restrictions as the names of Instance Variables do. Do I Need to Declare My Type Variables in My Methods? No. Once you've defined a type variable in the type definition, it can be used in Instance Methods or Type Methods without declaration. This differs from normal Tcl practice, in which all non-local variables in a proc need to be declared. Type variables are subject to the same speed/readability tradeoffs as instance variables; see Do I need to declare my instance variables in my methods? How Do I Pass a Type: snit::widget mywidget { typevariable labeltext "" constructor {args} { # ... label $win.label -textvariable [mytypevar labeltext] # ... } } How Do I Make a Type Variable Public?, snit::type mytype { typevariable myvariable } set ::mytype::myvariable "New Value" Type Methods What is a Type Method? A type method is a procedure associated with the type itself rather than with any specific instance of the type, and called as a subcommand of the type command. How Do I Define a Type Method? Type methods are defined in the type definition using the typemethod statement: snit::type dog { # List of pedigreed dogs typevariable pedigreed typemethod pedigreedDogs {} { return $pedigreed } }. How Does a Client Call a Type Method? The type method name becomes a subcommand of the type's command. For example, assuming that the constructor adds each pedigreed dog to the list of pedigreedDogs, snit::type dog { option -pedigreed 0 # List of pedigreed dogs typevariable pedigreed typemethod pedigreedDogs {} { return $pedigreed } # ... } dog spot -pedigreed 1 dog fido foreach dog [dog pedigreedDogs] { ... } Are There Any Limitations on Type Method Names? Not really, so long as you avoid the standard type method names: create, destroy, and info. How Do I Make a Type Method Private?. Are There Any Limitations on Type Method Arguments?. How Does an Instance or Type Method Call a Type Method? If an instance or type method needs to call a type method, it should use $type to do so: snit::type dog { typemethod pedigreedDogs {} { ... } typemethod printPedigrees {} { foreach obj [$type pedigreedDogs] { ... } } } How Do I Pass a Type Method As a Callback?: button .btn -text "Pedigrees" -command [list dog printPedigrees] pack .btn Alternatively, from a method or type method you can use the mytypemethod command, just as you would use mymethod to define a callback command for Instance Methods. Can Type Methods Be Hierarchical? Yes, you can define hierarchical type methods in just the same way as you can define hierarchical instance methods. See Instance Methods for more. Procs What is a Proc? A Snit proc is really just a Tcl proc defined within the type's namespace. You can use procs for private code that isn't related to any particular instance. How Do I Define a Proc? Procs are defined by including a proc statement in the type definition: snit::type mytype { # Pops and returns the first item from the list stored in the # listvar, updating the listvar proc pop {listvar} { ... } # ... } Are There Any Limitations on Proc Names?. How Does a Method Call a Proc? Just like it calls any Tcl command. For example, snit::type mytype { # Pops and returns the first item from the list stored in the # listvar, updating the listvar proc pop {listvar} { ... } variable requestQueue {} # Get one request from the queue and process it. method processRequest {} { set req [pop requestQueue] } } How Can I Pass a Proc to Another Object As a Callback? The myproc command returns a callback command for the proc, just as mymethod does for a method. Type Constructors What is a Type Constructor? A type constructor is a body of code that initializes the type as a whole, rather like a C++ static initializer. The body of a type constructor is executed once when the type is defined, and never again. A type can have at most one type constructor. How Do I Define a Type Constructor? A type constructor is defined by using the typeconstructor statement in the type definition. For example, suppose the type uses an array-valued type variable as a look-up table, and the values in the array have to be computed at start-up. % snit::type mytype { typevariable lookupTable typeconstructor { array set lookupTable {key value...} } } Constructors What is a Constructor?). How Do I Define a Constructor?. % % What Does the Default Constructor Do? If you don't provide a constructor explicitly, you get the default constructor, which is identical to the explicitly-defined constructor shown here: snit::type dog { constructor {args} { $self configurelist $args } }. Can I Choose a Different Set of Arguments for the Constructor? Yes, you can. For example, suppose we wanted to be sure that the breed was explicitly stated for every dog at creation time, and couldn't be changed thereafter. One way to do that is as follows: % The drawback is that this syntax is non-standard, and may limit the compatibility of your new type with other people's code. For example, Snit assumes that it can create Components using the standard creation syntax. Are There Any Limitations on Constructor Arguments? Constructor argument lists are subject to the same limitations as those on instance method argument lists. It has the same implicit arguments, and can contain default values and the args argument. Is There Anything Special About Writing the Constructor? Yes. Writing the constructor can be tricky if you're delegating options to components, and there are specific issues relating to snit::widgets and snit::widgetadaptors. See Delegation, Widgets, Widget Adaptors, and The TK Option Database. Destructors What is a Destructor? A destructor is a special kind of method that's called when an object is destroyed. It's responsible for doing any necessary clean-up when the object goes away: destroying Components, closing files, and so forth. How Do I Define a Destructor? Destructors are defined by using the destructor statement in the type definition. Suppose we're maintaining a list of pedigreed dogs; then we'll want to remove dogs from it when they are destroyed. } } Are There Any Limitations on Destructor Arguments? Yes; a destructor has no explicit arguments. What Implicit Arguments Are Passed to the Destructor? The destructor gets the same implicit arguments that are passed to Instance Methods: type, selfns, win, and self. Must Components Be Destroyed Explicitly?. Is There Any Special About Writing a. snit::type dog { component tail constructor {args} { $self configurelist $args set tail [tail %AUTO%] } destructor { catch {$tail destroy} } } Components What is a Component?.) How Do I Declare a Component?): snit::type dog { component mytail constructor {args} { # Create and save the component's command set mytail [tail %AUTO% -partof $self] $self configurelist $args } method wag {} { $mytail wag } } As shown here, it doesn't matter what the tail object's real name is; the dog object refers to it by its component name. The above example shows one way to delegate the wag method to the mytail component; see Delegation for an easier way. How is a Component Named?. Are There Any Limitations on Component Names? Yes. snit::widget and snit::widgetadaptor objects have a special component called the hull component; thus, the name hull should be used for no other purpose. Otherwise, since component names are in fact instance variable names they must follow the rules for Instance Variables. What is an Owned Component?: } }. What Does the Install Command Do? The install command creates an owned component using a specified command, and assigns the result to the component's instance variable. For example: snit::type dog { component mytail constructor {args} { # set mytail [tail %AUTO% -partof $self] install mytail using tail %AUTO% -partof $self $self configurelist $args } }. Must Owned Components Be Created in the Constructor? No, not necessarily. In fact, there's no reason why an object can't destroy and recreate a component multiple times over its own lifetime. Are There Any Limitations on Component Object Names?:. Must I Destroy the Components I Own?. Can I Expose a Component's Object Command As Part of My Interface?. How Do I Expose a Component's Object Command?: snit::widget combobox { component listbox -public listbox constructor {args} { install listbox using listbox $win.listbox .... } } combobox .mycombo .mycombo listbox configure -width 30. Type Components What is a Type Component?. How Do I Declare a Type Component?. snit::type veterinarian { ... } snit::type dog { typecomponent vet # ... } How Do I Install: snit::type veterinarian { ... } snit::type dog { typecomponent vet typeconstructor { set vet [veterinarian %AUTO%] } } Are There Any Limitations on Type Component Names? Yes, the same as on Instance Variables, Type Variables, and normal Components. Delegation What is Delegation?. } }. How Can I Delegate a Method to a Component Object?: % snit::type dog { delegate method wag to mytail constructor {} { install mytail using tail %AUTO% } } ::dog % snit::type tail { method wag {} { return "Wag, wag, wag."} } ::tail % dog spot ::spot % spot wag Wag, wag, wag.. Can I Delegate to a Method with a Different Name? Suppose you wanted to delegate the dog's wagtail method to the tail's wag method. After all you wag the tail, not the dog. It's easily done: snit::type dog { delegate method wagtail to mytail as wag constructor {args} { install mytail using tail %AUTO% -partof $self $self configurelist $args } } Can I Delegate to a Method with Additional Arguments?: snit::type dog { delegate method wagtail to mytail as {wag 3} # ... } snit::type tail { method wag {count} { return [string repeat "Wag " $count] } # ... } Can I Delegate a Method to Something Other Than an Object?: snit::type dog { delegate method save using {saverec %s} }). How Can I Delegate a Method to a Type Component Object? Just exactly as you would to a component object. The delegate method statement accepts both component and type component names in its to clause. How Can I Delegate a Type Method to a Type Component Object?. How Can I Delegate an Option to a Component Object?: % snit::type dog { delegate option -length to mytail constructor {args} { install mytail using tail %AUTO% -partof $self $self configurelist $args } } ::dog % snit::type tail { option -partof option -length 5 } ::tail % dog spot -length 7 ::spot % spot cget -length 7. Can I Delegate to an Option with a Different Name?: snit::type dog { delegate option -taillength to mytail as -length constructor {args} { set mytail [tail %AUTO% -partof $self] $self configurelist $args } } How Can I Delegate Any Unrecognized Method or Option to a Component Object?: snit::type dog { delegate option * to animal delegate method * to animal option -akc 0 constructor {args} { install animal using animal %AUTO% -name $self $self configurelist $args } method wag {} { return "$self wags its tail" } } *. How Can I Delegate All but Certain Methods or Options to a Component?:. Can a Hierarchical Method Be Delegated? # ... } Widgets What is a Snit::Widget?. How Do I Define a Snit::Widget? snit::widgets are defined using the snit::widget command, just as snit::types are defined by the snit::type command. The body of the definition can contain all of the same kinds of statements, plus a couple of others which will be mentioned below. How Do Snit::Widgets Differ from Snit::Types? -. What is a Hull Component? widget that defines the -class option. snit::widgetadaptors differ from snit::widgets chiefly in that any kind of widget can be used as the hull component; see Widget Adaptors. How Can I Set the Hull Type for a Snit::Widget? # ... } How Should I Name Widgets Which Are Components of a Snit::Widget?: snit::widget toolbar { delegate option * to hull constructor {args} { button $win.open -text Open -command [mymethod open] button $win.save -text Save -command [mymethod save] # .... $self configurelist $args } } See also the question on renaming objects, toward the top of this file. Widget Adaptors What is a Snit::Widgetadaptor?. How Do I Define a Snit::Widgetadaptor?. : }. Can I Adapt a Widget Created Elsewhere in the Program?: snit::widgetadaptor pageadaptor { constructor {args} { # The widget already exists; just install it. installhull $win # ... } } Can I Adapt Another Megawidget? What is the TK Option Database?. -. The interaction of Tk widgets with the option database is a complex thing; the interaction of Snit with the option database is even more so, and repays attention to detail. Do Snit::Types Use the TK Option Database?. What is My Snit::Widget's Widget snit::widget ::mylibrary::scrolledText { ... } is ScrolledText. The widget class can also be set explicitly using the widgetclass statement within the snit::widget definition: snit::widget ::mylibrary::scrolledText { widgetclass Text # ... } The above definition says that a scrolledText megawidget has the same widget class as an ordinary text widget. This might or might not be a good idea, depending on how the rest of the megawidget is defined, and how its options are delegated. What is My Snit::Widgetadaptor's Widget Class?. What Are Option Resource and Class Names?: -background background Background -borderwidth borderWidth BorderWidth -insertborderwidth insertBorderWidth BorderWidth -padx padX Pad As is easily seen, sometimes the resource and class names can be inferred from the option name, but not always. What Are the Resource and Class Names for My Megawidget's Options? For options implicitly delegated to a component using delegate option *, the resource and class names will be exactly those defined by the component. The configure method returns these names, along with the option's default and current values: % % How Does Snit Initialize My Megawidget's Locally-Defined Options?,". How Does Snit Initialize Delegated Options? That depends on whether the options are delegated to the hull, or to some other component. How Does Snit Initialize:]: delegate option {-borderwidth borderWidth BorderWidth} to hull: snit::widgetadaptor mywidget { # ... constructor {args} { # ... installhull using text -foreground white # ... } # ... } In this case, the installhull command will create the hull using a command like this: set hull [text $win -foreground white]: installhull [text $win -foreground white] This form still works--but Snit will not query the option database as described above. How Does Snit Initialize Options Delegated to Other Components?:. What Happens if I Install a Non-Widget As a Component of Widget?. Ensemble Commands What is an Ensemble Command?. How Can I Create an Ensemble Command Using Snit? There are two ways--as a snit::type, or as an instance of a snit::type. How Can I Create an Ensemble Command Using: snit::type ::mynamespace::mystringtype { delegate method * to stringhandler constructor {} { set stringhandler string } } ::mynamespace::mystringtype mystring info and destroy subcommands that you probably have no use for. But read on. How Can I Create an Ensemble Command Using a Snit::Type? } }: snit::type mystring { pragma -hastypeinfo no pragma -hastypedestroy no pragma -hasinstances no delegate typemethod * to stringhandler typeconstructor { set stringhandler string } }. Pragmas What is a Pragma? A pragma is an option you can set in your type definitions that affects how the type is defined and how it works once it is defined. How Do I Set a Pragma? Use the pragma statement. Each pragma is an option with a value; each time you use the pragma statement you can set one or more of them. How Can I Get Rid of the Info“ Type Method?” Set the -hastypeinfo pragma to no: snit::type dog { pragma -hastypeinfo no # ... } Snit will refrain from defining the info type method. How Can I Get Rid of the Destroy“ Type Method?” Set the -hastypedestroy pragma to no: snit::type dog { pragma -hastypedestroy no # ... } Snit will refrain from defining the destroy type method. How Can I Get Rid of the Create“ Type Method?” Set the -hasinstances pragma to no: snit::type dog { pragma -hasinstances). How Can I Get Rid of Type Methods Altogether?: snit::type dog { pragma -hastypemethods no #... } # Creates ::spot dog spot # Tries to create an instance called ::create dog create spot Pragmas -hastypemethods and -hasinstances cannot both be false (or there'd be nothing left). Why Can't I Create an Object That Replaces an Old Object with the Same Name? Up until Snit 0.95, you could use any name for an instance of a snit::type, even if the name was already in use by some other object or command. You could do the following, for example: snit::type dog { ... } dog proc: snit::type dog { pragma -canreplace yes # ... } How Can I Make My Simple Type Run Faster?. Macros What is a Macro? A Snit macro is nothing more than a Tcl proc that's defined in the Tcl interpreter used to compile Snit type definitions. What Are Macros Good for? You can use Snit macros to define new type definition syntax, and to support conditional compilation. How Do I Do: {} {...} } } How Do I Define New Type Definition Syntax?} } Are There Are Restrictions on Macro Names?: snit::macro mylib::propagate {option "to" components} { ... } snit::widget ::mylib::mywidget { option -background default -white option -foreground default -black mylib::propagate -background to {comp1 comp2 comp3} mylib::propagate -foreground to {comp1 comp2 comp3} } Bugs, Ideas, Feedback This document, and the package it describes, will undoubtedly contain bugs and other problems. Please report such in the category snit of the Tcllib Trackers []. Please also report any ideas for enhancements you may have for either package and/or documentation. Keywords BWidget, C++, Incr Tcl, adaptors, class, mega widget, object, object oriented, widget, widget adaptors Category Programming tools
https://www.mankier.com/n/snitfaq
CC-MAIN-2018-30
refinedweb
4,573
67.45
LPG Sensor Using Arduino Uno In the mood for a quick project? Learn how to create a gas sensor with Arduino Uno. Join the DZone community and get the full member experience.Join For Free in this article, i'll show you that how can we find out the lpg gas using the mq2 gas sensor and print the value in lcd. requirements - arduinomega. - bread board. - mq2 gas sensor. - lcd 16*2. - led. - buzzer. connection led - anode to digital pin 12. - cathode to ground. buzzer - anode pin to digital pin 10. - cathode pin to the ground. programming #include < liquidcrystal.h > int mq = a0; int led = 12; int buz = 10; int m; float p; liquidcrystal lcd(2, 3, 4, 5, 6, 7); void setup() { pinmode(led, output); pinmode(buz, output); digitalwrite(led, low); digitalwrite(buz, low); lcd.begin(16, 2); } void loop() { d = analogread(mq); lcd.setcursor(0, 0); lcd.print("lpg gas sensor"); if (m > 60) { p = 0; } else { p = (m - 60) / 9.64; } lcd.setcursor(0, 1); lcd.print(p); lcd.setcursor(5, 1); lcd.print("%"); if (p >= 30) { digitalwrite(led, low); digitalwrite(buz, high); lcd.setcursor(9, 1); lcd.print("little leakage"); } else { digitalwrite(led, high); digitalwrite(buz, low); } delay(500); lcd.clear(); } explanation - the gas sensor is connected to the analog input pin a0. - the digital pin 10 is used to control the buzzer. - the digital pin 12 is connected to the led. - if the gas sensor value is less than 60. - the buzzer and led are on. - displays the result in liquid crystal display. output Topics: iot app development, arduino Opinions expressed by DZone contributors are their own.
https://dzone.com/articles/lpg-sensor-using-arduino-uno
CC-MAIN-2021-39
refinedweb
272
70.6
Devel::VersionDump - Dump loaded module versions to the console 0.02 perl -MDevel::VersionDump your-script.pl use Devel::VersionDump; use Devel::VersionDump '-stderr'; use Devel::VersionDump qw(dump_versions); # later... dump_versions; This module prints a sorted list of modules used by your program to stdout. It does this by walking %INC in Perl's INIT phase. Tells the dumper to print to stderr instead of stdout. Exports the dump_versions function into the caller's namespace, and turns off the automatic printing in the INIT phase. Dumping versions is then achieved by calling dump_versions. Dumps versions to STDOUT or STDERR, depending on if '-stderr' was specified in import. Rob Hoelz <rob@hoelz.ro> Please report any bugs or feature requests to bug-Devel-VersionDump.
http://search.cpan.org/~rhoelz/Devel-VersionDump-0.02/lib/Devel/VersionDump.pm
CC-MAIN-2016-36
refinedweb
123
61.53
30 May 2008 19:51 [Source: ICIS news] TORONTO (ICIS news)--The US economy has not yet bottomed out and may worsen, Dow Chemical CEO Andrew Liveris said on Friday, describing the situation as ominous. ?xml:namespace> “A month ago we might have said … the ?xml:namespace> “I think we are in for a tough 2008 and maybe even a tougher 2009.” He described US economic conditions as ominous, and pointed to demand destruction on the consumer side because of mortgage and credit worries as well as rising costs of fuel and other products. Asked about Dow’s decision earlier this week to increase all its product prices by up to 20% effective 1 June to cope with rising oil and energy costs, Liveris said many customers actually welcomed the move as it helped their sales people, in turn, to push for higher product prices themselves. “Many of them are saying, ‘Thank you for the air cover.'” He spoke of a broad process of re-setting the chemical value chain to a high oil and energy price environment. In a televised media interview earlier on Friday, Liveris said he was not expecting quick Some 85% of Asked about his comment on the energy strategies of the 2008 But he added that “a sane energy policy” would need to incorporate climate
http://www.icis.com/Articles/2008/05/30/9128513/us-economy-ominous-may-worsen-dows-liveris.html
CC-MAIN-2014-10
refinedweb
220
61.19
in reply to use Very::Long::Module::Name as Foo; Sorry, but I prefer the existing solutions. In terms of complexity to use, all of the proposed solutions, including yours, are about equal. In terms of conceptual difficulty for a Perl programmer to figure out how they work under the hood, yours is significantly more complicated. In terms of avoiding possible conflicts between different modules making use of the feature, I prefer either putting the package name in a variable or a constant to anything that tramples over short global namespaces that other modules don't expect you to trample over. Also I like reserving source filtering for when it really buys a lot because I am afraid that, going forward, we will wind up with "interesting conflicts" because different source filters won't cooperate well with each other. (The heuristics which one uses to figure out what is going on don't take into account how the previous one altered Perl.) Traditional Perl modules have much lower odds of conflict. In fact a private theory of mine holds that one of the keys to what made CPAN work is that Perl didn't used to lend itself to customization, so code that worked for you probably works without many issues in my environment, and vice versa. This makes sharing easy. Compare, say, to a significant body of C code with heavy use of pre-processor definitions. I disagree with that. I think: use Very::Long::Module::Name as Foo; [download] use as qw(Very::Long::Module::Name Foo); # Package Alias approach [download] especially when it comes to parametrized uses. These would all work with my source filter: use Very::Long::Module::Name as Foo qw(foo bar baz); # import foo, bar + baz use Very::Long::Module::Name as Foo (); # don't import [download] ...conceptual difficulty for a Perl programmer to figure out how they work under the hood... I also disagree here. If you know about source filters, you will see that the filter is very simple. Creating the source filter involves some strange idioms, I agree, but I can't be blamed for that. And adding some more comments should take care of instructing any other Perl programmers who take a look under the hood. Traditional Perl modules have much lower odds of conflict. I agree. But I see the source filter merely as a means of achieving the end now, as a prototyping tool, rather than as the way to do such a thing in the long run. And so far nobody has commented on the API. So that at least feels right to the people who looked at this so far. I don't think there is a Perl 6 Apocalypse about this, is there? Liz Now... ;-) 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 (75 votes), past polls
http://www.perlmonks.org/?node_id=299116
CC-MAIN-2014-42
refinedweb
501
60.75
readlink, readlinkat - read the contents of a symbolic link relative to a directory file descriptor #include <unistd.h> ssize_t readlink(const char *restrict path, char *restrict buf, size_t bufsize); ssize_t readlinkat(int fd, mark for update the last data access timestamp of the symbolic link. The readlinkat() function shall be equivalent to the readlink() function except in the case where path specifies a relative path. In this case the symbolic link whose content is read readlinkat() is passed the special value AT_FDCWD in the fd parameter, the current working directory is used and the behavior shall be identical to a call to readlink(). Upon successful completion, readlink() shall return the count of bytes placed in the buffer. Otherwise, it shall return a value of -1, leave the buffer unchanged, and set errno to indicate the error. Upon successful completion, the readlinkat() function shall return 0. Otherwise, it shall return -1 and set errno to indicate the error. These functions. The read readlinkat() function may fail if: - [ENOTDIR] - The path argument is not an absolute path and fd is neither AT_FDCWD nor a file descriptor associated with a directory. POSIX.1-2008. The purpose of the readlinkat() function is to read the content of symbolic links in directories other than the current working directory without exposure to race conditions. Any part of the path of a file could be changed in parallel to a call to readlink(), resulting in unspecified behavior. By opening a file descriptor for the target directory and using the readlinkat() function it can be guaranteed that the symbolic link read is located relative to the desired directory. None. fstatat , symlink XBD ..
https://pubs.opengroup.org/onlinepubs/9699919799.2008edition/functions/readlinkat.html
CC-MAIN-2021-39
refinedweb
274
50.46
Jeff, Basemap methods like plot() include a "draw_if_interactive" command, followed by a call to the set_axes_limits() method, which ends with # force draw if in interactive mode. if is_interactive(): figManager = _pylab_helpers.Gcf.get_active() figManager.canvas.draw() It seems to me that you could eliminate all those "draw_if_interactive" blocks from plot etc., and replace the end block of set_axes_limits() with if is_interactive(): import matplotlib.pyplot as plt plt.draw_if_interactive() The advantages would be reduced clutter in the drawing methods, and consistent use of draw_if_interactive. I think the latter would make interactive running of functions and subclasses built on basemap more efficient by reducing redundant draw operations. It also looks like at least most of the operations in set_axes_limits really need to be done only once (although I have not checked this carefully). Instead of repeating them with every call to a plotting method, the basemap instance could keep a list of hashes of axes objects on which the operations have already been run, and use that to prevent duplication. Nothing urgent here--just some ideas that occur to me while working with basemap. If you think any are worth pursuing, and you want me to take a shot at it, let me know. Eric
https://discourse.matplotlib.org/t/duplicate-draw-operations-in-basemap/13488
CC-MAIN-2021-43
refinedweb
202
53.51
In this article, we will be looking at one of these new JavaScript frameworks, known as Svelte. Learn how to build a Bookstore App with Svelte. In the world of JavaScript, a new JavaScript. Which builds on the of the basic knowledge of HTML, CSS, and JavaScript, to give a unique and understandable approach to building platforms for the web. Before we go any further, this article assumes the following: Svelte is more understandable for those who are new to coding and it avoids getting lost in a world of hot reloads and components because it allows for application of DOM type manipulation. Svelte compiles all the generated files down to a single file (bundle.js). Svelte is a framework, meaning it doesn’t work with the virtual DOM but writes code that surgically updates the DOM when the state of your app changes. There are several ways to get Svelte up and running for a project. You can read more about the many ways to get started here. For the purpose of this article, we will be working with degit which is a software scaffolding tool. To start, run the following commands: npx degit sveltejs/template Book-app-svelte npm run dev After setting up, in the main.js , we should see a “hello world” that renders into the app.svelte – this would be a good time to note that components in Svelte are saved with .svelte extension. import App from './App.svelte'; const app = new App({ target: document.body, props: { name: 'world' } }); export default app; The above code shows a simple set-up with the app component accepting a prop of name and targets a place in the HTML file. In the app.svelte we can see some sort of VueJS format: <script> export let name; </script> <style> h1 { color: purple; } </style> <h1>Hello {name}!</h1> This is where the main.js gets handled by exporting the name variables to allow it to be manipulated from outside. When creating our components, there are a few things that are noteworthy about SvelteJS: h1styled in one component will not affect another in a different component In this section, we will be looking at creating a dynamic event with Svelte and linking the book.svelte component with app.svelte and passing props. The first step is setting up the book component and exporting variables which can be set from the parent tag in app.svelte: <script> export let bookTitle; export let bookPages; export let bookDescription; </script> <style> div{ margin: 1rem; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.26) } h1{ font-size: 1.25rem; margin: 0.25rem 0; } h2{ font-size: 1rem; margin: 0.25rem 0; color: aqua; } p{ margin: 0.25rem 0; } button{ font : larger; padding: 0.15rem 0.5rem; background-color: #1b1a1a; border: 1px solid aliceblue ; cursor: pointer; color: white; } </style> <div> <h1> {bookTitle} </h1> <h2> {bookPages}</h2> <p> {bookDescription}</p> <button> Add </button> </div> From the code block above, we can see that we have variables that are being dynamically passed to the tags in the div . They have their values coming from the app.svelte which we will see next and where most of the dynamic manipulations happen. In the app.svelte we have imported the book component and this is where we will do a lot of the dynamic manipulation. <script> import Book from './book.svelte' let title = ''; let pages = 0; let description = ''; function setTitle(event){ title = event.target.value; } </script> <style> h1 { color: purple; } section{ margin: auto; width :30rem; } label,input,textarea{width: 100%} </style> <section> <div> <label for="title">Title</label> <input type="text" id="title" value={title} on:input={setTitle}/> </div> <div> <label for="pages"> pages</label> <input type="number" id="price" value={pages} bind:value={pages}/> </div> <div> <label for="description">Description</label> <textarea rows="3" id="description" bind:value ={description}/> </div> </section> <Book bookTitle={title} bookPages={pages} bookDescription={description}/> From the code example above, we can see that inside our script tag, we have also set variables to empty “ ”. These are the values that are automatically updated, we can also notice a function setTitle , this function is used to set a title to target the object that calls it within the on:. Note that we call the function without parenthesis because we don’t want it immediately executed. Instead, we are trying to set up a refers so that Svelte can call the function on every keystroke. We use the on: to add event listeners in Svelte. We can use this to listen to the input event, and the curly braces are used to show dynamic input. Since the function we have uses two-way binding, we can use it on other tags using the bind: This binds the value property then binds to the price variable. We also do this for the description. Finally passing back to Book tag is the part where we update the props being exported in the book component. We do this by dynamically passing the values of title, pages, and descriptions using curly braces {}. Now that we have the card updating when we input value, the next step is to make sure that we are able to add books to our bookstore. The first thing we have to do is make our button a standalone component, in order to be able to use it in the other two components. We do this by creating a button.svelte and importing it to the book and app component respectively. <style> button{ font : larger; padding: 0.15rem 0.5rem; background-color: #1b1a1a; border: 1px solid aliceblue ; cursor: pointer; color: white; } </style> <button on:click > <slot/> </button> You might notice an on:click attribute in the button tag, this is used to trigger the event listener in the original calling of the button so that other importations can be able to actually work with the onclick event. Eg. : app.svelte <Button on:click={addBook}>ADD Book</Button> This engages with an addBook function that allows the button to add books dynamically to an array: let books =[] function addBook(){ const newBook = { title : title, pages : pages, description: description }; books = books.concat(newBook) } The above code exists inside the script tag and what it does is, call all the properties of the book from the form and concatenates them. We make use of a concat because push does not change the book variable. It only changes the array but assigning concat to a new value with trigger a change. We now have an array of books which is displayed conditionally using a special markup that Svelte gives us: {#if books.length === 0} <p> Add a new book </p> {:else} {#each books as book} <Book bookTitle={book.title} bookPages={book.pages} bookDescription={book.description}/> {/each} {/if} What this does is that it prompts the user to add new books then displays each new block as a new card: And displays the information on the card once the user updates: To achieve this, we will have to make another component called purchase.svelte . In the script tag, we would want to export the books variable so that it can be updated by the book tag, by passing the information as props in the app.svelte. In the app.svelte we add an empty array in the script to hold the purchased books. Now how do we add books to these purchases? We will use the buy button in the book component and then, add the purchaseBook function to script and bind to the button using on:{purchaseBook}. We then use the create a dispatch function from the Svelte’s custom library. Then we can link the function to the Book tag by adding the on:buy = {purchaseBook} This event dispatches from our purchaseBook function. function purchaseBook(event){ const selectedTitle= event.detail; purchases = purchases.concat({ ...books.find(book => book.title === selectedTitle ) }); } In this article, we have attempted to understand the basic use of Svelte by creating a book store demo. I hope this post helps you understand the power of SvelteJS and shows you the ways you can go about creating awesome applications. Here is a link to the demo. Happy coding! 😄 javascript angular reactjs vue-js>
https://morioh.com/p/428c278aaf0c
CC-MAIN-2020-40
refinedweb
1,364
62.38
Hi, I have a problem when I import data from CSV file and then when I make any updates in it it 's not updating on dynamo directly which means I need to import it again to read updates. How I can make synchronize between files and dynamo. I used dynamo 2.3 and Revit 2019. your must keep data from file in families and in file data at the same time. What is primary: datas in file or datas in revit? i have a solution for sync key shchedule with excel data. But there is a big problem: what is primary? If I make changes in file and revit project at the same time. Alternatively, you can transfer data from a file to the Extensible Storage field in family and store data there. Your task has no easy solution what I do with CSV files in dynamo is: I freeze a node to prevent any changes to be done, then I change the bool value in the “transpose” option of the “Import CSV” node, then, unfreeze, change again the boolean option and run the graph… I don’t know why csv is not updated automatically, but it’s no need to load the file again If you use the File.FromPath node this creates a watcher which will update the graph whenever the file changes on disk. maybe I need a python script to solve it You could use a path through node with your file path as the element to be sent through and a date/time input as the other input selection. This will then force it to re send your path and make the other nodes update. how I can use file path as the element? File path > File.FromPath yes deniz I know but I think this problem in dynamo 2.3 when I try 1.3 every think was okay, but in 2.3 version I need to load file txt or excel and etc… to refresh data. Now I am trying to refresh it by python but I have errors in python code. Enable Python support and load DesignScript library import clr clr.AddReference(‘ProtoGeometry’) from Autodesk.DesignScript.Geometry import * import time,datetime The inputs to this node will be stored as a list in the IN variables. dataEnteringNode = IN tex=IN[0] time=[1] Place your code below this line f=open(tex, “r”) if f.mode == ‘r’: contents =f.read() print(contents) ts = time.time() timestamp = datetime.datetime.fromtimestamp(ts).strftime(’%Y-%m-%d %H:%M:%S’) precursor ="[" timestamp "] --> " Assign your output to the OUT variable. OUT = contents just I try to refresh time of saving file by python can you help me in this?
https://forum.dynamobim.com/t/synchronize-between-csv-files-and-dynamo/46372
CC-MAIN-2020-50
refinedweb
454
74.08
- on Microsoft .NET Created by admin on 2008-07-15. Updated: 2008-07-28, 11:47 As our first example, we use the standard and we give the generated assembly file This is a guide on using Scala version 1.4 on the Microsoft .NET platform. Requirements Apart from the Scala software distribution you need to install the following software: - Microsoft .NET Framework Redistributable Package Version 1.0 (or newer)It includes everything you need to run applications built using the .NET Framework, including the Common Language Runtime and class libraries. Configuration Then you need to modify your working environment as follows: - Copy the file mscorlib.dll from the Microsoft .NET directory to the share\scala\libdirectory of the Scala installation directory. The Scala compiler will need it (see usage of the option -rin the example below) to access the metadata of the Microsoft .NET runtime library. C:\temp>copy %CLR_HOME%\mscorlib.dll %SCALA_HOME%\share\scala\libNB. For convenience we assume here that the environment variable CLR_HOMEis defined as follows: Name: CLR_HOME Value: C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322 - You may now set up your environment in two different ways in order to run the .NET executables generated by the Scala compiler: - If you have administrator privileges, than register the assembly file %SCALA_HOME%\lib\scala.dllinto the Global Assembly Cache.Hint: You will find the .NET configuration tool starting from the Start menu of the Windows taskbar and following the steps below: - Control Panel → Administrative Tools → Microsoft .NET Framework Configuration - In the "Assembly Cache" settings, we then choose the task "Add an Assembly to the Assembly Cache" and select the scala.dllfile from the Scala installation directory. - Otherwise you will need to copy the file %SCALA_HOME%\share\scala\lib\scala.dllin the same directory as the executable. Test Example As our first example, we use the standard Hello World program. import System.Console object test extends Application { Console.WriteLine("Hello world!") } To compile the example, we use the Scala compiler with the following two options: C:\temp>scalac -target:msil -r "%SCALA_HOME%"\share\scala\lib test.scala and we give the generated assembly file test.il as input to the IL Assembler: C:\temp>ilasm /output=test.exe /quiet test.il NB. For using the IL Assembler you may need to modify the environment variable PATHas follows: Name: PATH Value: ...;%CLR_HOME%\;... Finally, to run the example, we enter the following command: C:\temp>test and get the following output: Hello world! Additional Information Once you've compiled your first Scala program for .NET you may want to dig into more details on the quirks of Scala for .NET, or how .NET specific features map to Scala.
http://www.scala-lang.org/node/168
crawl-002
refinedweb
448
51.24
How to Get an image from the clipboard and then save it into a image file? Use WinAPI functions OpenClipboard(), CloseClipboard(), GetClipboardData() to deal with clipboard. You'll probably need to work with bitmap then. A n00b needs more help here: #include <windows.h> int main() { OpenClipboard(NULL); GetClipboardData(CF_BITMAP); return 0; } What now? 1) I would write smth like this: Code: HBITMAP hBitmap = (HBITMAP)GetClipboardData(CF_BITMAP); 2) Do you know what MSDN is? If you have any questions first look through some articles there: HBITMAP hBitmap = (HBITMAP)GetClipboardData(CF_BITMAP); Well, then I advice you to try to look what's there in the bitmap handle. Output it to window. Then find any bmp file format specification in the Internet and write bitmap to a file. This is one my question I asked to make sure I know all the methods to access RGB: By the way I'm also working on a problem related to BMP. View Tag Cloud Forum Rules
http://forums.codeguru.com/showthread.php?480947-Getting-image-from-the-clipboard-and-then-saving-it-into-a-image-file
CC-MAIN-2014-15
refinedweb
162
74.39
How to create a SAP Cloud Platform application using Predictive service In order to avoid to waste time and do things incorrectly, this document aims to show the necessary steps for the creation of a cloud application for the first time. Behind these steps, you will also discover some principle of SAP Cloud Platform and of the usage of REST predicitve services. Nevertheless, this document don’t replace the online documentation of SAP Cloud Platform programming. Before to start, we make these assumptions: - SAP Cloud Platform Predictive service is deployed and configured on your account. Refer to the online help of the predictive services. - APL, which comes with the predictive services, is installed on the HANA database of your cloud account. - The user who will develop the application has at least a developer role on the cloud account and C4PA-USER role for the Java application of the predictive services. Prepare HANA database Create accounts Connection to database with Eclipse On the SAP Cloud Platform, from the Persistence menu, go to Databases & Schemas, click on your database and in the page, click on Database User. If you have never did that before, you will get this dialog. Click on Create User. Then click on Show button to see you initial password. Now it is time to launch Eclipse (at least Mars version). In the toolbar, click on icon Add System and choose to add a cloud system because the HANA database on the SAP Cloud Platform cloud. Fill in the fields. Use you SAP Cloud Platform ID user and password and click Next. Then you can either choose a schemas or a database. It is here you will use the user ID and password provided just before in the HANA cockpit. Once connected the first time, you will be asked to choose your password. You can also check version of this HANA database. Select it and in the toolbar, click on Administration icon. In the window, you can see - HANA version and - Installed plug-ins and when you click on it, you will get the version of each plug-in. Create User It is not a good idea to use your database user ID to connect SAP Cloud Platform Predictive service to the HANA database. It is better to create a technical user because it not linked to you and a generic technical user can be shared between several developers. There are 2 ways to do this and it depends on the development environment used: - Eclipse as shown in previous section to add a cloud system or - SAP HANA Web-based Development Workbench which is run from SAP Cloud Platform To start with this environment, your database user must have specific roles (see table below). You can assign these roles directly from Eclipse if you have admin privilege, otherwise ask to an admin user. Refer to the help of SAP HANA Web-Based Develoment Workbench. From Eclipse From the Cloud System created, go to Security/Users, right click on Users and choose New Users. Then fill the form. Another easy way to do this is to open a SQL window in Eclipse and run this sql -- CREATE HANA TECHNICAL USER CREATE USER PS_USER PASSWORD Password1; It is then necessary to grant roles to this user. The roles to grant depends on the version of HANA. -- ROLES (SPS09) GRANT AFL__SYS_AFL_APL_AREA_EXECUTE TO PS_USER; GRANT AFLPM_CREATOR_ERASER_EXECUTE TO PS_USER; -- ROLE (SPS10) CALL GRANT_ACTIVATED_ROLE('sap.pa.apl.base.roles::APL_EXECUTE','PS_USER'); Now the password used for PS_USER needs to be changed. To do this, you will add the same cloud system but with PS_USER database user. In the first login dialog, enter your SAP Cloud Platform user ID and in the second login dialog, enter PS_USER and its password and click Finish button. As it is the first time you connect to HANA database with this user, the system asks you to change the initial password. So enter a new one. When done, if you double click on this new user, you should have this: From SAP HANA Web-based Development Workbench The root page looks like this: Click on the Security tile. Right click on Users and select New User. Fill the form with the user name, the password and the role(s). Create a schema for data To be secure, it is better that data will be loaded into a protected schema. Thus create schema PS_DATA. In order HCPps can access these data, it is necessary to grant select privilege to PS_USER to the tables of schema PS_DATA. To do this execute this SQL script on Eclipse. Here again 2 ways: From Eclipse Right click on the Catalog and select Open SQL Console. In this console, enter the SQL code to create the schema and grant select privilege. Note that the grant can be done from the UI of Eclipse for PS_USER From SAP HANA Web-based Development Workbench From the root page, click on Catalog tile. Right click on Catalog and select New Schema. Give a name and click OK. The schema is created. Go to Security tile and grant select privilege to PS_USER to the tables of schema PS_DATA. Load data into HANA For the sample of this document, my data are in a csv file. Here I will show how to import this csv file into a table of schema PS_DATA. The table will have the name of the csv. From Eclipse In File menu, choose Import. Then select SAP HANA Content and Data from Local File. Then click on Next. Select the HANA database on which you want to load data and click on Next. In the wizard, provide information about the data file and where you want to store data. Here in a new table of schema PS_DATA named SMALL_SALES. Click on Next. The next wizard manages the table definition and the data mappings. Here keeps what is proposed and click on Next. The last screen is a summary of the data imported. Click on Finish to do the import. Now in the schema PS_DATA, the new table SMALL_SALES has been created. Bind Predictive Services to HANA database Now that the database technical user is created and have an access to the schema PS_DATA which contains tables that can be used as dataset, a list step to finish configuration is to establish the link between the predictive services and the schema PS_DATA. To do this, SAP Cloud Platform uses the mechanism of destination. Here is how to set a destination between predictive services and schema PS_DATA through the technical user PS_USER. From SAP Cloud Platform go to the Java applications and select the Java application of the Predictive service. Click on aac4paservices and then on Data Source Bindings and then on New Binding. Leave the Data Source empty. Once saved the data source binding will have the name <DEFAULT>. Choose the database ID and use the database technical user PS_USER and its new password set in the previous section. Then click on Save button and the SAP Cloud Platform Predictive service is now ready to be consumed inside a cloud application. It is what we will see in the next sections. Create HTML/Javascript application Define destinations Destination is a SAP Cloud Platform mechanism to link an application to another one so that the second can be called by the first. The principle is this one: Account destination to SAP Cloud Platform Predictive service Once predictive services are deployed, configured and started, it is necessary to create a destination. SAP Cloud Platform Predictive service is a Java application generally named “aac4paservices” but this is not mandatory. This name is given during deployment and is part of the URL to designate this service. This URL is mentioned in the overview of the predictive services accessible from Java Applications menu. To create a destination, go to menu Destinations and click on button New Destination and set the fields like this and save. The URL is the URL of the predictive services shown just before. Application destination The application destination is set when the application is created in SAP Cloud Platform. This is visible in the overview of your application. The Edit button allows you to choose the account destination you want to bind to your application. At the end you have this schema: Initialize HTML Application From HTML5 Application, click on New Application. A small dialog appear; enter the name of your application: for example hcpps4ki. Now this application appears in the list. Click on it, go to Versioning and click on button Edit Online. WebIDE starts and as it is the 1st time for this application, it requests you to provide information for Git repository. On the next dialog, keep it as it is and click on Commit and Push. The application is created into your workspace. It contains only one file that you will not have to touch. Select you application, do a right click and choose New / Project from Template. Choose SAPUI5 Application, then Next. Keep the name of your application for the namespace. Then click Finish. Edit the file neo-app.json and add the code highlighted in yellow. In the Git pane, select all the files, give a version number and click on Commit and Push button with Orign/master. Go back to SAP Cloud Platform. In the Versioning window, you now see the version V0.1. You also see at the bottom a section about Destination. Click on Edit button to set the correct destination so that it looks like this and Save. During this step we did 2 things: - We have created the skeleton of a new HTML application which will use SAPUI5 controls - Create the 2nd step of the destination workflow by defining the application destination and linking it to the account destination. The consequences are: - Application can be run (click on link V0.1) - Application can now receive code to call SAP Cloud Platform Predictive service. Add code Objective here is not to describe how to do to develop a cloud HTML application. For this I let you read the SAP Cloud Platform online documentation. In this section I will tell you: - The high level steps to include predictive features into your application - How to call predictive services and - How to get the results of these services High Level steps Before doing any prediction it is necessary to prepare your data into the HANA database of your cloud account. These data will be either put into a specific table or view of a schema. Then this table or view will be registered as your dataset. You will use the dataset service to register your data. Input parameter of this service is the table or view where your data are. The service will return a description of the data and the most important is a dataset ID that you will use later to reference your data. Next step is to do prediction(s). This will be done by call to the predictive service(s) which correspond to your needs. At the end a good programming behavior is to delete the job IDs and the dataset ID when you will have finished with them. Here are these 3 high level steps. For more information refer to the online functional documentation or the API RAML documentation. How to call predictive services? Predicitive services are REST web services. This means that: - They are invoked through 3 verbs: GET, POST and DELETE - An URL is used to specify the service to call - A service can take one or several input arguments - The output is placed inside a variable which is parsed after the execution to retrieve the results. Furthermore there are 2 modes to invoke a service. - Synchronous mode: which means that your application has to wait for the end of the execution of the service to do the next instruction. Keyword “/sync” is added at the end of the URI to call a service with this mode. - Asynchronous mode: which means that the hand is given back to the application after the call to the service and you don’t have to wait until the end of the execution of the service. In this case the service returns a job ID and a job type that you can use later to check if the execution of the service is finished or not. This mode is very interesting when you have to process a big dataset because your application can do something else. In the next section, there are examples in Javascript of how to call predictive services Register a dataset An easy way to call a service in Javascript is to use the ajax function. $.ajax({ type : "POST", contentType : "application/json", url : root + "/api/analytics/dataset/sync", dataType : 'json', data: JSON.stringify({"hanaURL": "PS_DATA/SMALL_SALES"}), success : function(data, status, request) { $('#datasetID').val(data.id); displayVariables(data.id); }, error : function(request, status, error) { var msg = status + ": " + request.state(); $('#out_param').html(msg).css({"background-color": "red"}); } }); The 1st argument precises the verb. The url argument defines which service to call. The root variable is set like this: var root = "/HCPpsAppDest"; You recognize the name of the application destination mentioned above in this document. Finally the /sync indicates that the service will be called in synchronous mode. The input argument is given is JSON format: data: JSON.stringify({"hanaURL": "PS_DATA/SMALL_SALES"}), In case of success, the function displayVariables is called with the parameter data.id which represent the dataset ID. In case of failure, a message is displayed. Get dataset description function displayVariables(id) { $.ajax({ type : "GET", contentType : "application/json", url : root + "/api/analytics/dataset/" + id, dataType : 'json', success : function(data, status, request) { var i = 0; var rowCount = 0; var oItem; ddlb_variables.destroyItems(); for (i = 0; i < data.variables.length; i++) { addRowInTable("variablesTable", data.variables[i].name, data.variables[i].value); oItem = new sap.ui.core.ListItem(); oItem.setText(data.variables[i].name); ddlb_variables.addItem(oItem); } ddlb_variables.setValue(data.variables[data.variables.length - 1].name); gTarget = data.variables[data.variables.length - 1].name; ddlb_variables.attachChange(function(){ $('#target').html(ddlb_variables.getValue()); gTarget = ddlb_variables.getValue(); }); ddlb_variables.placeAt("ddlb_ChooseTarget"); $('#target').html(ddlb_variables.getValue()); }, error : function(request, status, error) { var msg = status + ": " + request.state(); $('#out_param').html(msg).css({"background-color": "red"}); } }); } We use again the ajax function, but his time the verb is GET. We also see that the URL is built dynamically with the variable root, the name of the service and the dataset ID. In case of success of the call of this service, we will get the description of the dataset by parsing the variable data. The structure of this variable is given into the API documentation. Call a Key Influencer $.ajax({ type : "POST", contentType : "application/json", url : root + "/api/analytics/keyinfluencer/", dataType : 'json', data: JSON.stringify({"datasetID": $('#datasetID').val(), "targetColumn": gTarget}), success : function(data, status, request) { gJobID = data.ID; var res = 'Job ID: ' + data.ID + ' Status: ' + data.status + ' type: ' + data.type; $('#status').html(res); }, error : function(request, status, error) { var msg = status + ": " + request.state(); $('#out_param').html(msg).css({"background-color": "red"}); } }); The same mechanism is used again with the ajax function. Verb is POST, URL is the one of the key influencer in asynchronous mode. Only the 2 mandatory input parameters are provided: the dataset ID and the target variable. In case of success the job ID is stored into variable gJobID. Get Status of a job $.ajax({ type : "GET", url : root + "/api/analytics/keyinfluencer/" + gJobID + "/status", dataType : 'json', success : function(data, status, request) { var res = 'id: ' + data.ID + ' status: ' + data.status + ' type: ' + data.type; $('#status').html(res).css("background-color", ""); }, error : function(request, status, error) { var msg = status + ": " + request.state(); $('#status').html(msg).css({"background-color": "red"}); } }); The application can continue and periodically, it is necessary to check the status of the key influencer job. This is done by a GET to the status of this job. It takes no input parameters. All necessary information is inside the URL. When the call of the status call is finished in success, we got the status of the key influencer job which can be: - Either PROCESSING. Which means that it is not finished. So another call to the status will be necessary. - Or SUCCESS. Which means that we now can get the result of the key influencer. - Or FAILURE. Which means there was a problem and an error code is given. Get result of a Key Influencers $.ajax({ type : "GET", url : root + "/api/analytics/keyinfluencer/" + gJobID, dataType : 'json', success : function(data, status, request) { // Get KI and KR $('#tKI').html(data.modelPerformance.predictivePower); $('#tKR').html(data.modelPerformance.predictionConfidence); var contrib = 0; for (var i = 0; i < data.influencers.length; i++) { contrib = data.influencers[i].contribution*100; addRowInTable("keyInfluencers", data.influencers[i].variable, contrib.toFixed(4)); } }, error : function(request, status, error) { var msg = status + ": " + request.state(); $('#status').html(msg).css({"background-color": "red"}); } }); To obtain the result, use the GET verb. The URL mentions the key influencer and the job ID. In case of success of the Get call, it is necessary to parse the variable data to display the key inflencers and their contributions. The data variable is a structured list of several levels and its description is is given into the API documentation. Conclusion There are some steps to do to prepare your environment before starting the development of a cloud application. This is not specific to predictive services but to the way SAP Cloud Platform handles services in general. The way data are managed in HANA database depends on each customers. The only constraints is to determined which data from which table is necessary for you to do the predictions you need. Then you will have to create a view containing these data and which will become your dataset. The mechanism to call REST services is standard in Web applications. It is always the same: select the good verb, build the URL corresponding to the service you want to call, set input parameters and parse the structured list which contains results of the service. Very well explained. Thanks.
https://blogs.sap.com/2017/02/10/how-to-create-a-hcp-application-using-predictive-services/
CC-MAIN-2022-27
refinedweb
3,000
65.32
Results 1 to 3 of 3 Thread: Comparing strings using == - Join Date - Nov 2010 - Location - Burlington, Vermont, USA - 2 - Thanks - 1 - Thanked 0 Times in 0 Posts Comparing strings using == I'm newish to Java- hoping someone can explain this to me... My understanding was that the equals method was necessary for comparing strings, because == compared the objects, not the literals. How come the code below returns true for c? If I declare a and b using String a= new String("hi") instead, then c is false. I thought that String a="hi" did the same thing as String a= new String("hi")? Any help would be most appreciated! Thanks. Code: public class TryEquals{ public static void main(String [] args){ String a="hi"; String b="hi"; boolean c=(a==b); System.out.println(c); } } Sting *LITERALS* are always allocated once, only, out of a static pool. So what you have *really* done here is equivalent this: Code: System.createStringLiteral("hi"); a = System.getStringFromLiteralPool("hi"); b = System.getStringFromLiteralPool("hi"); FWIW, you actually *can* force Java to see a pair of dynamically created strings as the same object, if they contain the same characters. You have to call the intern() method and then use the returned reference. Here, look at this: Essentially, *all* string literals are automatically returned via hidden calls to intern().Be yourself. No one else is as qualified. - Join Date - Nov 2010 - Location - Burlington, Vermont, USA - 2 - Thanks - 1 - Thanked 0 Times in 0 Posts Wow- that's really helpful. Thanks for taking the time. I had looked at the String reference you cited, but I doubt I would have ever found it.
http://www.codingforums.com/java-and-jsp/209282-comparing-strings-using-==.html
CC-MAIN-2017-22
refinedweb
274
65.62
Qt MySQL Support Hi All, I would like to build a tool using QT which can query an existing MySQL database on a local server. I found this example, but am having trouble getting it to work. After running the example code, I see the error message shown below. Does anyone know what next steps should be to get this to work? Thank you. #include <QCoreApplication> #include <QApplication> #include <QtSql/QSql> #include <QtSql/QSqlDatabase> #include <QtSql/QSqlDriver> #include <QtSql/QSqlQuery> #include <QDebug> #include <QMessageBox> #include <QSqlError> bool createConnection(); int main(int argc, char *argv[]) { QApplication app(argc, argv); if (!createConnection()){ qDebug() << "Not connected!"; return 1; } else{ qDebug() << "Connected!"; QSqlQuery query; query.exec("SELECT name FROM student"); while (query.next()) { QString name = query.value(0).toString(); qDebug() << "name:" << name; } return 0; } return app.exec(); } bool createConnection(){ QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL"); db.setHostName("10.0.0.181"); db.setDatabaseName("dbname"); db.setUserName("username"); db.setPassword("password"); if (!db.open()) { qDebug() << "Database error occurred"; /* QMessageBox::critical(0, "", "Cannot open database", QMessageBox::Cancel, QMessageBox::NoButton); QMessageBox::critical(0, "", db.lastError().text(), QMessageBox::Cancel, QMessageBox::NoButton); */ return false; } return true; } - Mike - A Former User last edited by Hi! This is a common problem. Please use the forum search :-) @Wieland Thank you, Wieland. I have done this but am still struggling, and am hopeful for a bit of guidance. Most discussions involve solving this problem under Linux. I am looking for a Windows solution (which I did fail to mention in my post). Even a small nudge in the right direction would be appreciated. This is the tutorial I am following. The tutorial does not say what to do if this error is shown. However, it is indicated that "libmysql.dll" must be present in the "MySQL directory", so maybe that is the problem. I have this file but the tutorial doesn't explain where it needs to be, other than the "MySQL directory" (this could be under the MySQL folder, or it could be under the QT folder, and then under any of several sub folders). It's unclear if QT is finding it but needs something else, or if this is what is needed but it can't find it. Referenced documentation mentions that there is a set of drivers which come with QT. MySQL is listed, so maybe I didn't even need to install MySQL. The error message shown above does show "QMYSQL" as having an available driver. db.lastError().text() shows "Driver not loaded Driver not loaded". Perhaps the driver exists but the path to it needs to be specified. I'm unsure where I would specify the path, though, and the tutorial doesn't do this. These are some basic questions I am unsure how to get answers to without help. - Mike Hi, Go to the Run part of the Project panel in Qt Creator, there modify the PATH environment variable and add the path to the folder where the MySQL .dll files can be found. @SGaist Thank you! Adding the path to the folder with the MySQL dll files to the environmental variables path solved the problem. Images showing how to add to the path variable from within QT are shown below. The path can alternately be added using the System control panel. From the System control panel, I selected "Advanced system settings": The "System Properties" window appered. I selected "Environmental Variables": From the Environmental Variables window, I selected the "Path" variable and clicked "Edit...": A list of paths appered. I clicked "New": An edit field for a new path became available, and I pasted in the path of the folder which contained the libmysql.dll file. (Which is simply the "lib" folder underneath where I unzipped the "mysql-5.7.16-win32" download to.) When I run the code I posted above, it now reports that it is able to connect to the database: - Mike Don't do that in your system environment variable. That's a bad habit ! Hello, i've the same problem. I'm on Mac and i'm on that problem since 3 days ... I tried your method but it doesn't worked :/ Did someone have a solution? Hi and welcome to devnet, Please search the forum a bit, I've already provided the solution several times for OS X/macOS.
https://forum.qt.io/topic/73732/qt-mysql-support
CC-MAIN-2022-21
refinedweb
718
66.84
Bummer! This is just a preview. You need to be signed in with a Basic account to view the entire video. Isolation Testing12:34 with Jeremy McLain There are many tactics for testing units independently from the rest of the code or system. - 0:04 Most classes have to use other classes in some way in order to do their job. - 0:09 At the beginning of this course we learned that unit - 0:12 testing focuses on testing a single unit of code. - 0:15 Independent from the rest of the system. - 0:18 When a test fails we need to know why it failed, and that - 0:21 the failure was caused by the unit being tested and not by code in some other unit. - 0:26 So how do we write a unit test for a class if it depends on another class? - 0:32 We should strive to test each unit independently from all of their units. - 0:36 This is probably the most difficult aspect of unit testing. - 0:41 There are many ways to achieve this goal. - 0:43 Following good object-oriented design principles when designing software is - 0:48 the first step to making this level of unit test possible. - 0:52 In object-oriented design, - 0:53 we strive to reduce the amount of concrete coupling there is between classes. - 0:58 There are many patterns and - 1:00 best practices that can help In fact, too many to cover in this course. - 1:04 So, we'll leave that for another day. - 1:07 However, the simplest way to reduce coupling between two classes, is to have - 1:11 the client class use an interface instead of a concrete implementation of the class. - 1:16 This gives us the greatest flexibility when testing the unit. - 1:20 We can provide an implementation of a class that has already been unit tested, - 1:25 or we can use a test double in its place. - 1:29 Test doubles are also known as mocks, stubs, spies, or fakes. - 1:34 Actually these are all slightly different concepts, but - 1:37 as a group they're called test doubles. - 1:40 You may hear people refer to them all as mocks which is probably okay. - 1:44 In this course I'll refer to them generally as test doubles. - 1:48 Test doubles are used to stand in for - 1:50 parts of the program in order to facilitate testing. - 1:54 In order to have better control over what is being tested and - 1:57 to ensure that a unit is tested independently from the rest of the code. - 2:01 We can replace its dependencies with much simpler objects that behave more - 2:06 predictably. - 2:07 To see what this really means, let's code up an example. - 2:11 Treehouse Defense has both towers and invaders. - 2:14 The towers try to disable the invaders by shooting at them. - 2:18 Here's a basic implementation of the tower class notice that the tower class depends - 2:23 on two other complex types map location and I invader. - 2:29 The question is how do we test the tower class in such a way that if a test fails, - 2:34 then we know that it's a failure in the tower class and - 2:37 not in one of these dependencies. - 2:39 One way is to unit test the dependencies first. - 2:42 That's what we've done with the map location class. - 2:45 However, invaders are much more complex objects than applications. - 2:48 And we haven't written a concrete implementation of an invader to test. - 2:52 IInvader is an interface and - 2:54 we don't know what the concrete implementation of it will be yet. - 2:57 However, when testing this class we need to pass it in an array of - 3:01 IInvader objects. - 3:02 Since we don't have a tested invader to pass it yet we can pass it a mock invader. - 3:07 First let's create a test class for Tower. - 3:10 I'll do this just by right clicking on Tower and clicking on Create unit test. - 3:17 I'll clean this up a little bit. - 3:21 Now let's create a mock invader in the test project. - 3:24 I'll create this mock in its own namespace and folder. - 3:27 I'll call the folder Mocks, so say add a folder. - 3:34 Mocks, and in here I'll Add a new class, - 3:40 and I'll call this new class - 3:44 InvaderMock If we - 3:51 had multiple invader mocks we'd probably want to give it a more descriptive name. - 3:55 We want invaderMock to implement the I invader interface. - 4:00 We can have Visual Studio do this code for - 4:03 us just hit control dot on the keyboard and select implement interface. - 4:08 Now that we have a concrete implementation of I invader to use, - 4:11 let's go back to the tower test class and start coding the test. - 4:15 We can get rid of the constructor test since it'll be tested in the course of - 4:19 the other test. - 4:20 And we'll remain this one to FireOnInvadersDecreases Invaders help. - 4:31 So in here we'll create a new instance of a tower, - 4:36 so I'll say var target = new tower. - 4:39 And we need to give it a location on the map, so - 4:43 we'll say new Map location and we'll just have this one be at 0, 0. - 4:48 And we need to give it an instance of the map. - 4:51 So let's create that say var map, - 4:55 = new map make it of size 3, 3. - 5:02 And pass in the map. - 5:04 Now let's create our array of invaders. - 5:07 So we'll say var invaders = new InvaderMock, - 5:12 we need to add the namespace. - 5:19 And it'll be an array of a couple of invaders. - 5:25 So I'll say new invaderMock and it will need to have a location so - 5:29 we'll just use a property setter for that. - 5:33 So I'll say location = new map location and - 5:38 we'll just have it be at 0, 0. - 5:45 And let's have a couple of these. - 5:48 Now we need to call fire on invaders on our target, so - 5:52 let's say target.FireOnInvaders and pas in the invaders. - 6:00 And our assertion will be that the health of each one of these - 6:05 invaders has been decreased by one. - 6:08 So to do that, we can use the Assert.All method. - 6:13 So we'll say Assert.All, we'll pass in all of the invaders. - 6:18 And then we give it a lambda. - 6:20 So we can say, for each i in invader. - 6:25 Assert that, Assert.Equal that the health is one. - 6:33 So we'll say i.health. - 6:37 There we go. - 6:39 Now, we need to think about what we need our mock to look like, in order for - 6:42 this test to work. - 6:43 We can figure that out by looking at both the test, and the tower class. - 6:47 So, here we see that InvanderMock is gonna need a public setter for - 6:52 the location property. - 6:54 And if we look at the tower class in the fire on invaders method. - 6:58 We'll see that it needs to have, is active and - 7:03 location and it needs to decrease the health of the invader by this much. - 7:12 And that's all it needs to do in order to pass this test. - 7:16 So we'll go over to our invader mock. - 7:19 And just to keep this simple, we'll just have HasScored always return false. - 7:29 And our Health, That's what's going to be decreased. - 7:36 We'll have a getter and a private setter. - 7:43 And we'll have it start out with a health of 2. - 7:46 Since after calling fire on invaders, - 7:49 we're going to have a health of 1 afterward. - 7:53 That's what our test here is doing. - 7:55 That's what it's checking. - 7:57 After calling fire on invaders the health should be 1. - 8:01 So we need to start off with a health of two in our mock. - 8:06 And IsActive we can just have that always return true. - 8:12 IsNeutralize can always return false and - 8:17 our location needs to have both the getter and a setter. - 8:23 So we'll say get, set. - 8:29 So decrease health would just be health -= factor. - 8:36 Which this is the behavior we'd expect. - 8:40 Now, notice that move still is thrown knew not implemented exception. - 8:46 The reason for this is in this mock we don't have to do anything with move, - 8:50 because move is never called by either the test or the fire on invaders method. - 8:55 So, we can just leave it as it is. - 8:57 Now, if we go back to the tower test. - 8:59 We'll see that we've got no red squiggly so it should compile. - 9:02 And let's compile and run this test. - 9:08 Let's check out the Tower Test, and it passes. - 9:14 So this is just one example of using a mock to facilitate testing. - 9:19 The purpose of mocks is to provide a super simplified version of a dependency - 9:24 that has a very specific. - 9:26 And very predictable behavior so that we can test exactly what we want to test and - 9:30 no more. - 9:31 Let's take a look at that Mock again, as you can see it's pretty simple. - 9:36 A lot simpler than a implementation of an invader would normally be. - 9:41 Mock should be as simple as possible. - 9:43 Otherwise we introduce the possibility of a bug in the mock itself. - 9:48 Notice that we didn't need to implement every property and method. - 9:51 Only what needed to be done in order to run our test. - 9:54 We could have many invader mocks that are specific - 9:57 to different types of test that we want to create. - 10:00 I mentioned earlier that mocks are just one category of test doubles. - 10:04 There are also spies stubs and fakes. - 10:06 However many people refer to all of these as mocks as well. - 10:10 I've included some links in the teacher's notes if you'd like to learn more about - 10:14 these other categories of test doubles. - 10:15 Just as there are frameworks for unit testing, there are also frameworks for - 10:19 creating doubles. - 10:20 One such popular framework for .NET is called MOQ spelled M-O-Q. - 10:25 You'll find a link to more information about the MOQ framework in the teacher's - 10:28 notes as well. - 10:29 As you can see we don't necessarily need a special framework to create MOQs. - 10:34 However they can help to create better testing code. - 10:37 Especially if a lot of different test doubles need to be created. - 10:40 For example using a mock framework we could have written the entire fire on - 10:44 invaders decreases invaders health test without actually implementing this invader - 10:49 mock class. - 10:50 The behavior of the invader mock class would have been put in the test itself. - 10:56 Right here. - 10:58 This would keep the mock code close to the test that - 11:01 was using it instead of in a separate class. - 11:04 While testing units in complete isolation from each other is the ideal - 11:08 it isn't always practical to do so. - 11:11 For example we didn't create a mock of the MapLocation class - 11:15 in order to test the tower class. - 11:17 In a lot of cases we can get away with this and - 11:20 still maintain a high degree of confidence in our test. - 11:23 The level of isolation testing to do depends on the specific situation. - 11:29 There are some situations where isolation testing is unavoidable. - 11:32 For example, in cases where there's uncertainty in a dependency. - 11:37 And example of this is a remote service that isn't always running or - 11:40 isn't completely stable. - 11:42 You don't want to temporary failure in an external dependency such as this - 11:46 to cause your unit test to fail. - 11:49 The dependency may not respond in a timely manner. - 11:52 This is another situation when creating a test double - 11:55 to stand in its place is a good idea. - 11:58 Another time when test doubles is unavoidable - 12:01 is when the dependency isn't complete enough to rely on during testing. - 12:05 In this case, we can create a simple version of the dependency, - 12:09 just like we did with the invader mock. - 12:12 This allows us to continue coding and - 12:14 testing before all of the dependencies are complete. - 12:18 Test doubles are also used to provide a reliable and predictable source of data. - 12:23 A random number generator that isn't random, or - 12:26 a time source that can be set to any time. - 12:28 Our examples where we could use stand ins to remove - 12:31 indeterminacy from a test environment.
https://teamtreehouse.com/library/isolation-testing
CC-MAIN-2017-39
refinedweb
2,377
81.73
I can't seem to get singletons resources to work by using any sort of annotation like @javax.inject.Singleton or using wink's singleton scope. Here is my class: @Singleton @Path("/test") public class MyResource{ public int i = 0; // This should increment if singleton public class IntVal { public int value = 0; } @GET @Produces(MediaType.APPLICATION_JSON) public IntVal getIntVal() { IntVal iv = new IntVal(); iv.value = i++; return iv; } } However, every time I do a GET on the resource, it always returns value=0. The MyResource class is being recreated on every request. I'm pretty sure my server.xml contains the correct features: <featureManager> <feature>jsp-2.2</feature> <feature>localConnector-1.0</feature> <feature>jaxrs-1.1</feature> <feature>cdi-1.0</feature> </featureManager> I'm also using an empty subclass of Application for my application class and my web.xml is as simple as can be: <servlet> <servlet-name>com.mycompany.MyApplication</servlet-name> </servlet> <servlet-mapping> <servlet-name>com.mycompany.MyApplication</servlet-name> <url-pattern>/rest/*</url-pattern> </servlet-mapping> Answer by Eric Covener (1231) | Nov 17, 2014 at 07:03 PM In CDI 1.0, javax.inject.Singleton doesn't have any meaning. It's a vestige of JSR 330. javax.ejb.Singleton is a different story altogether. If you need a singleton, I think you need to implement your jax-rs resource as an EJB. So you are saying that there is no way for a JAX-RS class to be a singleton unless you use EJBs? Answer by Tom Alcott (1742) | Nov 17, 2014 at 04:25 PM While it should work, in my (limited) experience In addition to the JAX-RS 1.1 feature you'll also need to enable the JSON 1.0 feature jaxrs-1.1 json-1.0 Refer to If that doesn't fix the problem, then there might be a defect and you'll need to contact product support Answer by gas (928) | Nov 20, 2014 at 03:53 AM You can use EJB singleton to achieve what you are looking for. Use the following code: import java.util.Date; import javax.ejb.Singleton; import javax.ws.rs.GET; import javax.ws.rs.Path; @Singleton @Path("/service") public class HelloService { private int counter = 0; @GET @Path("/hello") public String getHello() { counter ++; return "Hello:" + new Date() + " : " + counter; } } And enable the following feature: <feature>ejbLite-3.1</feature> 14 people are following this question. How to fix InitialContextFactory Not Found in Liberty Profile v8.5.5.4 2 Answers jax-rs and "java.lang.NoClassDefFoundError: org/slf4j/LoggerFactory" 1 Answer Example for OSGI Jax-RS 2.0 webservice in Websphere Liberty 2 Answers How to construct the corbaname url to call a remote ejb (2.x) resident in WAS full profile from Liberty 0 Answers Liberty jaxrs-2.0 fails to marshal JAXB objects containing List to JSON. 2 Answers
https://developer.ibm.com/answers/questions/164830/does-was-liberty-profile-support-singleton-resourc.html
CC-MAIN-2019-26
refinedweb
480
51.24
Hi all, I finally got started working on Olli stuff. I put a half G ide disk in the Olli so I can avoid our (overloaded) net. There were of course a set of DOS partitions on it already. This causes an adel in genhd.c-> extended_partition when it tries to do a partition check on the contents of the extended partition. I traced the problem to the line if (!NR_SECTS(p) || is_extended_partition(p)) (line 163 in drivers/block/genhd.c). The crash comes at NR_SECTS(p), this is defined at the top of genhd as follows: #ifdef __alpha__ /* * On the Alpha, we get unaligned access exceptions on * p->nr_sects and p->start_sect, when the partition table * is not on a 4-byte boundary, which is frequently the case. * This code uses unaligned load instructions to prevent * such exceptions. */ #include <asm/unaligned.h> #define NR_SECTS(p) ldl_u(&p->nr_sects) #define START_SECT(p) ldl_u(&p->start_sect) #else /* __alpha__ */ #define NR_SECTS(p) p->nr_sects #define START_SECT(p) p->start_sect #endif /* __alpha__ */ I can only assume that the MIPS needs similar handling to the alpha (to avoid unaligned access) but someone (Ralf? Michael?) borrowed my MIPS bible some time ago and never brought it back... Has anyone got the book on hand to tell me the nessecary code for MIPS? I seem to remember it was a construct not a single instruction but it's been months since I read the book. I wouldn't have bothered you all with this except that Ralf is away for a day or so and I'd like to get the disk installed so I can start on that disgusting console...>
http://www.linux-mips.org/archives/linux-mips-fnet/1996-04/msg00031.html
CC-MAIN-2013-48
refinedweb
275
61.77
TL;DR - The strtod/et al. (string-to-double) has a char **endptr output parameter, in which it stores the address of the next character after the parsed/converted-to-double number in the input buffer. This parameter is used by parsers to determine where to continue parsing after a number has been read. - Since internally strtod (or actually _fltin2 and _wfltin2 which are used deep inside) uses a 32-bit int type to store the number-of-parsed-characters, the final calculation of endptr (startptr + number-of-parsed-characters) may result in an address that is outside (in front) of the input text buffer on 64-bit systems. - This results in introducing DoS class, information leak class, or other types of bugs in parsers that rely on strtod and the endptr parameter. Note: Both glibc and MinGW (statically linked) strtod implementation don't have this bug - it's msvcr*.dll specific. Note 2: PoCs are at the bottom. Root causeDirect problem is in the _flt structure used by _fltin2 and _wfltin2 functions, which are used to do the actual string-to-double conversion in strtod/etc (see Affected versions and functions below). This structure looks as follows (Visual C++ CRT source code, file \crt\src\fltintrn.h): typedef struct _flt { int flags; int nbytes; /* number of characters read */ long lval; double dval; /* the returned floating point number */ } *FLT; This causes problems with overly long numbers on 64-bit platforms, since the nbytes might overflow (for numbers of length >= 2GB and < 4GB, etc), which leads to it having a negative or zero value. This is problematic for strtod/et al., since they calculate the *endptr value in the following way (\crt\src\strtod.c): struct _flt answerstruct; FLT answer; ... answer = _fltin2( &answerstruct, ptr, _loc_update.GetLocaleT()); if ( endptr != NULL ) *endptr = (char *) ptr + answer->nbytes; A reasonably common way to use strtod in parsers (think: a JSON/XML/CSV/etc parser) is to do something like this: ... if (looks_like_a_double(p)) { char *ep; val = strtod(p, &ep); // errno checking / usage of val here p = *ep; continue; } ... This in fact leads to p pointing outside of the buffer (up to 2GB in front of the buffer) and the parsing continues there. ImpactSince this is a low-level library function the impact depends on what is it used for. Here are a couple of examples (assuming that strtod is part of a parser that is passed untrusted input, e.g. a JSON or CSV file): - Infinite loop DoS - if the input string is 4 GB long, the result end pointer will be identical as the start pointer, so the parser will jump into an infinite loop (strtod doesn't report any errors of course, since the number is correctly parsed) - Crash DoS - setting end pointer so that it points to an unallocated memory (e.g. for a number of length 2GB the end pointer will be start pointer minus 2GB, which probably points to some unallocated memory or isn't even a canonical pointer) - Information disclosure - since you could redirect the "read pointer" of the parser to any buffer in memory that is on lower addresses than the start pointer, you could make it read arbitrary data from memory; if the read data would be later reflected back, you could fetch it back. - Other - there might be other, less probable (but still possible) examples; one would be a more complicated scenario where the parsed text (code) is verified beforehand, and then parsed and executed. In such case this bug could be used to redirect the parser to jump into e.g. a middle of the string/comment containing unsafe code (similar to jumping in the middle of an instruction in ROP, but on scripting language level). This would make an awesome CTF challenge, but I don't expect it to be found in real products. Affected versions and functions64-bit Windows only. This has been confirmed on: - default, fully patched Windows 7 msvcrt.dll - msvcr90.dll, msvcr110.dll - newest Visual Studio 2013 redistributables msvcr120.dll - Windows 8.1 (preview) default msvcrt.dll Affected functions (generally: everything that directly or indirectly uses _flt.nbytes for anything meaningful): - _fltin2/_wfltin2 - these incorrectly calculate the _flt.nbytes - _strtod_l/_wcstod_l - these directly use _flt.nbytes - strtod/wcstod - these are just wrappers for the above functions - _Stodx/_Stod/_Stofx/_Stof - these use strtod Proof of conceptThis proof of concept prints the correct and strtod returned end pointer. #include <stdio.h> #include <stdlib.h> #include <string.h> int main(void) { // SZ == INT_MAX + some more bytes #define SZ 0x80000016 char *number = (char*)malloc(SZ); memset(number, '1', SZ); number[SZ-1] = 'm'; // Break syntax. number[1] = '.'; // This is probably not needed. char *end_good = number + SZ - 1; char *end_strtod; // strtod(number, &end_strtod); is OK too // ... unless you use MinGW which uses it's own strtod, // then it's better to just use _strtod_l for PoC. _strtod_l(number, &end_strtod, NULL); printf("number = %p\n", number); printf("end_good = %p\n", end_good); printf("end_strtod = %p\n", end_strtod); // Example (faulty) results. // number = 000000007FFF0040 // end_good = 00000000FFFF0055 // end_strtod = FFFFFFFFFFFF0055 return 0; } Real world exampleA random JSON parser for Python with native code - ujson 1.33: FASTCALL_ATTR JSOBJ FASTCALL_MSVC decodePreciseFloat(struct DecoderState *ds) { char *end; double value; errno = 0; value = strtod(ds->start, &end); if (errno == ERANGE) { return SetError(ds, -1, "Range error when decoding numeric as double"); } ds->start = end; return ds->dec->newDouble(ds->prv, value); } And a crash DoS PoC in Python (2.7 AMD64): import ujson n = "4." + "3"*0x7fffffff x = ujson.loads(n, precise_float=True) WinDBG says: (2088.1fa4): Access violation - code c0000005 (first chance) ujson!JSON_DecodeObject+0x8c: 00000001`800050dc 8a0a mov cl,byte ptr [rdx] ds:00000001`00010061=?? (rdx==0x100010061) ReportI've reported the bug to Microsoft and the decision was to fix it in the future releases of Microsoft Visual C++ / Microsoft Windows. I think that's OK, especially taking into account that the possibility of severe vulnerabilities appearing as a result of this Microsoft C runtime library bug is minimal (that said, if you find one, let me know ;>). TimelineNote: A lot of e-mails were flying back and forth, so I'm not going to list all dates. 2013-Aug-21: Send the report to Microsoft. 2013-Sep-17: Confirmation that the bugs works as described and are planned to be fixed. 2013-Oct-26: More information - the bug will be fixed in the next versions of msvcr*.dll. 2013-Nov-13: Microsoft receives the draft of this blog post from me for comments. 2013-Nov-23: Blogpost is public. And that's it. Thanks! Fixed :) Add a comment:
https://gynvael.coldwind.pl/?id=521
CC-MAIN-2020-16
refinedweb
1,098
54.63
Open Source Increasingly Replaced By Open APIs 224 SharkLaser writes "Open APIs might be the way to get rich in 2012. At the same time, it can also be what ultimately hinders open source development. A wide range of companies, including Google, Facebook, Amazon and Twitter, are building open APIs for other developers to use and build upon. Open APIs can be used by companies to grow their user base and introduce new, interesting features on top of their platform. Independent developers can utilize established services and their users to grow their own business. A perfect example of open APIs is Facebook Apps, which lets individuals and companies develop applications and games on top of the Facebook platform. Developers gain access to Facebook's established user base and Facebook gains new features and fun stuff to do on their site. Instead of open sourcing their platforms, companies like Google and Facebook are providing Open APIs and data access to outside developers. The actual source code for the services sits safely inside the company's network and never needs to be disclosed to outside parties, thus hindering open source development." What's the point? (Score:3, Insightful) What's the point of opensourcing Facebook? It's the userbase that matters to web-developers, not the server code. Re:What's the point? (Score:4, Insightful) On your race to the First Post you completely missed the point. Hell, you even missed the headline! Re:What's the point? (Score:5, Insightful) Actually.... the summary does mention that the lack of open source code from Facebook and Google is "hindering open source development." He may be question the usefulness of Facebook being open source and why would it "hinder" anything. Still a flawed observation that I replied in another post, but at least it seems he did read enough of the summary (i.e. all of it, not just the title) to jump to his argument. Re: (Score:2) Actually.... the summary does mention that the lack of open source code from Facebook and Google is "hindering open source development." Ah yes, Facebook [facebook.com] has really waged a war on Open Source by not releasing code, eh? And don't get me started on those bastards at Google [google.com]. Re: (Score:2) Ehm.... I already stated that... and it's what I was refering to by saying "Still a flawed observation that I replied in another post" Re: (Score. With GPL V1 and V2 there were big enough loopholes that a corporation wouldn't feel directly threatened for using it, but with GPL V3 RMS might as well have sent a Goatse to every corporation on the planet with a note saying "Here is what i think of capitalist pigs!". Person Re:What's the point? (Score." Complete nonsense. Furthermore, the whole idea about open source is to control the destiny of your investment, customer base while at the same time allowing customers to partcipate as engineers, not just as end users in what amounts to a community which has the final say as to what changes are made to the software it uses, and even if the software will continue to be used for a given purpose. That result is open source. Open API's are not open source. No, if I have an open API it is not going to allow my customers to participate as engineers, it will not allow the community to control the destiny of the softwar either. Those API's could be removed tomorrow, you can't improve them, the bugs are intractable or ignored by the corporate Big Brother who is monitoring everything you are doing with those API's. Are you people just plain stupid or have you had your heads in the sand since 1992? How can someone post something like this and get a Score 5 as insightful? Go ahead and embrace your open API's. You probably enjoy TSA sticking their hands down your kids pants, why wouldn't you enjoy having someone monitor every API call your software does. F'in diots I hope you get the world you deserve. You don't deserve Stallman's vision or any sort of Freedom! -Hack Re: (Score:3, Informative) Uhhh...because unlike you I'm not a militant FOSSie which like a Moonie treats software as a religion? I mean when you equate a software license to be groped by the TSA? Step away from the keyboard little FOSSie for you are coming off as more than a little batshit. By the way FOSSie, where do you think software comes from? Magic fairies shit it out like that bunny shitting jelly beans? Newsflash the VAST majority of software INCLUDING FOSS is PAID FOR BY COMPANIES. Companies that got a Goatse in their inbox Reference implementation (Score:2) Re:What's the point? (Score:5, Interesting) There is a lot of point. Few online services can handle the level of activity Facebook handles every minute. It's not just about tossing more hardware at it either; it's not easy to make such a scalable system. Open sourcing Facebook gives developers access to the custom code that allows them to handle all this, making it easier for small startups to jump into large service hosting solutions. Also, not sure what the summary means with the last statement. It is my understanding that Facebook HAS open sourced their server code (very likely as a jab at Google who, despite being "Open" would never dare give any competitor access to their scaling server code.) Re:What's the point? (Score:5, Insightful) It’s sad that anyone who makes a web service thinks they don’t have to, and as soon as they get 10 more users than they tested their service with the entire thing falls apart and they can’t scale it up to manage users. All they can think of is to try to optimize code here and there, but that has its limits and eventually you will need a system that can handle the scaling demand. “Scalability” is not about being able to “be as big as facebook”, it’s about being able to handle increased user demands, be it seasonal or popularity based. Re: (Score:3) Re: (Score:3, Insightful) Re: (Score:3) What's the point of opensourcing Facebook? It's the userbase that matters to web-developers, not the server code. It's all about forking. Everyone on Facebook is all about forking too, but that's not what I mean ;-) If Facebook retain control of the code, they can choose to make whatever changes they wish and users will never defect to a competing network. If they open sourced, Microsoft for example could fork it and include it as a feature of Hotmail - okay not the best example but you get what I'm saying. Take an existing user base and hijack/poach Facebook users. I see no problem here. (Score:5, Insightful) Re:I see no problem here. (Score:5, Insightful) Re:I see no problem here. (Score:5, Interesting) The problem is that web app APIs can change at a moment's notice, without any announcement, and all the developers who depended on the API will be left out in the cold. While that's true, if they do it too often and to too great an extent they'll lose developers to some other platform; if the apps start breaking without replacement, users will start to leave for other sites. Facebook (as big as it is) is nothing without its userbase. Re: (Score:3) Except doing such a thing would drive away the very developers they are trying to bring in thus would kill their site. Re:I see no problem here. (Score:5, Insightful) While you in particular may not necessarily have a use for the source code, the point is that it is unavailable to those who do wish to use it. The "use" might be understanding what it is doing (what information is it sending to the parent company), modifying it (so that it does not do this), and having the ability in principal to continue to run the API (modified to run on your own or an alternate social network) if the site owner goes out of business, does things you don't like with the information you give them, or decides to ban your application. Re:I see no problem here. (Score:5, Insightful) > So why would anyone care about Linux? People care about Unix and Linux is just another Unix. THAT is what freely re-implementable interfaces get you. Now while it is possible to have proprietary interfaces that can be re-implemented, it is very rare. The whole point of "owning" the API is the fact that you can disallow drop in replacements. You are you're own monopoly and market pressures quickly enforce that. We haven't moved from Free to Proprietary but from proprietary apps to proprietary services where all of your eggs are in one basket at some Facebook owned data center. What's missing is mobility of data between different "compatible" services. Re: (Score:3) WINE implements the same APIs as Windows and several commercial products have shipped non-Windows versions by either compiling against winelib or just shipping a WINE wrapper. The idea in US copyright law that you can't copyright an interface means that any API is freely reimplementable (unless it is covered by patents, although patents cover implementations so are more likely to affect ABIs than APIs). The advantage of owning the API (which really just means owning the most popular implementation of the Re: (Score:2) Embrace the power of AND. I want....both! (I also want it immediately for no cost, but thats just typical isn't it?) Seriously though, the source availability may not be of use to you now, directly but, if you don't think it is of use to you, then realize that if the service with the published API goes away, you don't have a starting point to replace it, other than the API docs... unless someone else already implemented another version off the same docs. There are definite plusses to independent code bases... Re: (Score:2) Yes but, you are thinking in terms of a developer. its true, API docs are a great starting point, and if well done, will allow you to recreate the whole API from scratch. Now.... its friday at 6 pm. Your companies bread and butter is an app that was built on top of an API run by a company that just shuttered its doors forever. If that API was based on open source, then you may have a few hours, or a day or so getting dependencies, looking over docs, getting it installed. Hell, if its really complicated, maybe Re: (Score:2) Right I never said that your app and its requirements can't be complex as to make this infeasible. However, not every app is in that situation. Not everything runs on google or facebook or uses their specific APIs. Yes, its entirely possible that this is the case. However, in any case, rebuilding without the original players is generally going to be easier and faster with the source available. Clearly, in the high volume world of 5-20k hosts per admin, this may not matter so much. The idea that anything that Re: (Score:3) And how many times in your long programming career have you delved into the bowels of the Linux source to build a better *nix application? Speaking as a driver/kernel developer: on a very regular basis. Maybe not daily, but certainly several times a week. Sure, if you're a web developer, or work up in user space, you may not need to do this - but the reason that the web works as well as it does is because the low-level support is there, works well, and works efficiently. So the success of your application depends in part on the source being open, even if you never look at it yourself. Open API? (Score:4, Insightful) Re:Open API? (Score:5, Interesting) Re:Open API? (Score:5, Insightful) Another way of phrasing it (which I remember being used in the context of Microsoft's API): "software sharecropping." I don't know why this is marked flamebait. I think the comment is rather astute. What is the point in building code to support a library that puts you in a position wherein you immediately become dependant on something you cannot control. Resulting in a product that largely makes money for someone else. That's not flamebait, it's wisdom. Re: (Score:2) you know what's the only api product I used that did that?.. google api(for the search, back in the day). 1000 queries free per day. Re: (Score:2) What is the point in building code to support a library that puts you in a position wherein you immediately become dependant on something you cannot control. Resulting in a product that largely makes money for someone else. Many developers have made millions by using these APIs. Smart companies make their APIs mutually beneficial and aren't planning on screwing developers for no reason. Re: (Score:2) Re: (Score:3) When you hear "Open API" any programmer will think it just means a well-known or documented API; i.e. it's not a secret. Load the accumulator with the petscii character you want to output and JSR $FFD2 -- or make a certain REST call as documented at the service's site -- that's what people will think you're talking about, when you say "Open API." That isn't what TFA is talking about. He's talking about different services using the same APIs, being client-compatible. That is, if you make a competitor to AWS, No way (Score:5, Interesting) Re:No way (Score:5, Insightful) Like I want to build my software around an API that could disappear in 6 months to a year. You'd be foolish not to, if you could recoup the investment in less than 6 months to a year with a decent return. Programmers seem to routinely toss away their entire codebase from time to time anyway. Re:No way (Score:5, Informative) Programmers seem to routinely toss away their entire codebase from time to time anyway. With disastrous consequences: Netscape, KDE4, etc. Throwing away a large codebase is stupid. Re:No way (Score:5, Insightful) With disastrous consequences: Netscape, KDE4, etc. Throwing away a large codebase is stupid. That depends very much on the quality of the codebase. They don't age nicely like fine wine, you know. Re: (Score:2) Netscape was boned in part *because* of their crappy codebase. They had a hard time making it adapt to new capabilities and evolving standards. In the long run, that has worked well. With KDE4, I get the feeling that adherents have *mostly* toughed it out and found the end product acceptable. Sometimes to pursue a vision there is a long painful transition, but the end result may be impossible without taking risk. Re: (Score:3) Re: (Score:2) So you are going to build your own facebook and then start creating applications for it? Otherwise, having access to the source wont do you any good. Re: (Score:2) Re: (Score:2) I don't care if I make my money back or not. I don't want to wake up one morning and find my work broken. Most customers wouldn't look favourably towards paying for something that just dies without warning. So having the source code to FB would solve that how? APIs change far less frequently than the underlying source code. Re: (Score:3) So having the source code to FB would solve that how? APIs change far less frequently than the underlying source code. Unless we're talking about Linux ;) Re:No way (Score:5, Insightful) Doing it just because I can "recoup my investment" short term is stupid. Throwing away a large batch of hard won customers is stupid. If I had made a successful ad-supported app with Google Translate, what do I do my customer base disappears because Google closed the APIs? They already had one app from "my" company break. Think they're going to buy another? Way, way too many companies -- and individuals -- make decisions based on short-term profits, with little to no regard of the long-term impact. That "I'm going to get mine and screw everyone else" sense of entitlement is largely how we got to be in our current mess. Re: (Score:2) Doing it just because I can "recoup my investment" short term is stupid. How is it stupid? You make more money than you started with. Provided the margin is sufficient, it is a smart investment. Re: (Score:2) Re: (Score:2) Most cases I see where a vendor is reliant upon a service they do not control, they make it clear in their branding message. If it should break, they say 'sorry, Google has discontinued this service'. It's not like they'll blame you and *not* your upstream provider. If facebook closed up shop today, no one would be blaming you that facebook doesn't work as the reason will be self-evident. Either it is something that will be *very* obvious and ubiquitous (like facebook or google+ being shut down) or it's s Re: (Score:2) Re: (Score:2) Re: (Score:2) The business answer is that as you recoup your investment, you re-invest in diversifying. Using your Google Translate example, you search out alternatives and build code to be able to share or shift load off of Google's service. Similarly, if you are "freeloading" off of Google's service, you need to plan that eventually you may need to pay for that functionality and build it into your business model. Re: (Score:2) If you don't want to use their APIs, then you can't use their services to help grow your business and user base. Technology changes quickly and businesses need to adapt if they want to stay relevant. Re: (Score:2, Interesting) Puhleez (Score:2, Insightful) . Re: (Score:2) . It's a bit silly to answer the above to an article that ends with Open APIs are the new open source, except they require less geeky access to lines of code, and more programmatic interaction with software services. As an added bonus, open APIs don't come with the baggage of licensing fundamentalists. And of course, the main issue the fact that these open api's are very much "here today, gone tomorrow", which is also one of the driving force behind open source development (to reduce a third party's ability to take away features or to make it impossible to keep using some program on newer systems by refusing to update it in case of incompatibilities). Re: (Score:2) Except for the fact that these Open APIs are built on top of Open Source. Facebook uses PHP and has contributed back code that improves performance. Google are using Linux internally with their own Google File System and BigTables. Other web services are using NoSQL and LAMP stacks. An "Open API" would allow an open source application to use that API. If it does not, it cannot be called an "Open API" as it is restrictive in what you can use to interact with it. It is rather a "Public API" that is documented They are not the same thing. (Score:5, Insightful) Most of these APIs provide access to data "owned" by the providers of those APIs. They rarely ever provide functionality that is not coupled to their data. These Web APIs are not going to replace open source tools/libraries that provide functionality. Also, using the term Open API is bullshit. First of all, an API is pretty much always open otherwise it cannot be an "application programming interface". If the API was closed it would not even be an interface to program against but a blackbox. Re: (Score:2) Not true as there are plenty of private APIs. Windows, for example, has plenty of them. APIs are not necessarily always for public consumption. When is this news? (Score:3) I don't see how this is news, or how these APIs wiill suddenly make companies rich in 2012... when the APIs have been around since at least 2007. Re: (Score:2) 2007? :) Try 1987 Prior art (Score:2) Re: (Score:2) I think there's a clear and distinct difference between an "Open" API and a "Public" API. off by a few decades (Score:2) Reduce revenue... (Score:4, Insightful) 2. Don't require ads or developer fees 3. ??? 4. Profit? I would have written more, but I think that sums up my point. Be Wary (Score:4, Insightful) Many companies have built their products on top of someone else's APIs, to have those APIs change, vanish, or develop charges later on. Do be aware of the pitfalls before you make yourself totally dependent on someone who does not have your best interests at heart. Re: (Score:2) APIs change far less frequently than does the underlying source code. How would having access to the underlying source code mitigate the risk you are talking about? Surely, facebook and google don't just change the API while leaving the source code intact! Re: (Score:2) I don't remember saying anything about source code. Re: (Score:2) Let's take another example - Google Maps: [bbc.co.uk] or Google App Engine: [informationweek.com] Guess not (Score:3, Insightful) How should that work? Two totally different things. interesting idea but not FB (Score:4, Insightful) I do think Facebook is a bad example. Their API is open and the SDK is open too... yes, the code is executed remotely... but that is the whole point because it interacts with the user data... that is the beauty behind technologies like XML-RPC or soap... good luck to facebook opening up access to their whole database... they don't care about privacy but even they would not do that now, it is true that a lot of companies provide an open SDK with a binary part... a good example would be video drivers which are open source yet include a binary part that is not open source. Games are another example. Even then, I would still consider it progress because before that there was no SDK, the only way to modify existing products was through a hex editor... at least now, software editors provide an api to interact. The concept is not even new... windows operating system is based on binary DLLs that many times only microsoft has the source code... yet visual studio comes with sourcecode and a very complete toolkit... but even that was not the first time open api was provided to a binary core... I guess that is just the way software is done Re: (Score:2) they don't care about privacy but even they would not do that You say it as if Facebook has some moral obligation to keep the database secret. They simply do not want to allow their competition to access valuable product data (the product being Facebook users). Re: (Score:2) They do have legal obligations, actually. Most sites that handle financial transactions do. It's true! (Score:5, Funny) For example, just this morning I replaced Debian on my computer with the Twitter API. It works great, boot times are much faster. Now I'm going to uninstall Firefox and just access the web via the Facebook API. Open APIs renamed: APIs (Score:4, Insightful) It's an API. Tacking "Open" onto doesn't change the fact that it's just an interface to a black box. As Stallman's been saying for the last few years, having software freedom is about having control over your computing, and that requires that your computing is done on *your* computer: [gnu.org] Re:Open APIs renamed: APIs (Score:5, Insightful) Application key (Score:3) Walled gardens are bad (Score:5, Insightful) Remember the good old days of the Internet, in which techies used to invent useful protocols, document them as RFCs, and then the best of these would be turned into Internet standards at the IETF? That approach gave us an open Internet with multiple implementations of the same standard services, all competing on merit not through proprietary lock-in. Well that's not where we are today. Instead we have a ton of proprietary services that occasionally publish public APIs when it suits them, but they're almost always pathologically opposed to interoperating with anyone else that might provide competition. Imagine a world in which everyone used their own homegrown mail prototols instead of SMTP and POP or IMAP. That's where we are today with the social networking services. Walled gardens are bad. Publishing open APIs doesn't make them any better, as the gardens are still walled and these closed services reject federating with other similar ones. And even if they accepted federation, the complexity of a fully interconnected graph in which each node has a different public API grows explosively, so technically this is a very bad design approach. Things aren't at all healthy on this front of the Internet, and proprietary services having open APIs doesn't help much. The best that can be said is that it's a bit better than no API at all, but that's not saying much. It's a new game... (Score:4, Insightful) Assuming there *was* one universally accepted standard that Facebook embraced and was also implemented by MySpace. No one would still give a rat's ass about MySpace. The APIs in this case are trivial and you can make up your own or copy them as a de-facto standard, but the data and user connectedness that the service embodies is what matters. There are two good reasons these companies don't go through RFC process for things like this. One, as above, the APIs are trivial and only of value to their data so an RFC process makes no sense. Secondly, if they were married to the RFC process, every little enhancement has the potential of taking months to over a year to ratify. Nothing is stopping a community for creating an RFC to compete with a proprietary API and if you push it through and are successful and create an ecosystem, then Facebook might implement it on top of their proprietary API. Incidentally, the same phenomenon can be seen in the 'good old days' of the internet. Cisco frequently did (and still does) roll out a proprietary protocol and when the IETF finally ratifies a standard to do the same thing, Cisco implements the standard as well as their proprietary approach (ususally, some times Cisco ignores the standard, probably due to lack of explicit customer request). Also, at the upper layers, there is a large precedent for people not bothering with RFCs at all. As far as I know, there is still no IETF RFC covering bittorent. There we have a very popular, community driven technology that has been in use for years that doesn't bother with IETF RFC process. Ok (Score:2) I retract my criticism, I somehow completely missed the point about federation and assumed someone was oversimplifying the situation (as the original article did). Of course, open source is orthogonal to this (this thread hasn't brought it up, so I think that's well understood), you have to modify the behavior of Facebook, not have read access to their source. Re: (Score:2) While you're generally correct, at least in IM a standardization process has been happening. Google, Facebook and MSN have adopted the XMPP protocol [xmpp.org] (RFC 6120) for chatting. Once you have a generic XMPP client, it's easy to connect to those networks (well, some coding is required for MSN and recommended for Facebook to use their oauth implementations, but that's trivial compared to implementing a whole new protocol). All except Google's are still walled gardens, but I guess that's company policy. Re: (Score:2). Re: (Score:3). Well, yes :) Still, it's much better than what has to be done for other [khstu.ru] protocols [blackhat.com]. Oh noes! (Score:2) Open source was never the way to get rich (Score:5, Insightful) I'm not sure what the point of the submitter is. Open source and open API have little in common. It's not like one could develop an OS kernel based on some documented open API. Open API is also nothing novel. Getting rich as an individual is not the point of Open-Source. Getting richer as a software-building community in terms of software availability is. Re: (Score:2) It's not like one could develop an OS kernel based on some documented open API. One of the first design goals for Linux was following POSIX, even though the standard was too expensive for Linus [linuxjournal.com]. While standards like POSIX and TCP/IP don't directly state how an OS kernel must be written, wanting to comply with them does shape the basic form the kernel needs to take. If you read the Tanenbaum-Torvalds Debate [oreilly.com] thread, one of the recurring themes there is that even having easily available source code (as MINIX did) isn't enough. One of the necessary components to growing a software communi Compare Apples and Oranges much? (Score:2) Tone of summary antithetical to article tone (Score:2) Emphasis Mine. There's a lot of places to come down on this. I develop with Google Apps, which leverages a lot of Open Source software in order t Quotas per application (Score:2) Re: (Score:2) Apples and Oranges (Score:2) Companies offering Open APIs are not hindering open-source developers.... Open APIs remove barriers for all software developers and allows them to make interesting products. What hinders open-source developers is other developers keeping their source code closed. #include " proprietary_lib.h" (Score:2) "Open" API's are the new include files to proprietary libraries. At least in the good old bad days the library (usually) didn't stop working after the you compiled & distributed your program. These days.. no such guarantees. It's a moot point (Score:2) For the *most* part, the technical capabilities of sites like Facebook isn't the impressive thing. At small scale, anyone can make code to function well in that capacity. If your endeavor grew to the point that facebook does, you'd have the resources to do the harder, but not impossible part of making that stuff scale. These sites are not succeeding because of inherently superior technology, they are succeeding by knowing exactly how to draw everyday users into a platform. What philosophy to embrace (e. Re: (Score:2) I will revise my statement because someone else pointed out the theoretical answer. Services like Facebook would have to be federated, meaning Facebook would either have to die or change it's behavior, which is unlikely. Of course, that's the social networking case, still no answer on things like most of Google's non-social capabilities. cretinoid name (Score:2) If you can't change API, it aint "open". It's just published. Open API? - what a dumb name (Score:2) An API is just an interface - there's nothing inherently open or closed about it. The code behind the API might be either open source or closed source, and in this case we appear to be talking about closed source. Not only is open vs closed a meaningless adverb to apply to an API (the closest concept might be public vs private - e.g. hidden Winodows API's), but the trend the article is attempting to discuss is the growth of cloud based platforms - i.e services made available via web services (SOAP, .NET, etc Re: (Score:2) Re: (Score:2) Undocumented != Closed, and anyways you can certainly write apps to undocumented APIs if you can figure/reverse engineer what they do.. but you'd generally be unwise to as undocumented typically also means unsupported so they may disappear without warning in a subsequent release. The article anyways isn't talking about documented vs undocumented - they are struggling for the right words to describe the trend towards "platformization" of web based products - exposing their functionality via web-services APIs A Serious Question (Score:4, Interesting) As a software developer this is a serious question for me and one that I've never gotten a satisfactory answer to. How can I feed my family or control my own destiny if the software is all I have? Am I not dependent on the benevolence of a corporation or university to fund my project or work as a clerk or something during the day and code at night? I know Open Source companies can make money on services or hardware but I'm not an Open Source company, I'm just one guy trying to make a living. I don't have the capital to produce hardware and my software is designed for end-users who don't require much in the way of services. If I were working on some glue code that might be useful to other developers and where I would benefit from their contributions I certainly would open source it (and I do contribute patches to some of the open source projects I use). I also get the idea of an open source OS or other large projects because so many companies depend on it there are enough "payers" in the pool to fund a lot of full-time devs - more than enough to cover the people who make millions off it (eg: Linux) yet contribute nothing back... plus with millions of users you have enough part-time tinkerers that you also get significant contributions from them. But I just don't see why I would open source my apps. No company in the world can pay my salary based on them, yet there are thousands of users willing to pay $0.99 for them, enough that I can keep my hardware up to date and have a little bit left over to go out to eat every month (certainly not enough to quit my job). But there aren't enough users that there would be a lot of programmers willing to contribute. If I open-sourced them, I'd be in the same position as Google with Android - funding the majority of it but having Chinese search companies replacing all my services with their own and selling it while simultaneously cutting off part of the revenue stream I use to fund further development. I like open source, I use it, I contribute to it, but I have absolutely no desire to follow the Stallman "everything must be open source!" philosophy. I'm interested to hear other dev's thoughts on this stuff... Re:Software packages, too (Score:5, Informative) Different tools for different goals. When you need to recreate the functionality of an existing application in a new application, as would be the case if you wanted to create a Facebook competitor, you may want the source code of the existing application. When you want to integrate your new application with one that already exists, as would be the case if you are creating a complementary or dependent project, you want SDKs/APIs. Developers do frequently use the APIs published for toolkits (jQuery, for example) and often load those toolkits from a third-party hosting service (like Google's, for example). This does create a dependency that would need to be updated if the hosting service made an incompatible change or discontinued their service, and that is something that developers need to keep in mind. When developers tie into the APIs of platforms like Facebook and Twitter, it would usually do them no good to have access to the source code, as they are usually trying to tie into those existing platforms to connect with their user bases. If the developer chooses to make their application dependent upon a third-party API, that is a strategic decision and the committment is theirs to make. It makes sense if the purpose of the application is dependent upon the third-party platform. As for published APIs interfering with open source development, I think it is possible that developers may choose to use proprietary products with published APIs rather than implement an open source solution. An example might be a developer choosing to use Google Charts rather than integrating gnuplot into their project. This might have some impact on the momentum of some open source projects, but the examples given in the summary are way off. A developer choosing to use an API published by Facebook for Facebook integration is not taking anything away from open source software. Re:open source is a race to the bottom (Score:4, Insightful) Yes! So instead of a single vendor holding its customers hostage, you get competition that drives down prices and a platform that is independent of the hardware. That's a good thing. Well, unless you're a monopolistic corporation/control freak. Re: (Score:2) Because the software is running on your server, you are not distributing it, therefore you can even derive your product from GPL licensed code, provide an API, and never have to distribute your source. Writing your application on top of that means that you relinquish your software freedoms ; you are dependant on an implementation you cannot elect to control for yourself. Which is fine, as long as you are happy with that risk. Most people already do this on their own hardware, so it's not much of a stretch. A MOD PARENT UP (Score:2) I thought the exact same thing. How do open APIs on facebook replace Linux as an OS?
http://news.slashdot.org/story/11/12/30/1317216/open-source-increasingly-replaced-by-open-apis?sdsrc=prevbtmprev
CC-MAIN-2014-42
refinedweb
6,371
70.53
z3c.pt 1.0b4 Python template compiler which supports the Genshi and ZPT template languages including macro extensions and internationalization. This package extends chameleon.zpt to provide application-level template support corresponding to zope.app.pagetemplate, but using the fast Chameleon engine to compile templates into byte-code. For usage, see the README.txt file inside the package. Changelog Version 1.0b4 - November 19, 2008 Split out content provider function call to allow modification through subclassing. [malthe] Added language negotiation. [malthe] Simplified template class inheritance. [malthe] Added support for the question-mark operator in path-expressions. [malthe] Updated expressions to recent API changes. [malthe] Added 'exists' and 'not' translators. [malthe] Bug fixes Adjusted the bigtable benchmark test to API changes. [hannosch] Version 1.0b3 - November 12, 2008 - Added PageTemplate and PageTemplateFile classes. [malthe] Version 1.0b2 - November 3, 2008 Bug fixes - Allow '.' character in content provider expressions. - Allow '+' character in path-expressions. Version 1.0b1 - October 2, 2008 Package changes Split out compiler to "Chameleon" package. [malthe] Backwards incompatibilities Moved contents of z3c.pt.macro module into z3c.pt.template. [malthe] Namespace attribute "xmlns" no longer rendered for templates with no explicit document type. [malthe] Changes to template method signatures. [malthe] Engine now expects all strings to be unicode or contain ASCII characters only, unless an encoding is provided. [malthe] The default path traverser no longer proxies objects. [malthe] Template output is now always converted to unicode. [malthe] The ViewPageTemplateFile class now uses 'path' as the default expression type. [malthe] The compiler now expects an instantiated parser instance. [malthe] Features Added expression translator "provider:" (which renders a content provider as defined in the zope.contentprovider package). [malthe] Added template API to render macros. [malthe] Optimized template loader so only a single template is instantiated per file. [malthe] Made z3c.pt a namespace package. [malthe] Added reduce and restore operation to the compilation and rendering flow in the test examples to verify integrity. [malthe] The ZPT parser now supports prefixed native attributes, e.g. <tal:foo tal:. [malthe] Source-code is now written to disk in debug mode. [malthe] Custom validation error is now raised if inserted string does not validate (when debug mode is enabled). [malthe] Added support for omitting rendering of HTML "toggle" attributes (option's selected and input's checked) within dynamic attribute assignment. If the value of the expression in the assignment evaluates equal to boolean False, the attribute will not be rendered. If the value of the expression in the assignment evaluates equal to boolean True, the attribute will be rendered and the value of the attribute will be the value returned by the expression. [chrism] XML namespace attribute is now always printed for root tag. [malthe] Allow standard HTML entities. [malthe] Added compiler option to specify an implicit doctype; this is currently used by the template classes to let the loose XHTML doctype be the default. [malthe] Added support for translation of tag body. [malthe] Added security configuration for the TALES iterator (repeat dictionary). This is made conditional on the availability of the application security framework. [malthe] Dynamic attributes are now ordered as they appear in the template. [malthe] Added symbol_mapping attribute to code streams such that function dependencies can be registered at compile-time. [malthe] Allow BaseTemplate-derived classes (PageTemplate, PageTemplateFile, et. al) to accept a doctype argument, which will override the doctype supplied by the source of the template if specified. [chrism] Language negotiation is left to the page template superclass, so we don't need to pass in a translation context anymore. [malthe] The ViewPageTemplateFile class now uses the module path of the calling class to get an absolute path to a relative filename passed to the constructor. [malthe] Added limited support for the XInclude include directive. The implemented subset corresponds to the Genshi implementation, except Match-templates, which are not made available to the calling template. [malthe] Use a global template registry for templates on the file-system. This makes it inexpensive to have multiple template class instances pointing to the same file. [malthe] Reimplemented the disk cache to correctly restore all template data. This implementation keeps a cache in a pickled format in a file next to the original template. [malthe] Refactored compilation classes to better separate concerns. [malthe] Genshi macros (py:def) are now available globally. [malthe] A syntax error is now raised when an interpolation expression is not exhausted, e.g. only a part of the string is a valid Python-expression. [malthe] System variables are now defined in a configuration class. [malthe] Improve performance of codegen by not repeatedly calling an expensive "flatten" function. [chrism] Remove safe_render implementation detail. It hid information in tracebacks. [chrism] Implemented TAL global defines. [malthe] Added support for variables with global scope. [malthe] Curly braces may now be omitted in an expression interpolation if the expression is just a variable name; this complies with the Genshi syntax. [malthe] UTF-8 encode Unicode attribute literals. [chrism] Substantially reduced compiler overhead for lxml CDATA workaround. [malthe] Split out element compiler classes for Genshi and Zope language dialects. [malthe] Make lxml a setuptools "extra". To install with lxml support (currently required by Genshi), specify "z3c.pt [lxml]" in any references you need to make to the package in buildout or in setup.py install_requires. [chrism] Add test-nolxml and py-nolxml parts to buildout so the package's tests can be run without lxml. [chrism] No longer require default namespace. [malthe] Changed source code debug mode files to be named <filename>.py instead of <filename>.source. Generalized ElementTree-import to allow both Python 2.5's xml.etree module and the standalone ElementTree package. [malthe] Expression results are now validated for XML correctness when the compiler is running in debug-mode. [malthe] Preliminary support for using xml.etree as fallback for lxml.etree. [malthe] String-expressions may now contain semi-colons using a double semi-colon literal (;;). [malthe] Preserve CDATA sections. [malthe] Get rid of package-relative magic in constructor of BaseTemplateFile in favor of just requiring an absolute path or a path relative to getcwd(). Rationale: it didn't work when called from __main__ when the template was relative to getcwd(), which is the 99% case for people first trying it out. [chrism] Added support for METAL. [malthe] Add a TemplateLoader class to have a convenient method to instantiate templates. This is similar to the template loaders from other template toolkits and makes integration with Pylons a lot simpler. [wichert] Switch from hardcoding all options in config.py to using parameters for the template. This also allows us to use the more logical auto_reload flag instead of reusing PROD_MODE, which is also used for other purposes. [wichert] Treat comments, processing instructions, and named entities in the source template as "literals", which will be rendered into the output unchanged. [chrism] Bugfixes Skip elements in a "define-slot" clause if its being filled by the calling template. [malthe] Support "fill-slot" on elements with METAL namespace. [malthe] Omit element text when rendering macro. [malthe] Macros class should not return callable functions, but rather a Macro object, which has a render-method. This makes it possible to use a path-expression to get to a macro without calling it. [malthe] Fixed bug where a repeat-clause would reset the repeat variable before evaluating the expression. [malthe] Fixed an issue related to correct restoring of ghosted template objects. [malthe] Implicit doctype is correctly reestablished from cache. [malthe] Remove namespace declaration on root tag to work around syntax error raised when parsing an XML tree loaded from the file cache. [malthe] Attribute assignments with an expression value that started with the characters in (e.g. info.somename) would be rendered to the generated Python without the in prefix (as e.g. fo.somename). [chrism] When filling METAL slots (possibly with a specific version of libxml2, I am using 2.6.32) it was possible to cause the translator to attempt to add a stringtype to a NoneType (on a line that reads variable = self.symbols.slot+element.node.fill_slot because an XPath expression looking for fill-slot nodes did not work properly). [chrism] Preserve whitespace in string translation expressions. [malthe] Fixed interpolation bug where multiple attributes with interpolation expressions would result in corrupted output. [malthe] Support try-except operator ('|') when 'python' is the default expression type. [malthe] METAL macros should render in the template where they're defined. [malthe] Avoid printing a line-break when we repeat over a single item only. [malthe] Corrected Genshi namespace (needs a trailing slash). [malthe] Fixed a few more UnicodeDecodeErrors (test contributed by Wiggy). In particular, never upcast to unicode during transformation, and utf-8 encode Unicode attribute keys and values in Assign expressions (e.g. py:attrs). [chrism] Fixed off-by-one bug in interpolation routine. [malthe] The repeat-clause should not output tail with every iteration. [malthe] CDATA sections are now correctly handled when using the ElementTree-parser. [malthe] Fixed bug in path-expressions where string instances would be (attempted) called. [malthe] CDATA sections are now correctly preserved when using expression interpolation. [malthe] The Genshi interpolation operator ${} should not have its result escaped when used in the text or tail regions. [malthe] Fixed edge case bug where inserting both a numeric entity and a literal set of unicode bytes into the same document would cause a UnicodeDecodeError. See also [chrism] Static attributes are now properly overriden by py:attr-attributes. [malthe] Version 0.9 - August 7, 2008 - Added support for Genshi-templates. [malthe] - Cleanup and refactoring of translation module. [malthe] - If the template source contains a DOCTYPE declaration, output it during rendering. [chrism] - Fixed an error where numeric entities specified in text or tail portions of elements would cause a UnicodeDecodeError to be raised on systems configured with an 'ascii' default encoding. [chrism] - Refactored file system based cache a bit and added a simple benchmark for the cache. The initial load speed for a template goes down significantly with the cache. Compared to zope.pagetemplate we are only 3x slower, compared to 50x slower when cooking each template on process startup. - Got rid entirely of the _escape function and inlined the actual code instead. We go up again to 12x for path and 19x for Python expressions :) [hannosch] - Avoid string concatenation and use multiple write statements instead. These are faster now, since we use a list append internally. [hannosch] - Inline the _escape function, because function calls are expensive in Python. Added missing escaping for Unicode values. [fschulze, hannosch] - When templates are instantiated outside of a class-definition, a relative file path will be made absolute using the module path. [malthe] - Simplified the _escape function handling by pulling in the str call into the function. Corrected the bigtable hotshot test to only benchmark rendering. - Replaced the cgi.escape function by an optimized local version, we go up to 11x for path and 16x for Python expressions :) In the bigtable benchmark the enhancement is more noticable - we are the same speed as spitfire -O1 templates now and just half the speed of -O3 :)) - Added a new benchmark test called bigtable that produces results which are directly comparable to those produced by the bigtable.py benchmark in the spitfire project. - Introduce a new config option called Z3C_PT_DISABLE_I18N. If this environment variable is set to true, the template engine will not call into the zope.i18n machinery anymore, but fall back to simple interpolation in all cases. In a normal Zope environment that has the whole i18n infrastructure set up, this will render the templates about 15x faster than normal TAL, instead of only 10x faster at this point. - Removed the second rendering tests from the benchmark suite. Since we enable the file cache for the benchmarks, there's no difference between the first and second rendering anymore after the cache file has been written. - Require zope.i18n 3.5 and add support for using its new negotiate function. If you use the zope_i18n_allowed_languages environment variable the target language for a template is only negotiated once per template, instead of once for each translate function call. This more than doubles the speed and the benchmark is back at 9.2 times faster. - Extended the i18n handling to respect the passed in translation context to the template. Usually this is the request, which is passed on under the internal name of _context into the render functions. After extending the i18n tests to include a negotiator and message catalog the improvement is only at 4.5 anymore, as most of the time is spent inside the i18n machinery. - Added persistent file cache functionality. If the environment variable is set, each file system based template will add a directory to the cache (currently a SHA-1 of the file's absolute path is used as the folder name) and in the folder one file per params for the template (cache filename is the hash of the params). Once a template file is initialized, an instance local registry is added, which then looks up all cached files and pre-populates the registry with the render functions. - Fixed interpolation edge case bugs. [malthe] - Added new Z3C_PT_FILECACHE environment variable pointing to a directory. If set, this will be used to cache the compiled files. - Added a second variation of the repeat clause, using a simple for loop. It doesn't support the repeatdict, though and is therefor not used yet. Also began work to add introspection facilities to clauses about the variables being used in them. The simpler loop causes the benchmarks to go up to a 10.5 (old 9.5) for path expressions and 14.5 (12.5) for python expressions. So the next step is to introduce an optimization phase, that can decide which variant of the loops to use. - Made the debug mode independent from the Python debug mode. You can now specify an environment variable called Z3C_PT_DEBUG to enable it. - Added some code in a filecache module that can later be used to write out and reload the compiled Python code to and from the file system. We should be able to avoid reparsing on Python process restart. - Simplified the generated _escape code. cgi.escape's second argument is a simple boolean and not a list of characters to quote. - Use a simple list based BufferIO class instead of a cStringIO for the out stream. Avoiding the need to encode Unicode data is a bigger win. We do not support arbitrarily mixing of Unicode and non-ascii inside the engine. - Merged two adjacent writes into one inside the Tag clause. - Applied a bunch of micro-optimizations. ''.join({}) is slightly faster than ''.join({}.keys()) and does the same. Avoid a try/except for error handling in non-debug mode. Test against 'is None' instead of a boolean check for the result of the template registry lookup. Made PROD_MODE available defined as 'not DEBUG_MODE' in config.py, so we avoid the 'not' in every cook-check. - Added more benchmark tests for the file variants. - Optimized 'is None' handling in Tag clause similar to the Write clause. - Made the _out.write method directly available as _write in all scopes, so we avoid the method lookup call each time. - Optimized 'is None' handling in Write clause. - Slightly refactored benchmark tests and added tests for the file variants. - In debug mode the actual source code for file templates is written out to a <filename>.source file, to make it easier to inspect it. - Make debug mode setting explicit in a config.py. Currently it is bound to Python's __debug__, which is False when run with -O and otherwise True. - Use a simplified UnicodeWrite clause for the result of _translate calls, as the result value is guaranteed to be Unicode. - Added benchmark tests for i18n handling. - Added more tests for i18n attributes handling. - Don't generate empty mappings for expressions with a trailing semicolon. - Fixed undefined name 'static' error in i18n attributes handling and added quoting to i18n attributes. - Added condition to the valid attributes on tags in the tal namespace. - Made sure the traceback from the first template exception is carried over to __traceback_info__ - Added template source annotations on exceptions raised while rendering a template. Version 0.8 - March 19, 2008 - Added support for 'nocall' and 'not' (for path-expressions). - Added support for path- and string-expressions. - Abstracted expression translation engine. Expression implementations are now pluggable. Expression name pragmas are supported throughout. - Formalized expression types - Added support for 'structure'-keyword for replace and content. - Result of 'replace' and 'content' is now escaped by default. - Benchmark is now built as a custom testrunner Version 0.7 - March 10, 2008 Added support for comments; expressions are allowed inside comments, i.e. <!-- ${'Hello World!'} --> Version 0.6 - February 24, 2008 - Added support for text templates; these allow expression interpolation in non-XML documents like CSS stylesheets and javascript files. Version 0.5 - February 23, 2008 - Expression interpolation implemented. Version 0.4 - February 22, 2008 - Engine now uses cStringIO yielding a 2.5x performance improvement. Unicode is now handled correctly. Version 0.3 - December 23, 2007 - Code optimization; bug fixing spree - Added ViewPageTemplateFile class - Added support for i18n - Engine rewrite; improved code generation abstractions Version 0.2 - December 5, 2007 - Major optimizations to the generated code Version 0.1 - December 3, 2007 - First public release - Author: Malthe Borch and the Zope Community <zope-dev at zope org> - License: ZPL - Categories - Package Index Owner: malthe, hannosch, chrism, wichert - DOAP record: z3c.pt-1.0b4.xml
http://pypi.python.org/pypi/z3c.pt/1.0b4
crawl-002
refinedweb
2,910
58.99
How do I add a component You might first want to read Writing Components for a background in how to implement a new component. Typically it means you write an implementation of the Component interface, usually deriving from DefaultComponent. You can then register your component explicitly via However you can use the auto-discovery feature of Camel where by Camel will automatically add a Component when an endpoint URI is used. To do this you would create a file called with contents (you can add other property configurations in there too if you like) Then if you refer to an endpoint as foo://somethingOrOther Camel will auto-discover your component and register it. The FooComponent can then be auto-injected with resources using the Injector, such as to support Spring based auto-wiring, or to support @Resource (EJB3 style) injection or Guice style @Inject injection. Working with Spring XML You can configure a component via Spring using the following mechanism... Which allows you to configure a component using some name (activemq in the above example), then you can refer to the component using activemq:[queue:|topic:]destinationName. If you want to add explicit Spring 2.x XML objects to your XML then you could use the xbean-spring which tries to automate most of the XML binding work for you; or you could look in camel-spring at CamelNamespaceHandler you'll see how we handle the Spring XML stuff (warning its kinda hairy code to look at . If you wanted <fooComponent> to be a standard part of the core Camel schema then you'd hack that file to add your component & conftribute a patch to the camel XSD. Otherwise you could write your own namespace & schema if you prefer.
https://cwiki.apache.org/confluence/pages/viewpage.action?pageId=53834&showComments=true&showCommentArea=true
CC-MAIN-2015-35
refinedweb
289
54.46
#include <hpi_classes.h> List of all members. It will only function if it's activate() method is called. Note there is only a single instance of this class; it lives in hpi.cpp the python interface relies on two modules: Definition at line 50 of file hpi_classes.h. constructor Definition at line 64 of file hpi_classes.h. Definition at line 53 of file hpi_classes.cpp. References activated, hpi_module, and hsi_module. : loads the necessary modules hsi and hpi. this will only succeed if Python can find them. Currently this will only succeed if the modules are in PYTHONPATH, so you might either keep them in Python's module directory or set PYTHONPATH to where you keep them Definition at line 67 of file hpi_classes.cpp. References activated, hpi_module, hsi_module, and load_module(). Referenced by hpi::callhpi(). call a routine in the hsi module with a bunch of parameters. The parameters are passed in as a python tuple which is constructed with the python_arglist class below. note that currently the only function in hpi is hpi_dispatch() but since this may change it isn't hardcoded. Definition at line 99 of file hpi_classes.cpp. References hpi_module. Referenced by hpi::callhpi(). general module-loading function Definition at line 38 of file hpi_classes.cpp. Referenced by activate(). flag, true if activated Definition at line 54 of file hpi_classes.h. Referenced by activate(), and ~python_interface(). pointer to loaded hpi module Definition at line 58 of file hpi_classes.h. Referenced by activate(), call_hpi(), and ~python_interface(). pointer to loaded hsi module Definition at line 56 of file hpi_classes.h. Referenced by activate(), and ~python_interface().
http://hugin.sourceforge.net/docs/html/classhpi_1_1python__interface.html
CC-MAIN-2017-09
refinedweb
265
52.97
Description editquestions, answers, and discussion of the clock function. Discussion edit A common question is How do I format the current time into some specific format (such as hh:mm:ss)?Try clock format [clock seconds] -format %Tor clock format [clock seconds] -format %Xor if you need something more formatted, try clock format [clock seconds] -format {%H hours %M minutes and %S seconds} MPJ (2004/11/22) Question: The man pages for clock scan command implies that you can read a ISO 8601 point-in-time specifications. The reason for this question while parsing some RSS feeds the date field is set in 8601 format and Tcl did not like this data. So when I looked at the specification and examples from [1] I find that not all case are able to be parsed (Tcl 8.4.7). Therefore my question is how would you scan this data in correctly and is this command broken for ISO 8601? See test the results below:Year: # YYYY (eg 1997) % clock format [clock scan 1997] unable to convert date-time string "1997"Year and month: # YYYY-MM (eg 1997-07) % clock format [clock scan 1997-07] unable to convert date-time string "1997-07"Complete date: # YYYY-MM-DD (eg 1997-07-16) % clock format [clock scan 1997-07-16] Wed Jul 16 12:00:00 AM Eastern Daylight Time 1997Complete date plus hours and minutes: # YYYY-MM-DDThh:mmTZD (eg 1997-07-16T19:20+01:00) % clock format [clock scan 1997-07-16T19:20+01:00] unable to convert date-time string "1997-07-16T19:20+01:00" # but if we remove the time zone offset it works but is one hour to fast!!! % clock format [clock scan 1997-07-16T19:20] Wed Jul 16 8:20:00 AM Eastern Daylight Time 1997 # removing the T gives us the correct time ?? strange % clock format [clock scan "1997-07-16 19:20"] Wed Jul 16 7:20:00 PM Eastern Daylight Time 1997 # also if we remove the dashes and leave the T % clock format [clock scan "19970716T19:20:00"] Wed Jul 16 7:20:00 PM Eastern Daylight Time 1997Complete date plus hours, minutes and seconds: # YYYY-MM-DDThh:mm:ssTZD (eg 1997-07-16T19:20:30+01:00) % clock format [clock scan 1997-07-16T19:20:30+01:00] unable to convert date-time string "1997-07-16T19:20:30+01:00"Complete date plus hours, minutes, seconds and a decimal fraction of a second # YYYY-MM-DDThh:mm:ss.sTZD (eg 1997-07-16T19:20:30.45+01:00) % clock format [clock scan 1997-07-16T19:20:30.45+01:00] unable to convert date-time string ) Question: Does anyone have a pointer to a Tcl/Tk countdown clock - given a particular date/time, the number of years/months/weeks/days/hours/minutes/seconds until it is reached ticks away? Would be used for deadlines, retirement days, etc.See Years, months, days, etc. between two dates for a partial solution.MNO I knocked up A Little Countdown Clock for a friend who was looking forward to finishing his contract. It counts down in fractions of a second (mainly to catch the eye ;), and displays in seconds. Here's a common question that I have answered more than once: "How do I calculate elapsed time?" First, set your "granularity". Here I go for hours. % set secondsPerHour 3600.00 3600.00Then, use something like this: % set elapsedTime [expr {([clock scan "2:15 PM"] - [clock scan "11:00 AM"]) / $secondsPerHour}] 3.25I'm sure there are other questions concerning the exceedingly complex and useful clock function.....DKF - I corrected a minor formatting problem... How does one easily calculate changes in time over time zones? I.e. How do I find out how many hours have elapsed between 1:00 AM CDT and 1:00 AM GMT?DKF - Use [clock scan] to convert them both into standard format (i.e. seconds from beginning of epoch.) Then it is trivial to work out the time difference between them... % set cdt [clock scan "1:00 AM CDT"] 969343200 % set gmt [clock scan "1:00 AM GMT"] 969325200 % expr ($cdt-$gmt)/3600.0; # in hours... 5.0 LV - One pretty common problem/question with dates and times occurs when someone gets a date or time in a format in which the value has a leading zero, then attempts to use that. For 8 and 9 am (and pm) as well as for the 8th and 9th of the month, one has a 08 or 09 as a value, resulting in Tcl generating the error msg: "08" is an invalid octal number while evaluating {set b [expr $a + 1]}or whatever.DKF - The correct way to deal with this is to use [scan %d] to convert the digit string into a number: scan $a %d aNum set b [expr {$a+1}] LV - another question I've seen people ask is about getting the output they produce relating to dates and times to show a leading 0, since Tcl's treatment of numbers generally drops leading zeros for the reason just mentioned (octal number treatment).DKF - And the natural complement of [scan] is [format] which can do precise this with minimal fuss: puts [format %04d 123]RS - ... and [clock format] can do the typical application, zero-padded two-digit hours, minutes, seconds etc, with even less fuss: clock format [clock seconds] -format %y%m%d-%H%M%S 001004-091226 LV - another question I see a lot - how to take a user provided date and compare it to the current date, or to calculate a future/past date to it.KBK - # Compare two dates set date1 [clock scan {03/09/2001}] set date2 [clock scan {02/08/2001}] if { [expr { $date1 < $date2 }] } { puts "$date1 is earlier" } # Calculate a date relative to another date % set t [clock scan {03/09/2001}] 984114000 % set u [clock scan {+3 days} -base $t] 984373200 % clock format $u Mon Mar 12 00:00:00 Eastern Standard Time 2001 % set u [clock scan {+3 weeks} -base $t] 985928400 % clock format $u Fri Mar 30 00:00:00 Eastern Standard Time 2001 % set u [clock scan {+3 months} -base $t] 992059200 % clock format $u Sat Jun 09 00:00:00 Eastern Daylight Time 2001See also Date Calculations. Dave Griffin - For server-based applications, you may want to format the time for a timezone other than the local server's time. This seems to do the trick well enough: # # Format a date, optionally adjusting the local timezone # date - Tcl clock value # fmt - Date formatting string # gmt - True: format for GMT; False: local time # localTz - Local timezone setting (e.g., EST5EDT) # (if empty, use server local timezone) # proc formatDateTz { date fmt gmt localTz} { global env set saveTz "" if {$localTz != ""} { catch { set saveTz $env(TZ) } set env(TZ) $localTz } set r [clock format $date -format $fmt -gmt $gmt] if {$localTz != ""} { if {$saveTz != ""} { set env(TZ) $saveTz } else { unset env(TZ) } } return $r }Please note that I believe the setting of localTz (the env(TZ) variable) is system-dependent. If I'm wrong here, I'd love to know the syntax -- there seem to be several to choose from.RHS 10Sept2004 Will this cause problems in a multithreaded tcl? I believe env is shared across threads, so the lack of a lock around the code means that you could wind up with issues. LV New Issue: how to handle dates farther in the future than 2038. Is there a plan for Tcl to handle these? $ clock scan {12/31/2039}unable to convert date-time string "12/31/2039" while evaluating {clock scan {12/31/2039}}Check out What: clock with extended year range Where: 8.5 does not have the Y2038 problem. Description:Description: (Arthur Taylor)(Arthur Taylor) '''Number of days in a given month''': from [A little date chooser] proc numberofdays {month year} { if {$month==12} {set month 0; incr year} clock format [clock scan "[incr month]/1/$year 1 day ago"] \ -format %d } ;# RS What: Critchlow's Tcl support routines Where: above code deals with standard Tcl date range, but provides Julian to calendar date conversions (and vice versa), as well as day and time to date with fraction and vice versa conversions. Description:Description: (Roger E. Critchlow Jr.)(Roger E. Critchlow Jr.) Dave Griffin - the clock format command has a %Z option which returns the zone name, but no easy way to get the current timezone offset. (The zone name can be horribly non-standard on Windows systems: "Eastern Standard Time" instead of EST). RFC2822 also demands that dates use numeric timezone offsets. The following returns a RFC2822 compatible timezone offset: proc RFC2822TimezoneOffset {} { set gmt [clock seconds] set local1 [clock format [clock seconds] -format "%Y%m%d %H:%M:%S"] set local [clock scan $local1 -gmt 1] set offset [expr $local - $gmt] if {$offset < 0} { return "-[clock format [expr abs($offset)] -format "%H%M" -gmt 1]" } else { return "+[clock format $offset -format "%H%M" -gmt 1]" } }KBK - In Tcl 8.5, you have both %Z and %z (numeric or named time zones), and Tcl tries hard to avoid using Windows timezone names. Timezone offset, local vs. UTC, in hours: expr {([clock scan 0 -gmt 1]-[clock scan 0])/3600} ;# RSrpremuz (2008-12-05) This actually means the following: expr {([clock scan "today 00:00" -gmt 1]-[clock scan "today 00:00"])/3600}and hence it gives the expected result only if the current time in the local time zone and UTC belong to the same day. Otherwise the offset is increased or decreased for 24 hours. Moreover, the time interval should be divided by 3600.0 because the offset need not be an integer. Another problem is that there are time zones which have offset larger than 12 hours. See [2].The RFC2822TimezoneOffset proc above works well. Donal Fellows wrote in comp.lang.tcl: To get the number of days in the *current* month: set startOfMonth [clock format [clock seconds] -format %m/01/%Y] set days [clock format [clock scan "+1 month -1 day" \ -base [clock scan $startOfMonth] -format %d] [yahalom emet] tcl version: tcl8.4.1 when I do: set month [clock format [clock second] -format %b]I am getting the month name in a local format why? How can I get it in english?rmax: Starting with version 8.4 [clock format] respects locale settings on Unix. So depending of the contents of the LANG, LC_TIME, or LC_ALL environment variables you get localized day and month names. If you always want to have english names, you could set env(LC_TIME) POSIXinside your application.KBK - And starting with 8.5, you get localised time only if you've expressly requested it with a '-locale' setting (-locale system for the system locale; -locale current for whatever mclocale is currently set to). Defaulting to the C locale is intentional - far more times are formatted to be read by programs than by humans. escargo 22 Nov 2002 - According to - a uniform model of time for date and time arithmetic; 86,400 seconds per day with no corrections. - times measurable to microsecond precision. - interval times precise to one part per thousand (worst case) and typically two orders of magnitude better (when the clock isn't sliding) - absolute times precise to about a second (worst case) and typically three or four orders of magnitude better. Here's an algorithm for determining the day of the week from an ansi date: set date 2004-01-09 regexp {([0-9]*)-([0-9]*)-([0-9]*)} $date match year month day regexp {0(.)} $month match month extra regexp {0(.)} $day match day extra set alpha [expr {(14 - $month) / 12}] set y [expr {$year - $alpha}] set m [expr {$month + (12 * $alpha) - 2}] set day_of_week_pre_mod [expr {$day + $y + ($y / 4) - ($y / 100) + ($y / 400) + (31 * $m / 12)}] set day_of_week [expr {$day_of_week_pre_mod % 7}]0 is a SundayRS: Note that Tcl has that functionality built in: % clock format [clock scan $date] -format %w 5 Writing AM, PM, Am, Pm, am, pmRA2 A quick question. I have a date/time stamper. The Am, Pm is written in capital letters (AM, PM). Is there a way to put the AM/PM in lowercase (am/pm) or better with the a and the p capitalized but not the M (Am/Pm)? Thanks!Salut, Robert. You can use [string map] for this job, but note that most people consider Am/Pm to be wrong. string map [list AM Am PM Pm] $stringUn grand merci, 202. Michel? I'll try this right away!KBK In 8.5, you could also define a locale that has whatever strings you please. See also Reworking the clock command. For stardate formatting (input and output) see Star Trek. MNO Quick and dirty time interval calculation into weeks, days, hours, minutes, seconds etc. and although I did have a quick look, it won't surprise me in the least when someone points out that this functionality already exists in tcllib (or [clock]!). set end [clock scan "28 March 2005 0:00"] set now [clock seconds] set int [expr $end - $now] if { $int <= 0 } { puts "End date is not in the future (or integer overflow occurred!?)" exit } set out "seconds" set intervals [list 60 \ minutes 60 \ hours 24 \ days 7 \ weeks 52 \ years 10 \ decades 10 \ centuries 10 \ millennia] foreach { mult name } $intervals { set rem [expr $int % $mult] set int [expr $int / $mult] set out "$rem $out" if { $int == 0 } { break } set out "$name, $out" } puts $out davidw at a client's, but wanted to take a moment to include an improved version of the above that could go into tcllib. package provide timeleft 0.1 package require msgcat namespace eval timeleft { namespace import ::msgcat::mc array set singulars { seconds second minutes minute hours hour days day weeks week years year decades decade centuries century millennia millennium } } proc timeleft::timeleft {int} { variable singulars if { $int <= 0 } { error "End date is not in the future (or integer overflow occurred!?)" } set out "seconds" set intervals [list 60 \ minutes 60 \ hours 24 \ days 7 \ weeks 52 \ years 10 \ decades 10 \ centuries 10 \ millennia] foreach { mult name } $intervals { set rem [expr $int % $mult] set int [expr $int / $mult] set out "$rem $out" if { $int == 0 } { break } set out "$name $out" } set res "" foreach {num unit} $out { if {$num == 1} { set unitname $singulars($unit) } else { set unitname $unit } lappend res "$num [mc $unitname]" } return [join $res ", "] } RS 2007-02-08 ...or maybe this is enough? It uses weeks as biggest unit, since a year never has 7*52=364 days :) proc timediff reltime { set w [expr {$reltime/86400/7}] set d [expr {$reltime/86400%7}] list $w week(s) $d day(s) \ [clock format $reltime -gmt 1 -format %H:%M:%S] } % timediff 86500 0 week(s) 1 day(s) 00:01:40 % timediff 8650000 14 week(s) 2 day(s) 02:46:40 % timediff 86500000 143 week(s) 0 day(s) 03:46:40 % timediff 86500001 143 week(s) 0 day(s) 03:46:41KBK If you don't care about the intricacies of the calendar and clock, the proposed code will do nicely. But there are ways of calculating the years, months, days, etc. between two dates that *do* take the complexities into account. LES 2009-08-08: Meh. I should have searched Wikit before trying to make my own. Now it's too late, I've made it. But I think my code has two advantages: easier to customize (add or remove units) and a teensy bit more elegant output. The disadvantage is that it completely disregards the fact that not all months have 30 days. proc p.spell.seconds { argseconds } { set steps " zero year [expr {86400 * 365}] month [expr {86400 * 30}] week 604800 day 86400 hour 3600 minute 60 second 1 " set i 1 set _templist {zero} while {$i < [llength $steps]} { set unit [lindex $steps $i] incr i set number [lindex $steps $i] incr i set argseconds [::tcl::mathfunc::int $argseconds] if {$number > $argseconds} {continue} set nunit [expr {$argseconds / $number}] set argseconds [::tcl::mathfunc::fmod $argseconds $number] if {$nunit > 1} {set unit ${unit}s} lappend _templist "$nunit $unit" incr _llength } for {set i $_llength} {$i > 0} {incr i -1} { if {$i == $_llength} { set _return "[lindex $_templist $i]" } elseif {$i == [expr {$_llength -1}]} { set _return "[lindex $_templist $i] and $_return" } else { set _return "[lindex $_templist $i], $_return" } } return $_return }Test: [luc]5003> p.spell.seconds 49 49 seconds [luc]5004> p.spell.seconds 499 8 minutes and 19 seconds [luc]5005> p.spell.seconds 4999 1 hour, 23 minutes and 19 seconds [luc]5006> p.spell.seconds 49999 13 hours, 53 minutes and 19 seconds [luc]5007> p.spell.seconds 499999 5 days, 18 hours, 53 minutes and 19 seconds [luc]5008> p.spell.seconds 4999999 1 month, 3 weeks, 6 days, 20 hours, 53 minutes and 19 seconds [luc]5009> p.spell.seconds 49999999 1 year, 7 months, 3 days, 16 hours, 53 minutes and 19 seconds AM I needed to do some date/time computations and ran into the intricacies of daylight saving schemes. Here is a page about it: Clock and daylight saving time corrections zxpim
http://wiki.tcl.tk/948
CC-MAIN-2014-35
refinedweb
2,857
65.96
Plone Login System Project description Installation Install ploneconf.site by adding it to your buildout: [buildout] ... eggs = plone.login and then running bin/buildout. Install it as usual in /prefs_install_products_form Compatibility plone.login is tested to work with Plone 5.1. It should work with Plone 5.0 as well but is not yet tested. Customizing templates The templates for any plone.login can be customized because they’re simple browser-views. Use z3c.jbot to apply your own overides. Customize where to redirect after login You can customize the location the user will be redirected to after successfuly logging in to the site. Just write an adapter as follows from plone.login.interfaces import IRedirectAfterLogin from plone.login.interfaces import IInitialLogin from Products.CMFPlone.utils import safe_unicode from zope.interface import implementer from plone import api " /> As you can see, this adapter adapts context and request, so modify these according to your needs. The Plone Foundation, Author Changelog 1.0rc1 (2018-06-18) - Package created using templer [The Plone Foundation] Project details Release history Release notifications Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/plone.login/1.0rc1/
CC-MAIN-2019-51
refinedweb
198
53.58
Hello, I need help badly. I was able to compile the program but when i ran it, it didn't do what it is supposed to do. The program should continue to promt for next employee's info until user enters "stop". I am not sure what I am missing.. Any help would be very much appreciated. ------ import java.util.Scanner; public class PayrollProgramPart2 { public static void main( String args[] ) { System.out.println( "Welcome to the Payroll Program!" ); boolean stop = false; // Loop until user types "stop" as the employee name. { Scanner input = new Scanner(System.in ); System.out.print( "Enter Employee's Name or stop to exit program: " ); String empName = input.nextLine(); // employee name if ( empName.equals("stop")) { System.out.println( "Program Exited" ); stop = true; } else { double hourlyRate; // hourly rate double hoursWorked; // hours worked double weeklyPay; // Weekly Pay for employee System.out.print( "Enter hourly rate: " ); // prompt for hourly rate hourlyRate = input.nextDouble(); while (hourlyRate <= 0) // prompt until positive value is entered { System.out.print( "Hourly rate must be a positive number. " + "Please enter the hourly rate again: " ); hourlyRate = input.nextDouble(); // read hourly rate again } System.out.print( "Enter hours worked: " ); // prompt for hours worked hoursWorked = input.nextDouble(); while (hoursWorked <= 0) // prompt until a positive value is entered { System.out.print( "Hours worked must be a positive number. " + "Please re-enter hours worked: " ); // prompt for positive value for hours worked hoursWorked = input.nextDouble(); // read hours worked again } weeklyPay = (double) hourlyRate * hoursWorked; // multiply sum System.out.printf( "%s%.2f\n", "Employee: " + empName + " Weekly Pay:", weeklyPay ); // display employee's weekly gross income in U.S. dollar } } } // end method main } // end class PayrollPart2
https://www.daniweb.com/programming/software-development/threads/172519/payroll-program-part-2-help
CC-MAIN-2018-30
refinedweb
270
61.53
Hello forum After using Dynamo for some time I want to learn to use Python, but so far with very little success. I hope you will be able to help me: Problem: I have a list of values for angles and some are above 360 degrees. If a value is above 360 i want to subtract 360 from that number Example: The list 10, 10 , 375, 35 should be turned into 10, 10, 15, 35 I tried to make a Python script for this but so far i havent been able to. My script so far looks like this: import clr clr.AddReference(‘ProtoGeometry’) from Autodesk.DesignScript.Geometry import * angles = IN for i in range(0,len(angles)): if angles[i]>360 realangles[i]=angles[i]-360 else angles[i] realangles[i]=angles[i] OUT = realangles[] Im well aware that I might be way off, but I hope I can get some help to get on the right track.
https://forum.dynamobim.com/t/correction-of-angles-python-beginner/8425
CC-MAIN-2020-50
refinedweb
159
64.34
As I mentioned in the previous blog post (), m2e-wtp had to be pulled out of the m2e marketplace, as it forced its installation for all non-WTP systems. In order to fix this issue, the code responsible for generating the MANIFEST.MF for all projects had to be integrated into the mavenarchiver feature. That means m2e-wtp 0.13.1 now requires the installation of mavenarchiver from the m2e-extras update site. It will be discovered automatically from the new m2e-wtp update site, hosted by Red Hat, so it will be completely transparent for new users. However, please note that the mavenarchiver feature replaces the pomproperties one, so the pomproperties must be uninstalled before upgrading m2e-wtp. Thus, the preferred ways to install m2e-wtp remain :-wtp and proceed with the installation. 3) Old school installation : Use this JBoss / Red Hat update site : While reviewing the installation details, you can see that mavenarchiver 0.14.0 will be found and installed automatically (provided there is not a more recent version already installed) Other that the changes necessary to reinstate m2e-wtp to the m2e marketplace, There is only one other bugfix in 0.13.1, which fixes deployment of war archives overlays in Windows (). UPDATE (03/08/2011) : m2e-wtp is now also available from the Eclipse Marketplace. However, it seems some people are unable to install it directly. Please note that m2e-wtp requires m2e 1.0. So, if it's not installed already, Eclipse must be able to find it in the available update sites. m2e can be installed from either (for Indigo) or (for Helios and Indigo). The change in m2e's namespace (org.maven.ide -> org.eclipse.m2e) between m2e 0.12.x and 1.0 renders updates impossible from m2e-wtp 0.12.x to 0.13.x. Thus you have no choice but to uninstall m2e < 1.0 and m2e-wtp < 0.13 before proceeding with m2e-wtp 0.13.x's installation. (I hope I'm clear enough :-)) Enjoy, Fred.
https://developer.jboss.org/en/tools/blog/2011/08/01/m2eclipse-wtp-0131-back-to-the-m2e-marketplace
CC-MAIN-2015-11
refinedweb
339
67.86
Making for some users as they did not use nunit and did not want to include that dll in their codebase. I also have been frustrated because NUnit is strongly named and since I am using other framework that add a little extra on top of nunit I have found that I know need to add all sorts of Assembly Redirect configuration in my app.config files in order to trick all of the assemblies I am using to think they have the right version of NUnit. It is quite a big mess when you really think about it. So at the Alt.Net conference in Seattle I proposed a session to talk about Unit Test Framework agnostic assertions and helpers. I was quite lucky to have some very smart people in the room and on the kyte.tv feeds. The end result that came out of the was this. Just throw a custom exception and the test frameworks will pick it up. I was told that this is how Rhino Mocks handles it’s assertions and that the test frameworks would eventually add my namespace to there code base so that the Call stack reported to the developer running his tests would not see the frames that were used internally by my assertions. Let me give you a visual so that it is a little easier to understand exactly what the problem is…. The first line in this example shows a line that is from my special assertion code. I do not want that to show up when a user runs a unit test with my assertion. Here is my little assertion helper example. Since I just created a standard exception I got the default behavior.</p> The way to fix this is to throw a special exception which knows how to remove specific frames out of the call stack. This code was adapted from the xUnit source code and is working quite well in the MvcContrib Test Helper Library With some simple string manipulation of removing lines that contain the namespace of my exception it is really easy to reuse this exception in an Unit Test framework Agnostic helper library. Here is the result of an assertion that failed using this assertion. As you can see the test runner does not show lines that my assertion framework contain the call stack stops at the last line in my unit test code. Which is exactly what we want. That way there is no question as to where the developer using this needs to look to get information about the test failure. </p> This code is located in the MvcContrib TestHelper library located at in case you want to dig deeper into the code. I hope this helps others as it really took some time to get to this approach.. It seemed totally obvious to the developers of the unit test frameworks but for us mere mortals it took a little extra digging to really understand how the Unit Test runners work.
https://lostechies.com/erichexter/2009/06/18/making-a-unit-test-framework-agnostic-assertion-in-c/
CC-MAIN-2022-40
refinedweb
502
67.38
Python is a programming language that lets you work quickly and integrate systems more effectively, and PostgreSQL is the world's most advanced open source database. Those two work very well together. This article describes how to make the most of PostgreSQL (psql) when solving a simple problem. As tempting as it is to throw Python code at a problem, it's not always the best choice. SQL comes with quite a lot of processing power, and integrating SQL into your workflow often means writing fewer lines of code. As Edsger Dijkstra said, lines of code are lines spent:. — Dijkstra, "On the cruelty of really teaching computing science." By using SQL, you write less code, so you can write applications in less time. A simple use case To examine how PostgreSQL and Python work well together, we'll use the New York Stock Exchange (NYSE) "Daily NYSE Group Volume in NYSE Listed" dataset. To download the data, go to the Facts & Figures Interactive Viewer, click on Market Activity, then click on Daily NYSE Group Volume in NYSE Listed. Then click on the "Excel" symbol at the top (which is actually a CSV file that uses Tab as a separator) to save the "factbook.xls" file to your computer, open it and remove the headings, then load it into a PostgreSQL table. Here's what the data looks like. It includes comma-separated thousands and dollar signs, so we can't readily process the figures as numbers. 2010 1/4/2010 1,425,504,460 4,628,115 $38,495,460,645 2010 1/5/2010 1,754,011,750 5,394,016 $43,932,043,406 2010 1/6/2010 1,655,507,953 5,494,460 $43,816,749,660 2010 1/7/2010 1,797,810,789 5,674,297 $44,104,237,184 To change this, we can create an ad-hoc table definition, and once the data is loaded, it's transformed into a proper SQL data type, thanks to alter table commands. BEGIN; CREATE TABLE factbook ( YEAR INT, DATE DATE, shares text, trades text, dollars text ); \copy factbook FROM 'factbook.csv' WITH delimiter E'\t' NULL '' ALTER TABLE factbook ALTER shares TYPE BIGINT USING REPLACE(shares, ',', '')::BIGINT, ALTER trades TYPE BIGINT USING REPLACE(trades, ',', '')::BIGINT, ALTER dollars TYPE BIGINT USING SUBSTRING(REPLACE(dollars, ',', '') FROM 2)::NUMERIC; commit; We can use PostgreSQL's copy functionality to stream the data from the CSV file into our table. The \copy variant is a psql-specific command and initiates client/server streaming of the data, reading a local file, and sending its contents through any established PostgreSQL connection. Application code and SQL There is a lot of data in this file, so let's use the data from February 2017 for this example. The following query lists all entries in the month of February 2017: \SET START '2017-02-01' SELECT DATE, to_char(shares, '99G999G999G999') AS shares, to_char(trades, '99G999G999') AS trades, to_char(dollars, 'L99G999G999G999') AS dollars FROM factbook WHERE DATE >= DATE :'start' AND DATE < DATE :'start' + INTERVAL '1 month' ORDER BY DATE; We use the psql application to run this query, and psql supports the use of variables. The \set command sets the '2017-02-01' value to the variable start, and then we can reuse the variable with the expression :'start'. Writing date :'start' is equivalent to date '2017-02-01'—this is called a decorated literal expression in PostgreSQL. This allows us to set the data type of the literal value so that the PostgreSQL query parser won't have to guess or infer it from the context. This SQL query also uses the interval data type to compute the end of the month, which is, of course, the last day of February in our example. Adding an interval value of 1 month to the first day of the month gives us the first day of the next month, so we use the "less than" ( <) strict operator to exclude this day from our result set. The to_char() function (documented in the PostgreSQL docs section on Data Type Formatting Functions) will convert a number to its text representation with detailed control over the conversion. The format is composed of template patterns. We'll use the following patterns: - Value with the specified number of digits L: currency symbol (uses locale) G: group separator (uses locale) Other template patterns for numeric formatting are available—see the PostgreSQL docs for reference. Here's the result of our query: date │ shares │ trades │ dollars ════════════╪═════════════════╪═════════════╪══════════════════ 2017-02-01 │ 1,161,001,502 │ 5,217,859 │ $ 44,660,060,305 2017-02-02 │ 1,128,144,760 │ 4,586,343 │ $ 43,276,102,903 2017-02-03 │ 1,084,735,476 │ 4,396,485 │ $ 42,801,562,275 2017-02-06 │ 954,533,086 │ 3,817,270 │ $ 37,300,908,120 2017-02-07 │ 1,037,660,897 │ 4,220,252 │ $ 39,754,062,721 2017-02-08 │ 1,100,076,176 │ 4,410,966 │ $ 40,491,648,732 2017-02-09 │ 1,081,638,761 │ 4,462,009 │ $ 40,169,585,511 2017-02-10 │ 1,021,379,481 │ 4,028,745 │ $ 38,347,515,768 2017-02-13 │ 1,020,482,007 │ 3,963,509 │ $ 38,745,317,913 2017-02-14 │ 1,041,009,698 │ 4,299,974 │ $ 40,737,106,101 2017-02-15 │ 1,120,119,333 │ 4,424,251 │ $ 43,802,653,477 2017-02-16 │ 1,091,339,672 │ 4,461,548 │ $ 41,956,691,405 2017-02-17 │ 1,160,693,221 │ 4,132,233 │ $ 48,862,504,551 2017-02-21 │ 1,103,777,644 │ 4,323,282 │ $ 44,416,927,777 2017-02-22 │ 1,064,236,648 │ 4,169,982 │ $ 41,137,731,714 2017-02-23 │ 1,192,772,644 │ 4,839,887 │ $ 44,254,446,593 2017-02-24 │ 1,187,320,171 │ 4,656,770 │ $ 45,229,398,830 2017-02-27 │ 1,132,693,382 │ 4,243,911 │ $ 43,613,734,358 2017-02-28 │ 1,455,597,403 │ 4,789,769 │ $ 57,874,495,227 (19 rows) The dataset has data for only 19 days in February 2017 (the days the NYSE was open). What if we want to display an entry for each calendar day and fill in the missing dates with either matching data or a zero figure? Here's a typical Python implementation of that: #! /usr/bin/env python3 import sys import psycopg2 import psycopg2.extras from calendar import Calendar CONNSTRING = "dbname=yesql application_name=factbook" def fetch_month_data(year, month): "Fetch a month of data from the database" date = "%d-%02d-01" % (year, month) sql = """ select date, shares, trades, dollars from factbook where date >= date %s and date < date %s + interval '1 month' order by date; """ pgconn = psycopg2.connect(CONNSTRING) curs = pgconn.cursor() curs.execute(sql, (date, date)) res = {} for (date, shares, trades, dollars) in curs.fetchall(): res[date] = (shares, trades, dollars) return res def list_book_for_month(year, month): """List all days for given month, and for each day list fact book entry. """ data = fetch_month_data(year, month) cal = Calendar() print("%12s | %12s | %12s | %12s" % ("day", "shares", "trades", "dollars")) print("%12s-+-%12s-+-%12s-+-%12s" % ("-" * 12, "-" * 12, "-" * 12, "-" * 12)) for day in cal.itermonthdates(year, month): if day.month != month: continue if day in data: shares, trades, dollars = data[day] else: shares, trades, dollars = 0, 0, 0 print("%12s | %12s | %12s | %12s" % (day, shares, trades, dollars)) if __name__ == '__main__': year = int(sys.argv[1]) month = int(sys.argv[2]) list_book_for_month(year, month) In this implementation, we use the above SQL query to fetch our result set and, moreover, to store it in a dictionary. The dict's key is the day of the month, so we can then loop over a calendar's list of days, retrieve matching data when we have it, and install a default result set (e.g., zeroes) when we don't have any data. Below is the output when running the program. As you can see, we opted for an output similar to the psql output, which makes it easier to compare the effort needed to reach the same result. $ ./factbook-month.py 2017 2 day | shares | trades | dollars -------------+--------------+--------------+------------- 2017-02-01 | 1161001502 | 5217859 | 44660060305 2017-02-02 | 1128144760 | 4586343 | 43276102903 2017-02-03 | 1084735476 | 4396485 | 42801562275 2017-02-04 | 0 | 0 | 0 2017-02-05 | 0 | 0 | 0 2017-02-06 | 954533086 | 3817270 | 37300908120 2017-02-07 | 1037660897 | 4220252 | 39754062721 2017-02-08 | 1100076176 | 4410966 | 40491648732 2017-02-09 | 1081638761 | 4462009 | 40169585511 2017-02-10 | 1021379481 | 4028745 | 38347515768 2017-02-11 | 0 | 0 | 0 2017-02-12 | 0 | 0 | 0 2017-02-13 | 1020482007 | 3963509 | 38745317913 2017-02-14 | 1041009698 | 4299974 | 40737106101 2017-02-15 | 1120119333 | 4424251 | 43802653477 2017-02-16 | 1091339672 | 4461548 | 41956691405 2017-02-17 | 1160693221 | 4132233 | 48862504551 2017-02-18 | 0 | 0 | 0 2017-02-19 | 0 | 0 | 0 2017-02-20 | 0 | 0 | 0 2017-02-21 | 1103777644 | 4323282 | 44416927777 2017-02-22 | 1064236648 | 4169982 | 41137731714 2017-02-23 | 1192772644 | 4839887 | 44254446593 2017-02-24 | 1187320171 | 4656770 | 45229398830 2017-02-25 | 0 | 0 | 0 2017-02-26 | 0 | 0 | 0 2017-02-27 | 1132693382 | 4243911 | 43613734358 2017-02-28 | 1455597403 | 4789769 | 57874495227 PostgreSQL advanced functions The same thing can be accomplished with a single SQL query, without any application code "spent" on solving the problem: SELECT CAST(calendar.entry AS DATE) AS DATE, COALESCE(shares, 0) AS shares, COALESCE(trades, 0) AS trades, to_char( COALESCE(dollars, 0), 'L99G999G999G999' ) AS dollars FROM /* * Generate the target month's calendar then LEFT JOIN * each day against the factbook dataset, so as to have * every day in the result set, whether or not we have a * book entry for the day. */ generate_series(DATE :'start', DATE :'start' + INTERVAL '1 month' - INTERVAL '1 day', INTERVAL '1 day' ) AS calendar(entry) LEFT JOIN factbook ON factbook.date = calendar.entry ORDER BY DATE; In this query, we use several basic SQL and PostgreSQL techniques that might be new to you: - SQL accepts comments written either in the -- commentstyle, running from the opening to the end of the line, or C-style with a /* comment */style. As with any programming language, comments are best used to note intentions, which otherwise might be tricky to reverse engineer from the code alone. generate_series()is a PostgreSQL set returning function, for which the documentation reads: "Generate a series of values, from start to stop with a step size of step." As PostgreSQL knows its calendar, it's easy to generate all days from any given month with the first day of the month as a single parameter in the query. generate_series()is inclusive, much like the BETWEENoperator, so we exclude the first day of the next month with the expression - interval '1 day'. - The cast(calendar.entry as date)expression transforms the generated calendar.entry, which is the result of the generate_series()function call into the datedata type. We need to use castbecause the generate_series()function returns a set of timestamp entries, which is not relevant to us in this exercise. - The left joinbetween our generated calendartable and the factbooktable will keep every calendarrow and associate a factbookrow with it only when the datecolumns of both the tables have the same value. When the calendar.dateis not found in factbook, the factbookcolumns ( year, date, shares, trades, and dollars) are filled in with NULLvalues instead. - Coalesce returns the first of its arguments that is not null. So the expression coalesce(shares, 0) as sharesis either how many shares we found in the factbooktable for this calendar.daterow, or 0 when we found no entry for the calendar.date. In addition, the left joinkept our result set row and filled in the factbookcolumns with NULLvalues. Finally, here's the result of this query: date │ shares │ trades │ dollars ════════════╪════════════╪═════════╪══════════════════ 2017-02-01 │ 1161001502 │ 5217859 │ $ 44,660,060,305 2017-02-02 │ 1128144760 │ 4586343 │ $ 43,276,102,903 2017-02-03 │ 1084735476 │ 4396485 │ $ 42,801,562,275 2017-02-04 │ 0 │ 0 │ $ 0 2017-02-05 │ 0 │ 0 │ $ 0 2017-02-06 │ 954533086 │ 3817270 │ $ 37,300,908,120 2017-02-07 │ 1037660897 │ 4220252 │ $ 39,754,062,721 2017-02-08 │ 1100076176 │ 4410966 │ $ 40,491,648,732 2017-02-09 │ 1081638761 │ 4462009 │ $ 40,169,585,511 2017-02-10 │ 1021379481 │ 4028745 │ $ 38,347,515,768 2017-02-11 │ 0 │ 0 │ $ 0 2017-02-12 │ 0 │ 0 │ $ 0 2017-02-13 │ 1020482007 │ 3963509 │ $ 38,745,317,913 2017-02-14 │ 1041009698 │ 4299974 │ $ 40,737,106,101 2017-02-15 │ 1120119333 │ 4424251 │ $ 43,802,653,477 2017-02-16 │ 1091339672 │ 4461548 │ $ 41,956,691,405 2017-02-17 │ 1160693221 │ 4132233 │ $ 48,862,504,551 2017-02-18 │ 0 │ 0 │ $ 0 2017-02-19 │ 0 │ 0 │ $ 0 2017-02-20 │ 0 │ 0 │ $ 0 2017-02-21 │ 1103777644 │ 4323282 │ $ 44,416,927,777 2017-02-22 │ 1064236648 │ 4169982 │ $ 41,137,731,714 2017-02-23 │ 1192772644 │ 4839887 │ $ 44,254,446,593 2017-02-24 │ 1187320171 │ 4656770 │ $ 45,229,398,830 2017-02-25 │ 0 │ 0 │ $ 0 2017-02-26 │ 0 │ 0 │ $ 0 2017-02-27 │ 1132693382 │ 4243911 │ $ 43,613,734,358 2017-02-28 │ 1455597403 │ 4789769 │ $ 57,874,495,227 (28 rows) Note that we replaced 60 lines of Python code with a simple SQL query. Down the road that means less code to maintain and a more efficient implementation, too. Here, the Python is doing a Hash Join Nested Loop while PostgreSQL picks a Merge Left Join over two ordered relations. Computing weekly changes Imagine the analytics department now wants us to provide the weekly difference for each day. This means we need to add a column with the change calculated as a percentage of the dollars column between each date and the same day of the previous week. I'm using the "week-over-week percentage difference" example because it's both a classic analytics need (although maybe mostly in marketing circles), and because (in my experience) a developer's first reaction is rarely to write a SQL query to do all the math. Also, the calendar isn't very helpful in computing weeks, but for PostgreSQL, this task is as easy as spelling the word week: WITH computed_data AS ( SELECT CAST(DATE AS DATE) AS DATE, to_char(DATE, 'Dy') AS DAY, COALESCE(dollars, 0) AS dollars, lag(dollars, 1) OVER( partition BY EXTRACT('isodow' FROM DATE) ORDER BY DATE ) AS last_week_dollars FROM /* * Generate the month calendar, plus a week before * so that we have values to compare dollars against * even for the first week of the month. */; To implement this case in SQL, we need window functions that appeared in the SQL standard in 1992, but are often skipped in SQL classes. The last things executed in a SQL statement are windows functions, well after join operations and where clauses. So, if we want to see a full week before the first of February, we need to extend our calendar selection a week into the past and then, once again, restrict the data we issue to the caller. That's why we use a common table expression—the WITH part of the query—to fetch the extended data set we need, including the last_week_dollars computed column. The expression extract('isodow' from date) is a standard SQL feature that allows computing the day of the week following ISO rules. Used as a partition by frame clause, it allows a row to be a peer to any other row having the same isodow. The lag() window function can then refer to the previous peer dollars value when ordered by date; that's the number that we want to compare to the current dollars value. The computed_data result set is then used in the main part of the query as a relation we get data from, and the computation is easier this time, as we simply apply a classic difference percentage formula to the dollars and the last_week_dollars columns. Here's the result from running this query: date │ day │ dollars │ WoW % ════════════╪═════╪══════════════════╪════════ 2017-02-01 │ Wed │ $ 44,660,060,305 │ -2.21 2017-02-02 │ Thu │ $ 43,276,102,903 │ 1.71 2017-02-03 │ Fri │ $ 42,801,562,275 │ 10.86 2017-02-04 │ Sat │ $ 0 │ ¤ 2017-02-05 │ Sun │ $ 0 │ ¤ 2017-02-06 │ Mon │ $ 37,300,908,120 │ -9.64 2017-02-07 │ Tue │ $ 39,754,062,721 │ -37.41 2017-02-08 │ Wed │ $ 40,491,648,732 │ -10.29 2017-02-09 │ Thu │ $ 40,169,585,511 │ -7.73 2017-02-10 │ Fri │ $ 38,347,515,768 │ -11.61 2017-02-11 │ Sat │ $ 0 │ ¤ 2017-02-12 │ Sun │ $ 0 │ ¤ 2017-02-13 │ Mon │ $ 38,745,317,913 │ 3.73 2017-02-14 │ Tue │ $ 40,737,106,101 │ 2.41 2017-02-15 │ Wed │ $ 43,802,653,477 │ 7.56 2017-02-16 │ Thu │ $ 41,956,691,405 │ 4.26 2017-02-17 │ Fri │ $ 48,862,504,551 │ 21.52 2017-02-18 │ Sat │ $ 0 │ ¤ 2017-02-19 │ Sun │ $ 0 │ ¤ 2017-02-20 │ Mon │ $ 0 │ ¤ 2017-02-21 │ Tue │ $ 44,416,927,777 │ 8.28 2017-02-22 │ Wed │ $ 41,137,731,714 │ -6.48 2017-02-23 │ Thu │ $ 44,254,446,593 │ 5.19 2017-02-24 │ Fri │ $ 45,229,398,830 │ -8.03 2017-02-25 │ Sat │ $ 0 │ ¤ 2017-02-26 │ Sun │ $ 0 │ ¤ 2017-02-27 │ Mon │ $ 43,613,734,358 │ ¤ 2017-02-28 │ Tue │ $ 57,874,495,227 │ 23.25 (28 rows) Have fun writing code, and as SQL is code, have fun writing SQL! This article is based on an excerpt from Dimitri Fontaine's book Mastering PostgreSQL in Application Development, which explains how to replace thousands of lines of code with simple queries. The book goes into greater detail on these topics and provides many other examples so you can master PostgreSQL and issue the SQL queries that fetch exactly the result set you need. 5 Comments
https://opensource.com/comment/147226
CC-MAIN-2022-21
refinedweb
2,972
64.54
#include "dmx.h" #include "dmxsync.h" #include "dmxcursor.h" #include "dmxlog.h" #include "dmxprop.h" #include "dmxinput.h" #include "mipointer.h" #include "windowstr.h" #include "globals.h" #include "cursorstr.h" #include "dixevents.h" "This code is based very closely on the XFree86 equivalent (xfree86/common/xf86Cursor.c)." --David Dawes. "This code was then extensively re-written, as explained here." --Rik Faith The code in xf86Cursor.c used edge lists to implement the CursorOffScreen function. The edge list computation was complex (especially in the face of arbitrarily overlapping screens) compared with the speed savings in the CursorOffScreen function. The new implementation has erred on the side of correctness, readability, and maintainability over efficiency. For the common (non-edge) case, the dmxCursorOffScreen function does avoid a loop over all the screens. When the cursor has left the screen, all the screens are searched, and the first screen (in dmxScreens order) containing the cursor will be returned. If run-time profiling shows that this routing is a performance bottle-neck, then an edge list may have to be reimplemented. An edge list algorithm is O(edges) whereas the new algorithm is O(dmxNumScreens). Since edges is usually 1-3 and dmxNumScreens may be 30-60 for large backend walls, this trade off may be compelling. The xf86InitOrigins routine uses bit masks during the computation and is therefore limited to the length of a word (e.g., 32 or 64 bits) screens. Because Xdmx is expected to be used with a large number of backend displays, this limitation was removed. The new implementation has erred on the side of readability over efficiency, using the dmxSL* routines to manage a screen list instead of a bitmap, and a function call to decrease the length of the main routine. Both algorithms are of the same order, and both are called only at server generation time, so trading clarity and long-term maintainability for efficiency does not seem justified in this case.
http://dmx.sourceforge.net/html/dmxcursor_8c.html
CC-MAIN-2017-17
refinedweb
325
59.8
AWS Developer Blog the Amazon.Lambda.AspNetCoreServer has been upgraded to target .NET Core 2.0. If you’re already using this library, you need to update your ASP.NET Core project to .NET Core 2.0 before using this latest version. ASP.NET Core 2.0 has a lot of changes that make running a serverless ASP.NET Core Lambda function even more exciting. These include performance improvements in the ASP.NET Core and underlying .NET Core libraries. Razor Pages The Lambda runtime now supports Razor Pages. This means we can deploy both ASP.NET Core Web API and ASP.NET Core web applications. An important change with ASP.NET Core 2.0 is that Razor Pages are now precompiled at publish time. This means when our serverless Razor Pages are first rendered, Lambda compute time isn’t spent compiling the Razor Pages from cshtml to machine instructions. Runtime package store Starting with .NET Core 2.0 there is a new runtime package store feature, which is a cache of NuGet packages already installed on the target deployment platform. These packages have also been pre-jitted, meaning they’re already compiled from .NET’s intermediate language (IL) to machine instructions. This improves startup time when you use these packages. The store also reduces your deployment package size, further improving the cold startup time. For example, our existing ASP.NET Core Web API blueprint for .NET Core 1.0 had a minimum size of about 2.5 MB for the deployment package. For the .NET Core 2.0 version of the blueprint, the size is about 0.5 MB. To indicate that you want to use the runtime package store for an ASP.NET Core application, you add a NuGet dependency to Microsoft.AspNetCore.All. Adding this dependency makes all of the ASP.NET Core packages and Entity Framework Core packages available to your application. However, it doesn’t include them in the deployment package because they’re already available in Lambda. The Lambda blueprints that are available in Visual Studio are configured to use Microsoft.AspNetCore.All, just like the Microsoft-provided ASP.NET Core Web project templates inside Visual Studio. If you’re migrating a .NET Core 1.0 project to .NET Core 2.0, I highly recommend swapping out individual ASP.NET Core references to Microsoft.AspNetCore.All. .NET Core and runtime package store version Currently, the .NET Core 2.0 Lambda runtime is running .NET Core 2.0.4 and includes version 2.0.3 of Microsoft.AspNetCore.All. As the .NET Core 2.0 Lambda runtime was rolling out to the AWS Regions, Microsoft released version 2.0.5 of the .NET Core runtime and 2.0.5 of Microsoft.AspNetCore.All in the runtime package store. The Lambda runtime will be updated to include the latest versions shortly. However, in the meantime, if you update your Microsoft.AspNetCore.All reference to version 2.0.5, the Lambda function will fail to find the dependency when it runs. If you use either the AWS Toolkit for Visual Studio or our dotnet CLI extensions to perform the deployment, and attempt to deploy with a newer version of Microsoft.AspNetCore.All than is available in Lambda, our packaging will prevent the deployment and inform you of the latest version you can use with Lambda. This is another reason we recommend you use either the AWS Toolkit for Visual Studio or our dotnet CLI extensions to create the Lambda deployment package, so that we can provide that extra verification of your project. Getting started The AWS Toolkit for Visual Studio provides two blueprints for ASP.NET Core applications. The first is the ASP.NET Core Web API blueprint, which we updated from the preview in .NET Core 1.0 to take advantage of the new .NET Core 2.0 features. The second is a new ASP.NET Core Web App blueprint, which demonstrates the use of the ASP.NET Core 2.0 new Razor Pages feature in a serverless environment. Let’s take a look at that blueprint now. To access the Lambda blueprints, choose File, New Project in Visual Studio. Under Visual C#, choose AWS Lambda. The ASP.NET Core blueprints are serverless applications, because we want to use AWS CloudFormation to configure Amazon API Gateway to expose the Lambda function running ASP.NET Core to an HTTP endpoint. To continue, choose AWS Serverless Application (.NET Core), name your project, and then click OK. On the Select Blueprint page, you can see the two ASP.NET Core blueprints. Choose the ASP.NET Core Web App blueprint, and then click Finish. When the project is created, it looks just like a regular ASP.NET Core project. The main difference is that Program.cs was renamed to LocalEntryPoint.cs, which enables you to run the ASP.NET Core project locally. Another difference is the file LambdaEntryPoint.cs. This file contains a class that derives from Amazon.Lambda.AspNetCoreServer.APIGatewayProxyFunction and implements the Init method that’s used to configure the IWebHostBuilder, similar to LocalEntryPoint.cs. The only required element to configure is the startup class that ASP.NET Core will call to configure the web application. The APIGatewayProxyFunction base class contains the FunctionHandlerAsync method. This method is declared as the Lambda handler in the serverless.template file that defines the AWS Lambda function and configures Amazon API Gateway. If you rename the class or namespace, be sure to update the Lambda handler in the serverless.template file to reflect the new name. public class LambdaEntryPoint :>(); } } To deploy the ASP.NET Core application to Lambda, right-click the project in Solution Explorer, and then choose Publish to AWS Lambda. This starts the deployment wizard. Because no parameters are defined in the serverless.template, we just need to enter an AWS CloudFormation stack name and an Amazon S3 bucket in the region the application is being deployed, to which the Lambda deployment package will be uploaded. After that, choose Publish to begin the deployment process. Once the Lambda deployment package is created and uploaded to Amazon S3, and the creation of the AWS CloudFormation stack is initiated, the AWS CloudFormation stack view is launched. This view lists the events as the AWS resources are created. When the stack is created, a URL to the generated API Gateway endpoint is shown. Clicking the link displays your new serverless ASP.NET Core web application. Using images If your web application displays images, we recommend you serve those images from Amazon S3. This is more efficient for returning static content like images, Cascading Style Sheets, etc. Also, to return images from your Lambda function to the browser, you need to do extra configuration in API Gateway for binary data. Migrating Existing ASP.NET Core Web API Projects Before our new release we already had a preview blueprint for using ASP.NET Core Web API on Lambda using .NET Core 1.0. To migrate that project make the following changes to your csproj file project. - Make sure the Sdk attribute in root element of your csproj is set to Microsoft.NET.Sdk.Web. The preview blueprint had this attribute set to Microsoft.NET.Sdk. <Project Sdk="Microsoft.NET.Sdk.Web"> - Update Amazon.Lambda.AspNetCoreServer reference to 2.0.0 <PackageReference Include="Amazon.Lambda.AspNetCoreServer" Version="2.0.0" /> - Replace any references to Microsoft.AspNetCore.* and Microsoft.Extensions.* with Microsoft.AspNetCore.All version 2.0.3 <PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.3" /> - Update target framework to netcoreapp2.0 - Set the property GenerateRuntimeConfigurationFiles to true to make sure a project-name.runtimeconfig.json is created. <PropertyGroup> <TargetFramework>netcoreapp2.0</TargetFramework> <GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles> </PropertyGroup> - If your csproj has the following xml you can remove it because appsetings.json will now be included by default since you changed the Sdk attribute to Microsoft.NET.Sdk.Web. <ItemGroup> <Content Include="appsettings.json"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> </ItemGroup> After that make any changed necessary to your code to be compatible with ASP.NET Core 2.0 and you are ready to deploy. Conclusion With all of the improvements in .NET Core and ASP.NET Core 2.0, it’s exciting to see it running in a serverless environment. There’s a lot of potential with running ASP.NET Core on Lambda, and we’re excited to hear your thoughts about running a serverless ASP.NET Core application. Check out our GitHub repository which contains our libraries that make this possible. Feel free to open issues for any questions you have.
https://aws.amazon.com/blogs/developer/serverless-asp-net-core-2-0-applications/
CC-MAIN-2020-24
refinedweb
1,423
54.49
Set the seed for a pseudo-random number generator #include <stdlib.h> void srandom( unsigned int seed ); libc Use the -l c option to qcc to link against this library. This library is usually included automatically. The srandom() function initializes the current state array using the value of seed. Use this function in conjunction with the following: The random() and srandom() functions have (almost) the same calling sequence and initialization properties as rand() and srand(). After initialization, a state array can be restarted at a different point in one of two ways: POSIX 1003.1 XSI drand48(), initstate(), rand(), random(), setstate(), srand()
https://www.qnx.com/developers/docs/6.4.1/neutrino/lib_ref/s/srandom.html
CC-MAIN-2018-13
refinedweb
102
57.16
Organizing large JSP into smaller chunks Robin Clark Ranch Hand Joined: Dec 17, 2003 Posts: 81 posted Jan 21, 2004 15:37:00 0 I am trying to organize a very large JSP into smaller more organized chunks. However, when I implement some of the functionality in a separate java class, my jsp will not compile successfully because it can not see the new class. I have successfully compiled the java class and installed the .class file in my web application's WEB-INF/classes directory. I even created a jar file with the new class and placed it in the web application's WEB-INF/lib directory and the Tomcat common/lib directory. I've stopped and started Tomcat as well. Here is an excerpt from the jsp: <?xml version = "1.0"?> <vxml version = "2.0"> <form> <var name = "nextPrompt" expr = "'1'" /> <var name = "sessionCount" expr = "'1'" /> <block> at the beginning of the file capture prompt </block> <%@page import="java.util.*"%> <%@page import="com.oreilly.servlet.MultipartRequest"%> <%@page import="com.oreilly.servlet.multipart.*"%> <% com.oreilly.servlet.multipart.MultipartParser mpP= new MultipartParser(request, 1000000); Part pt; String channelType = ""; String phoneNbr = ""; String promptID = ""; String promptNbr = ""; String audioStream = ""; // retrieve parameters from getFileName.jsp submit while ((pt=mpP.readNextPart())!=null) { String name = pt.getName(); ParamPart paramPart = (ParamPart)pt; if (name != null && name.equals("channel_type")) { channelType = paramPart.getStringValue(); } else if (name != null && name.equals("phoneNbr")) { phoneNbr = paramPart.getStringValue(); } else if (name != null && name.equals("audio")) { audioStream = paramPart.getStringValue(); } else if (name != null && name.equals("promptID")) { promptID = paramPart.getStringValue(); } else if (name != null && name.equals("promptNbr")) { promptNbr = paramPart.getStringValue(); } else { getServletContext().log("Got a parameter I did not expect"); } } } // end of while loop to retrieve parameters passed in submit UtteranceInfo utt = new UtteranceInfo(channelType, promptID, PromptNbr, phoneNbr); The error that I get is when compiling the last statement that instantiates the UtteranceInfo object. The error message is: Generated servlet error: C:\Program Files\Apache Tomcat 4.0\work\Standalone\localhost\logTest\capturePrompt$jsp.java:123: Class org.apache.jsp.UtteranceInfo not found. UtteranceInfo utt = new UtteranceInfo(channelType, ^ Here is an excerpt for the code for the UtteranceInfo class: import java.io.*; import java.text.*; import java.util.*; public class UtteranceInfo { public static final String USERFILE = "users.txt"; public static final String TMPFILE = "tmpusers.txt"; private String channelType; private String promptID; private String promptNbr; private String phoneNbr; private String servletPathRoot; private String uttPathName; private String date; private int sessionNbr; public UtteranceInfo(String channelType, String sex, String promptID, String promptNbr, String phoneNbr) { this.channelType = channelType; this.sex = sex; this.promptID = promptID; this.phoneNbr = phoneNbr; this.promptNbr = promptNbr; //get the timestamp Date today; String dateString; SimpleDateFormat formatter; formatter = new SimpleDateFormat("ddMMyy_HHmm", Locale.US); today = new Date(); date = formatter.format(today); } private String getDate() { return date; } Robin Clark Ranch Hand Joined: Dec 17, 2003 Posts: 81 posted Jan 21, 2004 15:41:00 0 I accidently submitted that post before I finished editting it. Here is the correct code excerpt from the UtteranceInfo class: import java.io.*; import java.text.*; import java.util.*; public class UtteranceInfo { private String channelType; private String promptID; private String promptNbr; private String phoneNbr; public UtteranceInfo(String channelType, String promptID, String promptNbr, String phoneNbr) { this.channelType = channelType; this.promptID = promptID; this.phoneNbr = phoneNbr; this.promptNbr = promptNbr; } This is the first time that I have ever tried to instantiate a java class from within my jsp. I am using Tomcat 4.0.6 on Windows 2000 server. Thank you very much for your help. Bear Bibeault Author and ninkuma Marshal Joined: Jan 10, 2002 Posts: 58819 59 I like... posted Jan 21, 2004 16:28:00 0 You need to put the class in a package other than the nameless "default" package. [ Asking smart questions ] [ Bear's FrontMan ] [ About Bear ] [ Books by Bear ] Frank Carver Sheriff Joined: Jan 07, 1999 Posts: 6920 posted Jan 22, 2004 07:05:00 0 And you probably also need to add another line <%@page import="whatever.UtteranceInfo"%> so that your JSP knows where to look for the class. Read about me at frankcarver.me ~ Raspberry Alpha Omega ~ Frank's Punchbarrel Blog Robin Clark Ranch Hand Joined: Dec 17, 2003 Posts: 81 posted Jan 22, 2004 07:45:00 0 Thank you. I am having trouble putting these pieces together. I have created a new directory WEB-INF/classes/utterance. In this directory is my .class file for my java class. I changed the java class to add a package statement to the top. Is this the correct syntax for the package statement? package utterance; In my jsp, I added an import directive like this: <%@page import="utterance"%> I bounced Tomcat, but I still get the following error when I try to execute my jsp in a browser: org.apache.jasper.JasperException: Unable to compile class for JSP C:\Program Files\Apache Tomcat 4.0\work\Standalone\localhost\newtest\capturePrompt$jsp.java:8: Class utterance not found in import. import utterance; ^ 1 error I am confused a bit further because I am trying to do this in Eclipse and I don't understand what it is doing when I try to create a new package, "utterance" under the WEB-INF/classes directory when my project is at the web application root level. What it does is create a directory under the web application root level for the .java file, then it places the .class file in the WEB-INF/classes/utterance directory. But I guess that question should be directed to the IDE forum. Any help would be greatly appreciated. Robin Clark Ranch Hand Joined: Dec 17, 2003 Posts: 81 posted Jan 22, 2004 07:57:00 0 I think that I figured this out. My import directive in the jsp was wrong. It should have been: <%@page import="utterance.*"%> I think that I am trying to learn too many new things at one time: Java JSP VoiceXML Eclipse Tomcat subject: Organizing large JSP into smaller chunks Similar Threads Upload using O'Reilly package File field content Testing multipart submit in jsp request.getParameterValues not working Redirect after file upload All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter JForum | Paul Wheaton
http://www.coderanch.com/t/284150/JSP/java/Organizing-large-JSP-smaller-chunks
CC-MAIN-2013-48
refinedweb
1,026
50.94
Hey, Currently I making a little program that takes: Clients name and then the tracking code for that client and saves it in a 'char array' However, my following code is not producing a file: Code:#include <iostream> #include <fstream> #include <string.h> using namespace std; int main() { ofstream firstClass; char cname[25]; char trackno[14]; char outFileName[256]; int z; cout <<"Enter the client name: "; cin >> cname; cout <<"Okay, Thats saved..." << endl; cout <<" " << endl; cout <<"Please now enter the tracking code: "; cin >> trackno; cout << "Set the output file name: "; cin.getline(outFileName,256); firstClass.open(outFileName); firstClass << trackno; firstClass.close(); cin >> z; return 0; }
http://cboard.cprogramming.com/cplusplus-programming/149702-input-output-how-create-file.html
CC-MAIN-2015-18
refinedweb
105
60.85
I just started a computer course that involves basic Python programming. Unfortunately, I'm not finding it so 'basic'. The first couple of tasks were easier, but I struggling with the next part. We were given this code as starting point and have to finish it according to the requirements below: def askUserToSayHello(): return raw_input('Please say hello: ') I need to finish the code above so that it satisfies the following requirements: 1. There is a line of code before the loop that sets done to False. Where done represents whether the user has done what was asked of them - that is, they typed hello into the shell when asked 2. There is a while loop that will continue to loop until done is True 3. The function askUserToSayHello is used in the loop to repeatedly ask the user to say hello until they actually do. 4. When the user says hello, the program should print ‘Thanks!’ before finishing. Note that the result of askUserToSayHello can be compared against the equality operator, which is written as == 5. When the user says anything else, the program should print some sort of warning
http://www.python-forum.org/viewtopic.php?p=9406
CC-MAIN-2014-52
refinedweb
191
70.94
Testing Dependencies with Overrides¶ Warning The current page still doesn't have a translation for this language. But you can help translating it: Contributing. Overriding dependencies during testing¶ There are some scenarios where you might want to override a dependency during testing. You don't want the original dependency to run (nor any of the sub-dependencies it might have). Instead, you want to provide a different dependency that will be used only during tests (possibly only some specific tests), and will provide a value that can be used where the value of the original dependency was used. Use cases: external service¶ An example could be that you have an external authentication provider that you need to call. You send it a token and it returns an authenticated user. This provider might be charging you per request, and calling it might take some extra time than if you had a fixed mock user for tests. You probably want to test the external provider once, but not necessarily call it for every test that runs. In this case, you can override the dependency that calls that provider, and use a custom dependency that returns a mock user, only for your tests. Use the app.dependency_overrides attribute¶ For these cases, your FastAPI application has an attribute app.dependency_overrides, it is a simple dict. To override a dependency for testing, you put as a key the original dependency (a function), and as the value, your dependency override (another function). And then FastAPI will call that override instead of the original dependency. from typing import Union from fastapi import Depends, FastAPI from fastapi.testclient import TestClient app = FastAPI() async def common_parameters( q: Union[str, None] = None, skip: int = 0, limit: int = 100 ): return {"q": q, "skip": skip, "limit": limit} @app.get("/items/") async def read_items(commons: dict = Depends(common_parameters)): return {"message": "Hello Items!", "params": commons} @app.get("/users/") async def read_users(commons: dict = Depends(common_parameters)): return {"message": "Hello Users!", "params": commons} client = TestClient(app) async def override_dependency(q: Union[str, None] = None): return {"q": q, "skip": 5, "limit": 10} app.dependency_overrides[common_parameters] = override_dependency def test_override_in_items(): response = client.get("/items/") assert response.status_code == 200 assert response.json() == { "message": "Hello Items!", "params": {"q": None, "skip": 5, "limit": 10}, } def test_override_in_items_with_q(): response = client.get("/items/?q=foo") assert response.status_code == 200 assert response.json() == { "message": "Hello Items!", "params": {"q": "foo", "skip": 5, "limit": 10}, } def test_override_in_items_with_params(): response = client.get("/items/?q=foo&skip=100&limit=200") assert response.status_code == 200 assert response.json() == { "message": "Hello Items!", "params": {"q": "foo", "skip": 5, "limit": 10}, } Tip You can set a dependency override for a dependency used anywhere in your FastAPI application. The original dependency could be used in a path operation function, a path operation decorator (when you don't use the return value), a .include_router() call, etc. FastAPI will still be able to override it. Then you can reset your overrides (remove them) by setting app.dependency_overrides to be an empty dict: app.dependency_overrides = {} Tip If you want to override a dependency only during some tests, you can set the override at the beginning of the test (inside the test function) and reset it at the end (at the end of the test function).
https://fastapi.tiangolo.com/nl/advanced/testing-dependencies/
CC-MAIN-2022-40
refinedweb
536
50.53
function works fine without return value?@[b]lwtan90 (2)[/b]: Compiler should not return a error! It must return a warning, like that: [... inline functionAlready got it. I checked out mode: [b]"In C mode, support all ISO C90 programs."[/b] inline functionI try to use next declaration of [b]inline[/b] function: [code] #include <stdio.h> int main () ... Thats not supposed to hapen. Why did it?Yes, [b]Moschops[/b], right. You need to declare you function before [b]main.c[/b] or use header fi... Having trouble understanding logic of FunctionsYou need not to declare the variable "n" in external function. You need only declare the variabl... This user does not accept Private Messages
http://www.cplusplus.com/user/SimpleIce/
CC-MAIN-2017-09
refinedweb
116
73.03
Created on 2018-11-12 13:23 by 零欸特, last changed 2018-11-29 22:03 by eryksun. This issue is now closed. Windows 7 x64 Python 3.7.1 (v3.7.1:260ec2c36a, Oct 20 2018, 14:57:15) [MSC v.1915 64 bit (AMD64)] Steps to reproduce: 1. Create a script: ``` from subprocess import run run(["cmd.exe", "/c", "python"]) run(["python"]) run("python", shell=True) ``` 2. Run the script. Actual result: The script will invoke Python REPL 3 times. The first and the third REPL don't save the command history. Pressing up/down arrows would clear the entire line. Pressing F7 has no effect. The second REPL works fine. Expected result: Command history should work in all instances. The Windows console has a fixed number of history buffers. In Windows 7 the default maximum is four history buffers. In this case, if we run a script via cmd.exe -> py.exe -> python.exe, then only one history buffer remains for a child process. As you've observed, no history buffer is available for the fifth process if we run cmd.exe -> python.exe. You can increase the default maximum in the console's Alt+Space+D defaults dialog, under "Command History" -> "Number of Buffers". This corresponds to the "NumberOfHistoryBuffers" value in the registry key "HKCU\Console". You can increase the maximum for the current window in the console's Alt+Space+P properties dialog. If the current console was allocated by an application that was launched from a shortcut (i.e. a .LNK file), this property gets persisted in the shortcut itself. Otherwise it gets persisted in a registry key under "HKCU\Console" that's named for the startup window title. If no title was specified, the default title is the path to the executable, with backslashes replaced by underscore and the Windows directory as %SystemRoot%. For example, if you run cmd.exe from the Win+R run dialog, its console properties are stored in the registry key "HKCU\Console\%SystemRoot%_system32_cmd.exe".
https://bugs.python.org/issue35217
CC-MAIN-2021-17
refinedweb
337
69.28
We wanted a quick (and free) way to lookup the SIC code for a stock symbol in python. You can do this manually with the SEC’s EDGAR website, but if your list is 100’s of stock symbols this can get old pretty quickly. The following code makes use of Python’s BeautifulSoup package to extract the SIC code from the SEC’s website. To install Beautiful Soup on your CoCo, open a connection and type: sudo apt-get install python-bs4 Then you can import Beautiful Soup in python with: from bs4 import BeautifulSoup as bs Then we can define a function to grab the SIC code: def query_sic(symbol): url = '' + symbol.upper() url += '&Find=Search&owner=exclude&action=getcompany' res = urllib2.urlopen(url) res = res.read() soup = bs(res) return int(soup.find_all('a')[9].contents[0]) No doubt there are more robust ways to do this; if the SEC add’s or subtracts a link this will need adjustment. Nevertheless we thought this quick and dirty method would provide value, as our own Google searches on the subject did not yield any useful results. You could also extend this code to scrape the human readable name of the sector. Let’s redefine the function to accept an additional parameter, readable , which defaults to True and controls which format we want returned by the function: def query_sic(symbol, readable = True): url = '' + symbol.upper() url += '&Find=Search&owner=exclude&action=getcompany' res = urllib2.urlopen(url) res = res.read() soup = bs(res) if readable == True: return soup.p.text.split(' - ')[1].split('State location')[0] else: return int(soup.find_all('a')[9].contents[0]) Some examples: symbol = "AAPL" code = query_sic(symbol) Which produces an output of “ELECTRONIC COMPUTERS” Or you can download a list: import pandas as pd codes = [] symbols = ['AAPL', 'MSFT', 'CSCO', 'GILD', 'GE', 'V'] for symbol in symbols: codes.append(query_sic(symbol)) codes = pd.DataFrame(codes, index = symbols) Lead image licensed under CC-BY-SA 2.5 from EvaK Categories: Python, Quant Tools 3 replies »
https://mktstk.com/2015/03/03/sic-lookup-by-stock-symbol/
CC-MAIN-2018-17
refinedweb
338
64.91
Created on 2008-06-15.03:32:14 by pjenvey, last changed 2014-09-18.02:26:06 by zyasoft. old style classes create a PyFinalizableInstance when a__del__ method is defined (unfortunately there's even problems with that to: ) new style classes don't do anything similar however, thus __del__ methods are never called this prevents test_descr's delhoook and subtype_resurrection from passing Ideally we'd also warn the user if they apply a __del__ after the fact (see #1634167) But subtype resurrection is evil anyway ;) I think this is a major and longstanding departure from CPython's behavior. Can it be fixed for Jython 2.7 please? Blocker for 2.7, we really should fix Perhaps we can emulate this support via tracking with weak references, then dequeueing the corresponding reference queue and calling __del__, vs using a finalizer method that calls __del__. Such an approach would also support possible resurrection. The tricky bit will be to figure out how to making object construction even more expensive than it already is. As was discussed in #1634167, dynamically adding __del__ to the class of with some existing object x would not call x.__del__(), since we do not track the objects of a given class. A RuntimeWarning should be generated in this case like PyPy (). In dialogue with Jim, I developed a solution based on what was referred to as FinalizeGuardian in. Appended is only a draft and not yet an actual fix, because I wanted to discuss some of its implications here first. In addition to the appended stuff one would have to change all the XxxDerived classes as follows: Let XxxDerived-classes implement FinalizablePyObject and add a member FinalizeTrigger finalizeTrigger; like I demonstrated with PyFinalizableInstance and PyFinalizableObject. In every constructor must be appended: PyType self_type=getType(); PyObject impl=self_type.lookup("__del__"); if (impl!=null) finalizeTrigger = FinalizeTrigger.makeTrigger(this); And finally add a __del__-method: public void __del__() { PyObject impl = self_type.lookup("__del__"); if (impl != null) { impl.__get__(this,self_type).__call__(); FinalizeTrigger.resurrectOnDemand(this); } } IMHO, this should fix it; at least with the same constraint as in the fix of issue 1634167. The nice thing is, that for instances of XxxDerived that don't have a __del__ finalizer, Java won't have to create an expensive Java-finalizer, since finalizeTrigger just stays null. I developed this approach also with JyNI-integration as a design goal. Especially the methods FinalizeTrigger.prohibitFinalize and FinalizeTrigger.allowFinalize might seem inherently evil as they allow to make certain objects temporarily immortal. To implement a clean garbage collection in JyNI, it sometimes needs to resurrect a gc'ed object in a controlled way and in this case, the finalizer, if any, should not be called by a FinalizeTrigger, nor should the object be reclaimed. JyNI needs this time to check, whether native resources exist that still need the corresponding object. I reasoned carefully about this and do not see a feasible alternative to this approach. However, I will do my best to let such situations arise as rarely as possible. Again, if JyNI is not used, this evil stuff won't be done anyway. The implementation just ensures that it can be done without breaking Jython's own finalization process. As an implication of this, it must be forbidden for subclasses of PyObject to implement finalize(), which I enforce by adding protected final void finalize() throws Throwable {} to it. An appropriate adjustment for PyFinalizableInstance is included. However, it might break existing third-party implemented subclasses of PyObject, if they implement finalize. I still recommend this change for Jython 2.7., as such third-party implementations would be trivial to fix. Additionally, I suppose that they are rather rare, if existent at all, since there is a common consens to avoid using finalizers. Another note: The attached implementation would allow to reproduce CPython's behavior regarding to repeated object resurrection. Prior to 3.4 it would also repeatedly call the finalizer, which is not emulated by current solution for. My proposed solution would fix this for as well. However, Jim pointed out that it might be better to directly stick to Cpython's >= 3.4 behavior (i.e. call __del__ only once, like Java would do and thus prohibit repeated resurrection). The proposed solution would support both variants and switching between them is a trivial adjustment. One could even make it configurable. I did not yet test this approach with Jython, but I tested the used principles with some dummy classes in detail. Depending on your reply I will do actual test with Jython and work it out as an actual patch. I unfortunately discovered that the technique to automatically detect resurrection (used in resurrectOnDemand) only works, if there occurs a gc-run before the resurrected object becomes unreachable again. I overlooked this behaviour first (sorry for that!), because in my tests I always called System.gc multiple times to assure it ran at least once. Since in usual cases one does not control when gc runs, it would actually be undefined whether repeated finalization would work or not, wich I consider worse than having it never work. One would have to detect a gc-run and re-run every time, which is unreasonably expensive in best case and maybe even impossible. So I would stick to the suggestion to directly perform Python 3.4 behavior here. Next topic. I forked Jython to implement and test this. Besides other tests, I explored how CPython behaves if an instance (not the class!) acquires a finalizer. A = SomeClass() A.__del__ = blah There are issues with binding the method to the instance, but basically a __del__ method is not necessarily required to be bound to its instance. However it appears that instance-acquired finalizers are supported for old style classes in CPython, but not for new style. We could emulate this behavior in Jython for old style classes. The technique with FinalizeGuardian/FinalizeTrigger just requires that the Java object holds the single reference to a FinalizeTrigger, which in turn contains the actual finalizer. To support instace-acquired __del__, the PyInstanceClass would need to be enhanched by such a memeber, which would simply be null for all instances without __del__. If we chose this variant, there would be no more need for the PyFinalizableInstance class any more and it could be removed or deprecated. But maybe we would not want to increase the memory demand for old style python objects by one reference per object in general. To avoid this, one could add the FinalizeTrigger to the instance's dictionary instead. This would only increase memory usage for objects that need it, but would somehow mess up their dictionary with an object that is irrelevant from Python view. Additionally one would have to implement FinalizeTrigger as a PyObject, which also increases memory demand. And there would be checks necessary to move the trigger to the new dict if the dict is replaced. So please let's decide how to proceed. Shall instance-acquired finalizers be supported or not, considering the given costs? If so, should it be done via a member or via the dictionary? Or maybe someone has a better idea how to hide a reference to a FinalizeTrigger in the PyInstance I did not consider yet? I finally decided to have finalizeTrigger in every PyInstance and removed PyFinalizableInstance. Benefits: - It is possible for instances to acquire __del__ finalizers like in CPython - If a class acquires a __del__ method this will be only active for instances created after the calss acquired the finalizer. Now it is possible to at least manually tell already existing instances to be finalizable: Add to import section: if platform.system() == "Java": from org.python.core.finalization import FinalizeTrigger After a class acquired a finalizer, one can call if platform.system() == "Java": FinalizeTrigger.ensureFinalizer(alreadyExistingInstance) - CPython prior to 3.4 allows repeated object resurrection, i.e. calls finalizers again, if an object was already gc'ed, resurrected and gc'ed again. This behavior cannot be reproduced by Java automatically. So the fix behaves like CPython >= 3.4 by default. However, one can use if platform.system() == "Java": FinalizeTrigger.ensureFinalizer(resurrectedInstance) to tell Java manually that a repeated finalization is intended. This way one can fix code that depends on CPython < 3.4 behavior. I propose to forbid PyObjects o have a finalize method. This is done by adding a final empty implementation. This has no performance impact, since empty finalizers are optimized away. See This forces a clean use of the new finalization API. However, without this constraint everything should still work, except that one cannot fix repeated finalization manually. The real problems only arise if JyNI is used. It will cause that Java-finalizers might be called too early, i.e. when objects are still needed. This is a side-effect of its way to deal with garbage collection for extensions. Given that an easy fix for PyObjects that need Java finalizers is available (it is explained by detailed instructions in FinalizablePyObject's javadoc) and that Jython 2.7 is a significant step, I recommend to undertake this break here. If you should not agree, I would suggest to make it fire a compiler-warning (can anyone tell me how to do this?) stating that problems with JyNI will probably arise, if Java-finalizers are used. In that case I would recommend to forbid finalizers at least for Jython 3+ versions. Feel free to review the patch at It passes regrtests with no notable difference to Jython without the fix (which actually fails 25-27 regrtests on my system). I added a new test demonstrating the new capabilities as Lib/test/test_finalizers.py According to the patch guidelines, I should create an svn diff file and provide it here. These guidelines appear outdated to me, which is why I created a mercurial commit in bitbucket instead. Please let me know, if the svn diff is still needed or where I can find an updated patch guide. Fixed as of
http://bugs.jython.org/issue1057
CC-MAIN-2014-52
refinedweb
1,665
57.16
In App Engine push queues, a task is a unit of work to be performed by the application. Each task is an object of the Task Python app sets up queues using a configuration file named queue.yaml (see Python Task Queue Configuration). If an app does not have a queue.yaml file, it has a queue named default with some default settings. To enqueue a task, you call the taskqueue.add() function. (You can also create a Task object and call its add() method.) The task consists of data for a request, including a URL path, parameters, HTTP headers, and an HTTP payload. It can also include the earliest time to execute the task (the default is as soon as possible) and a name for the task. The task is added to a queue, then performed by the Task Queue service as the queue is processed. The following example defines a task handler ( CounterWorker) that increments a counter in the datastore, mapped to the URL /worker. It also defines a user-accessible request handler that displays the current value of the counter for a GET request, and for a POST request enqueues a task and returns. It's difficult to visualize the execution of tasks with the user-accessible handler if the queue processes them too quickly. Therefore, the task in this example should run at a rate no greater than once per second. import os import jinja2 import webapp2 from google.appengine.api import taskqueue from google.appengine.ext import ndb JINJA_ENV = jinja2.Environment( loader=jinja2.FileSystemLoader(os.path.dirname(__file__))) class Counter(ndb.Model): count = ndb.IntegerProperty(indexed=False) class CounterHandler(webapp2.RequestHandler): def get(self): template_values = {'counters': Counter.query()} counter_template = JINJA_ENV.get_template('counter.html') self.response.out.write(counter_template.render(template_values)) def post(self): key = self.request.get('key') # Add the task to the default queue. taskqueue.add(url='/worker', params={'key': key}) self.redirect('/') class CounterWorker(webapp2.RequestHandler): def post(self): # should run at most 1/s due to entity group limit key = self.request.get('key') @ndb.transactional def update_counter(): counter = Counter.get_or_insert(key, count=0) counter.count += 1 counter.put() update_counter() APP = webapp2.WSGIApplication( [ ('/', CounterHandler), ('/worker', CounterWorker) ], debug=True) (In this example, 'counters.html' refers to a Jinja2 template that contains the HTML for a page that displays the counter value, and a button to trigger a POST request to the / URL.) The full application is available at our github repository. Note that this example is not idempotent. It is possible for the task queue to execute a task more than once. In this case, the counter is incremented each time the task is run, possibly skewing the results. using the url parameter of the Task class. The url must be relative and local to your application's root directory. The module and version in which the handler runs is determined by: - The targetor headerkeyword arguments in your call to the Task()constructor. - The targetdirective in the queue.yamlfile. 1of a module named backend1, using the targetdirective: from google.appengine.api import taskqueue # ... def post(self): key = self.request.get('key') # Add the task to the default queue. taskqueue.add(url='/path/to/my/worker/', params={'key': key}, target='1.backend1') secondsedError(from the module google.appengine.runtime) before directive in queue.yaml. TaskRet Developers Console Task queues page .a property. This specifies the earliest time that a task can execute. App Engine always waits until after the specified ETA to process push tasks. - The value of the task's countdown property. This specifies the minimum number of seconds to wait before executing a task. Countdown and eta are mutually exclusive; if you specify one, do not specify the other. Deferred tasks, please see the Built-in Handlers section of the Python Application Configuration page., please refer to Background Work with the Deferred Library.: from google.appengine.api import taskqueue taskqueue.add(url='/path/to/my/worker') taskqueue.add(url='/path?a=b&c=d', You can prevent users from accessing URLs of tasks by restricting access to administrator accounts. Task queues can access admin-only URLs. You can restrict a URL by adding login: admin to the handler configuration in app.yaml. An example might look like this in app.yaml: application: hello-tasks version: 1 runtime: python27 api_version: 1 threadsafe: true handlers: - url: /tasks/process script: process.app login: admin For more information see Python Application Configuration: Requiring Login or Administrator Status. tasks from running in the development server, run the following command: dev_appserver.py --disable_task_running You can examine and manipulate tasks from the Developers Console Task queues page ..yaml Developers Console Quota details page ). The following limits apply to the use of push queues:
https://cloud.google.com/appengine/docs/python/taskqueue/overview-push
CC-MAIN-2015-32
refinedweb
784
52.76
Facets of Ruby by Dave Thomas You can learn Ruby in 4 hours. This talks isn't to learn Ruby, but rather to show facets of Ruby. Ruby has made programming fun again for Dave. It's also made him more productive. Languages and tools make a difference Ruby has variables, methods, but no types in methods. When Dave first started using Ruby, he had a strong typing background - and was terrified of Ruby's un-typed feature. He first thought Ruby was a toy language for hobbyists because of the lack of typing. Now, many years later, he really likes the lack of typing and hardly even has bugs relating to typing. He notes that with Java we store most of our data in Collections - and those are all Objects - so Java is essentially un-typed as well. How often do you get ClassCastExceptions? The rooms concensus is not not a whole lot. To make up for the lack of typing, Ruby developers tend to write a lot more unit tests. ActiveRecord - Ruby O/R Mapping Library Ruby on Rails - not a single line of XML. Uses intelligent defaults and allows you to override them. The following creates a wrapper around the "ranks" table. class Rank < ActiveRecord::Base end The original author of RoR thinks that every database table should be plural, so singular class names map to plural table names. It's even smart enough to change Person to a "people" database table. Apparently it has a bunch of the singular-to-plural mappings for the English language built-in. The key to Rails is clever defaulting - allow you to write a lot less code, but override if you really need to. ActiveRecord has many lifecyle hooks (17) that you can override. For example, before_save, before_destroy, validate. For example def before_save self.when_added ||= Time.now end I wonder if Rails has any support for transactions and specifying propagation behavior on transactions? I asked Dave this question and it sounds like ActiveRecord has a rich support for transactions - and even wraps the "save" method with a transaction by default. "Ruby is pretty damn good at web applications" Simple CGI is a common choice. FastCGI and mod_ruby in Apache are other common choices. There are also a number of different web frameworks for Ruby: - Roll-your-own - Templating systems - erb - Amarita - RDoc templates - Iowa - similar to WebObjects - Ruby on Rails Ruby on Rails - MVC Framework Contoller - one method per view. Setup context (a.k.a. the model) for views. Views contain "rhtml" - HTML with embedded Ruby. Lots of helper functions. Can access model data (context) setup by Controller. The name of the method in the Controller determines the name of the view file. A "select" method will dispatch to a "select.rhtml" file. The method name to call in a Controller is determined by the URI - for example, /ranks/view calls the "view" method in the RanksController class. Pretty slick! I like the idea of smart defaults - IMO this should be used a lot more in webapps. I'd love to get away from mapping URLs in Struts, Spring and WebWork. Rails has built-in support for configurable URLs - so you can change query strings to more slash-type URLs. What about things like client-side validation, success messages and sortable/pageable tables? Do those exist in Rails? I asked Dave and he said said they have good support for success messages with a "flash" concept and the post-to-redirect problem is almost non-existant because most controller invocations are redirects. Client-side validation and sortable/pageable tables don't exist in Rails. Rails has Needles - and IoC framework similar to Pico. However, there's a fair amount of traffic on the mailing list and a lot of Ruby developers think they just don't need IoC. Dave's suggestion is to use Class Injection. The largest Ruby application is probably Daves - 55,000 lines or code, couple hundred thousand users. There are entire companies who write all all their applications in Ruby. The founder of Rails wrote it so he could write Basecamp - which is only 4500 lines of code. Good stuff Dave - and definitely a nice overview of Rails. Will I be digging in an using Rails anytime soon? Not this year, I'm going to have some fun with Tapestry and JSF first. Maybe next year.
https://raibledesigns.com/rd/entry/facets_of_ruby_by_dave
CC-MAIN-2022-21
refinedweb
730
74.79
Recent changes to 42: problems when adding elements in Roma when adding elements in Roma2008-07-24T13:50:18Z2008-07-24T13:50:18Zron van den branden<div class="markdown_content"><p>I think there are two anomalies to the "Add elements" tab in Roma (<>). I'll describe the problems and provide a way of reproducing them, thereby pointing to two screenshots and an ODD file. I'll try to add those in a zip file to illustrate my point.</p> <p>1. When adding a new element with the same name as an existing TEI element, but in a different namespace, Roma objects with the error message: "Element already exists". I admit that adding elements with the same name is questionable, but thought that's what namespaces were for?<br /> --> steps taken:<br /> 1. start from <a href="" rel="nofollow"></a> --> 'Submit'<br /> 2. move to <a href="" rel="nofollow"></a><br /> 3. choose 'p' as element name; "" as namespace<br /> 4. press 'Submit'<br /> --> result: romaAdd1.jpg</p> <p>2. After successfully adding an element, the list of added elements shows a 'Submit query' button. If that is pressed, the Roma interface presents a new empty input screen for adding new elements. After successful addition of a new element, only the latter element shows up in the "List of added elements". What seems to happen underneath is that pressing the 'Submit query' button in the screen listing the added elements changes the "add" mode of these elements to "change" in the underlying ODD file. I think this is a bug; apparently the 'Submit query' button at this stage is not needed at all.<br /> --> steps taken:<br /> 1. start from <a href="" rel="nofollow"></a> --> 'Submit'<br /> 2. move to <a href="" rel="nofollow"></a><br /> 3. add an element 'blabla' in namespace "", belonging to the "model.divLike" class --> 'Submit'<br /> 4. press 'Submit' in the list of added elements (romaAdd2.jpg)<br /> 5. add a new element 'blabla2' in namespace "", belonging to the "model.divLike" class --> 'Submit'<br /> 6. the list of added elements only shows "blabla2"<br /> 7. generate the ODD file<br /> --> result: myTei.xml</p> <p>Ron</p></div>
https://sourceforge.net/p/tei/bugs/42/feed.atom
CC-MAIN-2017-13
refinedweb
363
67.25
{-# OPTIONS_GHC -O2 #-} import System.IO import System.Environment import System.CPUTime import Text.Printf import Control.Monad import Control.Concurrent import Control.Concurrent.MVar import Control.Exception {- This test creates a number of threads in blocked mode, and then calls killThread on each one in turn. Since the threads are in blocked mode, none of the killThreads can complete until the target thread has exited, so this tests thread creation/completion as well as throwTo blocking/unblocking performance. On a 1.86GHz Intel Xeon, with GHC 6.10.1 -threaded ./Main 300000 +RTS -s 338,144,560 bytes allocated in the heap 1,232,944,856 bytes copied during GC 307,446,192 bytes maximum residency (9 sample(s)) 109,796,160 bytes maximum slop 786 MB total memory in use (12 MB lost due to fragmentation) Generation 0: 640 collections, 0 parallel, 2.42s, 2.44s elapsed Generation 1: 9 collections, 0 parallel, 0.63s, 1.22s elapsed INIT time 0.00s ( 0.00s elapsed) MUT time 7.64s ( 7.75s elapsed) GC time 3.05s ( 3.65s elapsed) EXIT time 0.04s ( 0.04s elapsed) Total time 10.73s ( 11.44s elapsed) HEAD 7/1/2009 + patch to use HpLim for context-switching: ./Main 300000 +RTS -s 354,865,480 bytes allocated in the heap 1,229,475,576 bytes copied during GC 306,480,832 bytes maximum residency (9 sample(s)) 109,806,448 bytes maximum slop 780 MB total memory in use (13 MB lost due to fragmentation) Generation 0: 643 collections, 0 parallel, 2.53s, 2.56s elapsed Generation 1: 9 collections, 0 parallel, 0.66s, 1.27s elapsed INIT time 0.00s ( 0.00s elapsed) MUT time 1.06s ( 1.06s elapsed) GC time 3.19s ( 3.83s elapsed) EXIT time 0.04s ( 0.04s elapsed) Total time 4.28s ( 4.93s elapsed) (probably this is mostly due to not context-switching after forkIO) -} main :: IO () main = do hSetBuffering stdout NoBuffering [nthreads] <- fmap (map read) getArgs tids <- replicateM nthreads . mask_ $ forkIO $ return () m <- newEmptyMVar -- do it in a subthread to avoid bound-thread overhead forkIO $ do mapM_ killThread tids; putMVar m () takeMVar m return ()
https://gitlab.haskell.org/ghc/nofib/-/blame/cf032a225ce9e896f6a0ecadc6fd09969ade6249/smp/threads006/Main.hs
CC-MAIN-2020-45
refinedweb
360
69.68
. An interesting feature of NumPy arrays is that we can perform the same mathematical operation on every element with a single command. Note: Both exponential and logarithmic operations are supported. import numpy as np arr = np.array([[5, 10], [15, 20]]) # Add 10 to element values print("Adding 10: " + repr(arr + 10)) # Multiple elements by 5 print("Multiplying by 5: " + repr(arr * 5)) # Subtract 5 from elements print("Subtracting 5: " + repr(arr - 5)) # Matrix multiplication arr1 = np.array([[-8, 7], [17, 20], [8, -16], [11, 4]]) arr2 = np.array([[5, -5, 10, 20], [-8, 0, 13, 2]]) print("Multiplying two arrays: " + repr(np.matmul(arr1, arr2))) # Exponential arr3 = np.array([[1, 5], [2.5, 2]]) # Exponential of each element print("Taking the exponential: " + repr(np.exp(arr3))) # Cubing all elements print("Making each element a power of 3: " + repr(np.power(3, arr3))) Since the goal is to produce something useful out of a dataset, NumPy offers several statistical tools such as min, max, median, mean and sum. import numpy as np arr = np.array([[18, 5, -25], [-10, 30, 7], [8, 16, -2]]) print "Min: ", arr.min() print "Max: ", arr.max() print "Sum: ", np.sum(arr) print "Mean: ", np.mean(arr) print "Median: ", np.median(arr) print "Variance: ", np.var(arr)
https://www.educative.io/answers/how-to-perform-arithmetic-operations-in-numpy
CC-MAIN-2022-40
refinedweb
212
53.27
I am looking at the online Help as I write an export UDF, and I am not able to get the fileContents working. What is a stringified json and how do I use it. Can you please provide an example? It's just a json in string form. Check out this python library Great answer Ray! More color:To get the information, start with a function that looks like thisimport jsondef exportUDF(inStr): obj = json.loads(inStr) contents = obj["fileContents"] import jsondef exportUDF(inStr): obj = json.loads(inStr) contents = obj["fileContents"] Thanks for your help! I was trying to write a sample main to generate some data. I was missing double quotes My code below now works. msg = []ss = "AUDUSD,72850,2017-06-28 16:46:17.830,0.00344776010689,2878"for ii in xrange(100): msg.append(ss)jsonStr = '{{"fileContents" : "{}"}}'.format('\n'.join(msg))main(jsonStr) Nicely done Mark!
https://discourse.xcalar.com/t/white-check-mark-what-is-a-stringified-json/141
CC-MAIN-2020-40
refinedweb
150
62.14
11 February 2011 06:27 [Source: ICIS news] SINGAPORE (ICIS)--?xml:namespace> Prices were assessed to be stable at $650-700/tonne (€481-518/tonne) FOB (free on board) SE (southeast) Asia on 10 February from the previous month, according to data from ICIS. Most industry sources said they did not expect prices to change much during the rest of the month. Prices of feedstock tapioca - steady now - could be volatile later in February due to acute tapioca shortages in Indonesia and Thailand from bad weather conditions, traders said. But this was unlikely to impact the prices of sorbitol as monthly contracts had already been settled, an Indonesian producer said. Any volatility in tapioca feedstock prices in February would only impact March sorbitol cargo prices, the producer added. Feedstock tapioca prices in February was a lull season for sorbitol in ($1 = €0.74/ $1 = Bt30.83/ $1 = Rp8,9
http://www.icis.com/Articles/2011/02/11/9434386/asia-feb-sorbitol-prices-seen-steady-as-high-demand-declines.html
CC-MAIN-2015-22
refinedweb
149
64.3
view raw I was making a function that returns the longest string value from a list. My code works when there is only one string with the most characters. I tried to make it print all of the longest strings if there were more than one, and I do not want them to be repeated. When I run this, it only returns 'hello', while I want it to return 'ohman' and 'yoloo' also. I feel like the problem is in the line if item not list: list = ['hi', 'hello', 'hey','ohman', 'yoloo', 'hello'] def length(lists): a = 0 answer = '' for item in lists: x = len(item) if x > a: a = x answer = item elif x == a: if item not in list: answer = answer + ' ' + item return answer print length(list) First, we can find the maximum length of any string in the list: stringlist = ['hi', 'hello', 'hey','ohman', 'yoloo', 'hello'] #maxlength = max([len(s) for s in stringlist]) maxlength = max(len(s) for s in stringlist) # omitting the brackets causes max # to operate on an iterable, instead # of first constructing a full list # in memory, which is more efficient A little explanation. This is called a list comprehension, which allows you to comprehend one list as another list. The code [len(s) for s in stringlist] means "generate a list-like object, by taking stringlist, and for every s in that list, give me instead, len(s) (the length of that string). So now we have a list [2, 5, 3, 5, 5, 5]. Then we call the built-in max() function on that, which will return 5. Now that you have the max length, you can filter the original list: longest_strings = [s for s in stringlist if len(s) == maxlength] This does just as it reads in english: "For each string s in stringlist, give me that string s, if len(s) is equal to maxlength." Finally, if you want to make the result unique, you can use the set() constuctor to generate a unique set: unique_longest_strings = list(set(longest_strings)) (We are calling list() to turn it back into a list after removing the duplicates.) This boils down to: ml = max(len(s) for s in stringlist) result = list(set(s for s in stringlist if len(s) == ml)) Note: Don't use a variable named list, as it overrides the meaning of the name for the list type.
https://codedump.io/share/RqOZcv4dT2Pk/1/longest-strings-from-list
CC-MAIN-2017-22
refinedweb
399
65.09
Feature: Modules and workflow dependencies It would be really nice if I can: - write module in Pythonista - export it to Editorial to a place where I do not need to set path for modules, already set, just import module - update module in Editorial from Pythonista - set workflow dependencies - other workflows - modules - share workflow with dependencies - install workflow with dependencies Workflow dependencies on modules are more important from my point of view. I would like to put lot of shared functionality there. Yes, I know it's possible even now, but it's kind of not easy if anyone wants to use workflow with module, there are workflows like Save as Python, ... Is anything like this planned? Or at least better cooperation between Pythonista & Editorial in modules area? Sharing, exporting, updating, ... You might look at how these two Editorial workflows work. I know them, but they doesn't help in situations like this for example. Freshly installed workflow without dependencies. Lot of manual work to make it working on another device. This workflow depends on another one. Same applies to modules, ... I, as author, do know what to do, but other users will have no clue even if I describe it somewhere. When Editorial allows me to share workflow like this, it should share it with dependencies and download it with dependencies as well. Kind of bundle. To be able to install everything at once. Check my blogpost. User must go through tapping hell to install all workflows mentioned there. @ccc Check RV: Workflow Installer. That's what I meant (except Python modules). I made it for myself. Would be nice to have this in Editorial directly.
https://forum.omz-software.com/topic/1749/feature-modules-and-workflow-dependencies
CC-MAIN-2022-27
refinedweb
276
67.35
, ... EXECVE(2) OpenBSD Programmer's Manual EXECVE(2) NAME execve - execute a file SYNOPSIS #include <unistd.h> int execve(const char *path, char *const argv[], char *const envp[]); DESCRIPTION repre- senting the initial program (text) and initialized data pages. Addition- al pages may be specified by the header to be initialized with zero data; see a.out effective group ID is the first element of the group list.) The real us- er system as released is 20480. CAVEAT If a program is setuid to a non-super-user, but is executed when the real uid is ``root'', then the program has some of the powers of a super-user as well. SEE ALSO _exit(2), fork(2), execl(3), exit(3), environ(7) HISTORY The execve() function call appeared in 4.2BSD. OpenBSD 2.6 January 24, 1994 3
http://rocketaware.com/man/man2/execve.2.htm
CC-MAIN-2017-51
refinedweb
139
55.84
Decorator indicating a method is both a class and an instance method Project description Python has instance methods, class methods (@classmethod), and static methods (@staticmethod). But it doesn’t have a clear way to invoke a method on either a class or its instances. With combomethod, it does. from combomethod import combomethod class A(object): @combomethod def either(receiver, x, y): return x + y a = A() assert a.either(1, 3) == 4 assert A.either(1, 3) == 4 Voila! You method now takes either the class or the instance–whichever one you want to call it with. Discussion In some cases, you can fake @combomethod with @classmethod. In the code above, for example, there is no real reference to the class or instance, and either could have been designated a @classmethod, since they can be called with either classes or instances. But, there’s a problem: Class methods always pass the class to the method, even if they’re called with an instance. With this approach, you can never access the instance variables. Ouch! Alternatively, either could have been designated a @staticmethod, had its receiver parameter been removed. But while it would then be callable from either an instance or a class, in neither case would it pass the object the method was called from. There’d never be a way to access either the class or instance variables. Ouch again! As useful as @classmethod and @staticmethod are, they don’t handle the (occasionally important) corner case where you need to call with either the class or an instance and you need genuine access to the object doing the call. Here’s an example that needs this: class Above(object): base = 10 def __init__(self, base=100): self.base = base @combomethod def above_base(receiver, x): return receiver.base + x a = Above() assert a.above_base(5) == 105 assert Above.above_base(5) == 15 aa = Above(12) assert aa.above_base(5) == 17 assert Above.above_base(5) == 15 When you need to call with either an instance or a class, and you also care about the object doing the calling, @combomethod rocks and rolls. Notes This module is primarily a convenient packaging, testing, and documentation of insights and code from Mike Axiak’s Stack Overflow post. Thank you, Mike! Automated multi-version testing managed with pytest, pytest-cov, coverage, and tox. Continuous integration testing with Travis-CI. Packaging linting with pyroma. Successfully packaged for, and tested against, all late-model versions of Python: 2.6, 2.7, 3.3, 3.4, 3.5, 3.6, and 3.7 pre-release as well as the latest PyPy and PyPy3 builds. See CHANGES.yml for the complete Change Log. The author, Jonathan Eunice or @jeunice on Twitter welcomes your comments and suggestions. Installation To install or upgrade to the latest version: pip install -U combomethod You may need to prefix these with sudo to authorize installation. In environments without super-user privileges, you may want to use pip’s --user option, to install only for a single user, rather than system-wide. You may also need Python-version-sepecific pip2 or pip3 installers, depending on your system configuration. In cases where pip isn’t well-configured for a specific Python instance you need, a useful fallback: python3.6 -m pip install -U combomethod Project details Release history Release notifications | RSS feed Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/combomethod/
CC-MAIN-2022-40
refinedweb
576
65.93
Hey I am trying to created a dice game that roll the dice twice and then ask the user if he/she thinks the next two rolls will be more than or less than the first two. After the third roll the program is then suppose to ask the user if he/she would like to change her guess. Then after the fourth row the output is suppose to either say "you won" or "you lost." I can't seem to figure out how to get the machine to print out more than or less than and to accept the different words of "MORE," or "more,"or "m," or "M" all for the more than value. I also need help when it comes to asking the user if he/she would like to change his/her guess and how to set this up. I appreciate your help. Here is my code so far. import java.util.Scanner; public class DiceGame2 { public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); int aRandomNumber, resultOne, resultTwo; String moreThan, lessThan, userInput, userInput2, userInput3; aRandomNumber = (int) (Math.random()*6) + 1;{ System.out.println(aRandomNumber); System.out.println(aRandomNumber); resultOne = (aRandomNumber + aRandomNumber); System.out.println("Will the sum of the next two rolls be more than "+ "or less than " + resultOne+"?"); userInput = keyboard.nextLine(); System.out.println("Your third roll was "+ aRandomNumber +". Do you want" +" to change your guess?"); userInput2 = keyboard.nextLine(); resultTwo = (aRandomNumber + aRandomNumber); System.out.println("Your fourth roll is "+ aRandomNumber +". Your second " +"total is "+resultTwo +"."); } } }
https://www.daniweb.com/programming/software-development/threads/148362/dice-game-help
CC-MAIN-2017-26
refinedweb
254
58.08
shm_unlink - remove a shared memory object (REALTIME) [SHM] #include <sys/mman.h>#include <sys/mman.h> int shm_unlink(const char *name); The shm_unlink() function shall remove the name of the shared memory object named by the string pointed to by name. If one or more references to the shared memory object exist when the object is unlinked, the name shall be removed before shm_unlink() returns, but the removal of the memory object contents shall be postponed until all open and map references to the shared memory object have been removed.).: - [EACCES] - Permission is denied to unlink the named shared memory object. - [ENAMETOOLONG] - The length of the name argument exceeds {PATH_MAX} or a pathname component is longer than {NAME_MAX}. - [ENOENT] - The named shared memory object does not exist._open(), the Base Definitions volume of IEEE Std 1003.1-2001, <sys/mman.h>.
http://pubs.opengroup.org/onlinepubs/009604499/functions/shm_unlink.html
crawl-003
refinedweb
141
52.6
-- "@. module Control.Concurrent.CHP.Channels.Creation ( Chan, Channel(..), newChannel, ChanOpts(..), defaultChanOpts, chanLabel, newChannelWR, newChannelRW, ChannelTuple(..), newChannelList, newChannelListWithLabels, newChannelListWithStem, labelChannel ) where import Control.Monad import Data.Unique import Control.Concurrent.CHP.Base import Control.Concurrent.CHP.Channels.Base import Control.Concurrent.CHP.Mutex import Control.Concurrent.CHP.Traces.Base -- | A class used for allocating new channels, and getting the reading and -- writing ends. There is a bijective assocation between the channel, and -- its pair of end types. You can see the types in the list of instances below. -- Thus, 'newChannel' may be used, and the compiler will infer which type of -- channel is required based on what end-types you get from 'reader' and 'writer'. -- Alternatively, if you explicitly type the return of 'newChannel', it will -- be definite which ends you will use. If you do want to fix the type of -- the channel you are using when you allocate it, consider using one of the -- many 'oneToOneChannel'-like shorthand functions that fix the type.OptsShow :: a -> String, chanOptsLabel :: Maybe String } -- | The default: don't show anything, don't label anything -- -- Added in version 1.5.0. defaultChanOpts :: ChanOpts a defaultChanOpts = ChanOpts (const "") Nothing -- | Uses the Show instance for showing the data in traces, and the given label. -- -- Added in version 1.5.0. chanLabel :: Show a => String -> ChanOpts a chanLabel = ChanOpts show .). newChannel :: (MonadCHP m, Channel r w) => m (Chan r w a) newChannel = newChannel' defaultChanOpts -- |. class ChannelTuple t where newChannels :: MonadCHP m => m t -- | (const "") (Just $ s ++ show i) | i <- [0 .. (n - 1)]] -- | A helper that is like 'newChannelList', but labels the channels with the -- given list. The number of channels returned is the same as the length of -- the list of labels newChannelListWithLabels :: (Channel r w, MonadCHP m) => [String] -> m [Chan r w a] newChannelListWithLabels = mapM (newChannel' . ChanOpts (const "") . Just) instance (Channel r w) => ChannelTuple (Chan r w a, Chan r w a) where newChannels = do c0 <- newChannel c1 <- newChannel return (c0, c1) instance (Channel r w) => ChannelTuple (Chan r w a, Chan r w a, Chan r w a) where newChannels = do c0 <- newChannel c1 <- newChannel c2 <- newChannel return (c0, c1, c2) instance (Channel r w) => ChannelTuple (Chan r w a, Chan r w a, Chan r w a, Chan r w a) where newChannels = do c0 <- newChannel c1 <- newChannel c2 <- newChannel c3 <- newChannel return (c0, c1, c2, c3) instance (Channel r w) => ChannelTuple return (c0, c1, c2, c3, c4) instance (Channel r w) => ChannelTuple (Chan r w a, c5 <- newChannel return (c0, c1, c2, c3, c4, c5) -- | Labels a channel in the traces. It is easiest to do this at creation. -- The effect of re-labelling channels after their first use is undefined. -- -- Added in version 1.5.0. labelChannel :: MonadCHP m => Chan r w a -> String -> m () labelChannel c = liftCHP . liftPoison . liftTrace . labelUnique (getChannelIdentifier c) instance Channel Chanin Chanout where newChannel' o = do c <- chan (stmChannel $ <- newMutex c <- newChannel' o return $ Chan (getChannelIdentifier c) (Shared (m, reader c)) (writer c) sameChannel (Shared (_, Chanin x)) (Chanout y) = x == y instance Channel Chanin (Shared Chanout) where newChannel' o = do m <- <- newMutex m' <-)
http://hackage.haskell.org/package/chp-2.0.0/docs/src/Control-Concurrent-CHP-Channels-Creation.html
CC-MAIN-2016-50
refinedweb
516
53.92
The. Proxy switcher , network profiles , network settings management , network connection manager , automatic network detection , Internet settings , location profiles The free NPM Lite version has been developed for individuals that find themselves constantly changing Internet settings to access the internet. With NPM 2014 Lite you can create network profiles that match your frequently used locations (home, work and your favourite cafe) so that as soon as your there, the right Internet Settings will be applied; just open the lid and surf. NPM 2014 Lite works with ...all recent versions of Internet Explorer, Firefox, Chrome and Opera. Profiles are easily created using a query based system (DNS suffix, IP Address or SSID for example) to identify a network connection. When a network connection becomes available NPM qualifies each defined profile against the connection in priority order (top down) until a match is found. If no match is found the default ''Unknown Network'' profile is used. All actions associated to the matched profile will then be run. Proxy switcher , network profiles , network settings management , network connection manager , automatic network detection , Internet settings , location profiles. befaster lite , befaster review , BeFaster Lie , labelswin lite , kryptel lite , bearshare lite , divx lite , qt lite , myfolder l. Free sitemap generator , sitemap software. allproxy lite , messenger lite , freewire lite , kioware lite , Viewer Lite , godraw lite , weatherbug lite , notemagic lite , replay lite , passkey lite Opera 9.6 enhances the performance and flexibility of Operas built-in e-mail client, while adding new features to Operas free browser-synchronization service. Classic Opera features including tabbed browsing, Quick Find, fraud protection, saved sessions, Speed Dial, notes and the trash can also make for a great browsing experience. Significant speed improvements in Opera 9.6 allow you to spend more ...time getting things done online. Opera Mail (M2), Opera''s built-in e-mail client, now features low-bandwidth mode to facilitate working while on a network with limited connectivity. To enable low-bandwidth mode, click under the Mail menu option. Opera will then download only the minimal amount of data necessary to retrieve the e-mail. This feature also allows you to manage your emails quicker and more efficiently. Opera Mail (M2). Opera Link, Opera''s browser synchronization service, now synchronizes typed browser history and your customized search engines in addition to notes, bookmarks, your Speed Dial and personal bar. You can synch between multiple versions of Opera 9.6 and even Opera Mini, Operas free browser for your mobile phone. To learn more about Opera Link, visit Cutting-edge widgets - small and handy Web programs - make everyday browsing fun and useful by bringing a variety of Web content and data right to your desktop. You can play games, get organized, follow your favorite sports teams and more. update opera , opera dawnload , opera flashplayer , WYSIWYG opera , opera lite , metropolitan opera , opera help , opera flv , opera tablet , education opera platform to its users who want to import data from Opera Mail to Outlook. The software has simple GUI, supports ...single as well as batch conversion and provides consistent results, making it ideal application to import data from Opera Mail to Outlook. Use this application on any Windows based system (10, 8.1, 8, 7 XP etc.) and successfully import data from Opera Mail to Outlook for Mac (Outlook 2011) systems and Windows (Outlook 2016, 2013, 2010, 2007 and 2003) editions .Demo edition of the software allows conversion of 10 emails from every Opera Mail folder, as a free trial. Unlimited conversion of Opera Mail data to Outlook, licensed edition of the software is required available only at 29USD. import data from opera mail to outlook Opera Password Recovery!. Find out Opera Password , password manager , Opera Password remover , Opera Password Recovery. opera password manager , opera saved passwords , opera passwords , password safe , password storage , saved passwords , password keeper , sign into opera , saved passwords in opera PC Activity Monitor Lite (PC Acme Lite) is designed for monitoring user''s PC activity. cheating spouse , internet eraser This smart utility is for those who always forget their Internet passwords. It''s the first program that can decrypt Opera browser passwords as well as to decrypt Opera Master Password. The program has two recovery modes, has some extended features to view and organize Opera cookies, favorites, disk cache, AutoComplete and URL history. Opera Password , opera passwords , password recovery , password recovery rar , Recovery Passwords , Passwords Recovery , Recovery Password , wagner opera , opera latestversion , Opera Addin Speed across the web with this super-fast, flexible, and efficient browser. Opera is a fast, small, secure, configurable, and standards compliant Internet/intranet browser. Opera gives you the freedom to run multiple windows without opening up other instances and many more features that make it the best choice for the serious web enthusiast. With Opera, speed, flexibility, features, and security, ...the Internet is now even more convenient. opera version , opera english , opera browsers , browser version , version browser , browser opera , Opera Browser , english english , opera rss , opera download Opera Password by Thegrideon Software is advanced password recovery and decryption tool for Opera Browser. Opera Password allows you to recover Master Password and logins and passwords saved in Browser cache (decrypts wand.dat password database). Several configurable attacks are available for Master Password recovery. Highly optimized code guarantees maximum performance (e.g. more than 2 millions ...passwords per second on Intel i3). Supports up to 64 simultaneous processing threads (multi-CPU, multi-core and HT). opera password recovery , wand password recovery , wand dat , decrypt opera passwords , master password , opera profile , opera login recovery. The Phantom of the Opera by Gaston Leroux. The Phantom of the Opera , Gaston Leroux Challenging and fun opera glasses puzzle for you to solve. Complete to win! opera glasses puzzle , opera glasses jigsaw Filter: All / Freeware only / Title OS: Mac / Mobile / Linux Sort by: Download / Rating / Update Opera Block Flash Opera 10 fix Opera Flash Opera 10 opera 9 23 opera browser lite kaaza lite opera singer desktop Opera Capture Stream Video Opera Mini mp3 Player Import csv Contacts Opera opera mni 4 Opera Video Plugin Opera Flash Player cab pms opera donload Flash Plugin Audio Opera Mobile 10 wm
http://freedownloadsapps.com/s/opera-lite/
CC-MAIN-2018-17
refinedweb
1,017
54.42
MimeTreeParser::MessagePart #include <messagepart.h> Detailed Description The MessagePart class. Definition at line 54 of file mimetreeparser/src/messagepart.h. Member Function Documentation The KMime::Content* node that's the source of this part. This is not necessarily the same as content(), for example for broken-up multipart nodes. Definition at line 111 of file mimetreeparser/src/messagepart.cpp. - See also - KMime::Content::index() - See also - NodeHelper::asHREF Definition at line 131 of file mimetreeparser/src/messagepart.cpp. The KMime::Content* node that's represented by this part. Can be nullptr, e.g. for sub-parts of an inline signed body part. Definition at line 101 of file mimetreeparser/src/messagepart.cpp. Returns a string representation of an URL that can be used to invoke a BodyPartURLHandler for this body part. Definition at line 136 of file mimetreeparser/src/messagepart.cpp. The documentation for this class was generated from the following files: Documentation copyright © 1996-2021 The KDE developers. Generated on Fri Apr 9 2021 23:13:58 by doxygen 1.8.11 written by Dimitri van Heesch, © 1997-2006 KDE's Doxygen guidelines are available online.
https://api.kde.org/kdepim/messagelib/html/classMimeTreeParser_1_1MessagePart.html
CC-MAIN-2021-17
refinedweb
187
53.27
#include <lib_ca.h> Weight tag. Retrieves the joint object at index. Gets the total joint count. Retrieves the rest state for the joint at index. Sets the rest state for the joint at index. Fills map with the weights, which must be allocated with cnt elements (should be the point count). Sets the weights with map. Gets the total number of stored weights. Retrieves the windex weight and which point index pntindex. Retrieves the weight for the point formatParam{pntindex}. Sets the weight for formatParam{pntindex}. Gets the dirty state of the weights. Marks the weights dirty. Retrieves the global matrix for the bind geometry. Sets the global matrix for the bind geometry. Adds a joint object to the weight tag's "Joints" list. Removes a joint object from the weight tag's "Joints" list. Helper function to initialize the joint at index. Fills in the bind state (JointRestState::m_oMg and JointRestState::m_oMi) and then call the function to set JointRestState::m_bMg, JointRestState::m_bMi and JointRestState::m_Len. Reset the pose to the bind pose previously set. Set the bind pose to the currently set joint state. Transfers the weights from one weight tag to another.
https://developers.maxon.net/docs/Cinema4DCPPSDK/html/class_c_a_weight_tag.html
CC-MAIN-2021-39
refinedweb
195
79.87
I've created a program which outputs the capitals from different sentences within a file. So the output is like this: line 0: the dog_SUBJ bit_VERB the cat_OBJ ['SUBJ', 'VERB', 'OBJ'] line 1: the man_SUBJ ran_VERB ['SUBJ', 'VERB'] line 2: the cat_SUBJ ate_VERB the cheese_OBJ ['SUBJ', 'VERB', 'OBJ'] I want to number the lists of 'SUBJ', 'VERB' and 'OBJ' for each sentence so I can compare the order. I would like to do it all in the same loop (if it is possible). Can anybody help me do this with my current script? Here is the code: import re with open('findallEX.txt', 'r') as f: for ii, line in enumerate(f): print 'line %s: %s' % (ii, line) results = [] results += re.findall(r'[A-Z]+', line) Thanks!
http://www.python-forum.org/viewtopic.php?p=2855
CC-MAIN-2016-07
refinedweb
127
79.6
Pages: 1 This is a dumb question probably but I can't find the answer, I'm probably searching for the wrong term or something at python.org. I'm writing a bunch of classes to work with my LIRC remote, what do I have to do to set it up so I put the files in site-packages and then I can import them like: import lirc.mpd as mpd I've had a look at some of the setups that I already have from other packages, I'm guessing that the key is in the __init__.py file but I can't make any sense out of the contents. Any tips or even better links that point me in the right direction would be greatly appreciated. Thanks Offline if you don't wanna compile it to bytecode it's just to create a dir in site-packages and save the files in there with a __init__.py file, __init__.py is just a dummy file with no contents in it, if you want to compile it to bytecode you should use distutils, i've learned these things the hard way (trial and error) so if you got more problems i'm sure i could help you, edit: you can take a look at libpypac and lazy-pac-cli on my site for learning more about distutils arch + gentoo + initng + python = enlisy Offline Hurray, thanks heaps! I just created the blank __init__.py and now everything works like I wanted! I don't really think I need to worry about distutils, I'm just writing some scripts so that I can control as much of my computer's media functions as I can from my bed with my remote A nice Xosd menu would be good next, preferably in Python but anything that works will do. Pyosd isn't very mature and animenu won't compile with Xft enabled and it doesn't even work with the supplied example config so I guess I'll have to keep on looking Offline Pages: 1
https://bbs.archlinux.org/viewtopic.php?pid=109305
CC-MAIN-2016-36
refinedweb
344
70.06
Remote Control With NodeMCU and Web UI Introduction: Remote Control With NodeMCU and Web UI I recently made a video series on controlling an LED on a NodeMCU (esp8266) dev board from a web based UI on a remote server. The LED is used for an example but you can really control anything that is attached to the dev board. The goal of this instructable is to give a you a basic project that you can expand upon. I will break down the parts here in this instructable. However, the full walk-through is in the videos. The full code for this instructable and video series can be found on our Github page:... More videos and training at our website: Step 1: Setup the Arduino IDE for the NodeMCU You will first need to do a little setup with the Arduino IDE in order to make it work with the NodeMCU / ESP8266. Install the library: - Start the Arduino IDE - Open preferences - Add to the Additional Board Manager URL field. - Open the Boards Manager from the Tools -> Board menu, search for and install esp8862 library Step 2: Components Materials Needed The materials needed for this project are minimal. You can use the links below to see what you need. If you purchase from there, we do get a little extra money back. However, feel free to find these products anywhere you find a good deal. Step 3: Wiring It Up The wiring for this project is very simple. - Set the NodeMCU into the breadboard so that the USB side is facing out. - Place the LED somewhere off to the side of the NodeMCU. Made sure the LED pins are in their own column (side by side) not in the same column. For instance in the diagram: the long LED pin is in column 23 and the short LED pin is in 22. - Run 1 jumper wire from the same column of the long LED pin (23 in the diagram) over to the GPIO2 pin of the NodeMCU board. On the board it is actually labeled as D4. - Run 1 jumper wire from the same column of the short LED pin (22 in the diagram) over to the Ground pin of the NodeMCU. On the board is may be marked as GND - Lastly, plug your micro USB cable into the NodeMCU and then into your computer. Step 4: The Device Code The code is going to load in the ESP8266WiFi and the ESP8266HTTPClient library in order for you to interact with the NodeMCU within the Arduino IDE. #include <ESP8266Wifi.h> #include <ESP8266HTTPclient.h> Then we need to plug in the credentials to your WiFi. const char* ssid = "your wifi id"; const char* password = "yourpassword"; Next we will work on the setup() function. Step 5: The Setup() We next build out the setup function. This will run once prior to the main loop() function. - We will first start the serial monitor at a 115200 baud rate. - Then pause for a moment. - Set the pin mode for GPIO2 as 'OUTPUT' (remember: GPIO2 is marked as D4 on your board) - Write 0 or LOW to the pin to turn the LED off. - Print a welcome and connecting message to the serial monitor. - Attempt to start the wifi connection. - We will run a while loop until the get 'WL_CONNECTED' as the status. - We add a short delay to give it a sec on each loop through. void setup () { Serial.begin(115200); // Start the serial monitor. delay(10); // Give it a moment. pinMode(2, OUTPUT); // Set GPIO2 as an OUTPUT. digitalWrite(2, 0); // Start off. // Connect to WiFi network: Serial.println("Hello Digital Craft"); Serial.println("Connecting "); WiFi.begin(ssid, password); // Show ... until connected: while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println("WiFi connected"); // Print the IP address of the device: Serial.println(WiFi.localIP()); } Step 6: The Loop() Now we will run the loop that checks to see if the light should be on or off. This will connect to a remote server. It will read a simple text file that should have either a 1 or a 0 in it. This is using our test server now. The goal is to have your own server and control. - We first verify that the WiFi is still connected. - We create an HTTPClient object and call it 'http'. - We then make our request to the remote server. - We get the response code from the request. - If the code is greater than 0 then we at least made some sort of contact. (You could make this more defined by looking for a 200 or something). - Print a message that we connected. - Save the contents of the text faile as 'payload' - Write the value of payload (1 or 0) to the pin that controls the LED light. - If the value in the text file is 1 then the LED should turn on. If 0 it should turn off. - Close the http connection. void loop() { // Verfiy WiFi is connected: if (WiFi.status() == WL_CONNECTED) { HTTPClient http; // Object of the class HTTPClient. http.begin(""); // Request destination. int httpCode = http.GET(); // Send the request. if (httpCode > 0) { //Check the returning code Serial.println("We got a repsonse!"); String payload = http.getString(); // Get the text from the destination (1 or 0). Serial.println(payload); // Print the text. digitalWrite(2, payload.toInt()); // Send the payload value to the pin. }else{ Serial.println("Something baaaaaaad happened!"); } http.end(); //Close connection } delay(1000); //Send a request every 30 seconds } Step 7: The Web Interface The web interface is a simple interface that uses Twitter Bootstrap and Jquery to make things a bit easier. There are 4 files used in this step: - index.html - houses the interface and Javascript that triggers toggle.php to update the data and log files - toggle.php - sends 1 or 0 from index.html to data.txt and IP address and other info to log.txt - log.txt - holds user information - data.txt - holds the current state of the LED light (1 or 0) We use HTML, CSS, Javascript and PHP to add style and functionality to the UI. For fun, we incorporated a log of IP address and locations of the people using the UI. This is optional. The attached video is the video that walks through this portion of the project. This was recorded live so that there could be interaction while building it. There is too much involved in the Web UI to detail it all here. Please use the video for the full instructions. The summary of what is happening is: - A user clicks on the button. This triggers: - A request to toggle.php to change the state of the light to either on or off. - A request to toggle.php to add a line to the log file that includes: - The state of the LED - Location of the person who clicked the button (rough geolocation based on IP address) - A time-stamp of the moment that the button was clicked. - The simple light graphic in the header gets either .off or .on (CSS classes) applied to it and appears to be on or off to match the state of the light. The full code for this instructable and video series can be found on our Github page: More videos and training at our website: I fixed the code portions. The Instructables WYSIWYG editor seems to have a mind of it's own. :) The Digi Craft always make things great! Keep doing amazing works! Thank you!! I have more to come :) People really should take the time to up-vote this tutorial! It's rather thought out and well documented. You've even paid meticulous attention to overall presentation... a not so common theme on some of the other tutorials that I've come across. A great tutorial from The Digital Craft. thank you so much!! As always, another great tutorial from The Digi Craft. Thank you for sharing! Thank you! Plan to do many more on here :) Finished product
http://www.instructables.com/id/Remote-Control-With-NodeMCU-and-Web-UI/
CC-MAIN-2017-51
refinedweb
1,332
76.32
Type: Posts; User: Faraz95 hi.i wrote a code to sort elements of a matrix which are in one row,but it doesn't run well .what should i do?? here's the code #include <cstdlib> #include <iostream> #include <conio.h>... it's solved thanks for your help i don't know what debugger is??i use dev compiler i mean program run well when i entered sort but it also print you have entered wrong answer. hi.i have several if and else if,but the last if only check one if what's the problem. plz help if(strcmp(func,"add")==0 || strcmp(func,"ADD")==0) { //some orders. } else { you know,i understand how to solve it and it's over.but i want to know that how can i use debuger of a compiler? i use dev c++ compiler again i change the code to this but aint solved for( ;counter>=0;counter--) for(j=0;j<=(counter-1);j++) ... i use dev c++ compiler hi again.i change the main code to this but the output is not that i wanted.what should i do???? for( ;counter>=0;counter--) for(j=0;j<=count;j++) ... thanks,but i dont understood how to solve it and the correct code is not needed,just if you could guide me more. it means the last if should be :if(student[j-1]<student[j] everything would be... Hi.i program a software to get scores from admin and sort them ascending then show the middle score(if admin enter middle).but when i compile it nothing happen.what should i do?here's code ,i use dev...
http://forums.codeguru.com/search.php?s=561331adab58456a3a659602efabeab4&searchid=7385949
CC-MAIN-2015-32
refinedweb
278
77.43
I need to be able to tell, whether two lower-case strings differ at only one position, or they are the same. They must also be of the same length. That is abab - abab is OK abab - abaa is OK abab - qrst is not OK abab - abba is not OK abab - ababa is not OK sub compare{ return 0 unless length $_[0] == length $_[1]; return 1 if $_[0] eq $_[1]; my $diff = 0; my @l1 = split //, $_[0]; my @l2 = split //, $_[1]; for(my $i = 0; $i < scalar @l1; $i++){ $diff++ if $l1[$i] ne $l2[$i]; return 0 if $diff > 1; } return 1; } [download] rg0now Try sub compare{ return ( length $_[0] == length $_[1] ) && ( length( $_[0] ) - 1 <= ( $_[0] ^ $_[1] ) =~ tr[\0][\0] ) } [download] sub compare { (my $xor=$_[0]^$_[1]) =~ tr/\0//d; length $xor < 2; } [download] sub compare { (($_[0] ^ $_[1]) =~ tr/\0//c) < 2; } [download] sub compare { ($_[0] ^ $_[1]) =~ /^\0*(?:[^\0]\0*)?$/ } [download] I am beginning to see that after a certain point, Perl programming becomes a matter of pure aesthetics... sub compare { (($_[0] ^ $_[1]) =~ tr/\0//c) < 2; } print((compare('abc', 'abcd') ? 'ok' : 'not ok'), "\n"); [download] sub compare { length $_[0] == length $_[1] && (($_[0] ^ $_[1]) =~ tr/\0//c) < 2; } [download] Can't modify bitwise xor (^) in transliteration (tr///) at foo.pl line + 7, near "tr/\0//d) " [download] With /d and /c, you are modifying the string. Without either, and with source & destination tables being the same, is a special case designed for counting only. There would be no point in modifying the string just to replace like with like. Rate rg0now ikegami levenshtein blazar +BrowserUk rg0now 8801/s -- -57% -82% -87% + -87% ikegami 20414/s 132% -- -57% -69% + -70% levenshtein 47786/s 443% 134% -- -28% + -30% blazar 66258/s 653% 225% 39% -- + -4% BrowserUk 68683/s 680% 236% 44% 4% + -- [download] -- I'd like to be able to assign to an luser sub compare { return unless length $_[0] == length $_[1]; # Omit if expecting differences almost all the time. return 1 if $_[0] eq $_[1]; my $limit = 1; foreach (split('', $_[0]^$_[1])) { next unless ord; return 0 unless $limit--; } return 1; } [download] Doesn't work with Unicode. This: use strict; use warnings; # @data contains the (chomped, lower-cased) entries # from a 70K dictionary file (2076 words beginning with 'j') my $count; # Or whatever: this can check algorithm validity foreach my $item ( @data ) { compare( $item, $_ ) and $count++ for @data; } print $count; sub compare { return 0 unless length $_[0] == length $_[1]; my $diff = 0; for ( 0 .. length $_[0] ) { $diff++ if substr( $_[0], $_, 1 ) ne substr( $_[1], $_, 1 ); return 0 if $diff > 1; } return 1; } [download] is very much faster than your original code. Surprisingly(?), initial testing seems to show that it is also considerably faster than any of the replies you have hitherto received using bitwise XOR. I haven't got the time to do any precise benchmarking at the moment: however, since you need the "fastest solution on Earth", I shall leave that up to you Rate rg0now ikegami Not_a_Number BrowserUk blazar japhy rg0now 288/s -- -66% -82% -95% -96% -97% ikegami 849/s 195% -- -45% -87% -88% -90% Not_a_Number 1557/s 441% 83% -- -76% -78% -83% BrowserUk 6382/s 2118% 652% 310% -- -10% -28% blazar 7084/s 2362% 735% 355% 11% -- -20% japhy 8900/s 2993% 949% 472% 39% 26% -- It seems that japhy's solution is the clear winner, even if it is degraded to a sub call. I think that your results might be attributed your specific choice of data, but I do not know enough about the intrinsics of Perl string handling to say the decisive words (in fact, I do not know anything about it, so...) Both blazar's and japhy's return true when passed 'fred', 'freda' which obviously isn't right. When you add the code to detect that error, you get: Rate rg0now ikegami Not_a_Number blazar japhy + BrowserUk rg0now 412/s -- -69% -85% -96% -96% + -96% ikegami 1311/s 218% -- -54% -86% -88% + -89% Not_a_Number 2842/s 589% 117% -- -70% -74% + -75% blazar 9628/s 2236% 634% 239% -- -13% + -17% japhy 11086/s 2590% 745% 290% 15% -- + -4% BrowserUk 11580/s 2709% 783% 307% 20% 4% + -- [download] Playing more than understanding. Using the same benchmarks I got about a 3-5% speed up with a modified version of blazar's which skips lexical assignment by using $_. Tried a few arrangements with length and local and this was the fastest I stumbled on. OS X, v5.8.2. sub compare_blazar_mod { ( $_ = $_[0] ^ $_[1] ) =~ tr/\0//d; 2 < length; } [download] Its not clear to me if it would help or not, but you may want to look at Algorithm Showdown: Fuzzy Matching which has some high speed solutions for doing this type of problem, albeit for finding all of the fuzzy matches of a list of a words of the same length in gene strings. Warning: some of the discussion in that thread is somewhat acrimonious. Bloom::Filter (or an Bit::Vector based version of it) can tell you very quickly if there is a hit in the database, but can not tell you where it matched. It produces some false positives. You have to weight the creation of the hash table against getting a nearly linear scalability. Playing some tricks with an 'any' char seems to be neccessary. 'ab#d' would be an extended version of lowerc.
http://www.perlmonks.org/?node_id=480930
CC-MAIN-2016-18
refinedweb
933
66.51
I’ve updated all my extensions for Beta 2. Here are descriptions of the changes, as well as links to the source for each on github and the extension on VS Gallery. GoToDef GoToDef v1.2 on github GoToDef on vsgallery This was the only one that was somewhat substantial. There were essentially two changes: First, the classifier that underlines the text has been rewritten (very slightly) as an ITagger<ClassificationTag>, so that the provider can be rewritten as an IViewTaggerProvider. This is going to get its own blog article, but the short story is that if you are writing a classifier/tagger that is consuming other classifiers/taggers, you should write it as a view-specific tagger to avoid accidentally using an aggregator that uses another classifier/tagger that uses your classifier/tagger that uses an aggregator that uses…ad infinitum. Second, the mouse handler had some ugly logic for getting a service provider and getting the global shell command dispatcher. That has been simplified down (from ~20 lines to 1 line) to use the new [Import] System.IServiceProvider in Beta 2. ItalicComments ItalicComments v1.2 on github ItalicComments on vsgallery This one was really minor. The only change of note is that IEnvironment is gone in Beta 2 from everywhere, so you can just delete all references to it and its namespace (it has ApplicationModel in it, but it should be obvious if you re-compile an extension you wrote against Beta 1). TripleClick TripleClick v1.0 on github TripleClick on vsgallery This is the extension that I blogged about yesterday. Oh, and I also wanted to add: I heart git/github very, very much. Internet props to all them git/github people. All extensions are not working for me :/ Window 7 x64/ Visual Studio Ultimate Beta 2 can you help me? Can you be a bit more specific (which extensions, how did you install them, do they appear in the extension manager, etc.)? -Noah Italic Comments, i tried to install them via the new manager, via the download of the .vsix and all ways installed them correctly but it has no effect( i restarted VS and OS after every install of course) they appear in the manager. Alex For the file(s) that don’t show comments as italic – what language are they written in? FYI, in C#, it will only italicize // comments, and not doc comments. Since doing this through blog comments is going to get painful pretty fast, can you email me (noah.richards (a) microsoft) so we can figure out what is going wrong? here is the Solution: load per user extensions when running as administrator MUST be checked. now your great extensions works very fine ;D
https://blogs.msdn.microsoft.com/noahric/2009/10/20/updated-extensions-for-beta-2/
CC-MAIN-2016-44
refinedweb
453
62.98
Understanding Struts Controller Understanding Struts Controller In this section I will describe you the Controller.... It is the Controller part of the Struts Framework. ActionServlet is configured Hii.. - Struts Hii.. Hi friends, Thanks for nice responce....I will be very... me URL its very urgent Hi Soniya, I am sending you a link. I hope...:// Thanks. Amardeep Hi Hi Hi this is really good example to beginners who is learning struts2.0 thanks Struts - Struts Struts Dear Sir , I am very new in Struts and want to learn about validation and custom validation. U have given in a such nice way... provide the that examples zip. Thanks and regards Sanjeev. Hi friend.. - Java Beginners Hi.. Hi, I got some error please let me know what is the error integrity constraint (HPCLUSER.FAFORM24GJ2_FK) violated - parent key its very urgent Hi Ragini can u please send your complete source Java programming tutorial for very beginners Java programming tutorial for very beginners Hi, After completing my 12th Standard in India I would like to learn Java programming language. Is there any Java programming tutorial for very beginners? Thanks Hi Hi, - Java Beginners Hi, Hi friends I have some query please write the code and send me.I want adding value using javascript onChange() Events...please write the code and send me ts very urgent roseindia - Java Beginners hi roseindia what is java? Java is a platform independent..., Threading, collections etc. For Further information, you can go for very good...). Thanks/Regards, R.Ragavendran... Hi deepthi, Read for more Hi.... - Java Beginners Hi.... I hv 290 data and very large form..In one form it is not possible to save in one form so i want to break in to part....And i give...; Hi friend, Some points to be member to solve the problem : When Hi... - Struts Hi... Hi, If i am using hibernet with struts then require... of this installation Hi friend, Hibernate is Object-Oriented mapping tool... more information,tutorials and examples on Struts with Hibernate visit Big Problem - Java Beginners Very Big Problem Write a 'for' loop to input the current meter reading and the previous meter reading and calculate the electic bill.... Please give my answer in a for loop only and as soon as you can. Struts Provide material over struts? Hi Friend, Please visit the following link: Thanks Struts Struts How Struts is useful in application development? Where to learn Struts? Thanks Hi, Struts is very useful in writing web applications easily and quickly. Developer can write very extensible and high.java struts - Java Beginners java struts Hi sir i need complete digram of struts... how i can configer the struts in my eclipse... please send me the complete picture diagram hi - Java Beginners hi hi sir, i am entering the 2 dates in the jtable,i want to difference between that dates,plz provide the suitable example sir Hi.../beginners/DateDifferent.shtml Struts - Struts Struts for beginners struts for beginners example hi - Java Beginners hi Hi.... let me know the difference between object and instance variables with examples.... Hi friend, Objects are key to understanding object-oriented technology. Instance Method is a subroutine or function java material Hi Check this.... - Java Beginners Hi Check this.... Hi Sakthi here.. Run This Code.. Hi sakthi Your code is not visible here, can u send again please.. Thanks sir - Java Beginners hi sir Hi,sir,i am try in netbeans for to develop the swings,plz provide details about the how to run a program in netbeans and details about... the details sir, Thanks for ur coporation sir Hi Friend,Thanks for ur coporation, i am save the 1 image with customer data,when i am search that customer data,i want to see that image... sir,plzzzzzzzzzzzz Hi Friend, Please provide some more hi roseindia - Java Beginners hi roseindia what is object? A Blue print of class Hi deepthi, Objects are the basic run time entity or in other words object is a instance of a class . An object is a software bundle of variables friend - Java Beginners hi friend ummm i want to know a java code ...what are the code if i want to display inverted pyramid(shape). i mean a pyramid is reversed down.... thank u friends!!! Hi friend, Inverted pyramid code class hi Friend... - Java Beginners hi Friend... Hi friend... I have to import only " The System.out.println " Function Not any other Input Function ..How should i import... plz Explain this...Thank u.. Sakthi Hi friend, Java IO, what is the need for going to java.how java differ form .net.What is the advantage over .net.Is there any disadvantage in java Hi Friend, Difference between java and .net: 1)Java is developed by Sun Can someone explain Polymorphism with real time example Hi anjali, class ploy { public void ployTest(int x){ System.out.println("value of x: "+ x); } public void ployTest(int x, int y Friends, I want to write code in java for change password please provide the code change password have three field old_pwd,new_pwd,con_pwd Thanks Hi Friend, Create a database table login[id... I want to write code for change password from data base please help me import com.binsys.utility.DBOperation; package service... is occur Hi Friend, Try the following code: 1)change.jsp hi again - Java Beginners hi again i did the changes on the code but still the time is not decreasing i wanna reach increasing running time target sorry for asking too...; // testing every character for (int n=0 ;n Hi friend, Do changes Hi.. - Java Beginners Hi.. Hi friends, I want to display two calendar in my form,one is dislay successfully but another is not please tell me how display second... is successfully but date of birth is not why... Hi Friend, Try Struts - Struts Struts examples for beginners Struts tutorial and examples for beginners hi - Java Beginners hi hi sir,Thanks for ur coporation, i am save the 1 image with customer data,when i am search that customer data,i want to see that image (already... that image is rendered to my frame,that's my question Hi Friend ,plzzzzzzzzzzzzzzzzzzzzzzzzzzzz, i am declare the final for jtextfields Hi - Java Beginners singleton class in struts - Java Beginners singleton class in struts hi, This balakrishna, I want to retrive data from database on first hit to home page in struts frame work
http://www.roseindia.net/tutorialhelp/comment/13326
CC-MAIN-2014-10
refinedweb
1,071
66.54
Estimating cost of capital (WACC, IRR)-free rate did you use? Why? e. Which capital-structure weights did you use? Why? 2. Judged against your WACC, how attractive is the Boeing 7E7 project? a. Under what circumstances is the project economically attractive? b. What does sensitivity analysis (your own and/or that shown in the case) reveal about the nature of Boeing's gamble on the 7E7? 3. Should the board approve the 7E7? Solution Preview 1. What is an appropriate required rate of return against which to evaluate the prospective IRRs from the Boeing 7E7? From the case scenario, we see that computed IRR is 15.66%, hence the required rate of return should be at least, say 15.7% (to have NPV of the project > 0). There 3 possible scenarios involving NPV: NPV > 0 - the project should be undertaken in the majority of cases (of course, depending on the market and availabilty of alternatives, we may choose which one to pursue and if to pursue it) NPV = 0 - in we don't loose anything, but we don't again anything either. With a great volatility of the market, it's very easy to go from NPV = 0 to the negative NPV, therefore should be taken with a great caution. NPV< 0 - pretty obvious answer - no, don't pursue it, unless the goal is not the monetary gain, but rather a market share for a future potential gain. a. Please use the capital asset pricing model to estimate the cost of equity. According to CAPM, Cost of Equity = Rf + Beta*EMRP = 1.05% + 1.43*2.75% = 4.98%, where Rf is the Risk-free rate of return (3-month T-Bill), Beta is obtained from the financial reports about the company (quote.com or finance.yahoo.com would give you an appropriate one), which essentially shows how the Boeing's stock fluctuates with respect to S&P Index, EMRP is the Equity Market Risk Premium which is ... Solution Summary The solution estimates the cost of capital for the WACC and IRR.
https://brainmass.com/business/capital-asset-pricing-model/boeing-767-case-estimating-cost-of-capital-wacc-irr-204312
CC-MAIN-2017-09
refinedweb
343
63.7