text
stringlengths
20
1.01M
url
stringlengths
14
1.25k
dump
stringlengths
9
15
lang
stringclasses
4 values
source
stringclasses
4 values
Created on 2015-02-11 18:38 by antox, last changed 2016-09-08 18:02 by brett.cannon. This issue is now closed. That's the situation: a/ __init__.py first.py second.py #init.py __all__ = ['second', 'first'] print('i\'m starting the directory') #first.py print('hi, i\'m the first') from . import * #second.py print('hi, i\'m the second') From the interactive prompt: >>> import a.first i'm starting the directory hi, i'm the first hi, i'm the second Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/home/antox/Scrivania/a/first.py", line 2, in <module> from . import * AttributeError: module 'a' has no attribute 'first' It's pretty weird. If you put a print call after your `from . import *` call you will notice it never gets executed. Basically import is still in the middle of finishing imports when that import * is reached, including setting the module attributes on the package. Basically you have a circular import. I tried the following on python 3.5.0a1: #init.py __all__ = ['second', 'first'] print('i\'m starting the directory') #first.py print('hi, i\'m the first') from . import second #second.py print('hi, i\'m the second') from . import first >>> import a.first i'm starting the directory hi, i'm the first hi, i'm the second it just worked out perfectly, no errors. But the case I show before still continues to get the AttributeError error. You told me that basically it doesn't work because it is a circular import, but isn't python already able to manage circular import? What I expected when running the "from . import *" statament was Python looking up in the __all__ attribute and import everything within it. When it had to import 'first' I expected Python to check in the sys.modules to see if it was already imported so, in this case, it could see that first.py was already imported and no error was raised. This issue is a special case of the problem discussed in issue 992389, that modules within packages are not added to the package dictionary until they are fully loaded, which breaks circular imports in the form "from package import module". The consensus on that issue is that it doesn't need to be fixed completely, given the partial fix from issue 17636. I think the current issue is a corner case that was not covered by the fix, but which probably should be fixed as well, for consistency. The fix so far has made imports that name the module work, even though the module objects are still not placed into the package's namespace yet (this is why Antonio's last example works in the newly released 3.5a1, though not in previous versions). Wildcard imports however still fail. Can the fix be expanded to cover wildcard imports as well? I know, we're heaping up two kinds of usually-bad code (wildcard imports and circular imports) on top of one another, but still, the failure is very unexpected to anyone who's not read the bug reports. I don't know my way around the import system at all yet, so I'm not going to be capable of writing up a patch immediately, but if there's any interest at all, and nobody more knowledgeable gets to it first I might see what I can learn and try to put together something. Here's a more concise example of the issue: package/__init__.py: __all__ = ["module"] package/module.py: from . import module # this works in 3.5a1, thanks to the fix from issue 17636 from . import * # this still fails If you want to take a stab at it, Steven, go for it and I will review the patch, but as you pointed out this is such an edge case that I'm personally not going to worry about fixing it and still don't consider it a bug. I've finally gotten around to looking into this issue and it turns out that fixing "from package import *" to work with circular imports is pretty easy, as all that needs to be done is apply the same logic from the patch for issue 17636 to the loop in the next function. I'll attach a patch that does this. Unfortunately, my Windows build environment seems to be completely messed up at the moment and I'm getting link errors on everything in my python repo, so I've not been able to test the code at all. Since I have no idea when I'll actually have the time to learn what the hell's going wrong with MSVC, I though I'd submit my patch and perhaps somebody on a better OS can make sure it works properly. I've included a new test which should show the issue with circular imports (and verify that the rest of the patch fixes it, hopefully). Can someone reset the status and open fields, thanks. reset. Languishing? :) Yep: "The issue has no clear solution , e.g., no agreement on a technical solution or if it is even a problem worth fixing." Brett is saying he doesn't consider this a bug. Steven says he doesn't have time to push it forward. Oh, I see there is a patch attached though (I wish the attachments were linked at the message that adds them as well as globally). I've managed to partially fix my build environment, so I can verify that my patch (attached previously) works as intended. I'm not completely sure that it doesn't break unrelated things as my build still has lots of failing tests (which all appear to be unrelated to this issue). Nothing obviously new breaks with the patch applied. The test I added in the patch does fail (as expected) on the unpatched interpreter, but passes on a patched version (though I've just noticed that the attempt at catching the exception doesn't work, since the current import code raises an AttributeError rather than the ImportError I had expected). I don't believe any other tests failed anew on the patched code, but like I said, I've got a lot of unrelated test failures so I might be missing some subtle issues. I'm attaching an updated version of the patch with better exception handling in the test code. The patch applies cleanly to the latest dev branch. I'd appreciate any reviews or other feedback. Here is Steven's patch touched up. I still have not decided if the semantic change is worth it. If anyone else has an opinion please feel free to speak up. All tests do pass, though, so it at least doesn't seem to directly break anything. Just so Steven knows, I'm still thinking about whether I want to accept the patch (and waiting to see if anyone else has an opinion =). I did realize that the patch as it stands does not add the found module as an attribute on the package which is potentially one way the semantics subtly shift with this patch. Thanks for looking at the issue Brett. I think you're right that your patch has incorrect semantics, since it doesn't save the value to the provided namespace if it had to go through the special path to find the name. I think my patch got that part right (though I definitely missed one PyUnicode_Check). I've just noticed that our patches may not always do the right thing in all error situations. They may return -1 without setting an exception (or perhaps passing on a strange one from an internal call) if there's something weird going on like `__name__` not existing or not being a string. I'm attaching a new version of my patch that moves the PyErr_Format call down to the later check for `value == NULL`. This handles both the basic case where nothing strange goes on but the requested name is not found, and the weird cases where unexpected stuff goes wrong. It will replace any errors raised by the earlier code with an ImportError. I think an ImportError is the appropriate exception for most error cases, but perhaps some internal errors should not be overwritten and more complicated error logic is needed. I also notice that the code in the "import_from" function (from which I borrowed heavily for my patch) was changed in one of the 3.5rc patches to have new error handling (it raises ImportError more often I think). I don't see an obvious way to copy its new error logic to import_all_from, but my C coding skills are rather rusty so I could be missing an easy approach. I talked the semantic change over with Eric at the core sprint and we are both iffy enough on the semantic change and how it will impact stuff that we don't feel comfortable accepting the patch. Sorry, Steven, but thanks for taking a stab at it.
https://bugs.python.org/issue23447
CC-MAIN-2019-43
en
refinedweb
We are about to switch to a new forum software. Until then we have removed the registration on this forum. Hello everyone. I'm having a bit of trouble here, could you give me a hand, please? I need to read the frequencies from microphone input. My code runs fine on desktop, because I'm using Minim and getting fft to work there is pretty straightforward. But when I went to Android, I had to abandon Minim and I'm stuck at trying to apply fft to input myself (both in desktop and in android). On Android I get my input from AudioRecord.read( myarray , 0 , bufferSize ); On Desktop I get my input from AudioInput.mix.get( n ) and assign each value to a position in myarray. Apparently, it's picking up the same input for both. So input is fine, my problem is I don't know how to use FFT. I got a FFT java class from the internet. It asks for a real and an imaginary array. I pass "myarray" as the real array and another array with all 0-values as the imaginary one. For some reason, FFT is giving me negative values. Why? Aren't frequency bands supposed to start from zero? Any idea of what I am doing wrong? I attached a pic of what's happening (sorry for the bright red): And here's my code in case it helps: import ddf.minim.*; AudioInput in; Minim minim; double[] real; double[] imag; FFT fft; int bufferSize = 1024; int sampleRate = 5512; void setup() { size(1024,768); minim = new Minim( this ); in = minim.getLineIn( Minim.STEREO , bufferSize , sampleRate ); real = new double[bufferSize]; imag = new double[bufferSize]; fft = new FFT( bufferSize ); background(100,100,250); } void draw() { background( 100 , 100 , 200 ); noFill(); stroke( 255 , 255 , 255 ); strokeWeight(1); for ( int i=0; i<bufferSize; i++ ) { real[i] = in.mix.get(i)*1000; imag[i] = 0; } for ( int i=0; i<bufferSize; i++ ) line( i , 200 , i , 200 - (int)(real[i]) ); fft.fft( real , imag ); stroke( 255 , 255 , 0 ); for ( int i=0; i<bufferSize; i++ ) line( i , 600 , i , 600 - ((int)(real[i])/10) ); } I'm using a FFT class I got from the interwebs (this one: ) Answers what's up with using the fft from within minim? example: None, if you can get that to work on Android. sorry, didn't see that requirement. the code you posted still has minim calls in it... I wrote that as a test, just to see if I could get the manual FFT thing on desktop before moving to Android. Actually, I just stumbled upon a Minim FFT implementation for Android. :D I'm still going to try that out, but it should work. Sorry for coming here a little too desperate, I should have googled this a bit more before bothering you guys ;)
https://forum.processing.org/two/discussion/11400/how-to-manually-apply-fft-to-sound-input
CC-MAIN-2019-43
en
refinedweb
Okay this is just a fun topic not sure if it belongs hear but hear it goes. If we are living in a computer simulation wouldn't we notice it through programming. For example I have a soda on my desk right now I think the code would look something like this. inport objects def soda.spill () if: spill = 1 print "The soda is sitting on the desk." if: spill =2 print "A hand reaches out for the soda and takes it with a firm grip" if: spill = 3 print "A hand reaches out for the soda but hits the can sending the soda all over the desk." wile loop() I think I didn't do that right but if we are living in a computer simulation then how would you program the soda event. Because I only see 3 options in that but that soda can could have thousands of lines of code in that single action. I hope I'm making sence. If we were to build are own simulation how would we go about it. What would we use for weather patterns, population, and other information. I really hope I'm making sence I was half asleep when I thought of this. 1MeNca7h6m8du4TV3psN4m4X666p6Y36u5m
http://forum.audiogames.net/viewtopic.php?id=23230
CC-MAIN-2017-47
en
refinedweb
In this Tutorial, we will Discuss the Java Arrays with Different Data Types of Elements with Examples: In our previous tutorials, we discussed that array is a collection of elements of the same data type in a contiguous fashion. You can have array declared with most of the primitive data types and use them in your program. Some arrays like character arrays or string arrays behave little differently than the rest of the data types. In this tutorial, we will walk you through arrays with different data types and discuss their usage in Java programs by giving examples. => Visit Here To Learn Java From Scratch. What You Will Learn: Java Array Data Types Integer Array You can use an array with elements of the numeric data type. The most common one is the integer data type (int array in Java). The following program illustrates the usage of the array with the int data type. import java.util.*; public class Main { public static void main(String[] args) { int[] oddArray = {1,3,5,7,9}; //array of integers System.out.println("Array of odd elements:" + Arrays.toString(oddArray)); int[] intArray = new int[10]; for(int i=0;i<10;i++){ //assign values to array intArray[i] = i+2; } System.out.println("Array of Integer elements:" + Arrays.toString(intArray)); } } Output: The above program defines an array with initial values and another array in which the values are assigned in a For Loop. Java Double Array An array having elements of type double is another numeric array. The example given below demonstrates the double array in Java. import java.util.*; public class Main { public static void main(String[] args) { double[] d_Array = new double[10]; //array of doubles for(int i=0;i<10;i++){ d_Array[i] = i+1.0; //assign values to double array } //print the array System.out.println("Array of double elements:" + Arrays.toString(d_Array)); } } Output: In the above program, we initialize the double array through for loop and display its contents. Byte Array A byte in Java is the binary data having a 8-bit size. The byte array consists of elements of type ‘byte’ and is mostly used to store binary data. The shortcoming of byte array is that you should always load the byte data into the memory. Though you should refrain from converting byte data, it might become necessary sometimes to convert the byte data to string and vice-versa. The below example program shows a byte array that is converted to a string using a string constructor. import java.util.*; public class Main { public static void main(String[] args) { byte[] bytes = "Hello World!!".getBytes(); //initialize the bytes array //Convert byte[] to String String s = new String(bytes); System.out.println(s); } } Output: The above program defines a byte array and then passes it on to the String constructor to convert it to String. You can also convert byte array to string using Base64 encoding method available from Java 8 onwards. The program is left to the readers for implementation. Boolean Array Boolean array in Java only stores Boolean type values i.e. either true or false. The default value stored in the Boolean array is ‘false’. Suggested reading =>> What is a Boolean in Java Given below is an example of a Boolean array. import java.util.*; public class Main { public static void main(String args[]) { //declare and allocate memory boolean bool_array[] = new boolean[5]; //assign values to first 4 elements bool_array[0] = true; bool_array[1] = false; bool_array[2] = true; bool_array[3] = false; //print the array System.out.println("Java boolean Array Example:" + Arrays.toString(bool_array)); } } Output: Note that in the above program only the first four elements are assigned explicit values. When the array is printed, the last element has default value false. Character Array Character arrays or Char arrays in Java contain single characters as its elements. Character arrays act as character buffers and can easily be altered, unlike Strings. Character arrays do not need allocations and are faster and efficient. The program below shows the implementation of the character array. import java.util.*; public class Main { public static void main(String[] args) { char[] vowel_Array = {'a', 'e', 'i', 'o', 'u'}; //character array of vowels System.out.println("Character array containing vowels:"); //print the array for (int i=0; i<vowel_Array.length; i++) { System.out.print(vowel_Array[i] + " "); } } Output: The above program declares a character array consisting of English vowels. These vowels are then printed by iterating the character array using for loop. Java Array Of Strings A string in Java is a sequence of characters. For example, “hello” is a string in Java. An array of a string is a collection of strings. When the array of strings is not initialized or assigned values, the default is null. The following program exhibits the usage of an array of strings in Java. import java.util.*; public class Main { public static void main(String[] args) { String[] num_Array = {"one", "two", "three", "four", "five"}; //string array System.out.println("String array with number names:"); System.out.print(Arrays.toString(num_Array)); } } Output: In the above code, we have a string array consisting of number names till five. Then using the Arrays class, we have printed the string array with the toString method. You can also use enhanced for loop (for-each) or for loop to iterate through the array of strings. Empty Array In Java You can have empty arrays in Java i.e. you can define an array in Java with 0 as dimension. Consider the following array declarations. int[] myArray = new int[]; //compiler error int[] intArray = new int[0]; //compiles fine The difference between the above array declarations is that the first declaration has not specified any dimension. Such a declaration will not compile. The second declaration, however, declares an array with dimension as 0 i.e. this array cannot store any elements in it. This declaration will compile fine. The second declaration is for the empty array. Empty array is basically an array with 0 dimensions so that no elements are stored in this array. Then, why do we need empty arrays in our programs? One use is when you are passing an array between functions and you have a certain case when you don’t want to pass any array parameters. Thus instead of assigning null values to array parameters, you could just pass an empty array directly. The example given below demonstrates the use of an empty array. import java.util.*; public class Main { public static String appendMessage(String msg, String[] msg_params) { for ( int i = 0; i <msg_params.length; i++ ) { //appends the incoming message with array parameters int index = msg.indexOf("{" + i + "}"); while ( index != -1 ) { msg = (new StringBuffer(msg)).replace(index, index+3, msg_params[i]).toString(); index = msg.indexOf("{" + i + "}"); } } return msg; } public static void main(String[] args) throws Exception { String[] msgParam_1 = {"Java"}; //empty array String[] msgParam_2 = new String[0]; System.out.println(appendMessage("Learn {0}!", msgParam_1)); //pass empty array System.out.println(appendMessage("Start Programming", msgParam_2)); } } Output: In the above program, you can see that there are two calls made to function ‘appendMessage’. In the first call, an array having one element is passed. In the second call, there is no need to pass an array but as the prototype of the function demands the second parameter, an empty array is passed. Frequently Asked Questions Q #1) What is a Primitive Array in Java? Answer: Arrays having Primitive or built-in Data Types of elements are primitive arrays. An array can be declared as either having elements of primitive type or reference type. Q #2) What is Byte Array in Java? Answer: An array consisting of elements of type byte is the byte array. A byte is 8 bit in size and is usually used to represent binary data. Q #3) What is a Boolean Array in Java? Answer: An array that stores only Boolean type values i.e. true or false. If not explicitly assigned values, the default value of the Boolean array element is false. Q #4) Is a String a Char Array Java? Answer: No. The string is a class in Java that holds a sequence of characters. The string is immutable i.e. its contents cannot be changed once defined and it also has its own methods that operate on its contents. Q #5) What is String [] args? Answer: In Java, the command line arguments to the program are supplied through args which is a string of array. You can just perform operations on this array just like any other array. Conclusion In this tutorial, we learned that the arrays which are contiguous sequences of homogenous elements can be defined for various Java primitive data types as well as reference types. We mainly discussed the arrays of primitive data types and their examples. We will discuss the array of objects which is a reference type in a separate tutorial. => Watch Out The Simple Java Training Series Here.
https://www.softwaretestinghelp.com/java-array-data-types/
CC-MAIN-2021-17
en
refinedweb
Logistic Regression with Python in Machine Learning | KGP Talkie What is Logistic Regression? Logistic Regression is a Machine Learning algorithm which is used for the classification problems, it is a predictive analysis algorithm and based on the concept of probability. Logistic regression is basically a supervised classification algorithm. In a classification problem, the target variable(or output), y, can take only discrete values for given set of features(or inputs), X. Logistic regression becomes a classification technique only when a decision threshold is brought into the picture. The setting of the threshold value is a very important aspect of Logistic regression and is dependent on the classification problem itself. Some of the examples of classification problems are Email spam or not spam, Online transactions Fraud or not Fraud, Tumor Malignant or Benign. Logistic regression transforms its output using the logistic sigmoid function to return a probability value. We can call a Logistic Regression as a Linear Regression model but the Logistic Regression uses a more complex cost function, this cost function can be defined as the Sigmoid function or also known as the logistic function instead of a linear function . The hypothesis of Logistic regression tends it to limit the cost function between 0 and 1. Therefore linear functions fail to represent it as it can have a value greater than 1 or less than 0 which is not possible as per the hypothesis of Logistic regression. What are the types of Logistic regression Based on the number of categories, Logistic regression can be classified as: Binomial: Target variable can have only 2possible types: “ 0” or “1”which may represent “win” vs “loss”, “pass” vs “fail”, “dead” vs “alive”, etc. Multinomial: Target variable can have 3. What is the Sigmoid Function? In order to map predicted values to probabilities, we use the Sigmoid function. The function maps any real value into another value between 0 and 1. In machine learning, we use sigmoid to map predictions to probabilities. In the curve it shown that any small changes in the values of X in that region will cause values of Y to change significantly. That means this function has a tendency to bring the Y values to either end of the curve. Looks like it’s good for a classifier considering its property? Yes ! It indeed is. It tends to bring the activations to either side of the curve.Making clear distinction on prediction. Another advantage of this activation function is, unlike linear function, the output of the activation function is always going to be in range (0,1) compared to (-inf, inf) of linear function. So we have our activations bound in a range. Nice, it won’t blow up the activations then. This is great. Sigmoid functions are one of the most widely used activation functions today. Then what are the problems with this? If you notice, towards either end of the sigmoid function, the Y values tend to respond very less to changes in X. What does that mean? The gradient at that region is going to be small. It gives rise to a problem of “vanishing gradients”. Hmm. So what happens when the activations reach near the “near-horizontal” part of the curve on either sides? Gradient is small or has vanished (cannot make significant change because of the extremely small value). The network refuses to learn further or is drastically slow ( depending on use case and until gradient /computation gets hit by floating point value limits ). There are ways to work around this problem and sigmoid is still very popular in classification problems. In order to map predicted values to probabilities, we use the Sigmoid function. The function maps any real value into another value between 0 and 1. In machine learning, we use sigmoid to map predictions to probabilities. Decision Boundary We expect our classifier to give us a set of outputs or classes based on probability when we pass the inputs through a prediction function and returns a probability score between 0 and 1. Cost function We learned about the cost function in the Linear regression, the cost function represents optimization objective i.e. we create a cost function and minimize it so that we can develop an accurate model with minimum error. If we try to use the cost function of the linear regression in Logistic Regression then it would be of no use as it would end up being a non-convex function with many local minimums, in which it would be very difficult to minimize the cost value and find the global minimum. The. Lets go ahead and build a model which can predict if a passenger is gonna survive import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt %matplotlib inline from sklearn.linear_model import LogisticRegression titanic = sns.load_dataset('titanic') titanic.head(10) titanic.describe() Data understanding titanic.isnull().sum() survived 0 pclass 0 sex 0 age 177 sibsp 0 parch 0 fare 0 embarked 2 class 0 who 0 adult_male 0 deck 688 embark_town 2 alive 0 alone 0 dtype: int64. sns.heatmap(titanic.isnull(), cbar = False, cmap = 'viridis') plt.title('Number of people in the ship with respect their features ') plt.show() titanic['age'].isnull().sum()/titanic.shape[0]*100 19.865319865319865 Histogram A Histogram shows the frequency on the vertical axis and the horizontal axis is another dimension. Usually it has bins, where every bin has a minimum and maximum value. Each bin also has a frequency between x and infinite. ax = titanic['age'].hist(bins = 30, density = True, stacked = True, color = 'teal', alpha = 0.7, figsize = (16, 5)) titanic['age'].plot(kind = 'density', color = 'teal') ax.set_xlabel('Age') plt.title('Percentage of the people with respect to their age ') plt.show() In this part of the code, we plotted female survived & not survived passengers and aslo male survived & not survived passengers with respect to their age. distplot Flexibly plot a univariate distribution of observations. survived = 'survived' not_survived = 'not survived' fig, axes = plt.subplots(nrows = 1, ncols = 2, figsize = (20, 4)) women = titanic[titanic['sex'] == 'female'] men = titanic[titanic['sex'] == 'male'] ax = sns.distplot(women[women[survived]==1].age.dropna(), bins = 18, label = survived, ax = axes[0], kde = False) ax = sns.distplot(women[women[survived]==0].age.dropna(), bins = 40, label = not_survived, ax = axes[0], kde = False) ax.legend() ax.set_title('Number of female passenger whether survived or not with respect to their age ') ax = sns.distplot(men[men[survived]==1].age.dropna(), bins = 18, label = survived, ax = axes[1], kde = False) ax = sns.distplot(men[men[survived]==0].age.dropna(), bins = 40, label = not_survived, ax = axes[1], kde = False) ax.legend() ax.set_title('Number of male passenger whether survived or not with respect to their age') plt.ylabel('No. of people') plt.show() titanic['sex'].value_counts() male 577 female 314 Name: sex, dtype: int64 Let’s observe the people with respect to thier age who are in pclass. We will get this by using catplot() function. sns.catplot(x = 'pclass', y = 'age', data = titanic, kind = 'box') plt.title('Age of the people who are in pclass') plt.show() sns.catplot(x = 'pclass', y = 'fare', data = titanic, kind = 'box') plt.title('Fare for the different classes of the pclass') plt.show() titanic[titanic['pclass'] == 1]['age'].mean() 38.233440860215055 titanic[titanic['pclass'] == 2]['age'].mean() 29.87763005780347 titanic[titanic['pclass'] == 3]['age'].mean() 25.14061971830986 Imputation In the following function,We are dealing with missing values by using imputation. Imputation is the process of replacing missing data with substituted values.The missing values are substituted by another computed value. def impute_age(cols): age = cols[0] pclass = cols[1] if pd.isnull(age): if pclass == 1: return titanic[titanic['pclass'] == 1]['age'].mean() elif pclass == 2: return titanic[titanic['pclass'] == 2]['age'].mean() elif pclass == 3: return titanic[titanic['pclass'] == 3]['age'].mean() else: return age titanic['age'] = titanic[['age', 'pclass']].apply(impute_age, axis = 1) Let’s see the resultant plot : sns.heatmap(titanic.isnull(), cbar = False, cmap = 'viridis') plt.title('Number of people with respect to their features') plt.show() Analysing Embarked Analyzing number of passengers get into the ship. Facegrid: Multi-plot grid for plotting conditional relationships. f = sns.FacetGrid(titanic, row = 'embarked', height = 2.5, aspect= 3) f.map(sns.pointplot, 'pclass', 'survived', 'sex', order = None, hue_order = None) f.add_legend() plt.show() titanic['embarked'].isnull().sum() 2 titanic['embark_town'].value_counts() Southampton 644 Cherbourg 168 Queenstown 77 Name: embark_town, dtype: int64 common_value = 'S' titanic['embarked'].fillna(common_value, inplace = True) titanic['embarked'].isnull().sum() 0 sns.heatmap(titanic.isnull(), cbar = False, cmap = 'viridis') plt.title('Number of people with respect to their features') plt.show() We will try to print the output by removing labes: deck, embark_town, alive. We will do this by using drop() function. The drop() function is used to drop specified labels from rows or columns. Let’s look into the script: titanic.drop(labels=['deck', 'embark_town', 'alive'], inplace = True, axis = 1) Here is the resultant output : sns.heatmap(titanic.isnull(), cbar = False, cmap = 'viridis') plt.title('Number of people with respect to their features') plt.show() Here we can observe the difference between two figures. titanic.info() <class 'pandas.core.frame.DataFrame'> RangeIndex: 891 entries, 0 to 890 Data columns (total 12 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 survived 891 non-null int64 1 pclass 891 non-null int64 2 sex 891 non-null object 3 age 891 non-null float64 4 sibsp 891 non-null int64 5 parch 891 non-null int64 6 fare 891 non-null float64 7 embarked 891 non-null object 8 class 891 non-null category 9 who 891 non-null object 10 adult_male 891 non-null bool 11 alone 891 non-null bool dtypes: bool(2), category(1), float64(2), int64(4), object(3) memory usage: 65.5+ KB titanic.head() titanic['fare'] = titanic['fare'].astype('int') titanic['age'] = titanic['age'].astype('int') titanic['pclass'] = titanic['pclass'].astype('int') titanic.info() <class 'pandas.core.frame.DataFrame'> RangeIndex: 891 entries, 0 to 890 Data columns (total 12 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 survived 891 non-null int64 1 pclass 891 non-null int32 2 sex 891 non-null object 3 age 891 non-null int32 4 sibsp 891 non-null int64 5 parch 891 non-null int64 6 fare 891 non-null int32 7 embarked 891 non-null object 8 class 891 non-null category 9 who 891 non-null object 10 adult_male 891 non-null bool 11 alone 891 non-null bool dtypes: bool(2), category(1), int32(3), int64(3), object(3) memory usage: 55.0+ KB Convert categorical data into numerical data In this part categorical data( male , female) converted into numeriacl data(0,1,2..). genders = {'male': 0, 'female': 1} titanic['sex'] = titanic['sex'].map(genders) who = {'man': 0, 'women': 1, 'child': 2} titanic['who'] = titanic['who'].map(who) adult_male = {True: 1, False: 0} titanic['adult_male'] = titanic['adult_male'].map(adult_male) alone = {True: 1, False: 0} titanic['alone'] = titanic['alone'].map(alone) ports = {'S': 0, 'C': 1, 'Q': 2} titanic['embarked'] = titanic['embarked'].map(ports) titanic.head() titanic.drop(labels = ['class', 'who'], axis = 1, inplace= True) titanic.head() Build Logistic Regression Model In this part of code,we try to buid a Logistic model for the data values. from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score X = titanic.drop('survived', axis = 1) y = titanic['survived'] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.33, random_state = 42) model = LogisticRegression(solver= 'lbfgs', max_iter = 400) model.fit(X_train, y_train) y_predict = model.predict(X_test) model.score(X_test, y_test) 0.8271186440677966 Let’s go ahead with age and fare grouping Recursive Feature Elimination : Given an external estimator that assigns weights to features, recursive feature elimination (RFE) is to select features by recursively considering smaller and smaller sets of features. First, the estimator is trained on the initial set of features and the importance of each feature is obtained either through a coef_ attribute or through a featureimportances attribute. Then, the least important features are pruned from current set of features.That procedure is recursively repeated on the pruned set until the desired number of features to select is eventually reached. from sklearn.feature_selection import RFE model = LogisticRegression(solver='lbfgs', max_iter=500) rfe = RFE(model, 5, verbose=1) rfe = rfe.fit(X, y) rfe.support_ E:\callme_conda\lib\site-packages\sklearn\utils\validation.py:68: FutureWarning: Pass n_features_to_select=5 as keyword args. From version 0.25 passing these as positional arguments will result in an error warnings.warn("Pass {} as keyword args. From version 0.25 " Fitting estimator with 9 features. Fitting estimator with 8 features. Fitting estimator with 7 features. Fitting estimator with 6 features. array([ True, False, False, True, True, False, False, True, True]) titanic.head(3) X.head() XX = X[X.columns[rfe.support_]] XX.head() X_train, X_test, y_train, y_test = train_test_split(XX, y, test_size = 0.2, random_state = 8, stratify = y) model = LogisticRegression(solver= 'lbfgs', max_iter = 500) model.fit(X_train, y_train) y_predict = model.predict(X_test) model.score(X_test, y_test) 0.8547486033519553 Accuracy, F1-Score, P, R, AUC_ROC curve Let’s have some discussions on Precision, Recall, Accuracy . Accuracy tells the fraction of predictions our model got right . Recall tells us amount of actual positives are identified correctly . Precision tells us amount of positive proportion identifications are actually correct . Have a look at following formulae: from sklearn.model_selection import train_test_split, cross_val_score from sklearn.metrics import accuracy_score, classification_report, precision_score, recall_score from sklearn.metrics import confusion_matrix, precision_recall_curve, roc_auc_score, roc_curve, auc, log_loss model = LogisticRegression(solver= 'lbfgs', max_iter = 500) model.fit(X_train, y_train) y_predict = model.predict(X_test) Predict_proba ( ) The function predict_proba() returns a numpy array of two columns. The first column is the probability that target=0 and the second column is the probability that target=1. That is why we add [:,1] after predict_proba() in order to get the probabilities of target=1. Let’s find out y_predict_prob by using predict_proba() .Now have a look into the script: y_predict_prob = model.predict_proba(X_test)[:, 1] y_predict_prob[: 5] array([0.55566832, 0.87213996, 0.09376084, 0.09376084, 0.37996908]) We will compute the Compute Receiver operating characteristic (ROC) by using the function roc_curve().Since the thresholds are sorted from low to high values, they are reversed upon returning them to ensure they correspond to both fpr and tpr, which are sorted in reversed order during their calculation. Let’s see into the script: [fpr, tpr, thr] = roc_curve(y_test, y_predict_prob) [fpr, tpr, thr][: 2] [array([0. , 0. , 0. , 0. , 0.00909091, 0.00909091, 0.00909091, 0.00909091, 0.00909091, 0.00909091, 0.03636364, 0.03636364, 0.03636364, 0.06363636, 0.09090909, 0.12727273, 0.12727273, 0.13636364, 0.21818182, 0.23636364, 0.24545455, 0.27272727, 0.29090909, 0.43636364, 0.45454545, 0.47272727, 0.52727273, 0.92727273, 1. ]), array([0. , 0.07246377, 0.20289855, 0.24637681, 0.33333333, 0.39130435, 0.44927536, 0.55072464, 0.60869565, 0.63768116, 0.63768116, 0.65217391, 0.69565217, 0.7826087 , 0.7826087 , 0.7826087 , 0.79710145, 0.79710145, 0.86956522, 0.88405797, 0.88405797, 0.88405797, 0.88405797, 0.89855072, 0.91304348, 0.91304348, 0.92753623, 1. , 1. ])] Now we will calculate accuracy of predicted data ,log loss and auc.To get this we will use functions accuracy_score(), log_loss(), auc(). accuracy_score( ) In multilabel classification, this function can compute subset accuracy: the set of labels predicted for a sample must exactly match the corresponding set of labels in y_true. log_loss( ) It is defined as the negative log-likelihood of a logistic model that returns y_pred probabilities for its training data y_true . auc( ) Compute Area Under the Curve (AUC),ROC using the trapezoidal rule. Let’s look into the script: print('Accuracy: ', accuracy_score(y_test, y_predict)) print('log loss: ', log_loss(y_test, y_predict_prob)) print('auc: ', auc(fpr, tpr)) Accuracy: 0.8547486033519553 log loss: 0.36597373727139876 auc: 0.9007246376811595 idx = np.min(np.where(tpr>0.95)) Plot for True Positive Rate (recall) vs False Positive Rate (1 – specificity) i.e. Receiver operating characteristic (ROC) curve. A receiver operating characteristic curve, ROC curve, is a graphical plot that illustrates the diagnostic ability of a binary classifier system as its discrimination threshold is varied. The ROC curve is created by plotting the True Positive Rate (TPR) against the False Positive Rate (FPR) at various threshold settings. True positive rate = correctly identified(For example : Sick people correctly identified as sick) False positive rate = Incorrectly identified(For example : Healthy people incorrectly identified as sick) . Now we will try to plot the Receiver Operating Characteristics curve.Let’s have a look at the following code: plt.figure() plt.plot(fpr, tpr, color = 'coral', label = "ROC curve area: " + str() print("Using a threshold of %.3f " % thr[idx] + "guarantees a sensitivity of %.3f " % tpr[idx] + "and a specificity of %.3f" % (1-fpr[idx]) + ", i.e. a false positive rate of %.2f%%." % (np.array(fpr[idx])*100)) Using a threshold of 0.094 guarantees a sensitivity of 1.000 and a specificity of 0.073, i.e. a false positive rate of 92.73%.
https://kgptalkie.com/logistic-regression-with-python-in-machine-learning-kgp-talkie/
CC-MAIN-2021-17
en
refinedweb
SimpleTankController From Unify Community Wiki Revision as of 01:38, 7 September 2018 by Isaiah Kelly (Talk | contribs) Description A simple non-physics based tank movement controller. Usage Attach the script to a game object. A CharacterController component will be automatically added if one does not already exist. The forward and backwards motions is controlled by the vertical input axis, while rotation is controlled by horizontal input axis. Tweak the various variables in the inspector to obtain a desired behaviour. SimpleTankController.cs using UnityEngine; [RequireComponent (typeof (CharacterController))] public partial class SimpleTankController : MonoBehaviour { public enum MoveDirection { Forward, Reverse, Stop } [Header ("Motion")] [SerializeField] private float topForwardSpeed = 3.0f; [SerializeField] private float topReverseSpeed = 1.0f; [Tooltip ("Rate at which top speed is reached.")] [SerializeField] private float acceleration = 3.0f; [Tooltip ("Rate at which speed is lost when not accelerating.")] [SerializeField] private float deceleration = 2.0f; [Tooltip ("Rate at which speed is lost when braking (input opposite of current direction).")] [SerializeField] private float brakingDeceleration = 4.0f; [Tooltip ("Maintain speed when no input is provided.")] [SerializeField] private bool stickyThrottle = false; [Tooltip ("Delay between change of direction when sticky throttle is enabled.")] [SerializeField] private float stickyThrottleDelay = 0.35f; [SerializeField] private float gravity = 10.0f; [Header ("Rotation")] [SerializeField] private float topForwardTurnRate = 1.0f; [SerializeField] private float topReverseTurnRate = 2.0f; [SerializeField] private float stoppedTurnRate = 2.0f; private float currentSpeed; private float currentTopSpeed; private MoveDirection currentDirection = MoveDirection.Stop; private bool isBraking = false; private bool isAccelerating = false; private float stickyDelayCount = 9999f; private CharacterController m_Controller; private Transform m_Transform; private void Awake () { // Performance optimization - cache transform reference. m_Transform = GetComponent<Transform> (); m_Controller = GetComponent<CharacterController> (); currentTopSpeed = topForwardSpeed; } private void FixedUpdate () { // Direction to move this update. Vector3 moveDirection = Vector3.zero; // Direction requested this update. MoveDirection requestedDirection = MoveDirection.Stop; if (m_Controller.isGrounded) { // Simulate loss of turn rate at speed. float currentTurnRate = Mathf.Lerp (currentDirection == MoveDirection.Forward ? topForwardTurnRate : topReverseTurnRate, stoppedTurnRate, 1 - (currentSpeed / currentTopSpeed)); Vector3 angles = m_Transform.eulerAngles; angles.y += (Input.GetAxis ("Horizontal") * currentTurnRate); m_Transform.eulerAngles = angles; // Based on input, determine requested action. if (Input.GetAxis ("Vertical") > 0) // Requesting forward. { requestedDirection = MoveDirection.Forward; isAccelerating = true; } else { if (Input.GetAxis ("Vertical") < 0) // Requesting reverse. { requestedDirection = MoveDirection.Reverse; isAccelerating = true; } else { requestedDirection = currentDirection; isAccelerating = false; } } isBraking = false; if (currentDirection == MoveDirection.Stop) { stickyDelayCount = stickyDelayCount + Time.deltaTime; // If we are not sticky throttle or if we have hit the delay then change direction. if (!stickyThrottle || (stickyDelayCount > stickyThrottleDelay)) { // Make sure we can go in the requested direction. if (((requestedDirection == MoveDirection.Reverse) && (topReverseSpeed > 0)) || ((requestedDirection == MoveDirection.Forward) && (topForwardSpeed > 0))) { currentDirection = requestedDirection; } } } else { // Requesting a change of direction, but not stopped so we are braking. if (currentDirection != requestedDirection) { isBraking = true; isAccelerating = false; } } // Setup top speeds and move direction. if (currentDirection == MoveDirection.Forward) { moveDirection = Vector3.forward; currentTopSpeed = topForwardSpeed; } else { if (currentDirection == MoveDirection.Reverse) { moveDirection = -1 * Vector3.forward; currentTopSpeed = topReverseSpeed; } else { if (currentDirection == MoveDirection.Stop) { moveDirection = Vector3.zero; } } } if (isAccelerating) { // If we haven't hit top speed yet, accelerate. if (currentSpeed < currentTopSpeed) { currentSpeed = currentSpeed + (acceleration * Time.deltaTime); } } else { // If we are not accelerating and still have some speed, decelerate. if (currentSpeed > 0) { // Adjust deceleration for braking and implement sticky throttle. float currentDecelerationRate = isBraking ? brakingDeceleration : (!stickyThrottle ? deceleration : 0); currentSpeed = currentSpeed - (currentDecelerationRate * Time.deltaTime); } } // If our speed is below zero, stop and initialize. if ((currentSpeed < 0) || ((currentSpeed == 0) && (currentDirection != MoveDirection.Stop))) { SetStopped (); } else { // Limit the speed to the current top speed. if (currentSpeed > currentTopSpeed) { currentSpeed = currentTopSpeed; } } moveDirection = m_Transform.TransformDirection (moveDirection); } // Implement gravity so we can stay grounded. moveDirection.y = moveDirection.y - (gravity * Time.deltaTime); moveDirection.z = moveDirection.z * (Time.deltaTime * currentSpeed); moveDirection.x = moveDirection.x * (Time.deltaTime * currentSpeed); m_Controller.Move (moveDirection); } private void SetStopped () { currentSpeed = 0; currentDirection = MoveDirection.Stop; isAccelerating = false; isBraking = false; stickyDelayCount = 0; } }
https://wiki.unity3d.com/index.php?title=SimpleTankController&oldid=20087
CC-MAIN-2021-17
en
refinedweb
Introduction: download function By default, download() function does some permission checks (if they are set) and sends the uploaded files to the client. The problem: download prevents client side caching The problem is that download() function sends the following http headers, that prevents client side caching: - Expires: Thu, 27 May 2010 05:06:44 GMT - Pragma: no-cache - Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0 This may be good for some dynamic content, but, for example, a client browsing a site with several non static images, will see how each image loads every time the page is shown, slowing down navigation. @Caching download Caching download() with @cache will not help, it prevents permission checks to be made, and cache is done at server side, we need some at client side. One Solution: fast_download A best approach will be using a custom download function, allowing client side caching, so once the browser downloaded a file, that file doesn't need to be downloaded again soon. This can be done with a custom download function (ie. fast_download), doing simple security checks and modifying http headers to favor client side caching: - Last-Modified: Tue, 04 May 2010 19:41:16 GMT - Expires removed - Pragma removed - Cache-control removed Using Last-Modified allows If-Modified-Since http requests, whose speed up downloads preventing sending again unmodified contents. response.stream handles if-modified-since and range requests automatically. Other Solution: let webserver handle downloads This aproach need some webserver (apache) config files tweaking, so is not portable nor easily configurable. Using fast_download should be a better alternative, that requires no custom configuration and works quickly with almost all webservers, and the user would not notice any performance difference. fast_download code So, in controller, default.py add: def fast_download(): # very basic security (only allow fast_download on your_table.upload_field): if not request.args(0).startswith("yourtable.upload_field"): return download() # remove/add headers that prevent/favors client-side caching del response.headers['Cache-Control'] del response.headers['Pragma'] del response.headers['Expires'] filename = os.path.join(request.folder,'uploads',request.args(0)) # send last modified date/time so client browser can enable client-side caching response.headers['Last-Modified'] = time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.localtime(os.path.getmtime(filename))) return response.stream(open(filename,'rb')) In your view, remember to make URLs using fast_download instead of download function: URL(r=request, c='default', f='fast_download', args=your_table.upload_field) Thanks massimo for the advice and comments, for the full thread see: 0 select 10 years ago 0 thadeusb 10 years ago 0 thadeusb 10 years ago 0 reingart 10 years ago
http://www.web2pyslices.com/slice/show/1408/fast-downloads
CC-MAIN-2021-17
en
refinedweb
High Availability¶ In this guide we’ll go over design and programming considerations related to high availability in Cinder. The document aims to provide a single point of truth in all matters related to Cinder’s high availability. Cinder developers must always have these aspects present during the design and programming of the Cinder core code, as well as the drivers’ code. Most topics will focus on Active-Active deployments. Some topics covering node and process concurrency will also apply to Active-Passive deployments. Overview¶ There are 4 services that must be considered when looking at a highly available Cinder deployment: API, Scheduler, Volume, Backup. Each of these services has its own challenges and mechanisms to support concurrent and multi node code execution. This document provides a general overview of Cinder aspects related to high availability, together with implementation details. Given the breadth and depth required to properly explain them all, it will fall short in some places. It will provide external references to expand on some of the topics hoping to help better understand them. Some of the topics that will be covered are: Job distribution. Message queues. Threading model. Versioned Objects used for rolling upgrades. Heartbeat system. Mechanism used to clean up out of service cluster nodes. Mutual exclusion mechanisms used in Cinder. It’s good to keep in mind that Cinder threading model is based on eventlet’s green threads. Some Cinder and driver code may use native threads to prevent thread blocking, but that’s not the general rule. Throughout the document we’ll be referring to clustered and non clustered Volume services. This distinction is not based on the number of services running, but on their configurations. A non clustered Volume service is one that will be deployed as Active-Passive and has not been included in a Cinder cluster. On the other hand, a clustered Volume service is one that can be deployed as Active-Active because it is part of a Cinder cluster. We consider a Volume service to be clustered even when there is only one node in the cluster. Job distribution¶ Cinder uses RPC calls to pass jobs to Scheduler, Volume, and Backup services. A message broker is used for the transport layer on the RPC calls and parameters. Job distribution is handled by the message broker using message queues. The different services, except the API, listen on specific message queues for RPC calls. Based on the maximum number of nodes that will connect, we can differentiate two types of message queues: those with a single listener and those with multiple listeners. We use single listener queues to send RPC calls to a specific service in a node. For example, when the API calls a non clustered Volume service to create a snapshot. Message queues having multiple listeners are used in operations such as: Creating any volume. Call made from the API to the Scheduler. Creating a volume in a clustered Volume service. Call made from the Scheduler to the Volume service. Attaching a volume in a clustered Volume service. Call made from the API to the Volume service. Regardless of the number of listeners, all the above mentioned RPC calls are unicast calls. The caller will place the request in a queue in the message broker and a single node will retrieve it and execute the call. There are other kinds of RPC calls, those where we broadcast a single RPC call to multiple nodes. The best example of this type of call is the Volume service capabilities report sent to all the Schedulers. Message queues are fair queues and are used to distribute jobs in a round robin fashion. Single target RPC calls made to message queues with multiple listeners are distributed in round robin. So sending three request to a cluster of 3 Schedulers will send one request to each one. Distribution is content and workload agnostic. A node could be receiving all the quick and easy jobs while another one gets all the heavy lifting and its ongoing workload keeps increasing. Cinder’s job distribution mechanism allows fine grained control over who to send RPC calls. Even on clustered Volume services we can still access individual nodes within the cluster. So developers must pay attention to where they want to send RPC calls and ask themselves: Is the target a clustered service? Is the RPC call intended for any node running the service? Is it for a specific node? For all nodes? The code in charge of deciding the target message queue, therefore the recipient, is in the rpcapi.py files. Each service has its own file with the RPC calls: volume/rpcapi.py, scheduler/rpcapi.py, and backup/rpcapi.py. For RPC calls the different rcpapi.py files ultimately use the _get_cctxt method from the cinder.rpc.RPCAPI class. For a detailed description on the issue, ramifications, and solutions, please refer to the Cinder Volume Job Distribution. The RabbitMQ tutorials are a good way to understand message brokers general topics. Heartbeats¶ Cinder services, with the exception of API services, have a periodic heartbeat to indicate they are up and running. When services are having health issues, they may decide to stop reporting heartbeats, even if they are running. This happens during initialization if the driver cannot be setup correctly. The database is used to report service heartbeats. Fields report_count and updated_at, in the services table, keep a heartbeat counter and the last time the counter was updated. There will be multiple database entries for Cinder Volume services running multiple backends. One per backend. Using a date-time to mark the moment of the last heartbeat makes the system time relevant for Cinder’s operation. A significant difference in system times on our nodes could cause issues in a Cinder deployment. All services report and expect the updated_at field to be UTC. To determine if a service is up, we check the time of the last heartbeat to confirm that it’s not older than service_down_time seconds. Default value for service_down_time configuration option is 60 seconds. Cinder uses method is_up, from the Service and Cluster Versioned Object, to ensure consistency in the calculations across the whole code base. Heartbeat frequency in Cinder services is determined by the report_interval configuration option. The default is 10 seconds, allowing network and database interruptions. Cinder protects itself against some incorrect configurations. If report_interval is greater or equal than service_down_time, Cinder will log a warning and use a service down time of two and a half times the configured report_interval. Note It is of utter importance having the same service_down_time and report_interval configuration options in all your nodes. In each service’s section we’ll expand this topic with specific information only relevant to that service. Cleanup¶ Power outages, hardware failures, unintended reboots, and software errors. These are all events that could make a Cinder service unexpectedly halt its execution. A running Cinder service is usually carrying out actions on resources. So when the service dies unexpectedly, it will abruptly stop those operations. Stopped operations in this way leaves resources in transitioning states. For example a volume could be left in a deleting or creating status. If left alone resources will remain in this state forever, as the service in charge of transitioning them to a rest status (available, error, deleted) is no longer running. Existing reset-status operations allow operators to forcefully change the state of a resource. But these state resets are not recommended except in very specific cases and when we really know what we are doing. Cleanup mechanisms are tasked with service’s recovery after an abrupt stop of the service. They are the recommended way to resolve stuck transitioning states caused by sudden service stop. There are multiple cleanup mechanisms in Cinder, but in essence they all follow the same logic. Based on the resource type and its status the mechanism determines the best cleanup action that will transition the state to a rest state. Some actions require a resource going through several services. In this case deciding the cleanup action may also require taking into account where the resource was being processed. Cinder has two types of cleanup mechanisms: On node startup: Happen on Scheduler, Volume, and Backup services. Upon user request. User requested cleanups can only be triggered on Scheduler and Volume nodes. When a node starts it will do a cleanup, but only for the resources that were left in a transitioning state when the service stopped. It will never touch resources from other services in the cluster. Node startup cleanup is slightly different on services supporting user requested cleanups -Scheduler and Volume- than on Backup services. Backup cleanups will be covered in the service’s section. For services supporting user requested cleanups we can differentiate the following tasks: Tracking transitioning resources: Using workers table and Cleanable Versioned Objects methods. Defining when a resource must be cleaned if service dies: Done in Cleanable Versioned Objects. Defining how a resource must be cleaned: Done in the service manager. Note All Volume services can accept cleanup requests, doesn’t matter if they are clustered or not. This will provide a better alternative to the reset-state mechanism to handle resources stuck in a transitioning state. Workers table¶ For Cinder Volume managed resources -Volumes and Snapshots- we used to establish a one-to-one relationship between a resource and the volume service managing it. A resource would belong to a node if the resource’s host field matched that of the running Cinder Volume service. Snapshots must always be managed by the same service as the volume they originate from, so they don’t have a host field in the database. In this case the parent volume’s host is used to determine who owns the resource. Cinder-Volume services can be clustered, so we no longer have a one-to-one owner relationship. On clustered services we use the cluster_name database field instead of the host to determine ownership. Now we have a one-to-many ownership relationship. When a clustered service abruptly stops running, any of the nodes from the same cluster can cleanup the resources it was working on. There is no longer a need to restart the service to get the resources cleaned by the node startup cleanup process. We keep track of the resources our Cinder services are working on in the workers table. Only resources that can be cleaned are tracked. This table stores the resource type and id, the status that should be cleared on service failure, the service that is working on it, etc. And we’ll be updating this table as the resources move from service to service. Worker entries are not passed as RPC parameters, so we don’t need a Versioned Object class to represent them. We only have the Worker ORM class to represent database entries. Following subsections will cover implementation details required to develop new cleanup resources and states. For a detailed description on the issue, ramifications, and overall solution, please refer to the Cleanup spec. Tracking resources¶ Resources supporting cleanup using the workers table must inherit from the CinderCleanableObject Versioned Object class. This class provides helper methods and the general interface used by Cinder for the cleanup mechanism. This interface is conceptually split in three tasks: Manage workers table on the database. Defining what states must be cleaned. Defining how to clean resources. Among methods provided by the CinderCleanableObject class the most important ones are: is_cleanable: Checks if the resource, given its current status, is cleanable. create_worker: Create a worker entry on the API service. set_worker: Create or update worker entry. unset_worker: Remove an entry from the database. This is a real delete, not a soft-delete. set_workers: Function decorator to create or update worker entries. Inheriting classes must define _is_cleanable method to define which resource states can be cleaned up. Earlier we mentioned how cleanup depends on a resource’s current state. But it also depends under what version the services are running. With rolling updates we can have a service running under an earlier pinned version for compatibility purposes. A version X service could have a resource that it would consider cleanable, but it’s pinned to version X-1, where it was not considered cleanable. To avoid breaking things, the resource should be considered as non cleanable until the service version is unpinned. Implementation of _is_cleanable method must take them both into account. The state, and the version. Volume’s implementation is a good example, as workers table was not supported before version 1.6: @staticmethod def _is_cleanable(status, obj_version): if obj_version and obj_version < 1.6: return False return status in ('creating', 'deleting', 'uploading', 'downloading') Tracking states in the workers table starts by calling the create_worker method on the API node. This is best done on the different rpcapi.py files. For example, a create volume operation will go from the API service to the Scheduler service, so we’ll add it in cinder/scheduler/rpcapi.py: def create_volume(self, ctxt, volume, snapshot_id=None, image_id=None, request_spec=None, filter_properties=None, backup_id=None): volume.create_worker() But if we are deleting a volume or creating a snapshot the API will call the Volume service directly, so changes should go in cinder/scheduler/rpcapi.py: def delete_volume(self, ctxt, volume, unmanage_only=False, cascade=False): volume.create_worker() Once we receive the call on the other side’s manager we have to call the set_worker method. To facilitate this task we have the set_workers decorator that will automatically call set_worker for any cleanable versioned object that is in a cleanable state. For the create volume on the Scheduler service: @objects.Volume.set_workers @append_operation_type() def create_volume(self, context, volume, snapshot_id=None, image_id=None, request_spec=None, filter_properties=None, backup_id=None): And then again for the create volume on the Volume service: @objects.Volume.set_workers def create_volume(self, context, volume, request_spec=None, filter_properties=None, allow_reschedule=True): In these examples we are using the set_workers method from the Volume Versioned Object class. But we could be using it from any other class as it is a staticmethod that is not overwritten by any of the classes. Using the set_workers decorator will cover most of our use cases, but sometimes we may have to call the set_worker method ourselves. That’s the case when transitioning from creating state to downloading. The worker database entry was created with the creating state and the working service was updated when the Volume service received the RPC call. But once we change the status to creating the worker and the resource status don’t match, so the cleanup mechanism will ignore the resource. To solve this we add another worker update in the save method from the Volume Versioned Object class: def save(self): ... if updates.get('status') == 'downloading': self.set_worker() Actions on resource cleanup¶ We’ve seen how to track cleanable resources in the workers table. Now we’ll cover how to define the actions used to cleanup a resource. Services using the workers table inherit from the CleanableManager class and must implement the _do_cleanup method. This method receives a versioned object to clean and indicates whether we should keep the workers table entry. On asynchronous cleanup tasks method must return True and take care of removing the worker entry on completion. Simplified version of the cleanup of the Volume service, illustrating synchronous and asynchronous cleanups and how we can do a synchronous cleanup and take care ourselves of the workers entry: def _do_cleanup(self, ctxt, vo_resource): if isinstance(vo_resource, objects.Volume): if vo_resource.status == 'downloading': self.driver.clear_download(ctxt, vo_resource) elif vo_resource.status == 'deleting': if CONF.volume_service_inithost_offload: self._add_to_threadpool(self.delete_volume, ctxt, vo_resource, cascade=True) else: self.delete_volume(ctxt, vo_resource, cascade=True) return True if vo_resource.status in ('creating', 'downloading'): vo_resource.status = 'error' vo_resource.save() When the volume is downloading we don’t return anything, so the caller receives None, which evaluates to not keep the row entry. When the status is deleting we call delete_volume synchronously or asynchronously. The delete_volume has the set_workers decorator, that calls unset_worker once the decorated method has successfully finished. So when calling delete_volume we must ask the caller of _do_cleanup to not try to remove the workers entry. Cleaning resources¶ We may not have a Worker Versioned Object because we didn’t need it, but we have a CleanupRequest Versioned Object to specify resources for cleanup. Resources will be cleaned when a node starts up and on user request. In both cases we’ll use the CleanupRequest that contains a filtering of what needs to be cleaned up. The CleanupRequest can be considered as a filter on the workers table to determine what needs to be cleaned. Managers for services using the workers table must support the startup cleanup mechanism. Support for this mechanism is provided via the init_host method in the CleanableManager class. So managers inheriting from CleanableManager must make sure they call this init_host method. This can be done using CleanableManager as the first inherited class and using super to call the parent’s init_host method, or by calling the class method directly: cleanableManager.init_host(self, …). CleanableManager’s init_host method will create a CleanupRequest for the current service before calling its do_cleanup method with it before returning. Thus cleaning up all transitioning resources from the service. For user requested cleanups, the API generates a CleanupRequest object using the request’s parameters and calls the scheduler’s work_cleanup RPC with it. The Scheduler receives the work_cleanup RPC call and uses the CleanupRequest to filter services that match the request. With this list of services the Scheduler sends an individual cleanup request for each of the services. This way we can spread the cleanup work if we have multiple services to cleanup. The Scheduler checks the service to clean to know where it must send the clean request. Scheduler service cleanup can be performed by any Scheduler, so we send it to the scheduler queue where all Schedulers are listening. In the worst case it will come back to us if there is no other Scheduler running at the time. For the Volume service we’ll be sending it to the cluster message queue if it’s a clustered service, or to a single node if it’s non clustered. But unlike with the Scheduler, we can’t be sure that there is a service to do the cleanup, so we check if the service or cluster is up before sending the request. After sending all the cleanup requests, the Scheduler will return a list of services that have received a cleanup request, and all the services that didn’t because they were down. Mutual exclusion¶ In Cinder, as many other concurrent and parallel systems, there are “critical sections”. Code sections that share a common resource that can only be accessed by one of them at a time. Resources can be anything, not only Cinder resources such as Volumes and Snapshots, and they can be local or remote. Examples of resources are libraries, command line tools, storage target groups, etc. Exclusion scopes can be per process, per node, or global. We have four mutual exclusion mechanisms available during Cinder development: Database locking using resource states. Process locks. Node locks. Global locks. For performance reasons we must always try to avoid using any mutual exclusion mechanism. If avoiding them is not possible, we should try to use the narrowest scope possible and reduce the critical section as much as possible. Locks by decreasing order of preference are: process locks, node locks, global locks, database locks. Status based locking¶ Many Cinder operations are inherently exclusive and the Cinder core code ensures that drivers will not receive contradictory or incompatible calls. For example, you cannot clone a volume if it’s being created. And you shouldn’t delete the source volume of an ongoing snapshot. To prevent these from happening Cinder API services use resource status fields to check for incompatibilities preventing operations from getting through. There are exceptions to this rule, for example the force delete operation that ignores the status of a resource. We should also be aware that administrators can forcefully change the status of a resource and then call the API, bypassing the check that prevents multiple operations from being requested to the drivers. Resource locking using states is expanded upon in the Race prevention subsection in the Cinder-API section. Process locks¶ Cinder services are multi-threaded -not really since we use greenthreads-, so the narrowest possible scope of locking is among the threads of a single process. Some cases where we may want to use this type of locking are when we share arrays or dictionaries between the different threads within the process, and when we use a Python or C library that doesn’t properly handle concurrency and we have to be careful with how we call its methods. To use this locking in Cinder we must use the synchronized method in cinder.utils. This method in turn uses the synchronized method from oslo_concurrency.lockutils with the cinder- prefix for all the locks to avoid conflict with other OpenStack services. The only required parameter for this usage is the name of the lock. The name parameter provided for these locks must be a literal string value. There is no kind of templating support. Example from cinder/volume/throttling.py: @utils.synchronized('BlkioCgroup') def _inc_device(self, srcdev, dstdev): Note When developing a driver, and considering which type of lock to use, we must remember that Cinder is a multi backend service. So the same driver can be running multiple times on different processes in the same node. Node locks¶ Sometimes we want to define the whole node as the scope of the lock. Our critical section requires that only one thread in the whole node is using the resource. This inter process lock ensures that no matter how many processes and backends want to access the same resource, only one will access it at a time. All others will have to wait. These locks are useful when: We want to ensure there’s only one ongoing call to a command line program. That’s the case of the cinder-rtstool command in cinder/volume/targets/lio.py, and the nvmetcli command in cinder/volume/targets/nvmet.py. Common initialization in all processes in the node. This is the case of the backup service cleanup code. The backup service can run multiple processes simultaneously for the same backend, but only one of them can run the cleanup code on start. Drivers not supporting Active-Active configurations. Any operation that should only be performed by one driver at a time. For example creating target groups for a node. This type of lock use the same method as the Process locks, synchronized method from cinder.utils. Here we need to pass two parameters, the name of the lock, and external=True to make sure that file locks are being used. The name parameter provided for these locks must be a literal string value. There is no kind of templating support. Example from cinder/volume/targest/lio.py: @staticmethod @utils.synchronized('lioadm', external=True) def _execute(*args, **kwargs): Example from cinder/backup/manager.py: @utils.synchronized('backup-pgid-%s' % os.getpgrp(), external=True, delay=0.1) def _cleanup_incomplete_backup_operations(self, ctxt): Warning These are not fair locks. Order in which the lock is acquired by callers may differ from request order. Starvation is possible, so don’t choose a generic lock name for all your locks and try to create a unique name for each locking domain. Global locks¶ Global locks, also known as distributed locks in Cinder, provide mutual exclusion in the global scope of the Cinder services. They allow you to have a lock regardless of the backend, for example to prevent deleting a volume that is being cloned, or making sure that your driver is only creating a Target group at a time, in the whole Cinder deployment, to avoid race conditions. Global locking functionality is provided by the synchronized decorator from cinder.coordination. This method is more advanced than the one used for the Process locks and the Node locks, as the name supports templates. For the template we have all the method parameters as well as f_name that represents that name of the method being decorated. Templates must use Python’s Format Specification Mini-Language. Using brackets we can access the function name ‘{f_name}’, an attribute of a parameter ‘{volume.id}’, a key in a dictonary {snapshot[‘name’]}, etc. Up to date information on the method can be found in the synchronized method’s documentation. Example from the delete volume operation in cinder/volume/manager.py. We use the id attribute of the volume parameter, and the function name to form the lock name: @coordination.synchronized('{volume.id}-{f_name}') @objects.Volume.set_workers def delete_volume(self, context, volume, unmanage_only=False, cascade=False): Example from create snapshot in cinder/volume/drivers/nfs.py, where we use an attribute from self, and a recursive reference in the snapshot parameter. @coordination.synchronized('{self.driver_prefix}-{snapshot.volume.id}') def create_snapshot(self, snapshot): Internally Cinder uses the Tooz library to provide the distributed locking. By default, this library is configured for Active-Passive deployments, where it uses file locks equivalent to those used for Node locks. To support Active-Active deployments a specific driver will need to be configured using the backend_url configuration option in the coordination section. For a detailed description of the requirement for global locks in cinder please refer to the replacing local locks with Tooz and manager local locks specs. Cinder locking¶ Cinder uses the different locking mechanisms covered in this section to assure mutual exclusion on some actions. Here’s an incomplete list: - Barbican keys Lock scope: Global. Critical section: Migrate Barbican encryption keys. Lock name: {id}-_migrate_encryption_key. Where: _migrate_encryption_key method. File: cinder/keymgr/migration.py. - Backup service Lock scope: Node. Critical section: Cleaning up resources at startup. Lock name: backup-pgid-{process-group-id}. Where: _cleanup_incomplete_backup_operations method. File: cinder/backup/manager.py. - Image cache Lock scope: Global. Critical section: Create a new image cache entry. Lock name: {image_id}. Where: _prepare_image_cache_entry method. File: cinder/volume/flows/manager/create_volume.py. - Throttling: Lock scope: Process. Critical section: Set parameters of a cgroup using cgset CLI. Lock name: ‘’BlkioCgroup’. Where: _inc_device and _dec_device methods. File: cinder/volume/throttling.py. - Volume deletion: Lock scope: Global. Critical section: Volume deletion operation. Lock name: {volume.id}-delete_volume. Where: delete_volume method. File: cinder/volume/manager.py. - Volume deletion request: Lock scope: Status based. Critical section: Volume delete RPC call. Status requirements: attach_status != ‘attached’ && not migrating Where: delete method. File: cinder/volume/api.py. - Snapshot deletion: Lock scope: Global. Critical section: Snapshot deletion operation. Lock name: {snapshot.id}-delete_snapshot. Where: delete_snapshot method. File: cinder/volume/manager.py. - Volume creation: Lock scope: Global. Critical section: Protect source of volume creation from deletion. Volume or Snapshot. Lock name: {snapshot-id}-delete_snapshot or {volume-id}-delete_volume}. Where: Inside create_volume method as context manager for calling _fun_flow. File: cinder/volume/manager.py. - Attach volume: Lock scope: Global. Critical section: Updating DB to show volume is attached. Lock name: {volume_id}. Where: attach_volume method. File: cinder/volume/manager.py. - Detach volume: Lock scope: Global. Critical section: Updating DB to show volume is detached. Lock name: {volume_id}-detach_volume. Where: detach_volume method. File: cinder/volume/manager.py. - Volume upload image: Lock scope: Status based. Critical section: copy_volume_to_image RPC call. Status requirements: status = ‘available’ or (force && status = ‘in-use’) Where: copy_volume_to_image method. File: cinder/volume/api.py. - Volume extend: Lock scope: Status based. Critical section: extend_volume RPC call. Status requirements: status in (‘in-use’, ‘available’) Where: _extend method. File: cinder/volume/api.py. - Volume migration: Lock scope: Status based. Critical section: migrate_volume RPC call. Status requirements: status in (‘in-use’, ‘available’) && not migrating Where: migrate_volume method. File: cinder/volume/api.py. - Volume retype: Lock scope: Status based. Critical section: retype RPC call. Status requirements: status in (‘in-use’, ‘available’) && not migrating Where: retype method. File: cinder/volume/api.py. Driver locking¶ There is no general rule on where drivers should use locks. Each driver has its own requirements and limitations determined by the storage backend and the tools and mechanisms used to manage it. Even if they are all different, commonalities may exist between drivers. Providing a list of where some drivers are using locks, even if the list is incomplete, may prove useful to other developers. To contain the length of this document and keep it readable, the list with the Drivers Locking Examples has its own document. Cinder-API¶ The API service is the public face of Cinder. Its REST API makes it possible for anyone to manage and consume block storage resources. So requests from clients can, and usually do, come from multiple sources. Each Cinder API service by default will run multiple workers. Each worker is run in a separate subprocess and will run a predefined maximum number of green threads. The number of API workers is defined by the osapi_volume_workers configuration option. Defaults to the number of CPUs available. Number of green threads per worker is defined by the wsgi_default_pool_size configuration option. Defaults to 100 green threads. The service takes care of validating request parameters. Any detected error is reported immediately to the user. Once the request has been validated, the database is changed to reflect the request. This can result in adding a new entry to the database and/or modifying an existing entry. For create volume and create snapshot operations the API service will create a new database entry for the new resource. And the new information for the resource will be returned to the caller right after the service passes the request to the next Cinder service via RPC. Operations like retype and delete will change the database entry referenced by the request, before making the RPC call to the next Cinder service. Create backup and restore backup are two of the operations that will create a new entry in the database, and modify an existing one. These database changes are very relevant to the high availability operation. Cinder core code uses resource states extensively to control exclusive access to resources. Race prevention¶ The API service checks that resources referenced in requests are in a valid state. Unlike allowed resource states, valid states are those that allow an operation to proceed. Validation usually requires checking multiple conditions. Careless coding leaves Cinder open to race conditions. Patterns in the form of DB data read, data check, and database entry modification, must be avoided in the Cinder API service. Cinder has implemented a custom mechanism, called conditional updates, to prevent race conditions. Leverages the SQLAlchemy ORM library to abstract the equivalent UPDATE ... FROM ... WHERE; SQL query. Complete reference information on the conditional updates mechanism is available on the API Races - Conditional Updates development document. For a detailed description on the issue, ramifications, and solution, please refer to the API Race removal spec. Cinder-Volume¶ The most common deployment option for Cinder-Volume is as Active-Passive. This requires a common storage backend, the same Cinder backend configuration in all nodes, having the backend_host set on the backend sections, and using a high-availability cluster resource manager like Pacemaker. Attention Having the same host value configured on more than one Cinder node is highly discouraged. Using backend_host in the backend section is the recommended way to set Active-Passive configurations. Setting the same host field will make Scheduler and Backup services report using the same database entry in the services table. This may create a good number of issues: We cannot tell when the service in a node is down, backups services will break other running services operation on start, etc. For Active-Active configurations we need to include the Volume services that will be managing the same backends on the cluster. To include a node in a cluster, we need to define its name in the [DEFAULT] section using the cluster configuration option, and start or restart the service. Note We can create a cluster with a single volume node. Having a single node cluster allows us to later on add new nodes to the cluster without restarting the existing node. Warning The name of the cluster must be unique and cannot match any of the host or backend_host values. Non unique values will generate duplicated names for message queues. When a Volume service is configured to be part of a cluster, and the service is restarted, the manager detects the change in configuration and moves existing resources to the cluster. Resources are added to the cluster in the _include_resources_in_cluster method setting the cluster_name field in the database. Volumes, groups, consistency groups, and image cache elements are added to the cluster. Clustered Volume services are different than normal services. To determine if a backend is up, it is no longer enough checking service.is_up, as that will only give us the status of a specific service. In a clustered deployment there could be other services that are able to service the same backend. That’s why we’ll have to check if a service is clustered using cinder.is_clustered and if it is, check the cluster’s is_up property instead: service.cluster.is_up. In the code, to detect if a cluster is up, the is_up property from the Cluster Versioned Object uses the last_heartbeat field from the same object. The last_heartbeat is a column property from the SQLAlchemy ORM model resulting from getting the latest updated_at field from all the services in the same cluster. RPC calls¶ When we discussed the Job distribution we mentioned message queues having multiple listeners and how they were used to distribute jobs in a round robin fashion to multiple nodes. For clustered Volume services we have the same queues used for broadcasting and to address a specific node, but we also have queues to broadcast to the cluster and to send jobs to the cluster. Volume services will be listening in all these queues and they can receive request from any of them. Which they’ll have to do to process RPC calls addressed to the cluster or to themselves. Deciding the target message queue for request to the Volume service is done in the volume/rpcapi.py file. We use method _get_cctxt, from the VolumeAPI class, to prepare the client context to make RPC calls. This method accepts a host parameter to indicate where we want to make the RPC. This host parameter refers to both hosts and clusters, and is used to determine the server and the topic. When calling the _get_cctx method, we would need to pass the resource’s host field if it’s not clustered, and cluster_name if it is. To facilitate this, clustered resources implement the service_topic_queue property that automatically gives you the right value to pass to _get_cctx. An example for the create volume: def create_volume(self, ctxt, volume, request_spec, filter_properties, allow_reschedule=True): cctxt = self._get_cctxt(volume.service_topic_queue) cctxt.cast(ctxt, 'create_volume', request_spec=request_spec, filter_properties=filter_properties, allow_reschedule=allow_reschedule, volume=volume) As we know, snapshots don’t have a host or cluseter_name fields, but we can still use the service_topic_queue property from the Snapshot Versioned Object to get the right value. The Snapshot internally checks these values from the Volume Versioned Object linked to that Snapshot to determine the right value. Here’s an example for deleting a snapshot: def delete_snapshot(self, ctxt, snapshot, unmanage_only=False): cctxt = self._get_cctxt(snapshot.service_topic_queue) cctxt.cast(ctxt, 'delete_snapshot', snapshot=snapshot, unmanage_only=unmanage_only) Replication¶ Replication v2.1 failover is requested on a per node basis, so when a failover request is received by the API it is then redirected to a specific Volume service. Only one of the services that form the cluster for the storage backend will receive the request, and the others will be oblivious to this change and will continue using the same replication site they had been using before. To support the replication feature on clustered Volume services, drivers need to implement the Active-Active replication spec. In this spec the failover_host method is split in two, failover and failover_completed. On a backend supporting replication on Active-Active deployments, failover_host would end up being a call to failover followed by a call to failover_completed. Code extract from the RBD driver: def failover_host(self, context, volumes, secondary_id=None, groups=None): active_backend_id, volume_update_list, group_update_list = ( self.failover(context, volumes, secondary_id, groups)) self.failover_completed(context, secondary_id) return active_backend_id, volume_update_list, group_update_list Enabling Active-Active on Drivers¶ Supporting Active-Active configurations is driver dependent, so they have to opt in. By default drivers are not expected to support Active-Active configurations and will fail on startup if we try to deploy them as such. Drivers can indicate they support Active-Active setting the class attribute SUPPORTS_ACTIVE_ACTIVE to True. If a single driver supports multiple storage solutions, it can leave the class attribute as it is, and set it as an overriding instance attribute on __init__. There is no well defined procedure required to allow driver maintainers to set SUPPORTS_ACTIVE_ACTIVE to True. Though there is an ongoing effort to write a spec on testing Active-Active. So for now, we could say that it’s “self-certification”. Vendors must do their own testing until they are satisfied with their testing. Real testing of Active-Active deployments requires multiple Cinder Volume nodes on different hosts, as well as a properly configured Tooz DLM. Driver maintainers can use Devstack to catch the rough edges on their initial testing. Running 2 Cinder Volume services on an All-In-One DevStack installation makes it easy to deploy and debug. Running 2 Cinder Volume services on the same node simulating different nodes can be easily done: Creating a new directory for local locks: Since we are running both services on the same node, a file lock could make us believe that the code would work on different nodes. Having a different lock directory, default is /opt/stack/data/cinder, will prevent this. Creating a layover cinder configuration file: Cinder supports having different configurations files where each new files overrides the common parts of the old ones. We can use the same base cinder configuration provided by DevStack and write a different file with a [DEFAULT] section that configures host (to anything different than the one used in the first service), and lock_path (to the new directory we created). For example we could create /etc/cinder/cinder2.conf. Create a new service unit: This service unit should be identical to the existing devstack@c-vol except replace the ExecStart that should have the postfix –config-file /etc/cinder/cinder2.conf. Once we have tested it in DevStack way we should deploy Cinder in a new Node, and continue with the testings. It is not necessary to do the DevStack step first, we can jump to having Cinder in multiple nodes right from the start. Whatever way we decide to test this, we’ll have to change cinder.conf and add the cluster configuration option and restart the Cinder service. We also need to modify the driver under test to include the SUPPORTS_ACTIVE_ACTIVE = True class attribute. Cinder-Scheduler¶ Unlike the Volume service, the Cinder Scheduler has supported Active-Active deployments for a long time. Unfortunately, current support is not perfect, scheduling on Active-Active deployments has some issues. The root cause of these issues is that the scheduler services don’t have a reliable single source of truth for the information they rely on to make the scheduling. Volume nodes periodically send a broadcast with the backend stats to all the schedulers. The stats include total storage space, free space, configured maximum over provisioning, etc. All the backends’ information is stored in memory at the Schedulers, and used to decide where to create new volumes, migrate them on a retype, and so on. For additional information on the stats, please refer to the volume stats section of the Contributor/Developer docs. Trying to keep updated stats, schedulers reduce available free space on backends in their internal dictionary. These updates are not shared between schedulers, so there is not a single source of truth, and other schedulers don’t operate with the same information. Until the next stat reports is sent, schedulers will not get in sync. This may create unexpected behavior on scheduling. There are ongoing efforts to fix this problem. Multiple solutions are being discussed: using the database as a single source of truth, or using an external placement service. When we added Active-Active support to the Cinder Volume service we had to update the scheduler to understand it. This mostly entailed 3 things: Setting the cluster_name field on Versioned Objects once a backend has been chosen. Grouping stats for all clustered hosts. We don’t want to have individual entries for the stats of each host that manages a cluster, as there should be only one up to date value. We stopped using the host field as the id for each host, and created a new property called backend_id that takes into account if the service is clustered and returns the host or the cluster as the identifier. Prevent race conditions on stats reports. Due to the concurrency on the multiple Volume services in a cluster, and the threading in the Schedulers, we could receive stat reports out of order (more up to date stats last). To prevent this we started time stamping the stats on the Volume services. Using the timestamps schedulers can discard older stats. Heartbeats¶ Like any other non API service, schedulers also send heartbeats using the database. The difference is that, unlike other services, the purpose of these heartbeats is merely informative. Admins can easily know whether schedulers are running or not with a Cinder command. Using the same host configuration in all nodes defeats the whole purpose of reporting heartbeats in the schedulers, as they will all report on the same database entry. Cinder-Backups¶ Originally, the Backup service was not only limited to Active-Passive deployments, but it was also tightly coupled to the Volume service. This coupling meant that the Backup service could only backup volumes created by the Volume service running on the same node. In the Mitaka cycle, the Scalable Backup Service spec was implemented. This added support for Active-Active deployments to the backup service. The Active-Active implementation for the backup service is different than the one we explained for the Volume Service. The reason lays not only on the fact that the Backup service supported it first, but also on it not supporting multiple backends, and not using the Scheduler for any operations. Scheduling¶ For backups, it’s the API the one selecting the host that will do the backup, using methods _get_available_backup_service_host, _is_backup_service_enabled, and _get_any_available_backup_service. These methods use the Backup services’ heartbeats to determine which hosts are up to handle requests. Cleaning¶ Cleanup on Backup services is only performed on start up. To know what resources each node is working on, they set the host field in the backup Versioned Object when they receive the RPC call. That way they can select them for cleanup on start. The method in charge of doing the cleanup for the backups is called _cleanup_incomplete_backup_operations. Unlike with the Volume service we cannot have a backup node clean up after another node’s.
https://docs.openstack.org/cinder/latest/contributor/high_availability.html
CC-MAIN-2021-17
en
refinedweb
Boyer Moore String Search Algorithm Sign up for FREE 1 month of Kindle and read all our books for free. Get FREE domain for 1st year and build your brand new site Reading time: 20 minutes | Coding time: 10 minutes Boyer Moore string search algorithm is an efficient string searching algorithm which was developed by Robert S. Boyer and J Strother Moore in 1977. Bad Character Heuristic and Strong Suffix Heuristic. In boyer moore there are two ways of skipping positions:- 1. Bad Character Heuristic. 2. Good Suffix Heuristic. Bad Character Heuristic After alignment of pattern along text we start matching pattern and text character by character from right end of pattern until we get first unmatched character and then we try to shift pattern to right side in such a way that this unmatched character get matched with shifted alignment of pattern. Note that pattern can be aligned such that either mismatch become a match or pattern move past the mismatch character.Given below is an example to demonstrate: Precomputation for bad character heuristic, we just need to store index of last occurence of each character in pattern in array.For above example badCharacterArray is like one given below: A well commented code is given below for precomputation of both heuristic. Good Suffix Heuristic After alignment of pattern along text we start matching pattern and text character by character from right end of pattern untill we get first unmatched character and then we try to align pattern to right side in such a way that the matched substring or its suffix get matched again.There can be three cases: 1. Another occurence of matched substring found in pattern. Given below an example, The substring "ab" is matched. The pattern can be shifted until the next occurence of ab in the pattern is aligned to the text symbols ab, i.e. to position 2. 2. A prefix of pattern get matched with suffix of matched substring.. 3. Pattern moves past matched substring. In the following situation the suffix ab has matched. There is no other occurence of ab in the pattern.Therefore, the pattern can be shifted behind ab, i.e. to position 5. In precomputation of shift according to good suffix heuristic it is required to understand concept of border. I would suggest you to read my blog on KMP Here.In KMP we already used border to find shift but there we find border for all prefixes and here we are going to find border of all suffixes of pattern.Note that logic behind algorithm of finding border for each prefix is same as written in KMP but here we start our calculation from right end. With the help of border we compute shift array, whose value at each index represent the amount of alignments we can safely skips if mismatch occur at corresponding index. Lets consider a pattern ANPANMAN, now its shift array will look like image given below: - In first row, mismatch occur at first comparision i.eN and as here there is no matched suffix so we can get maximum shift of 1. - In second row, mismatch occur in second comparision i.e A and now we try to find another N which is not preceded by A and as there no such substring "*N"(here * star can be any character except A) in pattern so we shift pattern by size of pattern.i.e 8.(Case 3) 3.In third row, substring "AN" is matched and mismatch is due to character "M", so we try to find substring of form "*AN"(where * can be any character except M) and we found substring "PAN" at index 2 of pattern this alignment can be possible shifting pattern by 3 positions.(Case 1) In similar way remaining values of remaining indices will be calculated. Complexity Time Complexity for precomputation: O(m + size of alphabet) Time Complexity for searching: O(n) Space Complexity: O(m + size of alphabet) Implementation #include <bits/stdc++.h> using namespace std; #define CHARSETSIZE 26 // I am considering that only A-Z capital letters are allowed in TEXT and PATTERN ///PreComputation for Bad Character Heuristic vector<int> badCharacterPreComputation(string pattern) { vector<int> badCharacterArray( CHARSETSIZE, -1); for(int i=0; i < pattern.size(); i++) { //We are storing the last occurence of each latters badCharacterArray[pattern[i]-65]=i; } return badCharacterArray; } ////////// ///PreComputation of shifts for Good Suffix Heristic vector<int> goodSuffixHeuristicPreComputation(string pattern) { int m=pattern.size(), i=m, j=m+1; // Initialize all shift with zero vector<int> borderPos(m+1), shifts(m+1,0); borderPos[i]= j; // Loop given below is used to find border for each index while(i> 0) { /* if character at position i-1 is not equal to character at j-1, then continue searching to right of the pattern for border. */ while( j<=m && pattern[i-1]!= pattern[j-1]) { /* The preceding character of matched string is diffent than mismatching character. */ if(shifts[j]==0) shifts[j] = j-i; // update the position of next border j = borderPos[j]; } /*As pattern[i-1] is equal to pattern[j-1], position of border for prefix starting from i-1 is j-1*/ i--; j--; borderPos[i] = j; } /* untill now we calculated shift according to case1 i.e when full matched substring with different preceding charater exists in pattern*/ /* now we will fill those shifts generated beacause of case 2 i.e some suffix of matched string is found as prefix of pattern */ j= borderPos[0]; for(i=0; i<=m; i++) { if(shifts[i] == 0) shifts[i] = j; if(i == j) j = borderPos[j]; } return shifts; } //////// vector<int> boyerMooreSearch(string text, string pattern) { int i=0, j, m=pattern.size(); int badShift,goodShift; //preprocessing vector<int> badCharacterArray= badCharacterPreComputation(pattern); vector<int> shifts= goodSuffixHeuristicPreComputation(pattern); vector<int> results; while(i <= text.size()-m) { j=m-1; while(j>=0 && pattern[j]==text[i+j]) j--; if(j<0) { results.push_back(i); badShift= (i+m < text.size())? m - badCharacterArray[text[i+m]]: 1; goodShift = shifts[0]; i+=max(badShift,goodShift); //We take max shift from both heuristic } else { badShift= max(1, j - badCharacterArray[text[i+j]]); goodShift = shifts[j+1]; i+=max(badShift,goodShift); //We take max shift from both heuristic } } return results; } int main() { string pattern, text; cin>>text>>pattern; vector<int> result= boyerMooreSearch(text, pattern); if(result.size()==0) cout<<"Pattern is not found in given text!!\n"; else { cout<<"Pattern is found at indices: "; for(int i=0; i< result.size(); i++) cout<< result[i] <<" "; } return 0; } Application - Boyer-Moore algorithm is extremely fast when large number of alphabets are involved in pattern. (relative to the length of the pattern) - Combination of Aho-Corasick Algorithm and Boyer Moore Algorithm is used in Network Intrusion detection systems to find malicious patterns in requests from intruder. To know more about it refer here . References1. Boyer Moore Wikipidea 2. Application of Boyer-Moore and Aho-Corasick Algorithm in Network Intrusion Detection System by Kezia Suhendra
https://iq.opengenus.org/boyer-moore-string-search-algorithm/
CC-MAIN-2021-17
en
refinedweb
Reversing an Array is one of the Crucial Operations in Java. In this tutorial, we will Learn how to Reverse an Array in Java: Sometimes programmers need to process arrays starting with the last element, in that case, it is always efficient to reverse the array so that the first element is placed at the last position in the array, and the second element is placed at the second last position in the array and so on until the last element is at the first index. Let’s consider an array as shown below: After applying the reverse functionality, the resultant array should be like: What You Will Learn: Printing Array In Reverse Order Alternatively, if we want to print the array in the reverse order, without actually reversing it, then we can do that just by providing a for loop that will start printing from the end of the array. This is a good option as long as we just want to print the array in reverse order without doing any processing with it. The following program prints the array in reverse order. import java.util.*; import java.util.stream.*; public class Main { public static void main(String[] args) { Integer[] intArray = {10,20,30,40,50,60,70,80,90}; //print array starting from first element System.out.println("Original Array:"); for(int i=0;i<intArray.length;i++) System.out.print(intArray[i] + " "); System.out.println(); //print array starting from last element System.out.println("Original Array printed in reverse order:"); for(int i=intArray.length-1;i>=0;i--) System.out.print(intArray[i] + " "); } } Output: This is a feasible option to print the array only. Java provides various methods to actually reverse the indices of elements in the array. Enlisted below are the various methods that we are going to discuss in detail in this tutorial. - Using ArrayList reverse method - Using traditional for loop - Using in-place reversal Reverse An Array Using ArrayList Reversing an array in Java can be done using the ‘reverse’ method present in the collections framework. But for this, you first need to convert an array to a list as the ‘reverse’ method takes the list as an argument. The following program reverses an array using the ‘reverse’ method. import java.util.*; public class Main { /*function reverses the elements of the array*/ static void reverse(Integer myArray[]) { Collections.reverse(Arrays.asList(myArray)); System.out.println("Reversed Array:" + Arrays.asList(myArray)); } public static void main(String[] args) { Integer [] myArray = {1,3,5,7,9}; System.out.println("Original Array:" + Arrays.asList(myArray)); reverse(myArray); } } Output: In this program, we use the reverse function on an array by changing it into the list. In a similar manner, we can also reverse a string array as shown in the following example. Example: import java.util.*; public class Main { /*function reverses the elements of the array*/ static void reverse(String myArray[]) { Collections.reverse(Arrays.asList(myArray)); System.out.println("Reversed Array:" + Arrays.asList(myArray)); } public static void main(String[] args) { String [] myArray = {"one", "Two", "Three", "Four", "Five", "Six","Seven"}; System.out.println("Original Array:" + Arrays.asList(myArray)); reverse(myArray); } } Output: The above program defines a string array. By converting it to the list and using the reverse method on it, we reverse the array. Reverse An Array Using Traditional For Loop Yet another approach for reversing the array is to write a separate method to reverse an array in which you can have a new array and put the elements of the original array into this new array in a reverse manner. Check the following implementation. public class Main { static void reverse_array(char char_array[], int n) { char[] dest_array = new char[n]; int j = n; for (int i = 0; i < n; i++) { dest_array[j - 1] = char_array[i]; j = j - 1; } System.out.println("Reversed array: "); for (int k = 0; k < n; k++) { System.out.print(dest_array[k] + " "); } } public static void main(String[] args) { char [] char_array = {'H','E','L','L','O'}; System.out.println("Original array: "); for (int k = 0; k <char_array.length; k++) { System.out.print(char_array[k] + " "); } System.out.println(); reverse_array(char_array, char_array.length); } } Output: Here we have used a character array as an example. Using the reverse function, we reverse the array elements one by one and then display the reversed array. In-place Reversal Of Array The third method of array reversal is reversing the elements of array in-place without using a separate array. In this method, the first element of the array is swapped with the last element of the array. Similarly, the second element of the array is swapped with the second last element of the array and so on. This way at the end of array traversal, we will have the entire array reversed. The following program demonstrates in-place reversal of array. import java.util.Arrays; public class Main { /*swap the first elemnt of array with the last element; second element with second last and so on*/ static void reverseArray(intintArray[], int size) { int i, k, temp; for (i = 0; i < size / 2; i++) { temp = intArray[i]; intArray[i] = intArray[size - i - 1]; intArray[size - i - 1] = temp; } /*print the reversed array*/ System.out.println("Reversed Array: \n" + Arrays.toString(intArray)); } public static void main(String[] args) { int [] intArray = {11,22,33,44,55,66,77,88,99}; //print the original array System.out.println("Original Array: \n" + Arrays.toString(intArray)); //function call to reverse the array reverseArray(intArray, intArray.length); } } Output: As shown in the output, the program generates a reversed array by swapping the elements in the original array itself without using the second array. This technique is more efficient as it saves memory space. Frequently Asked Questions Q #1) How do you Reverse an Array in Java?. Q #2) How do you Reverse a List in Java? Answer: You can use the reverse method provided by the Collections interface of Java. Q #3) Which method of Reversing an Array is better? Answer: Normally, converting an array to list and reversing it using the reverse method is best. Also, in-place reversal is better than using another array to reverse the array as this saves on memory. Conclusion In this tutorial, we discussed the various methods to reverse an array in Java. Though for demonstration purposes we have used integer data, you can apply the same methods to reverse the array with any other data whether primitives or non-primitives. In our subsequent tutorials, we discuss more topics on arrays like exceptions, string arrays, etc. => Read Through The Simple Java Guide Here
https://www.softwaretestinghelp.com/reverse-an-array-in-java/
CC-MAIN-2021-17
en
refinedweb
We're almost done setting up our environment. In this lesson, we'll add several front-end dependencies that we've been using in previous sections: jQuery and Bootstrap. Fortunately, we can use webpack to manage both. To add jQuery to our project we need to do two things: We don't need to make any updates to our webpack.config.js file. To install the npm package for jQuery, use this command: $ npm install jquery --save Notice that we are using the --save flag and not the --save-dev. This lets npm know that we want to use this package for production and development. You'll see that a new section has been created in package.json called dependencies and jquery has been added to it. Now that we have a node module for jQuery installed, if we want to use jQuery in a file, we simply need to import it into that file: import $ from 'jquery'; (Note that the name of the file may vary depending on which file needs jQuery.) Don't forget to remove the scripts tag for jQuery from index.html - we will no longer need it. And that's all we need to do to get jQuery into our projects using webpack. Adding Bootstrap is also fairly simple. Since the full version of Bootstrap requires both js and css files, there are a few extra steps. Note that Bootstrap has several dependencies, including jQuery and a library called Popper.js. Popper.js is a tool that calculates the position of an element on the page, including pop ups and notifications. Make sure you have jQuery and Popper.js installed properly first before installing Bootstrap. We'll assume that you followed along above and already have jQuery installed. Let's install Popper.js as a dependency using npm: $ npm install popper.js --save Now we're ready to add Bootstrap. We're going to use the same steps as we did above to install the js files for Bootstrap: $ npm install bootstrap If we open up package.json we can see that both Popper.js and Bootstrap have been added to our list of dependencies: { ... "dependencies": { "bootstrap": "^4.5.0", "jquery": "^3.5.1", "popper.js": "^1.16.1" } ... } Note that because we haven't pinned versions of these libraries, the versions showing for your project may be later versions. As of now, we don't anticipate later versions of these packages not being compatible with each other. Now all we need to do is import Bootstrap into main.js so that it will be included in our bundle: import 'bootstrap'; That takes care of adding the js files for Bootstrap. Now we need to import the css files. We are going to work with the minified css for Bootstrap. To do that we simply add another import statement to main.js: ... import 'bootstrap'; import 'bootstrap/dist/css/bootstrap.min.css'; import './css/styles.css'; Note: In order for both your Bootstrap styles and your custom styles to render properly, make sure to place the styles.css import after the bootstrap import statements. This is exactly what we needed to do with our scripts as well - remember that our custom styles need to override Bootstrap styles where necessary. With these configurations in place, we can now use jQuery and Bootstrap in our projects. Lesson 18 of 48 Last updated more than 3 months ago.
https://www.learnhowtoprogram.com/intermediate-javascript/test-driven-development-and-environments-with-javascript/adding-frontend-dependencies
CC-MAIN-2021-17
en
refinedweb
Making our way through our .NET Exception Handling series, today we’ll take a closer look at the System.ArgumentNullException. Similar to the System.ArgumentException that we covered in another article the System.ArgumentNullException is the result of passing an invalid argument to a method — in this case, passing a null object when the method requires a non-null value. Similar to other argument exception types the System.ArgumentNullException isn’t typically raised by the .NET Framework library itself or the CLR, but is usually thrown by the library or application as an indication of improper null arguments. In this article we’ll explore the System.ArgumentNullException in more detail including where it resides in the .NET exception hierarchy. We’ll also take a look at some functional sample C# code to illustrate how System.ArgumentNullException should typically be thrown in your own projects, so let’s get going! The Technical Rundown - All .NET exceptions are derived classes of the System.Exceptionbase class, or derived from another inherited class therein. System.SystemExceptionis inherited from the System.Exceptionclass. System.ArgumentExceptioninherits directly from System.SystemException. - Finally, System.ArgumentNullExceptioninherits directly from System.ArgumentException. When Should You Use It? As mentioned in the introduction the occurrence of a System.ArgumentNullException typically means the developer of the module or library you’re using wanted to ensure that a non-null object was passed to the method in question that caused the exception. Similarly, when writing your own code it’s considered a best practice to always validate the passed arguments of your methods to ensure no passed values are null and, therefore, might break your code or lead to unintended consequences. For more information on the code quality rules that apply see CA1062: Validate arguments of public methods. In practice this means that throwing System.ArgumentNullExceptions should be performed within virtually every method you write that should not accept a null argument. To illustrate we have a simple example of our custom Book class with a few properties of Author and Title: public class Book { private string _author; private string _title; public string Author { get { return _author; } set { // Check if value is null. if (value is null) // Throw a new ArgumentNullException with "Author" parameter name. throw new System.ArgumentNullException("Author"); _author = value; } } public string Title { get { return _title; } set { // Check if value is null. if (value is null) // Throw a new ArgumentNullException with "Title" parameter name. throw new System.ArgumentNullException("Title"); _title = value; } } public Book(string title, string author) { Author = author; Title = title; } } We’ve opted to create the private _author and _title fields and then use them for our public properties of Authorand Title, respectively. This allows us to create a custom Author.set() and Title.set() methods in which we check if the passed value is null. In such cases we throw a new System.ArgumentNullException and, rather than passing in a full error message as is often the case, System.ArgumentNullException expects just the name of the parameter that cannot be null. To illustrate this behavior we have two basic example methods: private static void ValidExample() { try { // Instantiate book with valid Title and Author arguments. var book = new Book("The Stand", "Stephen King"); // Output book results. Logging.Log(book); } catch (System.ArgumentNullException e) { Logging.Log(e); } } private static void InvalidExample() { try { // Instantiate book with valid Title but invalid (null) Author argument. var book = new Book("The Stand", null); // Output book results. Logging.Log(book); } catch (System.ArgumentNullException e) { Logging.Log(e); } } As you can see the ValidExample() method creates a new Book instance where both the Title and Author parameters are provided so no exceptions are thrown and the output shows us our book object as expected: {Airbrake.ArgumentNullException.Book} Author: "Stephen King" Title: "The Stand" On the other hand our InvalidExample() method passed null as the second Author parameter, which is caught by our null check and throws a new System.ArgumentNullException our way: [EXPECTED] System.ArgumentNullException: Value cannot be null. Parameter name: Author Using copy constructors is another area to be careful of and to potentially throw System.ArgumentNullExceptions within. For example, here we’ve modified our Book class slightly to include a copy constructor with a single Book parameter that copies the Author and Title properties. In addition, to illustrate the difference between regular instances and copies, we’ve also added the IsCopy property and set it to true within the copy constructor method only: public class Book { // ... public bool IsCopy { get; set; } public Book(string title, string author) { Author = author; Title = title; } // Improper since passed Book parameter could be null. public Book(Book book) : this(book.Title, book.Author) { // Specify that this is a copy. IsCopy = true; } } This presents a potential problem which we’ll illustrate using two more example methods: private static void ValidCopyExample() { try { // Instantiate book with valid Title and Author arguments. var book = new Book("The Stand", "Stephen King"); var copy = new Book(book); // Output copy results. Logging.Log(copy); } catch (System.ArgumentNullException e) { Logging.Log(e); } } private static void InvalidCopyExample() { try { // Instantiate book with valid Title and Author arguments. var copy = new Book(null); // Output copy results. Logging.Log(copy); } catch (System.ArgumentNullException e) { Logging.Log(e); } } ValidCopyExample() works just fine because we first create a base Book instance then copy that using our copy constructor to create the copy instance, which we then output to our log. The result is a Book instance with the IsCopy property equal to true: {Airbrake.ArgumentNullException.Book} IsCopy: True Author: "Stephen King" Title: "The Stand" However, we run into trouble in the InvalidCopyExample() method when trying to pass a null object to our copy constructor (remember that C# knows we’re using that copy constructor since we’ve only passed one argument and the other constructor [ Book(string title, string author)] requires two arguments). This actually throws a System.NullReferenceException when we hit the : this(book.Title, book.Author) line since our code cannot reference properties of the null book object that we passed. The solution is to use an intermediary null checking method on our passed instance before we actually attempt to set the properties. Here we’ve modified our copy constructor to use the newly added NullValidator() method: // Validates for non-null book parameter before copying. public Book(Book book) // Use method-chaining to call the Title and Author properties // on the passed-through book instance, if valid. : this(NullValidator(book).Title, NullValidator(book).Author) { // Specify that this is a copy. IsCopy = true; } // Validate for non-null copy construction. private static Book NullValidator(Book book) { if (book is null) throw new System.ArgumentNullException("book"); // If book isn't null then return. return book; } With these changes we can now invoke our InvalidCopyExample() method again and produce the System.ArgumentNullException that we expect because our passed book argument is still null: [EXPECTED] System.ArgumentNullException: Value cannot be null. Parameter name: book.
https://airbrake.io/blog/dotnet-exception-handling/argumentnullexception
CC-MAIN-2021-17
en
refinedweb
I am developing a ASP.Net5 MVC6 website Using EF7. I wanted to access DbContext from one of my classes which is not being called from Controller. Is it possible to access from there? If yes then please guide me a little so that I can learn how to do it. So far searched a lot from GitHub and stackoverflow. Very little information on this topic. If i need to inject to my class then how should I do it? public class CarAppContext : DbContext { public DbSet<Car> Cars { get; set; } public DbSet<BodyType> BodyTypes { get; set; } } public Class NotificationManager { CarAppContext ctx; public NotificationManager(CarAppContext AppCtx) { ctx = AppCtx; } public void SendNotification(Car HisCar, UserNotification HisNotification) { //need to check he has subscribed or not //ctx is null here } } You could call new CarAppContext(). But if you want to use Dependency Injection instead, you will need to make sure that Not surprised you haven't found docs. As ASP.NET 5 is still in beta, our docs haven't been written yet. When its ready, there will be more posted here:
https://entityframeworkcore.com/knowledge-base/31749775/mvc6-access-dbcontext-from-classes-not-related-to-controller
CC-MAIN-2021-17
en
refinedweb
. In a world of limited resources, Design Patterns help us achieve the most results with the least amount of used resources. It is also important to note that Design Patterns do not apply to all situations and it is crucial to assess the problem at hand in order to choose the best approach for that particular scenario. Design Patterns are divided into a few broad categories, though mainly into Creational Patterns, Structural Patterns, and Behavioral Patterns. The Factory Method pattern is a Creational Design Pattern. The Factory Method Design Pattern Definition The Factory Method is used in object-oriented programming as a means to provide factory interfaces for creating objects. These interfaces define the generic structure, but don't initialize objects. The initialization is left to more specific subclasses. The parent class/interface houses all the standard and generic behaviour that can be shared across subclasses of different types. The subclass is in turn responsible for the definition and instantiation of the object based on the superclass. Motivation The main motivation behind the Factory Method Design Pattern is to enhance loose coupling in code through the creation of an abstract class that will be used to create different types of objects that share some common attributes and functionality. This results in increased flexibility and reuse of code because the shared functionality will not be rewritten having been inherited from the same class. This design pattern is also known as a Virtual Constructor. The Factory Method design pattern is commonly used in libraries by allowing clients to choose what subclass or type of object to create through an abstract class. A Factory Method will receive information about a required object, instantiate it and return the object of the specified type. This gives our application or library a single point of interaction with other programs or pieces of code, thereby encapsulating our object creation functionality. Factory Method Implementation Our program is going to be a library used for handling shape objects in terms of creation and other operations such as adding color and calculating the area of the shape. Users should be able to use our library to create new objects. We can start by creating single individual shapes and availing them as is but that would mean that a lot of shared logic will have to be rewritten for each and every shape we have available. The first step to solving this repetition would be to create a parent shape class that has methods such as calculate_area() and calculate_perimeter(), and properties such as dimensions. The specific shape objects will then inherit from our base class. To create a shape, we will need to identify what kind of shape is required and create the subclass for it. We will start by creating an abstract class to represent a generic shape: import abc class Shape(metaclass=abc.ABCMeta): @abc.abstractmethod def calculate_area(self): pass @abc.abstractmethod def calculate_perimeter(self): pass This is the base class for all of our shapes. Let's go ahead and create several concrete, more specific shapes: class Rectangle(Shape): def __init__(self, height, width): self.height = height self.width = width def calculate_area(self): return self.height * self.width def calculate_perimeter(self): return 2 * (self.height + self.width) class Square(Shape): def __init__(self, width): self.width = width def calculate_area(self): return self.width ** 2 def calculate_perimeter(self): return 4 * self.width class Circle(Shape): def __init__(self, radius): self.radius = radius def calculate_area(self): return 3.14 * self.radius * self.radius def calculate_perimeter(self): return 2 * 3.14 * self.radius So far, we have created an abstract class and extended it to suit different shapes that will be available in our library. In order to create the different shape objects, clients will have to know the names and details of our shapes and separately perform the creation. This is where the Factory Method comes into play. The Factory Method design pattern will help us abstract the available shapes from the client, i.e. the client does not have to know all the shapes available, but rather only create what they need during runtime. It will also allow us to centralize and encapsulate the object creation. Let us achieve this by creating a ShapeFactory that will be used to create the specific shape classes based on the client's input: class ShapeFactory: def create_shape(self, name): if name == 'circle': radius = input("Enter the radius of the circle: ") return Circle(float(radius)) elif name == 'rectangle': height = input("Enter the height of the rectangle: ") width = input("Enter the width of the rectangle: ") return Rectangle(int(height), int(width)) elif name == 'square': width = input("Enter the width of the square: ") return Square(int(width)) This is our interface for creation. We don't call the constructors of concrete classes, we call the Factory and ask it to create a shape. Our ShapeFactory works by receiving information about a shape such as a name and the required dimensions. Our factory method create_shape() will then be used to create and return ready objects of the desired shapes. The client doesn't have to know anything about the object creation or specifics. Using the factory object, they can create objects with minimal knowledge of how they work: def shapes_client(): shape_factory = ShapeFactory() shape_name = input("Enter the name of the shape: ") shape = shape_factory.create_shape(shape_name) print(f"The type of object created: {type(shape)}") print(f"The area of the {shape_name} is: {shape.calculate_area()}") print(f"The perimeter of the {shape_name} is: {shape.calculate_perimeter()}") Running this code will result in: Enter the name of the shape: circle Enter the radius of the circle: 7 The type of object created: <class '__main__.Circle'> The area of the circle is: 153.86 The perimeter of the circle is: 43.96 Or, we could build another shape: Enter the name of the shape: square Enter the width of the square: 5 The type of object created: <class '__main__.Square'> The area of the square is: 25 The perimeter of the square is: 20 What's worth noting is that besides the client not having to know much about the creation process - when we'd like to instantiate an object, we don't call the constructor of the class. We ask the factory to do this for us based on the info we pass to the create_shape() function. Pros and Cons Pros One of the major advantages of using the Factory Method design pattern is that our code becomes loosely coupled in that the majority of the components of our code are unaware of other components of the same codebase. This results in code that is easy to understand and test and add more functionality to specific components without affecting or breaking the entire program. The Factory Method design pattern also helps uphold the Single Responsibility Principle where classes and objects that handle specific functionality resulting in better code. Cons Creation of more classes eventually leads to less readability. If combined with an Abstract Factory (factory of factories), the code will soon become verbose, though, maintainable. Conclusion.
https://stackabuse.com/the-factory-method-design-pattern-in-python/
CC-MAIN-2021-17
en
refinedweb
Created on 2020-07-14 22:02 by eryksun, last changed 2020-07-14 22:02 by eryksun. A console script should be able to handle Windows console logoff and shutdown events with relatively simple ctypes code, such as the following: import ctypes kernel32 = ctypes.WinDLL('kernel32', use_last_error=True) CTRL_C_EVENT = 0 CTRL_BREAK_EVENT = 1 CTRL_CLOSE_EVENT = 2 CTRL_LOGOFF_EVENT = 5 CTRL_SHUTDOWN_EVENT = 6 @ctypes.WINFUNCTYPE(ctypes.c_int, ctypes.c_ulong) def console_ctrl_handler(event): if event == CTRL_SHUTDOWN_EVENT: return handle_shutdown() if event == CTRL_LOGOFF_EVENT: return handle_logoff() if event == CTRL_CLOSE_EVENT: return handle_close() if event == CTRL_BREAK_EVENT: return handle_break() if event == CTRL_C_EVENT: return handle_cancel() return False # chain to next handler if not kernel32.SetConsoleCtrlHandler(console_ctrl_handler, True): raise ctypes.WinError(ctypes.get_last_error()) As of 3.9, it's not possible for python.exe to receive the above logoff and shutdown events via ctypes. In these two cases, the console doesn't even get to send a close event, so a console script cannot exit gracefully. The session server (csrss.exe) doesn't send the logoff and shutdown console events to python.exe because it's seen as a GUI process, which is expected to handle WM_QUERYENDSESSION and WM_ENDSESSION instead. That requires creating a hidden window and running a message loop, which is not nearly as simple as a console control handler. The system registers python.exe as a GUI process because user32.dll is loaded, which means the process is ready to interact with the desktop in every way, except for the final step of actually creating UI objects. In particular, loading user32.dll causes the system to extend the process and its threads with additional kernel data structures for use by win32k.sys (e.g. a message queue for each thread). It also opens handles for and connects to the session's "WinSta0" interactive window station (a container for an atom table, clipboard, and desktops) and "Default" desktop (a container for UI objects such as windows, menus, and hooks). (The process can connect to a different desktop or window station if set in the lpDesktop field of the process startup info. Also, if the process access token is for a service or batch logon, by default it connects to a non-interactive window station that's named for the logon ID. For example, the SYSTEM logon ID is 0x3e7, so a SYSTEM service or batch process gets connected to "Service-0x0-3e7$".) Prior to 3.9, python3x.dll loads shlwapi.dll (the lightweight shell API) to access the Windows path functions PathCanonicalizeW and PathCombineW. shlwapi.dll in turn loads user32.dll. 3.9+ is one step closer to the non-GUI goal because it no longer depends on shlwapi.dll. Instead it always uses the newer PathCchCanonicalizeEx and PathCchCombineEx functions from api-ms-win-core-path-l1-1-0.dll, which is implemented by the base API (kernelbase.dll) instead of the shell API. The next hurdle is extension modules, especially the _ctypes extension module, since it's needed for the console control handler. _ctypes.pyd loads ole32.dll, which in turn loads user32.dll. This is just to call ProgIDFromCLSID, which is rarely used. I see no reason that ole32.dll can't be delay loaded or just manually link to ProgIDFromCLSID on first use via GetModuleHandleW / LoadLibraryExW and GetProcAddress. I did a quick patch to implement the latter, and, since user32.dll no longer gets loaded, the console control handler is enabled for console logoff and shutdown events. So this is the minimal fix to resolve this issue in 3.9+. --- Additional modules winsound loads user32.dll for MessageBeep. The Beep and PlaySound functions don't require user32.dll, so winsound is still useful if it gets delay loaded. _ssl and _hashlib depend on libcrypto, which loads user32.dll for MessageBoxW, GetProcessWindowStation and GetUserObjectInformationW. The latter two are called in OPENSSL_isservice [1] in order to get the window station name. If StandardError isn't a valid file handle, OPENSSL_isservice determines whether an error should be reported as an event or interactively shown with a message box. user32.dll can be delay loaded for this, which, if I'm reading the source right, will never occur as long as StandardError is a valid file. [1]:
https://bugs.python.org/issue41298
CC-MAIN-2021-17
en
refinedweb
OSError: Couldn't connect to Modem! Hello. We are trying to debug a problem we are having related to the LTE modem on the FiPy. When pycom.lte_modem_en_on_boot() is set to False we are experiencing that we can not start LTE communication at all after a reset (deepsleep, machine.reset or button), but not after power cycling the device. As far as I understand, this flag should only stop the LTE modem from starting up every boot, but should not disable it all together. Will not post the entire code where we have done most of our testing with (too many files), but have created a simplified version that we have been able to reproduce it with: from network import LTE import pycom import time import machine if pycom.lte_modem_en_on_boot(): print("LTE on boot was enabled. Disabling.") pycom.lte_modem_en_on_boot(False) lte = LTE() print("got lte!") time.sleep(10) machine.reset() expected output when doing a "soft" reset: "OSError: Couldn't connect to Modem!" expected output after powercycle: "got lte" fipy firmware: 1.18.2.r7 modem firmware: LR5.1.1.0-41065 Any help or suggestions would be appreciated. @tveito Sorry for the late reply. I meant 1.18.2 with no revision update. So I had 1.18.2.r7 and it didn't work so I downgraded to 1.18.2 and it worked. @rskoniec Thank you for your support. I've already fixed this problem by upgrading the modem firmware. Now I am trying to connect to Telstra network in Australia but I got stuck when lte is not attached, as shown in the picture below. Could you please help me to figure out this problem? @diepducle Maybe clues from this thread would be helpful @rskoniec Thank you for your reply. I tried to downgrade to some versions like: FiPy-1.18.2.r6, FiPy-1.18.2.r5, FiPy-1.18.2, FiPy-1.18.1.r7 but all show the same problem is that the triple arrows are disappeared. When I upgrade to version FiPy-1.18.3 from the version FiPy-1.18.2.r7 (using), they show the problem of OSError: Couldn't connect to modem. @diepducle Try with downgrade to or upgrade to Here is the full list of FiPy f/w @rskoniec By the way, before the firmware version 1.18.2.r7 being used, I used to upgraded the firmware to version 1.18.2.r6 [pybytes], and I got a different problem when entering the code "lte = LTE()" (as same as the following topic:). I wonder that which firmware version should I use and am I doing the right track. @rskoniec Thank you for your reply. I tried to use pycom.lte_modem_en_on_boot(False) but the result was still the same. I am a newbie in this area and trying to send data to pybytes after this. But now I am struggling with LTE M1 connection. Could you please tell me the way to fix this problem? Many thanks! @diepducle From the logic of your code/commands you want to disable pycom.lte_modem_en_on_bootif it's enabled so you shold use pycom.lte_modem_en_on_boot(False)or pycom.lte_modem_en_on_boot(0) @tveito Hi, I got the same problem here. My device has firmware version 1.18.2.v7. I did a reset but there is still stuck after entering the code "lte = LTE()". Please help me. Thank you!! @Edward-Dimmack Hello and thanks for the response. Could you please give me the last part of the firmware? As my units did have firmware version 1.18.2.r7 (so still 1.18.2). If anyone still have problems we have figured out a way of reliably turning on the modem: When communicating set lte_modem_en_on_boot() to True. Do a reset. communicate. This does however introduce the need to keep state between resets, but that can be done by ether checking if lte_modem_en_on_boot is set to True or by checking reset cause if you don't want to start using the eeprom. @rskoniec Thank you for that. I tried all the modem firmware and it seemed to have little effect. However, I changed the firmware version to version 1.18.2 on the FiPy and so far they are all working. Even the ones that weren't working at all. Not sure if it will work for anyone else and I haven't done thorough testing yet. Will update if anything changes. @Edward-Dimmack said in OSError: Couldn't connect to Modem!: (...) Maybe the Sequans firmware on the first device is different but I am not sure where to get an older firmware for the modem. You can use my prv modem f/w repo I agree. I wasn't having this issue with the first device we bought so we bought 14 more and all 14 are having the same issue. Some intermittent and some simply never work. I need to try downgrading the firmware but other than that everything is the same. Maybe the Sequans firmware on the first device is different but I am not sure where to get an older firmware for the modem. @tveito It's insane that this thread never received a response from Pycom. I'm facing the same issue on the GPy which is entirely foreclosing usage of the one and only thing I bought the board for: LTE communications.
https://forum.pycom.io/topic/4922/oserror-couldn-t-connect-to-modem/1
CC-MAIN-2021-17
en
refinedweb
Image Classification using pre-trained VGG-16 model How to use Pre-trained VGG16 models to predict object. Architecture Explained: - The input to the network is an image of dimensions (224, 224, 3). - The first two layers have 64 channels of 3*3 filter size and same padding. Then after a max pool layer of stride (2, 2), two layers have convolution layers of 256 filter size and filter size (3, 3). - This followed by a max-pooling layer of stride (2, 2) which is same as the previous layer. Then there are 2 convolution layers of filter size (3, 3) and 256 filter. - After that, there are 2 sets of 3 convolution layer and a max pool layer. Each has 512 filters of (3, 3)size with the same padding. - This image is then passed to the stack of two convolution layers. - In these convolution and max-pooling layers, the filters we use are of the size 3*3 instead of 11*11 in AlexNet and 7*7 in ZF-Net. In some of the layers, it also uses 1*1 pixel which is used to manipulate the number of input channels. There is a padding of 1-pixel (same padding) done after each convolution layer to prevent the spatial feature of the image. - After the stack of convolution and max-pooling layer, we got a (7, 7, 512) feature map. We flatten this output to make it a (1, 25088) feature vector. - After this there are 3 fully connected layer, the first layer takes input from the last feature vector and outputs a (1, 4096) vector, the second layer also outputs a vector of size (1, 4096) but the third layer output a 1000 channels for 1000 classes of ILSVRC challenge, then after the output of 3rd fully connected layer is passed to softmax layer in order to normalize the classification vector. After the output of classification vector top-5 categories for evaluation. All the hidden layers use ReLU as its activation function. ReLU is more computationally efficient because it results in faster learning and it also decreases the likelihood of vanishing gradient problem. This model achieves 92.7% top-5 test accuracy on ImageNet dataset which contains 14 million images belonging to 1000 classes Additional Reading VGG Paper ILSVRC challenge Watch Full Lesson Here: Importing Libraries from tensorflow.keras.applications.vgg16 import VGG16, preprocess_input, decode_predictions from tensorflow.keras.preprocessing.image import load_img, img_to_array import os #creating an object for VGG16 model(pre-trained) model = VGG16() Downloading data from 553467904/553467096 [==============================] - 255s 0us/step model.summary() Model: "vgg16" _________________________________________________________________ _________________________________________________________________ In the below steps, we are performing following activities : - Converting the image to array and then reshaping it. - After performig the above steps, we are pre-process it and then predicting the output. - top=2 in decode_predictions() function means which we are taking top 2 probability values for the particular prediction. #Here we are taking sample images and predicting the same images on top of pre-trained VGG16 model. #top=2 in decode_predictions() function means which we are taking top 2 probability values for the particular prediction. for file in os.listdir('sample'): print(file) full_path = 'sample/' + file image = load_img(full_path, target_size=(224, 224)) image = img_to_array(image) image = image.reshape((1, image.shape[0], image.shape[1], image.shape[2])) image = preprocess_input(image) y_pred = model.predict(image) label = decode_predictions(y_pred, top = 2) print(label) print() bottle1.jpeg [[('n04557648', 'water_bottle', 0.6603951), ('n04560804', 'water_jug', 0.08577988)]] bottle2.jpeg [[('n04557648', 'water_bottle', 0.5169559), ('n04560804', 'water_jug', 0.2630159)]] bottle3.jpeg [[('n04557648', 'water_bottle', 0.88239855), ('n04560804', 'water_jug', 0.051655706)]] monitor.jpeg [[('n03782006', 'monitor', 0.46309018), ('n03179701', 'desk', 0.16822667)]] mouse.jpeg [[('n03793489', 'mouse', 0.37214068), ('n03657121', 'lens_cap', 0.1903602)]] mug.jpeg [[('n03063599', 'coffee_mug', 0.46725288), ('n03950228', 'pitcher', 0.1496518)]] pen.jpeg [[('n02783161', 'ballpoint', 0.6506707), ('n04116512', 'rubber_eraser', 0.12477029)]] wallet.jpeg [[('n04026417', 'purse', 0.530347), ('n04548362', 'wallet', 0.24484588)]] Challenges Of VGG 16: - It is very slow to train (the original VGG model was trained on Nvidia Titan GPU for 2-3 weeks). - The size of VGG-16 trained imageNet weights is 528 MB. So, it takes quite a lot of disk space and bandwidth that makes it inefficient.
https://kgptalkie.com/image-classification-using-pre-trained-vgg-16-model/
CC-MAIN-2021-17
en
refinedweb
#include <conio.h> and getch() I am working on an online C course. I am currently working on lectures introducing stacks. However in this lecture I am told to include #include <conio.h> however it will not work on repl.it. the second problem I am having is the use of getch() this function also doesn't seem to be working. Could anyone please help me figure out why these two parts of the code won't work? And how I can fix the problem or even use different headers and functions? just a side not I have commented out #include <conio.h> in the attached code because the error stopped the code from running. conio.h is a windows header, won't compile on repl.it while they use linux OS's same for the system("cls") command The linux equivalent would be printing a special character that clears the console screen: if you wanted to put that in a define:
https://replit.com/talk/ask/include-lessconiohgreater-and-getch/40216
CC-MAIN-2021-17
en
refinedweb
Security Updates: Fixed ReDoS vulnerability in the Autolink plugin. Issue summary: It was possible to execute a ReDoS-type attack inside CKEditor 4 by persuading a victim to paste a specially crafted URL-like text into the editor and press Enter or Space. Fixed ReDoS vulnerability in the Advanced Tab for Dialogs plugin. Issue summary: It was possible to execute a ReDoS-type attack inside CKEditor 4 by persuading a victim to paste a specially crafted text into the Styles dialog. An upgrade is highly recommended! New Features: - #2800: Unsupported image formats are now gracefully handled by the Paste from Word plugin on paste, additionally showing descriptive error messages. - #2800: Unsupported image formats are now gracefully handled by the Paste from LibreOffice plugin on paste, additionally showing descriptive error messages. - #3582: Introduced smart positioning of the Autocomplete panel used by the Mentions and Emoji plugins. The panel will now be additionally positioned related to the browser viewport to be always fully visible. - #4388: Added the option to remove an iframe created with the IFrame Dialog plugin from the sequential keyboard navigation using the tabindexattribute. Thanks to Timo Kirkkala! Fixed Issues: - #1134: [Safari] Fixed: Paste from Word does not embed images. - #2800: Fixed: No images are imported from Microsoft Word when the content is pasted via the Paste from Word plugin if there is at least one image of unsupported format. - #4379: [Edge] Fixed: Incorrect detection of the high contrast mode. - #4422: Fixed: Missing space between the button name and the keyboard shortcut inside the button label in the high contrast mode. - #2208: [IE] Fixed: The Autolink plugin duplicates the native browser implementation. - #1824: Fixed: The Autolink plugin should require the Link plugin. - #4253: Fixed: The Editor Placeholder plugin throws an error during the editor initialization with config.fullPageenabled when there is no <body>tag in the editor content. - #4372: Fixed: The Autogrow plugin changes the editor's width when used with an absolute config.widthvalue. API Changes: - #4358: Introduced the CKEDITOR.tools.colorclass which adds colors validation and methods for converting colors between various formats: named colors, HEX, RGB, RGBA, HSL and HSLA. - #3782: Moved the CKEDITOR.plugins.pastetools.filters.word.imagesfilters to the CKEDITOR.plugins.pastetools.filters.imagenamespace. - #4297: All CKEDITOR.plugins.pastetools.filtersare now available under the CKEDITOR.pasteToolsalias. - #4394: Introduced CKEDITOR.ajaxspecialized loading methods for loading binary ( CKEDITOR.ajax.loadBinary()) and text ( CKEDITOR.ajax.loadText()) data. Other Changes: - The WebSpellChecker (WSC) plugin is now disabled by default in Standard and Full presets. It can be enabled via extraPluginsconfiguration option. Security Updates: Fixed XSS vulnerability in the Color History feature reported by Mark Wade. Issue summary: It was possible to execute an XSS-type attack inside CKEditor 4 by persuading a victim to paste a specially crafted HTML code into the Color Button dialog. An upgrade is highly recommended! Fixed Issues: - #4293: Fixed: The CKEDITOR.inlineAll()method tries to initialize inline editor also on elements with an editor already attached to them. - #3961: Fixed: The Table Resize plugin prevents editing of merged cells. - #3649: Fixed: Applying a block format should remove existing block styles. - #4282: Fixed: The script loader does not execute callback for scripts already loaded when called for the second time. Thanks to Alexander Korotkevich! - #4273: Fixed: A memory leak in the CKEDITOR.domReady()method connected with not removing loadevent listeners. Thanks to rohit1! - #1330: Fixed: Incomplete CSS margin parsing if an autoor 0value is used. - #4286: Fixed: The Auto Grow plugin causes the editor width to be set to 0on editor resize. - #848: Fixed: Arabic text not being "bound" correctly when pasting. Thanks to Thomas Hunkapiller and J. Ivan Duarte Rodríguez! API Changes: - #3649: Added a new stylesRemoveeditor event. Other Changes: - #4262: Removed the global reference to the stylesLoadedvariable. Thanks to Levi Carter! - Updated the Export to PDF plugin to 1.0.1version: - Improved external CSS support for classic editor by handling exceptions and displaying convenient error messages. New features: - #3940: Introduced the colorNameproperty for customizing foreground and background styles in the Color Button plugin via the config.colorButton_foreStyleand config.colorButton_backStyleconfiguration options. - #3793: Introduced the Editor Placeholder plugin. - #1795: The colors picked from the Color Dialog are now stored in the Color Button palette and can be reused easily. - #3783: The colors used in the document are now displayed as a part of the Color Button palette. Fixed Issues: - #4060: Fixed: The content inside a widget nested editable is escaped twice. - #4183: [Safari] Fixed: Incorrect image dimensions when using the Easy Image plugin alongside the IFrame Editing Area plugin. - #3693: Fixed: Incorrect default values for several Color Button configuration variables in the API documentation. - #3795: Fixed: Setting the config.dataIndentationCharsconfiguration option to an empty string is ignored and replaced by a tab ( \t) character. Thanks to Thomas Grinderslev! - #4107: Fixed: Multiple Autocomplete instances cause keyboard navigation issues. - #4041: Fixed: The selection.scrollIntoViewmethod throws an error when the editor selection is not set. - #3361: Fixed: Loading multiple custom editor configurations is prone to a race condition between these. - #4007: Fixed: Screen readers do not announce the Rich Combo plugin is collapsed or expanded. - #4141: Fixed: The styles are incorrectly applied when there is a <select>element inside the editor. Fixed Issues: - #2607: Fixed: The Emoji plugin SVG icons file is not loaded in CORS context. - #3866: Fixed: The config.readOnlyconfiguration option not considered for startup read-only mode of inline editor. - #3931: [IE] Fixed: An error is thrown when pasting using the Paste button after accepting the browser Clipboard Access Prompt dialog. - #3938: Fixed: Cannot navigate the Autocomplete panel with the keyboard after switching to source mode. - #2823: [IE] Fixed: Cannot resize the last table column using the Table Resize plugin. - #909: Fixed: The Table Resize plugin does not work when the editor is placed in an absolutely positioned container. Thanks to Roland Petto! - #1959: Fixed: The Table Resize plugin does not work in a maximized editor when the Div Editing Area feature is enabled. Thanks to Roland Petto! - #3156: Fixed: Autolink config.autolink_urlRegexand config.autolink_emailRegexoptions are not customizable. Thanks to Sergiy Dobrovolsky! - #624: Fixed: Notification does not work with the bottom toolbar location. - #3000: Fixed: Auto Embed does not work with the bottom toolbar location. - #1883: Fixed: The editor.resize()method does not work with CSS units. - #3926: Fixed: Dragging and dropping a widget sometimes produces an error. - #4008: Fixed: Remove Format does not work with a collapsed selection. - #3998: Fixed: An error is thrown when switching to the source mode using a custom Ctrl + Enter keystroke with the Widget plugin present. Other Changes: - Updated WebSpellChecker (WSC) and SpellCheckAsYouType (SCAYT) plugins: - Fixed: Active Autocomplete panel causes active suggestions to be unnecessarily checked by the SCAYT spell checking mechanism. Security Updates: Fixed XSS vulnerability in the HTML data processor reported by Michał Bentkowski of Securitum. or (i) copy the specially crafted HTML code, prepared by the attacker and (ii) paste it into CKEditor in WYSIWYG mode. Fixed XSS vulnerability in the WebSpellChecker plugin reported by Pham Van Khanh from Viettel Cyber Security. Issue summary: It was possible to execute XSS using CKEditor after persuading the victim to: (i) switch CKEditor to source mode, then (ii) paste a specially crafted HTML code, prepared by the attacker, into the opened CKEditor source area, then (iii) switch back to WYSIWYG mode, and (iv) preview CKEditor content outside CKEditor editable area. An upgrade is highly recommended! New features: - #2374: Added support for pasting rich content from LibreOffice Writer with the Paste from LibreOffice plugin. - #2583: Changed emoji suggestion box to show the matched emoji name instead of an ID. - #3748: Improved the color button state to reflect the selected editor content colors. - #3661: Improved the Print plugin to respect styling rendered by the Preview plugin. - #3547: Active dialog tab now has the aria-selected="true"attribute. - #3441: Improved widget.getClipboardHtml()support for dragging and dropping multiple widgets. Fixed Issues: - #3587: [Edge, IE] Fixed: Widget with form input elements loses focus during typing. - #3705: [Safari] Fixed: Safari incorrectly removes blocks with the editor.extractSelectedHtml()method after selecting all content. - #1306: Fixed: The Font plugin creates nested HTML <span>tags when reapplying the same font multiple times. - #3498: Fixed: The editor throws an error during the copy operation when a widget is partially selected. - #2517: [Chrome, Firefox, Safari] Fixed: Inserting a new image when the selection partially covers an existing enhanced image widget throws an error. - #3007: [Chrome, Firefox, Safari] Fixed: Cannot modify the editor content once the selection is released over a widget. - #3698: Fixed: Cutting the selected text when a widget is partially selected merges paragraphs. API Changes: - #3387: Added the CKEDITOR.ui.richCombo.select() method. - #3727: Added new textColorand bgColorcommands that apply the selected color chosen by the Color Button plugin. - #3728: Added new fontand fontSizecommands that apply the selected font style chosen by the Font plugin. - #3842: Added the editor.getSelectedRanges()alias. - #3775: Widget mask and parts can now be refreshed dynamically via API calls.
https://ckeditor.com/cke4/release-notes
CC-MAIN-2021-17
en
refinedweb
table of contents - bullseye 7.74.0-1.3+deb11u3 - bullseye-backports 7.85.0-1~bpo11+1 - testing 7.85.0-1 - unstable 7.85.0-1 NAME¶ curl_mime_encoder - set a mime part's encoder and content transfer encoding SYNOPSIS¶ #include <curl/curl.h> CURLcode curl_mime_encoder(curl_mimepart *part, const char *encoding); DESCRIPTION¶ curl_mime_encoder() requests a mime part's content to be encoded before being transmitted. part is the part's handle to assign an encoder. encoding is a pointer to a null-terminated encoding scheme. It may be set to NULL to disable an encoder previously attached to the part. The encoding scheme storage may safely be reused after this function returns. Setting a part's encoder multiple times curl_mime_headers() instead of setting a part encoder. Encoding should not be applied to multiparts, thus the use of this function on a part with content set with curl_mime_subparts() is strongly discouraged. EXAMPLE¶ curl_mime *mime; curl_mimepart *part; /* create a mime handle */ mime = curl_mime_init(easy); /* add a part */ part = curl_mime_addpart(mime); /* send a file */ curl_mime_filedata(part, "image.png"); /* encode file data in base64 for transfer */ curl_mime_encoder(part, "base64"); AVAILABILITY¶ As long as at least one of HTTP, SMTP or IMAP is enabled. Added in 7.56.0. RETURN VALUE¶ CURLE_OK or a CURL error code upon failure. SEE ALSO¶ curl_mime_addpart(3), curl_mime_headers(3), curl_mime_subparts(3)
https://manpages.debian.org/testing/libcurl4-doc/curl_mime_encoder.3.en.html
CC-MAIN-2022-40
en
refinedweb
>> Using useEffect() in React.js functional component React for Absolute Beginners 40 Lectures 4.5 hours Eduonix Learning Solutions React Native For Absolute Beginners with React Hooks 23 Lectures 1.5 hours Fundamentals of React and Flux Web Development 48 Lectures 10.5 hours The React hook useEffect helps in adding componentDidUpdate and componentDidMount combined lifecycle in React’s functional component. So far we know we can add lifecycle methods in stateful component only. To use it, we will need to import it from react − import React, { useEffect } from ‘react’; const tutorials=(props)=>{ useEffect( ()=>{ console.log(‘hello’); setTimeout( ()=>{ alert(‘hello’); }, 2000); }); } If we run it, we will see the console log and alert on every render cycle. Here we can call http requests also inside useEffect. Now this is similar to componentDidUpdate lifecycle of stateful component. We can add multiple useEffect functions in a single component. How to make it work like componentDidMount Passing an empty array as a second argument to useEffect function call makes it work like componentDidMount. const tutorials=(props)=>{ useEffect( ()=>{ console.log(‘hello’); setTimeout( ()=>{ alert(‘hello’); }, 2000); }, [] ); } We can pass a second argument to useEffect, if there is any change on the second argument then React will execute this useEffect function call. The second argument shown below is an array means we can add multiple elements inside that array. import React, { useEffect } from ‘react’; const tutorials=(props)=>{ useEffect( ()=>{ console.log(‘hello’); setTimeout( ()=>{ alert(‘hello’); }, 2000); }, [props.player]); } How to do cleanup work in functional component Inside useEffect we can add a return statement at the end of function call which returns a function. This return function does the cleanup work. Frequency execution of the cleanup work also depends upon the second argument passed to useEffect function. import React, { useEffect } from ‘react’; const tutorials=(props)=>{ useEffect( ()=>{ console.log(‘hello’); setTimeout( ()=>{ alert(‘hello’); }, 2000); return ( ()=>{ console.log(‘cleanup on change of player props’); }); }, [props.player]); } We know that componentWillUnmount executes when component is removed from actual DOM. Similarly if we use useEffect with an empty second argument and adding a return function call it will work as componentWillUnmount’ const tutorials=(props)=>{ useEffect( ()=>{ console.log(‘hello’); setTimeout( ()=>{ alert(‘hello’); }, 2000); return ( ()=>{ console.log(‘cleanup similar to componentWillUnmount’); }); }, []); } With above code example, we are sure that we combined three lifecycles in one function useEffect. These lifecycles are componentDidUpdate , componentDidMount, componentWillUnmount. Adding return statement is optional in useEffect that means clean up work is optional and depends upon the use cases. If we use multiple useEffect, then they will execute with the same order as per declaration. Giving correct second argument we can optimize the performance of useEffect. useEffect will trigger only if the specified second argument is changed. The code execution in useEffe ct happens asynchronously. There is another hook similar to useEffect but that works in synchronous way. It called as useLayoutEffect. As the execution of useLayoutEffect happens synchronously it can block visual update for some time before call completes. So it should be used in very specific usecases and standard useEffect is preferred in common usecases. There is one more hook which can used in debug and with third party libraries such as Redux. It is called as useDebugValue to display a label for custom hooks. - Related Questions & Answers - Drawing arrows between DOM elements in React JS using react-archer - SVG morphing in React JS - Using pointer light for better lighting in React JS with React-Three-Fiber - Making a timer in React JS using reactspring animation - Adding Lottie animation in React JS - SVG drawing in React JS frontend - React.js memo function in functional component - Creating a Particle Animation in React JS - Creating a Customizable Modal in React JS - Creating animated loading skeletons in React JS - Creating a Map in React JS without using third-party API - Creating a PDF in React JS using plain CSS and HTML - Creating an Airbnb Rheostat Slider in React JS - Creating a Rich Text Editor in React JS - Device Detection and Responsive Design in React JS
https://www.tutorialspoint.com/using-useeffect-in-react-js-functional-component
CC-MAIN-2022-40
en
refinedweb
You are browsing a read-only backup copy of Wikitech. The live site can be found at wikitech.wikimedia.org Analytics/Data access: Difference between revisions Revision as of 02:14, 29 July 2015 This page documents the internal and external data sources that Wikimedia Foundation staffers have access to,. Create a Phabricator ticket in the "Ops-Access-Requests" project with: - Your public SSH key and your preferred shell username (the default naming convention is first name initial and surname, e.g. jdoe); - Your manager CCed in so that they can confirm you need access; - An explanation of why you need access to the service; ...and they'll add you to the relevant lists. If you're looking for access to services on stat1003 or stat1002, be aware that you also need access to bast1001. Mention this in the RT ticket; it's occasionally missed. connecting to the SQL research slaves. - statistics-privatedata-users - Access to stat1002 where private webrequest logs are hosted. - analytics-users - Access to stat1002 to connect to the Analytics/Cluster. - analytics-privatedata-users - Access to stat1002 to connect to the Analytics/Cluster and to query private data hosted there. (fill in about different levels of staffer and corresponding different levels of access). The schemas that set out each table, and what they contain, can be found on Meta in the Schema namespace. Pageviews data An important piece of community-facing data is information on our pageviews; what articles are being read, and how much? This is currently stored in Hive, which is described below. The data structure is: Request logs Another important source of reader data is the RequestLogs - the logs of actual requests to Wikimedia machines. These can be found in two different places, with two different data structures, depending on the sort of data you're interested in. For Mobile request logs, you should look in our Hive cluster. the data has the format: For Desktop and historical mobile request logs, we have the sampled request logs, which are sampled and stored at a 1:1000 ratio. These currently stretch from May 2013 to the present, and are stored in the /a/squid/archive/sampled directory on stat1002, as .TAR.GZs. They take the format: The sampled logs' format is described on the Cache log format page. These files are both not quoted, and lack headers, which can make parsing them a bit of a pain. At the moment we do not have standardised scripts for doing so, although that will (hopefully!) change.3 and stat1002: a full guide to geolocation and some examples of how to do it can be found on the 'geolocation' page. Data sources API The API is a core component of every wiki we run - with the exception Another common public datasource is the collection of XML snapshots. These are generated each month, and so2. or stat1002, and then type: mysql -u research -h analytics-store.eqiad.wmnet -p -A You'll then be prompted for the password for the 'research' account, which you should have, and dropped into the MySQL command line. Type USE enwiki , and then run whatever query you need. As well as connecting directly, it's also possible to connect automatically from your programming language of choice, be it R or Python. For Python, we have the MySQLdb module installed on stat1003 and stat1002. For R, we have RMySQL. On the other hand, if you just want to generate a TSV or CSV and then retrieve the data from that file later, you can easily do so from the command line. Taking the English-language Wikipedia example from above, you'd type: mysql -u research -h analytics-store.eqiad.wmnet -p enwiki -e "your query goes here;" > file_name.tsv For CSVs, just change the file ending. Either way, it'll prompt you to enter the password, and. All other production wikis and their locations on the slaves can be found in the table below. Hive Finally, we have Hive - our storage system for large amounts of data. Hive can be accessed from stat1002 - simply type ' hive' in the terminal, switch to the <wmf_raw>: hive --database wmf_raw -e "query goes here" > file_name.tsv Again, switching out .tsv to .csv alters the format the file is saved in.
https://wikitech-static.wikimedia.org/w/index.php?title=Analytics/Data_access&diff=20826&oldid=10121
CC-MAIN-2022-40
en
refinedweb
Chronograf release notes v1.10 [2022-08-19] Features - Update the admin UI to provide database-level role-based access control (RBAC). Also, made the following improvements to the UI: - Show permissions mappings more intuitively - Improve the process of creating users and roles - Improve visualization of effective permissions on Usersand Rolespages - Add reader rolefor users that require read-only access to dashboards. - Add convenient redirection back to an original URL after OAuth authentication. - Allow InfluxDB connection with context path. - Ability to customize annotation color. Bug fixes - Repair table visualization of string values. - Improve InfluxDB Enterprise server type detection. - Avoid stale reads in communication with InfluxDB Enterprise meta nodes. - Properly detect unsupported values in Alert Rulebuilder. - Markdown cell content can be selected and copied. Error messaging - Improve InfluxDB Enterprise user creation process so “user not found” error no longer occurs, even when user is successfully created. - Enhance error message notifying user to use InfluxDB v2 administration. Maintenance updates v1.9.4 [2022-03-28] Features This release renames the Flux Query Builder to the Flux Script Builder (and adds improvements), and improves on Kapacitor integration. Flux Builder improvements - Rename the Flux Query Builderto the Flux Script Builder, and add new functionality including: - Ability to load truncated tags and keys into the Flux Script Builder when connected to InfluxDB Cloud. - Script Builder tag keys and tag values depend on a selected time range. - Make aggregation function selection optional. - Autocomplete builtin v object in Flux editor. - Add a warning before overriding the existing Flux Editor script. Kapacitor integration improvements Improved pagination and performance of the UI when you have large numbers of TICKscripts and Flux tasks. - Move Flux Tasks to a separate page under Alerting menu. - Add TICKscripts Pageunder Alerting menu. - Optimize Alert Rules API. - Open Alert Rule Builderfrom the TICKscripts page. - Remove Manage Taskspage, add Alert Rulespage. - Add alert rule options to not send alert on state recovery and send regardless of state change. Bug fixes - Respect BASE_PATHwhen serving API docs. - Propagate InfluxQL errors to UI. - Rename Flux Query to Flux Script. - Repair time zone selector on Host page. - Report correct Chronograf version. - Show failure reason on Queries page. - Reorder Alerting side menu. v1.9.3 [2022-02-02] NOTE: We did not release version 1.9.2 due to a bug that impacted communication between the browser’s main thread and background workers. This bug has been fixed in the 1.9.3 release. Features - Add ability to rename TICKscripts. - Add the following enhancements to the InfluxDB Admin - Queriestab: CSV downloadbutton. - Rename Runningcolumn to Duration. - Add Statuscolumn. When hovering over the Durationcolumn, status shows Killconfirmation button. - Modify the CSVexport to include the Statuscolumn. - Upgrade to use new google.golang protobuflibrary. Bug Fixes - Ability to log the InfluxDB instance URL when a ping fails, making connection issues easier to identify. - Repair enforcement of one organization between multiple tabs. - Configure HTTP proxy from environment variables in HTTP clients. Improvements were made to: - Token command within chronoctl - OAuth client - Kapacitor client - Flux client Security - Upgrade github.com/microcosm-cc/bluemondayto resolve CVE-2021-42576. v1.9.1 [2021-10-08] Features - Distinguish tasks created from templates by appending “created from template” on the Manage Tasks page. - Upgrade Golang to 1.17.1. Bug Fixes Flux fixes - Update time range of Flux queries when zooming in on dashboard. - Repair calculation of Flux query range duration. Kapacitor integration - When using a nametask variable, the TICKscript name that appears in the Alert portion of Chronograf now reflects that variable. Previously, name variables were ignored and this led to confusion. - TICKscripts created from templates are now visible in a read-only mode from within Chronograf. In addition, TICKscripts created from templates will not appear in the Alert Rule section of the UI. This requires Kapacitor 1.6.2, which now provides information about the template used to create the underlying TICKscript. - Pagination of more than 500 Flux tasks was broken. This has now been addressed. Browser support - Safari only: Fix issue displaying Single Stat cells in dashboard. - Avoid extraneous browser history change. - Resolve issues that occurred attempting to open multiple organizations across tabs in one browser. Now, the session enforces one organization across browser tabs. - Support Firefox private mode. Visualization fixes - Repair time rendering in horizontal table. - Skip missing values in line chart instead of returning zeros. - Fix calculations to use the appropriate v.windowPeriodvalue. Previously, v.windowPeriodwas stuck at 3ms. Package fixes - Rename ARM RPMs with yum-compatible names. Security - Upgrade github.com/microcosm-cc/bluemondayto resolve CVE-2021-29272. - Upgrade github.com/golang-jwt/jwtto resolve CVE-2020-26160. v1.9.0 [2021-06-25] Breaking Changes OAuth PKCE Add OAuth PKCE (RFC7636) to OAuth integrations in Chronograf. PKCE mitigates the threat of the authorization code being intercepted during the OAuth token exchange. Google, Azure, Octa, Auth0, Gitlab, and others already support OAuth PKCE. Enabling PKCE should have no effect on integrations with services that don’t support it yet (such as Github or Bitbucket). To disable PKCE, set the OAUTH_NO_PKCE environment variable to =true or include the–oauth-no-pkce flag when startingchronograf`. Features - Support data migrations to ETCD over HTTPS. - Set trusted CA certificates for ETCD connections. - Configure new Kapacitor alert endpoints in the UI. - Remove HipChat alert endpoints. - Show or hide the log status histogram in the Log Viewer. - Add the following meta query templates in the Data Explorer: SHOW FIELD KEYS SHOW SUBSCRIPTIONS SHOW QUERIES SHOW GRANTS SHOW SHARDS SHOW SHARD GROUPS EXPLAIN EXPLAIN ANALYZE - Flux improvements and additional functionality: - Add predefined and custom dashboard template variables to Flux query execution. Flux queries include a vrecord with a key value pair for each variable. - Define template variables with Flux. - Add Kapacitor Flux tasks on the Manage Tasks page (read only). - Provide documentation link when Flux is not enabled in InfluxDB 1.8+. - Write to buckets when Flux mode is selected. - Filter fields in the Query Builder. - Select write precision when writing data through the Chronograf UI. - Support GitHub Enterprise in the existing GitHub OAuth integration. - Update the Queries page in the InfluxDB Admin section of the UI to include the following: - By default, sort queries by execution time in descending order. - Sort queries by execution time or database. - Include database count in the Queries page title. - Select the refresh interval of the Queries page. - Set up InfluxDB Cloud and InfluxDB OSS 2.x connections with the chronografCLI. - Add custom auto-refresh intervals. - Send multiple queries to a dashboard. - Add macOS arm64 builds. Bug Fixes - Open alert handler configuration pages with URL hash. - Omit errors during line visualizations of meta query results. - Delete log stream when TICKscript editor page is closed. - Generate correct Flux property expressions. - Repair stale database list in Log Viewer. - Exclude _startand _stopcolumns in Flux query results. - Improve server type detection in the Connection Wizard. - Add error handling to Alert History page. - Don’t fetch tag values when a measurement doesn’t contain tags. - Filter out roles with unknown organization references. - Detect Flux support in the Flux proxy. - Manage execution status per individual query. - Parse exported dashboards in a resources directory. - Enforce unique dashboard template variable names. - Don’t modify queries passed to a Dashboard page using a query URL parameter. - Fix unsafe React lifecycle functions. - Improve communication with InfluxDB Enterprise. Other - Upgrade UI to TypeScript 4.2.2. - Upgrade dependencies and use ESLint for TypeScript. - Update dependency licenses. - Upgrade Markdown renderer. - Upgrade Go to 1.16. - Upgrade build process to Python 3. v1.8.10 [2020-02-08] Features - Add the ability to set the active InfluxDB database and retention policy for InfluxQL commands. Now, in Chronograf Data Explorer, if you select a metaquery template (InfluxQL command) that requires you to specify an active database, such as DROP MEASUREMENT, DROP SERIES FROM, and DELETE FROM, the USEcommand is prepended to your InfluxQL command as follows: USE "db_name"; DROP MEASUREMENT "measurement_name" USE "db_name"; DROP SERIES FROM "measurement_name" WHERE "tag" = 'value' USE "db_name"; DELETE FROM "measurement_name" WHERE "tag" = 'value' AND time < '2020-01-01' - Add support for Bitbucket emailsendpoint with generic OAuth. For more information, see Bitbucket documentation and how to configure Chronograf to authenticate with OAuth 2.0. Bug Fixes - Repair ARMv5 build. - Upgrade to Axios 0.21.1. - Stop async executions on unmounted LogsPage. - Repair dashboard import to remap sources in variables. - UI updates: - Ignore databases that cannot be read. Now, the Admin page correctly displays all databases that the user has permissions to. - Improve the Send to Dashboard feedback on the Data Explorer page. - Log Viewer updates: - Avoid endless networking loop. - Show timestamp with full nanosecond precision. v1.8.9.1 [2020-12-10] Features - Configure etcd with client TLS certificate. - Support Flux in InfluxDB Cloud and InfluxDB OSS 2.x sources. - Support Flux Schema Explorer in InfluxDB Cloud and InfluxDB OSS 2.x sources. - Let users specify InfluxDB v2 authentication. - Validate credentials before creating or updating InfluxDB sources. - Use fully qualified bucket names when using Flux in the Data Explorer. - Upgrade Go to 1.15.5. - Upgrade Node.js to 14 LTS. Bug Fixes - Prevent briefly displaying “No Results” in dashboard cells upon refresh. - Warn about unsupported queries when creating or editing alert rules. - Use the ANDlogical operator with not-equal ( !=) tag comparisons in generated TICKscript wherefilters. - Disable InfluxDB admin page when administration is not possible (while using InfluxDB Cloud or InfluxDB OSS 2.x sources). - Use token authentication against InfluxDB Cloud and InfluxDB OSS 2.x sources. - Avoid blank screen on Windows. - Repair visual comparison with time variables ( :upperDashboardTime:and :dashboardTime:). - Repair possible millisecond differences in duration computation. - Remove deprecated React SFC type. v.1.8.8 [2020-11-04] Features Bug Fixes - Ensure the alert rule name is correctly displayed in the Alert Rules and TICKscript lists. - Resolve the issue that caused a truncated dashboard name. - Ensure the TICKscript editor is scrollable in Firefox. - Apply default timeouts in server connections to ensure a shared HTTP transport connection is used between Chronograf and InfluxDB or Kapacitor. - Retain the selected time zone (local or UTC) in the range picker. - Export CSV with a time column formatted according to the selected time zone (local or UTC). v.1.8.7 [2020-10-06] This release includes breaking changes: TLS1.2 is now the default minimum required TLS version. If you have clients that require older TLS versions, use one of the following when starting Chronograf: - The --tls-min-version=1.1option - The TLS_MIN_VERSION=1.1environment variable Features - Allow to configure HTTP basic access authentication. - Allow setting token-prefix in Alerta configuration. - Make session inactivity duration configurable. - Allow configuration of TLS ciphers and versions. Bug Fixes - Disable default dashboard auto-refresh. - Fix to user migration. - Add isPresentfilter to rule TICKscript. - Make vertical scrollbar visible when rows overflow in TableGraph. - Upgrade papaparseto 5.3.0. - Require well-formatted commit messages in pull request. - Upgrade nodeto v12. v1.8.6 [2020-08-27] Features - Upgrade Dockerfile to use Alpine 3.12. Bug Fixes - Escape tag values in Query Builder. - Sort namespaces by database and retention policy. - Make MySQL protoboard more useful by using derivatives for counter values. - Add HTTP security headers. - Resolve an issue that caused existing data to be overwritten when there were multiple results for a specific time. Now, all query results are successfully shown in the Table visualization. - Resolve an issue that prevented boolean field and tag values from being displayed. Now, field and tag values are printed in TICKscript logs. v1.8.5 [2020-07-08] Bug Fixes - Fix public-url generic OAuth configuration issue. - Fix crash when starting Chronograf built by Go 1.14 on Windows. - Keep dashboard’s table sorting stable on data refresh. - Repair TICKscript editor scrolling on Firefox. - Better parse Flux CSV results. - Support .Time.Unixin alert message validation. - Fix error when viewing Flux raw data after edit. - Repair management of Kapacitor rules and TICKscripts. - Avoid undefined error when dashboard is not ready yet. - Fall back to point timestamp in log viewer. - Add global functions and string trimming to alert message validation. - Merge query results with unique column names. - Avoid exiting presentation mode when zooming out. - Avoid duplication of csv.fromin functions list. v1.8.4 [2020-05-01] Bug Fixes - Fix misaligned tables when scrolling. v1.8.3 [2020-04-23] Bug Fixes - Fixed missing token subcommand. - Incomplete OAuth configurations now throw errors listing missing components. - Extend OAuth JWT timeout to match cookie lifespan. Features - Added ability to ignore or verify custom OAuth certs. v1.8.2 [2020-04-13] Features - Update to Flux v0.65.0. Bug Fixes - Fix table rendering bug introduced in 1.8.1. v1.8.1 [2020-04-06] Warning: Critical bug that impacted table rendering was introduced in 1.8.1. Do not install this release, install v1.8.2, which includes the features and bug fixes below. Features - Add ability to directly authenticate single SuperAdmin user against the API. Bug Fixes - Update table results to output formatted strings rather than as single-line values. - Handle change to newsfeed data structure. v](/chronograf/v1.9/administration/create-high-availability/). If you're upgrading Chronograf, learn how to [migrate your existing Chronograf configuration to HA](/chronograf/v1.9/administration/migrate-to-high-availability/). -. ’line’ http:// - ’new-sources’ server flag example by adding ’type’ Was this page helpful? Thank you for your feedback! Support and feedback Thank you for being part of our community! We welcome and encourage your feedback and bug reports for Chronograf and this documentation. To find support, use the following resources:
https://docs.influxdata.com/chronograf/v1.10/about_the_project/release-notes-changelog/
CC-MAIN-2022-40
en
refinedweb
Automating And Controlling Browser With Python And Selenium Python Scripting Is One Of The Powerful Tool We Have And Browser Automation Is One Of Them Python is one of the best tools a developer can have. Giving power to a user the power to solve daily problems or create an advanced application. Browser automation is one of them. Just suppose you are filling some forms daily on the web from a file and wasting hours doing this or doing another browser task. And you wish there should be a tool that can do this for you so you can do more productive things. So, here we are with selenium with python. It automates and controls browser for you. Requirements We need to install Selenium module and web drivers for our script. Installing Selenium module: You can install selenium package with pip command. pip install selenium Downloading Web Drivers Selenium requires a driver to interface with the chosen browser. Firefox, for example, requires geckodriver, which needs to be installed before the below examples can be run. Other supported browsers will have their own drivers available. Links to some of the more popular browser drivers follow. Chrome: Edge: Firefox: Safari: Let’s Code Our Script In this article, we are going to fill a form using Selenium with Python. I created a test form for our script:. You can read the full documentation for Selenium with Python:. Importing Required Modules We need to import modules before them using. from selenium import webdriver Setting Web Driver And Opening Form So, we have imported the web driver from selenium now we need to set the browser and web driver that we have downloaded. I’m going to use Chrome then I need to tell it and also need to provide the location of web driver we downloaded for browser. driver = webdriver.Chrome('chromedriver.exe') I moved the chrome driver to the same folder as our script and if you have downloaded that driver in another folder then provide the location for the driver to our method. Opening link: Now we have set our driver; it’s time to provide the link that we want to open. Here we are going to open our form then: driver.get('') get method open the link when we run the script. So always provide the right link. Locating An Element There are various strategies to locate elements in a page. You can use the most appropriate one for your case. Selenium provides the following methods to locate elements in a page: - find_element_by_id - find_element_by_name - find_element_by_xpath - find_element_by_link_text - find_element_by_partial_link_text - find_element_by_tag_name - find_element_by_class_name - find_element_by_css_selector You can also select multiple elements. Search for id if there is one otherwise follow given steps. We are going to find our element by XPath - Right-click on the field that we want to select and choose inspect element. Then right-click on highlighted code and choose copy and then copy XPath. 2. Repeat the same for all fields. By doing this, we will get XPath for all the fields and repeat the same for the submit button also. We are going to use all the XPath values in our script. We need to find XPath for Name, Email, Twitter and Comment field, and we are going to store them in a specific variable. send_keys(data) method send the data to the input fields. Here we are going to hardcode our data, but you can read from a file or any other resource according to your need. name_field = driver.find_element_by_xpath(‘//*[@id=”mG61Hd”]/div[2]/div/div[2]/div[1]/div/div/div[2]/div/div[1]/div/div[1]/input’)name_field.send_keys(‘Rajesh Berwal’)email_field = driver.find_element_by_xpath(‘//*[@id=”mG61Hd”]/div[2]/div/div[2]/div[2]/div/div/div[2]/div/div[1]/div/div[1]/input’)email_field.send_keys(‘irajeshberwal@gmail.com’)twitter_filed = driver.find_element_by_xpath(‘//*[@id=”mG61Hd”]/div[2]/div/div[2]/div[3]/div/div/div[2]/div/div[1]/div/div[1]/input’)twitter_filed.send_keys(‘imrajeshberwal’)comment_field = driver.find_element_by_xpath(‘//*[@id=”mG61Hd”]/div[2]/div/div[2]/div[4]/div/div/div[2]/div/div[1]/div[2]/textarea’)comment_field.send_keys(‘You are going to get that thing one day. Just be strong’) Submitting The Form Now we have filled the form, and it’s time to submit it. We also need XPath or any other selector for the submit button. So, we have copied the Xpath for submit button, and I’m also going to store it in a variable: submit_btn = driver.find_element_by_xpath('//*[@id="mG61Hd"]/div[2]/div/div[3]/div[1]/div/div/span/span')submit_btn.click() click() method provide us with the power to click on any link or button in the browser. After that, it is going to submit that form. Now Let’s Look Our Final Code from selenium import webdriverfrom getpass import getpassdriver = webdriver.Chrome('chromedriver.exe')driver.get('')name_field = driver.find_element_by_xpath('//*[@id="mG61Hd"]/div[2]/div/div[2]/div[1]/div/div/div[2]/div/div[1]/div/div[1]/input')name_field.send_keys('Rajesh Berwal')email_field = driver.find_element_by_xpath('//*[@id="mG61Hd"]/div[2]/div/div[2]/div[2]/div/div/div[2]/div/div[1]/div/div[1]/input')email_field.send_keys('irajeshberwal@gmail.com')twitter_filed = driver.find_element_by_xpath('//*[@id="mG61Hd"]/div[2]/div/div[2]/div[3]/div/div/div[2]/div/div[1]/div/div[1]/input')twitter_filed.send_keys('imrajeshberwal')comment_field = driver.find_element_by_xpath('//*[@id="mG61Hd"]/div[2]/div/div[2]/div[4]/div/div/div[2]/div/div[1]/div[2]/textarea')comment_field.send_keys('You are going to get that thing one day. Just be strong')submit_btn = driver.find_element_by_xpath('//*[@id="mG61Hd"]/div[2]/div/div[3]/div[1]/div/div/span/span')submit_btn.click() Step By Step Video Instructions If you like it then consider subscribing.
https://imrajeshberwal.medium.com/automating-and-controlling-browser-with-python-and-selenium-5471df99784
CC-MAIN-2022-40
en
refinedweb
Buy me a coffee widget Did you ever needed a widget for buy me a coffee, well here it is. Important note Be very careful with using this widget. According to the Google Play Guidelines you are not allowed to get payments from external ressources. So a donation button could lead to a ban of your app! This app should only be used in Web or in Stores that allow a donation. For more information please read this Getting Started You have to import import 'package:buy_me_a_coffee_widget/buy_me_a_coffee_widget.dart'; then you can use the Widget. Container( width: 217.0, child: BuyMeACoffeeWidget( sponsorID: "sBGXj7Pl4", theme: theme, ), ) For a more in depth example please go to the Example Folder.
https://pub.dev/documentation/buy_me_a_coffee_widget/latest/index.html
CC-MAIN-2022-40
en
refinedweb
Lat/long to timezone mapper in Java and Swift and C#. Does not require web services or data files. The "lat/long to timezone polygon mapping" is hardcoded, and we hope this rarely changes, but the changes to offsets and daylight savings changeover dates etc. (which are more frequent) are taken care of by your system libraries and so these are automatically kept up-to-date. From time to time, someone updates the files with the latest timezone polygons, but these rarely change…I think the most recent change is the Crimean peninsular. 99% of people using this project just need the one file: (Java) (Swift) (CSharp) Install CocoaPods # Podfile use_frameworks! pod 'LatLongToTimezone', '~> 1.1' In the Podfile directory, type: $ pod install Carthage Add this to Cartfile github "drtimcooper/LatLongToTimezone" ~> 1.1 $ carthage update Versions For Swift 2.3 and earlier, use version 1.0.4 of the Podspec. For Swift 3 to 4.1, use version 1.1.3 of the Podspec. For Swift 4.2 or later, use the latest version. Usage In your code, you can do import LatLongToTimezone let location = CLLocationCoordinate2D(latitude: 34, longitude: -122) let timeZone = TimezoneMapper.latLngToTimezone(location) Latest podspec { "name": "LatLongToTimezone", "version": "1.1.6", "summary": "Convert a latitude and longitude to a time zone string or TimeZone", "description": "Converts a CLLocationCoordinate2D to a time zone identifier or TimeZone.nUses polygonal regions with accuracy at worst ~2km. Works entirely offline.", "homepage": "", "license": { "type": "MIT", "file": "LICENSE.md" }, "authors": { "Andrew Kirmse": "[email protected]" }, "platforms": { "ios": "8.0", "osx": "10.9" }, "source": { "git": "", "tag": "1.1.6" }, "source_files": "Classes/*.swift", "exclude_files": "Classes/Exclude", "swift_version": "4.2" } Wed, 10 Apr 2019 10:30:59 +0000
https://tryexcept.com/cocoapod/latlongtotimezone/
CC-MAIN-2022-40
en
refinedweb
This page will take you through the steps to blink an LED from a Node.js console app running on a Raspberry Pi. This sample is similar to the Hello blinky background service. The difference is that we’ll be using the win32 console version of Node.js (Chakra) and running it via command line. This sample only works with the Windows 10 IoT Core Anniversary Update (Build 14393) release with Visual Studio 2015 and does not currently work with any newer Windows releases or Visual Studio 2017. We are looking into adding Node.js support to UWP in a future release of Windows 10 IoT Core. The hardware setup for this sample is the same as the C# ‘Blinky’ sample. npm install uwp --target_arch=arm. This step will install the uwp npm package that will allow you to access UWP APIs from your Node.js code. var http = require('http'); // Inject 'Windows' namespace to global var uwp = require("uwp"); uwp.projectNamespace("Windows"); var gpioController = Windows.Devices.Gpio.GpioController.getDefault(); var pin = gpioController.openPin(5); pin.setDriveMode(Windows.Devices.Gpio.GpioPinDriveMode.output) pin.write(Windows.Devices.Gpio.GpioPinValue.high); setInterval(function () { if (pin.read() == Windows.Devices.Gpio.GpioPinValue.high) { pin.write(Windows.Devices.Gpio.GpioPinValue.low); } else { pin.write(Windows.Devices.Gpio.GpioPinValue.high); } }, 1000); Here’s what the code above is doing: GpioController.getDefault()is called to get the GPIO controller. GpioController.openPin()with the LED pin value. pin, we set it to be off (high) by default using the GpioController.write()function. Open up an explorer window on your PC and enter \\<IP address of your device>\C$ to access files on your device. The credentials (if you have not changed them) are: username: <IP address or device name, default is minwinpc>\Administrator password: p@ssw0rd Copy your MyNodejsBlinky folder to C:\ drive root. C:\NodejsChakrafolder on your Raspberry Pi and copy node.exe to that location. C:\NodejsChakra\Node.exe C:\MyNodejsBlinky\blinky.jsto start the app. setx APPDATA c:\Users\Default\AppData\Roaming /Mto set the APPDATA environment variable permanantly. shutdown /r /t 0to restart your device. When the device has booted you can now run c:\NodejsChakra\npm.cmd
https://developer.microsoft.com/en-us/windows/iot/samples/helloblinkynode
CC-MAIN-2017-47
en
refinedweb
Building QT5 with OpenGL global namespace errors I'm trying to build the latest QT5 with OpenGL support from source. I've followed the instructions here: I've configured with configure -c++11 -developer-build -opensource -opengl desktop -nomake examples -nomake tests and running nmake from the VS2012 x86 Native Tools Command Prompt. I am getting errors related to OpenGL: qopenglfunctions.h(593) : error C2039: 'glClearDepth' : is not a member of '`global namespace'' qopenglfunctions.h(593) : error C3861: 'glClearDepth' : identifier not found qopenglfunctions.h(715) : error C2039: 'glDepthRange' : is not a member of '`global namespace'' qopenglfunctions.h(715) : error C3861: 'glDepthRange' : identifier not found and also errors like kernel\qopenglcontext.cpp : error C2065: 'GL_PROXY_TEXTURE_2D' : undeclared identifier GL_TEXTURE_WIDTH and glGetTexLevelParameteriv are also undeclared identifiers, similar to GL_PROXY_TEXTURE_2D. Unfortunately I have searched this problem, but could not find a solution. The QT build is successful when I am not passing -opengl desktop to configure. Here is my graphics card and opengl version info: GLEW version 1.9.0 Reporting capabilities of pixelformat 1 Running on a GeForce GT 540M/PCIe/SSE2 from NVIDIA Corporation OpenGL version 4.2.0 is supported If anyone can provide any pointers I would be grateful. Hi. Hmm weird it should build fine with -opengl desktop. Which branch are you building from? Those functions should be found inside of src/gui/opengl/qopenglext.h which gets included from qopengl.h which in turn should be included from qopenglfunctions.h. Having the same trouble with the released version of 5.1.1, using Visual Studio 2012 x64. Any luck?
https://forum.qt.io/topic/24548/building-qt5-with-opengl-global-namespace-errors
CC-MAIN-2017-47
en
refinedweb
...one of the most highly regarded and expertly designed C++ library projects in the world. — Herb Sutter and Andrei Alexandrescu, C++ Coding Standards The header boost/polymorphic_cast.hpp provides polymorphic_cast and polymorphic_downcast function templates designed to complement the C++ built-in casts. The header boost/polymorphic_pointer_cast.hpp provides polymorphic_pointer_cast and polymorphic_pointer_downcast function templates.. While polymorphic_downcast and polymorphic_cast work with built-in pointer types only, polymorphic_pointer_downcast and polymorphic_pointer_cast are more generic versions with support for any pointer type for which the following expressions would be valid: For polymorphic_pointer_downcast: static_pointer_cast<Derived>(p); dynamic_pointer_cast<Derived>(p); For polymorphic_pointer_cast: dynamic_pointer_cast<Derived>(p); !p; // conversion to bool with negation This includes C++ built-in pointers, std::shared_ptr, boost::shared_ptr, boost::intrusive_ptr, etc.) template <class Derived, class Base> inline auto polymorphic_pointer_cast(Base x); // Throws: std::bad_cast if ( dynamic_pointer_cast<Derived>(x) == 0 ) // Returns: dynamic_pointer_cast<Derived>(x) template <class Derived, class Base> inline auto polymorphic_pointer_downcast(Base x); // Effects: assert( dynamic_pointer_cast<Derived>(x) == x ); // Returns: static_pointer_cast<Derived>(x) } #include <boost/polymorphic_cast.hpp> ... class Fruit { public: virtual ~Fruit(){}; ... }; class Banana : public Fruit { ... }; ... void f( Fruit * fruit ) { // ... logic which leads us to believe it is a Banana Banana * banana = boost::polymorphic_downcast<Banana*>(fruit); ... #include <boost/polymorphic_pointer_cast.hpp> class Fruit { public: virtual ~Fruit(){} }; class Banana : public Fruit {}; // use one of these: typedef Fruit* FruitPtr; typedef std::shared_ptr<Fruit> FruitPtr; typedef boost::shared_ptr<Fruit> FruitPtr; typedef boost::intrusive_ptr<Fruit> FruitPtr; void f(FruitPtr fruit) { // ... logic which leads us to believe it is a banana auto banana = boost::polymorphic_pointer_downcast<Banana>(fruit); ... }. An old numeric_cast that was contributed by Kevlin Henney is now superseeded by the Boost Numeric Conversion Library Revised June 23, 2005 © Copyright boost.org 1999. Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at)
http://www.boost.org/doc/libs/1_63_0/libs/conversion/cast.htm
CC-MAIN-2017-47
en
refinedweb
Opened 8 years ago Closed 8 years ago #8283 closed defect (fixed) A better Carmichael lambda function Description Reported by ylchapuy: Here is another implementation: def carmichael_lambda(n): n = Integer(n) if n < 1: raise ValueError("Input n must be a positive integer.") F = n.factor() L = [] # first get rid of the even part if n & 1 == 0: e = F[0][1] F = F[1:] if e < 3: e = e-1 else: e = e-2 L.append(1<<e) # then other prime factors L += [ p**(k-1)*(p-1) for p,k in F] # finish the job return lcm(L) This is a bit faster than the current implementation and, if you replace lcm with sage.rings.integer.LCM_list, it is even faster. A bug with the current function is that the output is not always an integer: e.g., carmichael_lambda(16) is of type sage.rings.rational.Rational . Attachments (2) Change History (9) Changed 8 years ago by comment:1 Changed 8 years ago by - Status changed from new to needs_review I don't use sage.rings.integer.LCM_list because I think it's less readable. comment:2 follow-up: ↓ 3 Changed 8 years ago by Applies okay to 10.26.2 mac and passes sage -testall. Okay with me. Minh, what do you think? Changed 8 years ago by apply on top of previous one comment:3 in reply to: ↑ 2 Changed 8 years ago by - Milestone set to sage-4.3.4 - Reviewers set to David Joyner, Minh Van Nguyen Okay with me. Minh, what do you think? I agree with Yann's rewrite. It's much more compact than the previous version. However, I have attached the reviewer patch trac_8283-reviewer.patch, whose changes include: - Remove the import statements from sage.rings.arith import factor from sage.structure.element import generic_powerThese import statements are no longer required due to Yann's rewrite of the Carmichael lambda function. - Move the import statement import sage.rings.integerto the module preamble, so that it now reads from sage.rings.integer import IntegerThis has the effect of importing only what is required, i.e. the class Integer, instead of importing the whole module sage.rings.integer. - Some typo fixes. - Clean up à la PEP8. - Removing a redundant lambdaconstruct by replacing lambda x: int(x)with the more compact int Only my patch needs review by anyone but me. If it's OK, then the whole ticket gets a positive review. comment:4 follow-up: ↓ 5 Changed 8 years ago by - Status changed from needs_review to positive_review I read this over - looks good. I also installed it on top of the previous patch - passed sage -t devel/sage/sage/crypto/util.py. Is that enough, or it sage -testall necessary? If that is okay, positive review from me. comment:5 in reply to: ↑ 4 Changed 8 years ago by I read this over - looks good. I also installed it on top of the previous patch - passed sage -t devel/sage/sage/crypto/util.py. Is that enough, or it sage -testall necessary? Running all doctests in the cryptography module subdirectory would be nice. Something like: ./sage -t -long devel/sage-main/sage/crypto/ The module sage/crypto/util.py is at least used by the Blum-Goldwasser class under sage/crypto/public_key/. So naturally one would like to know how the above two patches would affect any other modules under the cryptography subdirectory. comment:6 Changed 8 years ago by Done. All tests passed! comment:7 Changed 8 years ago by - Merged in set to sage-4.3.4.alpha1 - Resolution set to fixed - Status changed from positive_review to closed based on 4.3.3
https://trac.sagemath.org/ticket/8283
CC-MAIN-2017-47
en
refinedweb
This topic describes the Market concept, which is central to Episerver Commerce. A single site can have multiple markets, each with its own product catalog, language, currency, and promotions. Classes in this topic are available in the Mediachase.Commerce or Mediachase.Commerce.Markets namespaces. CurrentMarket interface Sites that implement multi-market functionality must also implement the ICurrentMarket interface. The ICurrentMarket implementation must return the market of the current request, and is called to get the appropriate market for the execution of most market-sensitive business logic. You register custom ICurrentMarket implementations at the application's initialization step by implementing IConfigurableModule. A business's market segmentation strategy determines its implementation of the ICurrentMarket interface. If your business segments markets geographically, you may want to use a prestitial page, an IP geolocation service, or a simple drop-down control to determine a user's region and market. Markets are not constrained to a region; a business-to-business is likely to permit only authenticated users to use the system, and may assign a market to each customer when the customer is created. In this case, the ICurrentMarket implementation's retrieval of the current market is based on the current authenticated user. The default, supplied implementation of ICurrentMarket always returns the default market. This is the correct behavior for sites that do not implement multi-market functionality. The ICurrentMarket interface public interface ICurrentMarket { // Gets the current market. IMarket GetCurrentMarket(); } using EPiServer.Framework; using EPiServer.Framework.Initialization; using EPiServer.Framework.ServiceLocation; using Mediachase.Commerce; // The custom implementation of ICurrentMarket public class MyCurrentMarketImplementation : ICurrentMarket { public IMarket GetCurrentMarket() { ... implementation ... } } [ModuleDependency(typeof(Mediachase.Commerce.Initialization.CommerceInitialization))] a region; and languages and currencies are not automatically filtered based on the value of the current market. You can use the MarketImpl class as a default implementation of the IMarket interface. There always is a default market, with ID MarketId.Default. You can disable this market for sites that implement multi-market functionality, but do not delete it. public interface IMarket { // Gets the market's unique identifier. MarketId MarketId { get; } // Gets a value indicating if the the market is enabled. bool IsEnavvcvbled { Access market data with the IMarketService API, which exposes simple create/replace/update/delete operations for market data., orders, carts, and wishlists To enable processing when the ICurrentMarket implementation may not be available, orders, carts, and wishlists include a market ID. Carts are market-dependent, so are unique to a user and market, instead of just a user. If a site lets a user switch markets, then switching the market may also switch associated carts to a new or different carts. Because wishlists are carts, this also applies to wishlists.
http://world.episerver.com/documentation/developer-guides/commerce/markets/
CC-MAIN-2017-47
en
refinedweb
With the solution we have from yesterday we still have a big problem. Whoever uses ImportantObject must also create the transaction. That is really a bad idea since it is too easy to use the ImportantObject in an unsafe way (i.e. not using transactions at all). To fix this I'm going to introduce an ImportantProvider: 1: public class Given_an_ImportantProvider 2: { 3: private ImportantProvider _importantProvider = new ImportantProvider(new DummyObject()); 4: 5: [Fact] 6: void It_should_return_a_transaction() 7: { 8: Assert.NotNull(_importantProvider.Transaction); 9: } 10: } 11: 12: public class ImportantProvider 13: { 14: private ImportantInterface _importantObject; 15: 16: public ImportantProvider(ImportantInterface importantObject) 17: { 18: _importantObject = importantObject; 19: } 20: 21: public Transaction Transaction 22: { 23: get 24: { 25: return new Transaction(_importantObject, new MutexLock()); 26: } 27: } 28: }
https://blogs.msdn.microsoft.com/cellfish/2009/12/09/2009-advent-calendar-december-9th/
CC-MAIN-2017-47
en
refinedweb
HOUSTON (ICIS)--Stonegate Agricom expects the permit for its Paris Hills phosphate project in ?xml:namespace> Located in southeastern The life of the underground mine is anticipated at 19 years and the company expects the operation to have a capital cost of $120m. Production capacity has been estimated at 904,000 tonnes annually of saleable phosphate rock concentrate. Stonegate CEO Mark Ashcroft said that the project is exciting for the company not only because of its approach to producing high quality phosphate rock, but also because the phosphate market has begun to rebound since the end of last year. Ashcroft said it is an ideal time to be a domestic producer of phosphate as the US remains a net importer. Essential to the company’s projected success at the Paris Hills project is that the site has been proven to contain a very high grade of the phosphate in the ore body. Measured at 30% phosphorus pentoxide (P2O5), the resources are equivalent to concentrate grade and are considered the highest grade deposit in the Americas. The resource quality will greatly assist the operations, as Stonegate will mine the ore and bring it to the surface where there will be no need for a processing facility as typically required. The product will be trucked and shipped to customers as phosphate rock concentrate. The lack of the processing plant benefits the company as it lowers capital cost and construction time. “We are a bit unique in that we have a very high grade of phosphate that we can send as rock concentrate, and we are close to infrastructure, and we have all the variables you need to put a project together. We are also very unique in that our permit process is by the state, so we have a lot of certainty with this project,” said Ashcroft. Ashcroft said the Paris Hills site, located south of Soda Springs near the Utah border, was the area where the first phosphate was recovered in the state and that, through the use of modern, established mining techniques, the company is able to increase the commercial viability of the existing phosphate deposits. Encouraging to the company’s outlook is the revitalisation of the phosphate market, which, like other fertilizers, faced a decline towards the close of last year. Stonegate is counting on North America remaining a net importer of phosphate, and Ashcroft said that, considering the current geopolitical tensions in other rock producing regions of the world, it is an optimum opportunity for domestic producers and phosphate development companies. “The phosphate market is beyond the verge of coming back, it has improved especially the prices of DAP [diammonium phosphate] over the past 12 weeks,” Ashcroft said. “One of the interesting aspects is that there is limited overcapacity and there remains an absolute need for rock concentrate. The US is a net importer and requires over 3m tonnes per year and Canada needs 1m tonnes per year.” Ashcroft said that the company is currently in negotiations for an off-take agreement with potential customers. In its most recent corporate presentation, Stonegate mentions potential customers as being large fertilizer producers, trading companies and end-user groups seeking secure supply.
https://www.icis.com/resources/news/2014/03/06/9760371/us-stonegate-expects-permit-for-idaho-phosphate-project-by-q4/
CC-MAIN-2017-47
en
refinedweb
In the 4.0 release, the Berkeley DB C++ API has been changed to use the ISO standard C++ API in preference to the older, less portable interfaces, where available. This means the Berkeley DB methods that used to take an ostream object as a parameter now expect a std::ostream. Specifically, the following methods have changed: DbEnv::set_error_stream Db::set_error_stream Db::verify On many platforms, the old and the new C++ styles are interchangeable; on some platforms (notably Windows systems), they are incompatible. If your code uses these methods and you have trouble with the 4.0 release, you should update code that looks like this: #include <iostream.h> #include <db_cxx.h> void foo(Db db) { db.set_error_stream(&cerr); } to look like this: #include <iostream> #include <db_cxx.h> using std::cerr; void foo(Db db) { db.set_error_stream(&cerr); }
http://docs.oracle.com/cd/E17276_01/html/programmer_reference/upgrade_4_0_cxx.html
CC-MAIN-2015-48
en
refinedweb
Lee, I have no idea if you've received any replies as this list replies directly to the sender. I run exactly the same configuration as you are trying to get going. Issue A - I don't understand what you're saying here. Issue B - you need a new line in Moin.py - "sys.path.insert(0, r'c:\moin\lib\site-packages')" Issue C - See B Issue D - This is a reported bug, change that line to read " if os.name == 'posix' and os.getuid() == 0 : " so that the os check happens first. Craig -----Original Message----- From: moin-user-admin@lists.sourceforge.net [mailto:moin-user-admin@lists.sourceforge.net] On Behalf Of Lee James Sent: 26 September 2005 05:05 PM To: Moin-user@lists.sourceforge.net Subject: [Moin-user] Sources of advice while setting up a moinmoin I am in the process of installing moinmoin. As an initial attempt I am installing it on my personal LAN as a standalone wiki. The specific machine is running Windows 2000 and already has Python 2.4 installed at C:\Python24. Here is what has transpired so far: following downloaded the install file and unpacked it into:\work\JOBS\2005Applications\OTI\wiki\moin-1.3.5 needed to upgrade WinRAR before this was successful. command line install appears to have worked, install.log contains 814 entries all entries installed under C:\moin predicted message about the search path did not appear added c:\moin to the python path No messages in response to import MoinMoin appears that the MoinMoin source code is located in C:\moin\Lib\site-packages\MoinMoin\ Note that the predicted python2.4 is missing issue A appears that the templates are located in C:\moin\share\moin\ appears that some scripts that help to use the MoinMoin shell commands are located in C:\moin\Scripts following Not sure I found the 'dedicated pages' being referred to assuming this refers to the Installation scenarios section of . for first instance will use the name of trial and be at C:\moin\wikis\trial PREFIX=C:\moin SHARE=$PREFIX\share\moin WIKILOCATION=$PREFIX\wikis INSTANCE=trial copied the relevant files to C:\moin\wikis\trial permissions set so the directory is not shared, but everyone on this machine has access. This is the windows default. editing wikiconfig.py changing line 36 sitename = u'Untitled Wiki' to sitename = u'Trial Wiki' changing line 83 #acl_rights_before = u"YourName:read,write,delete,revert,admin" to acl_rights_before = u"lee:read,write,delete,revert,admin" see changing line 96 mail_smarthost = "" to mail_smarthost = "mail.storm.ca" looking up SMTP server: Outlook Express -> Tools -> Accounts: pop.storm.ca -> properties: servers changing line 99 mail_from = "" to mail_from = "Wiki Trial " following copied moin.py from C:\moin\share\moin\server to C:\moin\wikis\trial editing moin.py changing line 15 sys.path.insert(0, '/path/to/wikiconfig') to sys.path.insert(0, 'C:/moin/wikis/trial') changing line 32 docs = '/usr/share/moin/htdocs' to docs = 'C:/moin/share/moin/htdocs' changing line 44 interface = 'localhost' to interface = '' changing line 49 ## logPath = 'moin.log' to logPath = 'moin.log' try running by double-clicking moin.py failed to find MoinMoin.server.standalone to import from issue B moved MoinMoin from C:\moin\Lib\site-packages to C:\Python24\Lib\site-packages try running by running moin.py from cmd window issue C File "C:\moin\Lib\site-packages\MoinMoin\server\standalone.py", line 485, in run AttributeError: 'module' object has no attribute 'getuid' copied MoinMoin back so it appears as both C:\moin\Lib\site-packages and C:\Python24\Lib\site-packages try running by running moin.py from cmd window and by doulble clicking File "C:\moin\Lib\site-packages\MoinMoin\server\standalone.py", line 485, in run if os.getuid() == 0 and os.name == 'posix': issue D AttributeError: 'module' object has no attribute 'getuid' I am left with several confusions: A: I presume that if I had followed the instructions for downloading Python, instead of already having it installed, I would have had the default directory structure B: given that c:\moin is in the pythonpath, why would python be unable to find this file? C: how is it the error is being reported in a file that does not exist where it is being reported to be. Is this a bug? In Python or MoinMoin? D: getuid is only defined for UNIX systems apparently. How did I get to be executing Unix code in a windows installation. Is this a MoinMoin bug? I hope someone can help de-confuse me on some or all of these issues! Thanx Lee James 8161 Fallowfield Road Ashton ON K0A 1B0 Telephone: 613 253-6154 lee.james@ieee.org Please note that Edcon's e-Mail addresses have changed. Please update your address book with the new e-Mail address as displayed in the "From:" field. ------------------Edcon Disclaimer ------------------------- This email is private and confidential and its contents and attachments are the property of Edcon. It is solely for the named addressee. Any unauthorised Edcon, the company does not accept any responsibility for the contents of this email or any opinions expressed in this email or its attachments .If you are not the named addressee please notify us immediately by reply email and delete this email and any attached files.Due to the nature of email Edcon cannot ensure and accepts no liability for the integrity of this email and any attachments, nor that they are free of any virus.Edcon accepts no liability for any loss or damage whether direct or indirect or consequential, however caused, whether by negligence or otherwise, which may result directly or indirectly from this communication or any attached files. Edgars Consolidated Stores LTD ,Post office box 200 Crown Mines, Telephone: (011) 495-6000
http://sourceforge.net/p/moin/mailman/attachment/D9724EA89D806C48ADFA732EF3BE3CFC858B38%40ORMEXVS01.production.fr-prod.edcon.co.za/1/
CC-MAIN-2015-48
en
refinedweb
Quartz { Introduction to Quartz Scheduler Introduction to Quartz Scheduler Introduction to Quartz Scheduler This introductory section... in java applications. Here, you will learn how Quartz Job Scheduler helps. Configuration, Resource Usage and StdSchedulerFactory to the scheduler: jobs, triggers, calendars, etc. The important step for Quartz... work of creating a Quartz Scheduler instance based on the content of properties... Quartz is architected Java developer desk . ? Covalent Technologies, Inc. - uses Quartz within their CAM product to handle...; What is Quartz? Quartz is a fully...-alone application to the largest e-commerce system. Quartz can be used to reate PRODUCT PRODUCT WHAT IS THE DIFFERENCE BETWEEN PRODUCT AND PROJECT Convert String to Class - JSP-Servlet Convert String to Class Hi all, I am using Quartz as a scheduler... to : http... reading class name, retrieve as a string format but Quartz required in "Class" format grouping similar data of array grouping similar data of array I have sorted array of integer . how can I define new arrays with similar data . indeed I want to grouping similar data of array . example: input : int num[] = {20,21,21,24,26,26,26,30}; output spring question - Java Interview Questions spring question what is quartz API in spring product enquiry form product enquiry form how frames are created and write a java program for product enquiry form using Jframe The product of data processing is The product of data processing is The product of data processing is 1. Data 2. Information 3. Software 4. Computer 5. All of the above Answer: 3. Software Date Scheduler - JSP-Servlet What is a Cartesian product? What is a Cartesian product? What is a Cartesian product? Hi, Here is the answer, The Cartesian product, also referred to as a cross-join, returns all the rows in all the tables listed in the query. Each row implementation of two level scheduler in cloud computing environment implementation of two level scheduler in cloud computing environment job submission in cloud computing java - Java Server Faces Questions Thanks pure:variants Variant Management for a group of similar products (e.g. a software product line). Through variant... reliable. With pure::variants a tool for variant management of product line based Product Life Cycle Diagram Product life cycle diagram is the graphical representation of four stages of a product life namely: Introduction, Growth, Maturity and Decline phase. Product... the various stages of a product in its entire existence period or life. The four Product Life Cycle Product life cycle is an important concept of marketing which shows the stages through which a product passes in its entire lifecycle. The different phases of a product life cycle including introduction to growth, maturity and decline the array list contains similar type of elements or disimilar type of elements the array list contains similar type of elements or disimilar type of elements the array list contains similar type of elements or disimilar type of elements Proficy Portal Proficy Portal Proficy Portal Commercial product. Similar to "enterprise-level" business apps. development environments like JD Edwards except that it is built based on interfacing write program have product - using loops write program have product - using loops Write a program for a grocery that reads products data and determine and display the product that has the highest price and the average price. A product has three pieces of data: id (int Standalone Product should support 64 bit java. Standalone Product should support 64 bit java. I am working on a project and I am freshers. Today my Team lead told me to update our product.... When we deliver our product we bundle jdk 32 bit with it. So now what jdk we How to code a Product id search engine? How to code a Product id search engine? I always wonder how people... id:1234 (and hits search button) go to product page url:" if user enters id:5678 go to product page url:" and if user enters any other id go Java Compiler error - Swing AWT JobExecutionException{ System.out.println("Hello World Quartz Scheduler...Java Compiler error Hi, I try to add quartz Lib in my HelloQuartz... available". Where must I put the Quartz Jar Files? Hi friend, import Product Register System using Java Product Register System In this section, you will learn how to create product... given discount of 0% to product code 1 , 5% product code 2, 15% product code 3, 10% product code 4 and 0% product code 5. Then, we have used the switch Product Components of JDBC Product Components of JDBC JDBC has four Components: 1. The JDBC API. 2. The JDBC Driver Manager. 3. The JDBC Test Suite. 4. The JDBC-ODBC Bridge iPad Apps Development iPad Apps Development Apple Inc that is know for its unique quality and innovative product has set the date on April 03, 2010 to introduce it's another wonder – iPad – world's first table computer that works similar BI: Key for building profits in B2B similar products. It also enables you to target a product that needs promotion... why one product is bought more by customer and others not? What is the best market for a particular product? What are the basic customer’s needs runnning the application as stand alone i.e through main() method it works fine Open Source Jobs protocol intended, like Sun's similar openGRID framework, to reduce internal data..., and then we will focus on Quartz, an open source library for those who need some extra.... An integrated WYSIWYG editor with a user interface similar to well known office java - Java Beginners java Hi, how to run a java class at particular time everyday automatically. please reply me. Hello, i think you want to use job sheduling. why not try Quartz api for time and job sheduling CronExpression - Date Calendar , Please visit the following links: Hope GE Matrix Diagram portfolio and product management. GE (General Electric) matrix diagram is conceptually similar to the BCG matrix (Boston Consulting Group) which, overcomes... defines the position of a product based on two factors: the Market attractiveness JavaScript determine add, product of two numbers JavaScript determine add, product of two numbers In this section, you...;+sum); } function product(){ var num1...)*Number(num2); alert("Product is: "+sum); } function Growing Consumer Interest in GPS Product: Market Research Growing Consumer Interest in GPS Product: Market Research In our busy life schedule... and GPS product occupy a considerable place with its growing number of uses Introducing Flex of ECMAScript and is similar to OOP based JavaScript. In Adobe Flash Player Website Designing Services information on a single or more topics while a web page is a page of the website similar... an XML document into many formats for publishing and printing. XSL is similar... to delivering the product according to client's desire, our professionals at RoseIndia Java Vector Java Vector Vector represents a collection of similar items. In Java, the Vector class is defined in java.util package that implements a growable array of objects. Like an array Advance (Enterprise) Features other instance is running against. JTA Transaction Quartz jobs can execute within... Features Plug-Ins For plugging-in additional functionality Quartz provides an org.quartz.spi.SchedulerPlugin interface. Plugins are ship with Quartz Open Source Browser the millions of lines of code of its flagship product Netscape Communicator... are taking potshots at the project. The failure to ship a new product, the limited... community of people making demands upon us to solve similar issues and problems iPhone Cost and Pricing iPhone Cost and Pricing iPhone is a great product and like other great..., will be more or less similar over a period of time. The iPhone faces another hurdle TriggerListeners and JobListeners and these actions are based on events occurring within the scheduler... listeners are registered with the scheduler, and must be given a name. Listeners... and JobListeners, but they receive notification of events within the Scheduler itself iPhone Application Development in developing product according to need. The Xcode suite includes a modified... to run on Apple’s iPhone and iPod. Cocoa Touch provides a similar set... graphics frameworks including QuickTime, Quartz, OpenGL and Quartz Composer What You Get Out Of Apple's New iPad early in 2010 and there was tons of hype surrounding the product... is very similar to the one fitted in the iPhone but incorporates certain advances More About Simple Trigger Trigger. group: This is the name of scheduler group. startTime: ... the Quartz. There are following misfire instructions to use for informing the Quartz. MISFIRE_INSTRUCTION_FIRE_NOW MISFIRE Outsourcing iPhone development a unique product, which will able to establish their brand name firmly... Applications, LBS, proximity sensor, sqlite3 database, Quartz... to provide you quality product in minimum prices. So, if you JSP Array JSP Array Array is defined as the set of similar type of data in series. The Array can be String, int or character kind of datatypes VDividedBox layout container VDividedBox layout container VDividedBox Layout Container is similar to VBox Layout Container. The difference is, it adds a divider between its child components which can be used DividedBox layout container DividedBox layout container DividedBox Layout Container is similar to Box Layout Container. The difference is, it adds a divider between its child components which can be used The final Keyword The final Keyword The final is a keyword. This is similar to const keyword in other languages. This keyword may not be used as identifiers i.e. you cannot declare HDividedBox layout container HDividedBox layout container HDividedBox Layout Container is similar to HBox Layout Container. The difference is, it adds a divider between its child components which can be used Pop-up Menus Pop-up Menus A PopupMenu is similar to a Menu as it contains MenuItem objects. The Pop-up Menu can be popped over any component while generating the appropriate mouse Calculation Example . This code displays the product name and their price with the total amount of all product. Here in this code we have used method init...;ArrayList list = new ArrayList(); list.add(new Product Mysql Multiply ; Mysql Multiply is used to define the product of any two or more numbers... Multiply'. The example elaborate a query that help you to return the product of any... the product of two numbers a and b. Query: The given below query is used Mysql Multiply ; Mysql Multiply is used to define the product of any two or more... the product of any two or more numbers in a specified table. select(a*b) : The Query return you the product of two numbers a and b. Query:   CROSSFIRE O/R CROSSFIRE O/R ?CROSSFIRE O/R? is a product to generate Java Program instead of human. We can generate Java Program executing SQL by using JDBC with this product Offshore iPhone Apps Development that has gained specialization in iPhone Application Development. The product..., and Quartz. We use MySQL and SQLite for database while we can also used other RDBMS on the demand of our clients. Whereas the matter of product quality is concerned Overview of RMI Overview of RMI The Remote Method Invocation(RMI) works similar... allow programmer to execute remote function which behave similar to local Ansoff Matrix tool that helps a company or business built an effective product and market... the factor that whether the business is marketing a new product or the existing product in a new or existing market. Based on this, factor Ansoff matrix Advertisements If you enjoyed this post then why not add us on Google+? Add us to your Circles
http://www.roseindia.net/tutorialhelp/comment/62119
CC-MAIN-2015-48
en
refinedweb
Build Light: Continuous Delivery Meets Reengineering a USB Driver The DevOps Zone is brought to you in partnership with Librato. Check out Librato's whitepaper on Selecting a Cloud Monitoring Solution. Continuous Delivery is a pattern language used in software development to automate and improve the process of software delivery. Techniques such as automated testing, continuous integration and continuous deployment allow software to be developed to a high standard, easily packaged and deployed to test environments. Continuous delivery treats the commonplace notion of a deployment pipeline: a set of validations through which a piece of software must pass on its way to release. Code is compiled if necessary and then packaged by build servers like Jenkins or Bamboo every time a change is committed to a source control repository, then tested by a number of different techniques before it can be marked as releasable. As a developer you have to monitor the build server after each commit, in order to see if your work has impacts on the upcomming release. The article Using a Raspberry PI to control an extreme feedback device has inspired us to buy a traffic light in the Cleware Shop. We find the idea cool to visualize the results of our commits with a traffic light and see it as addition to the cS Jenkins Bell. The traffic light is a simple USB device that has a green, a yellow and a red led. Unfortunately, the original driver of the traffic light only support Microsoft Windows and Linux. But many people at comSysto use Apple PowerBooks.That is why we decided to reengieer the driver and put it in an Java API. We monitored the linux driver on an Ubuntu virtual machine with the usbmon facility of the Linux kernel. Usbmon can be used to dump information on the raw packet that is sent during the USB communication of the computer and the USB device, which is in our case the Cleware traffic light. sudo modprobe usbmon If you do not want to watch the whole communication between a computer and USB device, a tool called Usbdump helps to view only the communication to a defined USB device. Usbdump is a simple frontend for the Linux kernel’s usbmon facility. Every USB device is identified by a vendor and product ID. In case of the Cleware traffic light, the vendor ID is 0D50 and the product ID is 0008. usbdump -d 0D50:0008 -u 1 Once the usbdump is started, you can switch on and off the traffic light with the original driver and you will get a similar dump as result of the observation. The dump is compressed a little bit. It only shows the switch on and off sequence of the yellow led of the traffic light. 3.680370 1<-- 6: 8a00 0000 0000 3.686056 -->2 3: 0011 01 11.649153 1<-- 6: 8e00 0000 0000 11.675358 -->2 3: 0011 00 11.681172 1<-- 6: 8e00 0000 0000 As you can see, the switch-on sequence of the yellow LED is 0011 01, and the switch-off sequence is 0011 00. Now, all information is available to implement a driver. The HID-API provides a simple Java API for devices such as USB Devices on Mac, Linux and Windows. It is a very simple API. As you can see in the class diagram below, it only consists of four classes. The ClassPathLibraryLoader initializes the native driver, and with the HIDManager you can access a specific device or list all devices. The HIDDeviceInfo delivers information about the USB device and HIDDevice is responsible for the write operations. The write method of the HIDDevice must be used to write to the USB device. In our case that means, if you want to switch on the yellow light of the traffic light, you have to create a byte array for the sequence 0011 01 using the write method. After the data is written, the yellow light will flash. We are able to create a very simple Java API for the Cleware traffic light with the help of the HID-API. As you can see in the class diagram below, there is a TrafficLightFactory that creates a TrafficLightImpl instance, which is used to perform operations like switching on and off the LEDs of the traffic light USB device. You can easily use this API in your own application, you only have to put the following dependency in your Maven POM.xml: <dependency> <groupId>com.comsysto.buildlight</groupId> <artifactId>cleware-driver</artifactId> <version>1.0</version> </dependency> If you are using a modern build system like Gradle, you can put the following dependency in your build.gradle: compile "com.comsysto.buildlight:cleware-driver:1.0" Here is a code example of how to use the Cleware Traffic Light Java Driver with the above mentioned dependency: public class TrafficLightFactoryTest { public static void main(String[] args) { TrafficLight light = TrafficLightFactory.createNewInstance(); light.switchOn(Led.RED); light.switchOffAllLeds(); light.close(); } } Now, let’s come back to continous delivery. We created a small application on top of the Cleware Traffic Light Java Driver, which is called Build Light. It is a watchdog for Jenkins and Bamboo that switches the green LED on the traffic light on when a build succeeds, blinks the yellow light when a build is running and flashes the red light when a build has failed. You can see how it looks like in the following videos: You can get the Build Light source code from comSysto’s GitHUB repository. The only thing you have to do is visit the link below and unzip the compressed file. It is available for Windows, Mac OS X, Linux and the Raspberry Pi. Download Build Light artifacts and source The following Shell commands show how you can install Build Light on Mac OS X: bzuther@MacBook ~/Downloads$ tar xvf buildlight-0.1-DEV.zip bzuther@MacBook ~/Downloads$ cd buildlight-0.1-DEV/bin bzuther@MacBook ~/Downloads$ ./buildlight You have to create a buildlight.properties file in the bin directory after you have unzipped Build Light. You define the build you want to watch in this file. Here is an example for Jenkins and Bamboo: #Jenkins example: build.server=Jenkins jenkins.server.url= jenkins.build.name=Build-Light-Test-Build #Bamboo example: build.server=Bamboo bamboo.server.url= bamboo.build.key=BUILDLIGHT_JOB bamboo.username=zutherb bamboo.password=t0ps3cr3t {{ parent.title || parent.header.title}} {{ parent.tldr }} {{ parent.linkDescription }}{{ parent.urlSource.name }}
https://dzone.com/articles/build-light-continuous?mz=38541-devops
CC-MAIN-2015-48
en
refinedweb
What flexvault said: you should be safe from accidental overwriting if you put your functions in a separate package. However, you still have to trust your users not to do Evil Things---as far as I know there's no way to write-protect a namespace so even an ill-intentioned user can't screw with your code. Edit: actually it's not "package something.pm" but "package Something", conventionally in a file called "Something.pm". User package names should not be all-lowercase. In reply to Re: Checking for duplicate subroutine names by mbethke in thread Checking for duplicate subroutine names by SirBones
http://www.perlmonks.org/?parent=998749;node_id=3333
CC-MAIN-2015-48
en
refinedweb
byobu 5.16-0ubuntu1 source package in Ubuntu Changelog byobu (5.16-0ubuntu1) precise; urgency=low * usr/lib/byobu/updates_available: LP: #942469 - fix regression clearing updates_available status - and fix a typo in that commit * usr/lib/byobu/reboot_required, usr/lib/byobu/updates_available: - powersave flag and reload flag suffered from the same problem as LP: #942469 * usr/bin/byobu: LP: #949385 - namespace a few environment variables more appropriately -- Dustin Kirkland <email address hidden> Thu, 23 Feb 2012 15:01:55 -0600 Upload details - Uploaded by: - Dustin Kirkland on 2012-03-11 - Original maintainer: - Dustin Kirkland - Component: - main - Architectures: - all - Section: - misc - Urgency: - Low Urgency See full publishing history Publishing Downloads Available diffs - diff from 5.15-0ubuntu1 to 5.16-0ubuntu1 (11.9.
https://launchpad.net/ubuntu/+source/byobu/5.16-0ubuntu1
CC-MAIN-2015-48
en
refinedweb
public class JAXBElement<T> extends Object implements Serializable JAXB representation of an Xml Element. This class represents information about an Xml Element from both the element declaration within a schema and the element instance value within an xml document with the following properties The declaredType and scope property are the JAXB class binding for the xml type definition. Scope is either JAXBElement.GlobalScope or the Java class representing the complex type definition containing the schema element declaration. There is a property constraint that if value is null, then nil must be true. The converse is not true to enable representing a nil element with attribute(s). If nil is true, it is possible that value is non-null so it can hold the value of the attributes associated with a nil element. clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait protected final QName name protected final Class<T> declaredType protected final Class scope JAXBElement.GlobalScopefor global xml element declaration. - local element declaration has a scope set to the Java class representation of complex type defintion containing xml element declaration. protected T value protected boolean nil public JAXBElement(QName name, Class<T> declaredType, Class scope, T value) Construct an xml element instance. name- Java binding of xml element tag name declaredType- Java binding of xml element declaration's type scope- Java binding of scope of xml element declaration. Passing null is the same as passing GlobalScope.class value- Java instance representing xml element's value. getScope(), isTypeSubstituted() public JAXBElement(QName name, Class<T> declaredType, T value) public Class<T> getDeclaredType() public QName getName() public void setValue(T t) Set the content model and attributes of this xml element. When this property is set to null, isNil() must by true. Details of constraint are described at isNil(). isTypeSubstituted() public T getValue() public Class getScope() isGlobalScope() public boolean isNil() Returns true iff this element instance content model is nil. This property always returns true when getValue() is null. Note that the converse is not true, when this property is true, getValue() can contain a non-null value for attribute(s). It is valid for a nil xml element to have attribute(s). public void setNil(boolean value) Set whether this element has nil content. isNil() public boolean isGlobalScope() public boolean isTypeSubstituted() Copyright © 1996-2015, Oracle and/or its affiliates. All Rights Reserved. Use is subject to license terms.
http://docs.oracle.com/javaee/7/api/javax/xml/bind/JAXBElement.html
CC-MAIN-2015-48
en
refinedweb
One common programming question is how to randomly shuffle an array of numbers in-place. There are a few wrong answers to this question - some simple shuffles people tend to think of immediately turn out to be inadequate. In particular, the most common naive algorithm that comes up is [1]: naive_shuffle(arr): if len(arr) > 1: for i in 0 .. len(arr) - 1: s = random from inclusive range [0:len(arr)-1] swap arr[s] with arr[i] This algorithm produces results that are badly skewed. For more information consult this post by Jeff Attwood, and this SO discussion. The correct answer is to use the Fisher-Yates shuffle algorithm: fisher_yates_shuffle(arr): if len(arr) > 1: i = len(arr) - 1 while i > 0: s = random from inclusive range [0:i] swap arr[s] with arr[i] i-- It was first invented as a paper-and-pencil method back in 1938, and later was popularized by Donald Knuth in Volume II of TAOCP. For this reason it's also sometimes called the Fisher-Yates-Knuth algorithm. In this article I don't aim to compare Fisher-Yates to the naive algorithm. Nor do I plan to explain why the naive shuffle doesn't work. Others have done it before me, see the references to Jeff's post and the SO discussion above. What I do plan to do, however, is to explain why the Fisher-Yates algorithm works. To put it more formally, why given a good random-number generator, the Fisher-Yates shuffle produces a uniform shuffle of an array in which every permutation is equally likely. And my plan is not to prove the shuffle's correctness mathematically, but rather to explain it intuitively. I personally find it much simpler to remember an algorithm once I understand the intuition behind it. An analogy Imagine a magician's hat: And a bunch of distinct balls. Let's take pool balls for the example: Suppose you place all those balls into the hat [2] and stir them really well. Now, you look away and start taking balls randomly out of the hat and placing them in a line. Assuming the hat stir was random and you can't distinguish the balls by touch alone, once the hat is empty, the resulting line is a random permutation of the balls. No ball had a larger chance of being the first in line than any other ball. After that, all the remaining balls in the hat had an equal chance of being the second in line, and so on. Again, this isn't a rigorous proof, but the point of this article is intuition. If you understand why this procedure produces a random shuffle of the balls, you can understand Fisher-Yates, because it is just a variation on the same theme. The intuition behind Fisher-Yates shuffling The Fisher-Yates shuffle performs a procedure similar to pulling balls at random from a hat. Here's the algorithm once again, this time in my favorite pseudo-code format, Python [3]: def fisher_yates(arr): if len(arr) > 1: i = len(arr) - 1 while i > 0: s = randint(0, i) arr[i], arr[s] = arr[s], arr[i] i -= 1 The trick is doing it in-place with no extra memory. The following illustration step by step should explain what's going on. Let's start with an array of 4 elements: The array contains the letters a, b, c, d at indices [0:3]. The red arrow shows where i points initially. Now, the initial step in the loop picks a random index in the range [0:i], which is [0:3] in the first iteration. Suppose the index 1 was picked, and the code swaps element 1 with element 3 (which is the initial i). So after the first iteration the array looks like this: Notice that I colored the part of the array to the right of i in another color. Here's spoiler: The blue part of the array is the hat, and the orange part is the line where the random permutation is being built. Let's make one more step of the loop. A random number in the range [0:2] has to be picked, so suppose 2 is picked. Therefore, the swap just leaves the element at index 2 in its original place: We make one more step. Suppose 0 is picked at random from [0:1] so elements at indices 0 and 1 are swapped: At this point we're done. There's only one ball left in the hat, so it will be surely picked next. This is why the loop of the algorithm runs while i > 0 - once i reaches 0, the algorithm finishes: So, to understand why the Fisher-Yates shuffling algorithm works, keep in mind the following: the algorithm makes a "virtual" division of the array it shuffles into two parts. The part at indices [0:i] is the hat, from which elements will be picked at random. The part to the right of i (that is, [i+1:len(arr)-1]) is the final line where the random permutation is being formed. In each step of the algorithm, it picks one element from the hat and adds it to the line, removing it from the hat. Some final notes: - Since all the indices [0:i] are in the hat, the selection can pick i itself. In such case there's no real swapping being done, but the element at index i moves from the hat and to the line. Having the selection from range [0:i] is crucial to the correctness of the algorithm. A common implementation mistake is to make this range [0:i-1], which causes the shuffle to be non-uniform. - The vast majority of implementations you'll see online run the algorithm from the end of the array down. But this isn't set in stone - it's just a convention. The algorithm will work equally well with i starting at 0 and running until the end of the array, picking items in the range [i:len(arr)-1] at each step. Conclusion Random shuffling is important for many applications. Although it's a seemingly simple operation, it's easy to do wrong. The Internet is abound with stories of gambling companies losing money because their shuffles weren't random enough. The Fisher-Yates algorithm produces a uniform shuffling of an array. It's optimally efficient both in runtime (running in O(len(arr))) and space (the shuffle is done in-place, using only O(1) extra memory). In this article I aimed to explain the intuition behind the algorithm, firmly believing that a real, deep understanding of something [4] is both intellectually rewarding and useful.
http://eli.thegreenplace.net/2010/05/28/the-intuition-behind-fisher-yates-shuffling/
CC-MAIN-2015-48
en
refinedweb
Co-authored by Ben Willis (bwillis) and Jim Jones (aantix). Version Cake is an unobtrusive way to version APIs in your Rails app. - Easily version any view with their API version: app/views/posts/ - index.xml.v1.builder - index.xml.v3.builder - index.json.v1.jbuilder - index.json.v4.jbuilder - Gracefully degrade requests to the latest supported version - Clients can request API versions through different strategies - Dry your controller logic with exposed helpers Check out for a comparison of traditional versioning approaches and a versioncake implementation. Install gem install versioncake rails g versioncake:install Requirements Upgrade v2.0 -> v3.0 Accept header name changes The default accept header was changed from 'X-API-Version' to 'API-Version'. If you require the 'X-' or some other variant, you can specify a custom strategy as outlined in Extraction Strategy section below. Configuration changes Configuration is now done with an initializer-you can generate a default one with rails g versioncake:install and then modify the generated file to match your configuration. Configuration changes The configuration options for Version Cake have changed: Upgrade v1.* -> v2.0 Filename changes: versioncake migrate or versioncake migrate path/to/views Configuration changes The configuration options for Version Cake have been namespaced and slightly renamed. The following is a mapping of the old names to the new names: Example In this simple example we will outline the code that is introduced to support a change in a version. config/application.rb VersionCake.setup do |config| config.resources do |r| r.resource %r{.*}, [], [], (1..4) end config.extraction_strategy = :query_parameter # for simplicity config.missing_version = 4 end. PostsController class PostsController < ApplicationController def index # shared code for all versions @posts = Post.scoped # version 3 or greated supports embedding post comments if request_version >= 3 @posts = @posts.includes(:comments) end end end See the view samples below. The basic top level posts are referenced in views/posts/index.json.v1.jbuilder. But for views/posts/index.json.v4.jbuilder, we utilize the additional related comments. Views Notice the version numbers are denoted by the "vnumber" extension within the file name. views/posts/index.json.v1.jbuilder json.array!(@posts) do |json, post| json.(post, :id, :title) end views/posts/index.json.v4.jbuilder json.array!(@posts) do |json, post| json.(post, :id, :title) json.comments post.comments, :id, :text end Sample Output. or [ { configured missing_version will be used to render a view.!" } ] } ] How to use Configuration The configuration lives in config/initializers/versioncake.rb. Versioned Resources Each individual resource uri can be identified by a regular expression. For each one it can be customized to have obsolete, deprecated, supported versions. config.resources do |r| # r.resource uri_regex, obsolete, deprecated, supported # version 2 and 3 are still supported on users resource r.resource %r{/users}, [1], [2,3], [4] # all other resources only allow v4 r.resource %r{.*}, [1,2,3], [], [4] end Extraction Strategy You can also define the way to extract the version. The extraction_strategy allows you to set one of the default strategies or provide a proc to set your own. You can also pass it a prioritized array of the strategies. ruby config.extraction_strategy = :query_parameter # [:http_header, :http_accept_parameter] These are the available strategies: If you use the path_parameter strategy with resources routes, you will want to setup your routes.rb config file to capture the api version. You can do that in a few ways. If you have just a few api routes you might specify the path directly like this: resources :cakes, path: '/api/v:api_version/cakes' If you are using a lot of routes it might be better to keep them all inside a scope like this: scope '/api/v:api_version' do resources :cakes end Default Version When no version is supplied by a client, the version rendered will be the latest version by default. If you want to override this to another version, set the following property: ruby config.missing_version = 4 Version String The extraction strategies use a default string key of api_version, but that can be changed: ruby config.version_key = "special_version_parameter_name" Version String If you do not wish to use the magic mapping of the version number to templates it can be disabled: ruby config.rails_view_versioning = false Response Version If a client requests a specific version (or does not) and a version applies to the resource you can configure it to be in the response. Use the following configuration: ruby config.response_strategy = [:http_content_type, :http_header] Version your views. Controller You don't need to do anything special in your controller, but if you find that you want to perform some tasks for a specific version you can use requested_version and latest_version. This may be updated in the near future. ```ruby def index # shared code for all versions @posts = Post.scoped # version 3 or greated supports embedding post comments if request_version >= 3 @posts = @posts.includes(:comments) end end ``` Client requests When a client makes a request it will automatically receive the latest supported version of the view. The client can also request for a specific version by one of the strategies configured by view_version_extraction_strategy. Raised exceptions These are the types of exceptions VersionCake will raise: Handling Exceptions Handling exceptions can simply be done by using Rails rescue_from to return app specific messages to the client. class ApplicationController < ActionController::Base ... rescue_from VersionCake::UnsupportedVersionError, :with => :render_unsupported_version private def render_unsupported_version headers['API-Version-Supported'] = 'false' respond_to do |format| format.json { render json: {message: "You requested an unsupported version (#{requested_version})"}, status: :unprocessable_entity } end end ... end How to test Testing can be painful but here are some easy ways to test different versions of your api using version cake. Test configuration Allowing more extraction strategies during testing can be helpful when needing to override the version. ```ruby config/environments/test.rb config.extraction_strategy = [:query_parameter, :request_parameter, :http_header, :http_accept_parameter] ``` Testing a specific version One way to test a specific version for would be to stub the requested version in the before block: ruby before do @controller.stubs(:request_version).returns(3) end You can also test a specific version through a specific strategy such query_parameter or request_parameter strategies (configured in test environment) like so: ```ruby test/integration/renders_integration_test.rb#L47 test "render version 1 of the partial based on the parameter _api_version" do get renders_path("api_version" => "1") assert_equal "index.html.v1.erb", @response.body end ``` Testing all supported versions You can iterate over all of the supported version numbers by accessing the AppName::Application.config.versioncake.supported_version_numbers. VersionCake.config.resources.first.supported_versions.each do |supported_version| before do @controller.stubs(:requested_version).returns(supported_version) end test "all versions render the correct template" do get :index assert_equal @response.body, "index.html.v1.erb" end end Thanks! Thanks to all those who have helped make Version Cake really sweet: - Manilla - Alicia - Rohit - Sevag - Billy - Jérémie Meyer de Ville - Michael Elfassy - Kelley Reynolds - Washington L Braga Jr - mbradshawabs - Richard Nuno - Andres Camacho - Yukio Mizuta - David Butler - Jeroen K. Related Material Usages - Manilla (original use case) - Spree and the pull request Libraries - - - Discussions - Peter Williams on versioning rest web services - Steve Klabnik on how to version in a resful way - Rails API project disucssion on versioning - Railscast on versioning - Ruby5 on versioncake - Rails core discussion - RubyWeekly - API building tools on Ruby Toolbox Security issues? If you think you have a security vulnerability, please submit the issue and the details to Questions? Create a bug/enhancement/question on github or contact aantix or bwillis through github. License Version Cake is released under the MIT license:
http://www.rubydoc.info/github/bwillis/versioncake/frames
CC-MAIN-2015-48
en
refinedweb
XML External Entity (XXE) Processing This is a Vulnerability. To view all vulnerabilities, please see the Vulnerability Category page. Last revision (mm/dd/yy): 10/6/2015 Vulnerabilities Table of Contents Description, port scanning from the perspective of the machine where the parser is located, DocumentBuilderFactory and SAXParserFactory Both DocumentBuilderFactory and SAXParserFactory XML Parsers can be configured using the same techniques to protect them against XXE. Only the DocumentBuilderFactory example is presented here. The JAXP DocumentBuilder for DocumentBuilderFactory, click here. For a syntax highlighted code snippet for SAXParserFactory, click here. import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; // catching unsupported features ... DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try { // This is the PRIMARY defense. If DTDs (doctypes) are disallowed, almost all XML entity attacks are prevented // Xerces 2 only - String FEATURE = ""; dbf.setFeature(FEATURE, true); // If you can't completely disable DTDs, then at least do the following: // Xerces 1 - // Xerces 2 - FEATURE = ""; dbf.setFeature(FEATURE, false); // Xerces 1 - // Xerces 2 - FEATURE = ""; dbf.setFeature(FEATURE, false); // and these as well, per Timothy Morgan's 2014 paper: "XML Schema, DTD, and Entity Attacks" (see reference below)." //. - Do not include parameter entities by setting this feature to false. - Disallow an inline DTD by setting this feature to true. - Do not include external entities by setting this feature to false. - Do not include parameter entities by setting this feature to false. StAX and XMLInputFactory StAX parsers such as XMLInputFactory allow various properties and features to be set. To protect a Java XMLInputFactory from XXE, do this: - xmlInputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false); // This disables DTDs entirely for that factory .NET The following information for .NET are almost direct quotes from this great article on how to prevent XXE and XML Denial of Service in .NET:. In the .NET Framework, you can prevent XmlReader from resolving external entities while still allowing it to resolve inline entities by setting the XmlResolver property of XmlReaderSettings to null. settings.XmlResolver = null; To protect your app from XML Denial of Service attack you should prohibit inline entities resolving by changing DTD parsing settings. .NET 3.5, .NET 4.. References -
https://www.owasp.org/index.php?title=XML_External_Entity_(XXE)_Processing&setlang=es
CC-MAIN-2015-48
en
refinedweb
The base class of Event implementations. More... #include <rtt/EventBase.hpp> The base class of Event implementations. Definition at line 52 of file EventBase. Implements RTT::ActionInterface. Definition at line 50 of file EventBase.hpp. References RTT::detail::EventBase< Signature >::cloneI(), and RTT::detail::EventBase< Signature >::readArguments()..
http://www.orocos.org/stable/documentation/rtt/v1.12.x/api/html/classRTT_1_1detail_1_1EventBase.html
CC-MAIN-2015-48
en
refinedweb
Opened 10 years ago Closed 10 years ago Last modified 9 years ago #1111 closed defect (fixed) Documentation Error in custom validator example Description From the documentation as it is at the time of this bug report: from django.core import validators, formfields class ContactManipulator(formfields.Manipulator): def __init__(self): self.fields = ( # ... snip fields as above ... formfields.EmailField(field_name="to", validator_list=[self.isValidToAddress]) ) def isValidToAddress(self, field_data, all_data): if not field_data.endswith("@example.com"): raise ValidationError("You can only send messages to example.com e-mail addresses.") Calls to ValidationError be written as such: raise validators.ValidationError(...) ValidationError by itself is undefined. Change History (1) comment:1 Changed 10 years ago by adrian - Resolution set to fixed - Status changed from new to closed Note: See TracTickets for help on using tickets. (In [1776]) Fixed #1111 -- Fixed bug in docs/forms.txt. Thanks, afarhham
https://code.djangoproject.com/ticket/1111
CC-MAIN-2015-48
en
refinedweb
This chapter describes how to enable interoperability between BEA AquaLogic Data Services Platform data services and ADO.NET client applications. With support for ADO.NET client applications, Microsoft Visual Basic and C# developers who are familiar with Microsoft's disconnected data model can leverage AquaLogic Data Services Platform data services as if they were ADO.NET Web services. From the Microsoft ADO.NET developers' perspective, support is transparent: you need do nothing extraordinary to invoke functions on a AquaLogic Data Services Platform data service—all the work is done on the server-side. ADO.NET-client-application developers need only incorporate the AquaLogic Data Services Platform-generated WSDL into their programming environments, as you would when creating any Web service client application. General information about how AquaLogic Data Services Platform achieves ADO.NET integration is provided in this chapter, as are the server-side operations required to enable it. The chapter includes the following sections: Functionally similar to service data objects (SDO), ADO.NET is data object technology for Microsoft ADO.NET client applications. ADO.NET provides a robust, hierarchical, data access component that enables client applications to work with data while disconnected from the data source. Developers creating data-centric client applications use C#, Visual Basic.NET, or other Microsoft .NET programming languages to instantiate local objects based on schema definitions. These local objects, called DataSets, are used by the client application to add, change, or delete data before submitting to the server. Thus, ADO.NET client applications sort, search, filter, store pending changes, and navigate through hierarchical data using DataSets, in much the same way that SDOs are used by AquaLogic Data Services Platform client applications. See Role of the Mediator and SDOs for more information about working with SDOs in a Java client application. Developing client applications to use ADO.NET DataSets is roughly analogous to the process of working with SDOs. Although functionally similar on the surface, as you might expect with two dissimilar platforms (Java and .NET), the ADO.NET and SDO data models are not inherently interoperable. To meet this need, Data Services Platform provides ADO.NET-compliant DataSets so that ADO.NET client developers can leverage data services provided by Data Services Platform, just as they would any ADO.NET-specific data sources. Enabling a Data Services Platform data service to support ADO.NET involves three key steps: ADO.NET is a set of libraries included in the Microsoft .NET Framework that help developers communicate from ADO.NET client applications to various data stores. The Microsoft ADO.NET libraries include classes for connecting to a data source, submitting queries, and processing results. The DataSet also includes several features that bridge the gap between traditional data access and XML development. Developers can work with XML data through traditional data access interfaces, and vice-versa. Although ADO.NET supports both connected (direct) and disconnected models, in Data Services Platform only the disconnected model is supported. ADO.NET client applications are typically created using Microsoft Windows Forms, Web Forms, C#, or Visual Basic. Microsoft Windows Forms is a collection of classes used by client application developers to create graphical user interfaces for the Windows .NET managed environment. Web Forms provides similar client application infrastructure for creating Web based client applications. Any of these client tools can be used by developers to create applications that leverage ADO.NET for data sources. Support for ADO.NET clients is provided via Web services, so before you can use your Microsoft tools of choice, you must perform the two basic tasks required for web-service client development, just as you normally would for any Microsoft Web services client application (see Figure 9-1): Once the client-side artifacts have been incorporated into your development environment, you can invoke functions on the data service and manipulate the DataSet objects in your code as you normally would. BEA AquaLogic Data Services Platform supports ADO.NET at the data object level. That is, Data Services Platform maps inbound ADO.NET DataSet objects to SDO DataObjects, and maps outbound SDOs to DataSets. The mapping is performed transparently on the server, and is bidirectional. As shown in Figure 9-3, the ADO.NET typed DataSet is submitted to and returned by AquaLogic Data Services Platform. At runtime, when a Microsoft-.NET client application makes a SOAP invocation to the ADO.NET-enabled Web service, the Web service intercepts the object and passes it to the Data Service control. The ADO.NET-enabled Data Service control is the linchpin of the interoperability between the two platforms. It comprises several wrapper classes—one for each typed DataSet—that are used to provide bidirectional mapping. The required wrapper classes are created automatically, during the process of creating the ADO.NET-enabled Data Service control, as described later in this chapter. The wrapper classes are based on the XML schema file that gets generated during Data Service control creation. At runtime, the ADO.NET-enabled Data Service control uses the wrapper classes to provide the ADO.NET client with the appropriate objects. The specifics vary, depending on the type of function or procedure: As mentioned previously, mapping, transformation, and packaging processes are transparent to client application developers and data services developers. Only the items listed in Table 9-4 are exposed to data service developers. The WSDL generated by the WebLogic Server from an ADO.NET-enabled Data Service control is specific for use by Microsoft ADO.NET clients. Exposing data services as Web services that are usable by Java clients is generally the same, although the actual steps (and the generated artifacts) are specific to Java. The steps are summarized in Table 9-5. The process of providing ADO.NET clients with access to data services is a server-side operation that takes place in the context of an application and WebLogic Workshop. The instructions in this section assume that you have created a data service application and that you want to provide access to the functions of the service to ADO.NET client applications. (For information about designing and developing data services, see the Data Services Developer's Guide.) Enabling a AquaLogic Data Services Platform application to support ADO.NET clients is generally a three-step process: The tasks described in the remaining sections assume that a data services application is open in WebLogic Workshop. Since the ADO.NET support is accomplished through the use of Data Service controls, and since the Data Service controls require being exposed as Web services in order to make them network accessible, the first step is to create a Web service project and the folder structure necessary to hold generated components. In the data service application that you want to ADO.NET-enable, create a new Web service project specifically for the ADO.NET-enabling components of the application (see Figure 9-6). Data Service controls can be ADO.NET-enabled simply by selecting the appropriate checkbox during the creation process. The ADO.NET-Enabled Data Service controls created (as described in this section) are designed exclusively to support ADO.NET clients through a Web services interface: such controls cannot be used in Page Flows, Portals, or other development scenarios. Starting from the Web service project folder, here are the general steps: As the ADO.NET-enabled Data Service control file is being generated, a folder is also created inside the controls folder, and a Microsoft-style XML schema definition file (XSD) is generated and placed inside the folder. The generated folder follows this simple naming convention: <Data Service control name>_schema The schema file created in the <Data Service control name>_schema folder is a combination of the Data Service control name and "DataSet;" for example, CustomerDataSet.xsd. (See Table 9-4 for other relevant naming conventions.) The XML schema file contains method calls for all selected functions and procedures. As the XSD is created, you may see a Message box display briefly in WebLogic Workshop, notifying you that you have added one or more XSD files to a non-Schema project. Such a message can be disregarded; it is raised because the Microsoft ADO.NET style XSD is not the same as other data service XSD files. Java controls are not network-addressable unless wrapped as Web services. Invoking a Java Control of any kind, including a Data Service control from outside the application, requires that it be exposed as a Web service or as another Web-based application, such as a JSP (JavaServer Page). After the ADO.NET-enabled Data Service control has been generated, it is used as the basis for generating a Java Web service file (JWS), as follows: Shortly, the JWS is generated; you will see it displayed as a node under the Data Service control. From this JWS you can now generate the companion WSDL (Web Services Description Language) file that will be used by Web service client-application developers. To generate the companion WSDL (Web Services Description Language) file from the JWS that can be used by Web service clients to invoke operations on the ADO.NET-enabled Web service: In a moment, the WSDL is generated; you will see it displayed as a node under the JWS file. The WSDL should be made available to ADO.NET developers directly (for example, by sending the physical file to them). Developers can also obtain the WSDL from the BEA WebLogic Server's home page. Fundamentally, Microsoft's ADO.NET DataSet is designed to provide data access to a data source that is — or appears very much like — a database table (columns and rows). Although, later adapted for consumption of Web services, ADO.NET imposes many design restrictions on the Web service data source schemas. Due to these restrictions, Data Services Platform XML types (also called schemas or XSD files) that work fine with data services may not be acceptable to ADO.NET's DataSet. This section explains how you can prepare XML types for consumption by ADO.NET clients. It covers both read and update from the ADO.NET client side to the AquaLogic Data Services Platform server, specifically explaining how to: There are several approaches to adapting XML types for use with an ADO.NET DataSet: The following guidelines are provided to help you develop ADO.NET DataSet-compatible XML types (schemas) by providing pattern requirements for various data service artifacts. Requirements for supporting a complex type in an ADO.NET DataSet include: Since ADO.NET does not support true recurring references among complex types, the requirements noted in Requirements for Complex Types should be followed when simulating schema definitions utilizing such constructs as: As an example, if an address complex type has been referenced by both Company and Department, there should be two element definitions, CompanyAddress and DepartmentAddress, each with an anonymous complex type. The following code illustrates this: <xsd:schema <xsd:element <xsd:complexType> <xsd:sequence> <xsd:element <xsd:element <xsd:complexType> <xsd:sequence> <xsd:element </xsd:sequence> </xsd:complexType> </xsd:element> <xsd:element <xsd:complexType> <xsd:sequence> <xsd:element <xsd:element <xsd:complexType> <xsd:sequence> <xsd:element </xsd:sequence> </xsd:complexType> </xsd:element> </xsd:sequence> </xsd:complexType> </xsd:element> </xsd:sequence> </xsd:complexType> </xsd:element> </xsd:schema> Requirements for supporting simple types in an ADO.NET DataSet include: Requirements for using target namespaces and namespace qualification include: Further information regarding XML schemas can be found at: The process of creating a ADO.NET-enabled Data Service control and Web service generates two ADO.NET-specific artifacts: Technical specifications for these artifacts are included in this section. During the process of creating a ADO.NET-enabled data service control, WebLogic Workshop generates a special schema file that conforms to Microsoft's specifications for typed DataSet objects. A schema is generated for each data service query that has been selected for inclusion in the ADO.NET-enabled data service control. These schema files take the name of the source schema's root element. In the generated schema, the root element has the IsDataSet attribute (qualified with the Microsoft namespace alias, msdata) set to True, as in: msdata:IsDataSet="true" In keeping with Microsoft's requirements for ADO.NET artifacts, the generated target schema of the data service and all schemas on which it depends are contained in the same file as the schema of the typed DataSet. As you select functions to add to the control, WebLogic Workshop obtains the associated schemas and copies the content into the schema file. In addition, the generated schema includes: xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" Listing 9-1 shows an excerpt of a schema— CustomerDS.xsd—for a typed DataSet generated from a AquaLogic Data Services Platform Customer schema. <xs:schema xmlns: <xs:element msdata: <xs:complexType> <xs:choice <xs:element </xs:choice> </xs:complexType> </xs:element> <xs:element . . . </xs:element> </xs:schema> The process of generating the Java Web service produces a WSDL for the client-side application development. The WSDL file contains import statements that correspond to each typed DataSet. Each of the import statements is qualified with the namespace of its associated DataSet schema, as in this example: <import namespace="" location="LDTest1NET/CustomerDataSet.xsd"/> In addition, the WSDL includes the ADO.NET compliant wrapper type definitions. The wrappers' type definitions comprise complex types that contain sequences of any type element from the same namespace as the typed DataSet, as in: <s:complexType <s:sequence> <s:any </s:sequence> </s:complexType>
http://docs.oracle.com/cd/E13167_01/aldsp/docs25/appdev/adodotnetintegration.html
CC-MAIN-2015-48
en
refinedweb
C Programming Structure Structure is the collection of variables of different types under a single name for better handling. For example: You want to store the information about person about his/her name, citizenship number and salary. You can create these information separately but, better approach will be collection of these information under single name because all these information are related to person. Structure Definition in C Keyword struct is used for creating a structure. Syntax of structure struct structure_name { data_type member1; data_type member2; . . data_type memeber; }; We can create the structure for a person as mentioned above as: struct person { char name[50]; int cit_no; float salary; }; This declaration above creates the derived data type struct person. Structure variable declaration When a structure is defined, it creates a user-defined type but, no storage is allocated. For the above structure of person, variable can be declared as: struct person { char name[50]; int cit_no; float salary; }; Inside main function: struct person p1, p2, p[20]; Another way of creating sturcture variable is: struct person { char name[50]; int cit_no; float salary; }p1 ,p2 ,p[20]; In both cases, 2 variables p1, p2 and array p having 20 elements of type struct person are created. Accessing members of a structure There are two types of operators used for accessing members of a structure. - Member operator(.) - Structure pointer operator(->) (will be discussed in structure and pointers chapter) Any member of a structure can be accessed as: structure_variable_name.member_name Suppose, we want to access salary for variable p2. Then, it can be accessed as: p2.salary Example of structure Write a C program to add two distances entered by user. Measurement of distance should be in inch and feet.(Note: 12 inches = 1 foot) #include <stdio.h> struct Distance{ int feet; float inch; }d1,d2,sum; int main(){ printf("1st distance\n"); printf("Enter feet: "); scanf("%d",&d1.feet); /* input of feet for structure variable d1 */ printf("Enter inch: "); scanf("%f",&d1.inch); /* input of inch for structure variable d1 */ printf("2nd distance\n"); printf("Enter feet: "); scanf("%d",&d2.feet); /* input of feet for structure variable d2 */ printf("Enter inch: "); scanf("%f",&d2.inch); /* input of inch for structure variable d2 */ sum.feet=d1.feet+d2.feet; sum.inch=d1.inch+d2.inch; if (sum.inch>12){ //If inch is greater than 12, changing it to feet. ++sum.feet; sum.inch=sum.inch-12; } printf("Sum of distances=%d\'-%.1f\"",sum.feet,sum.inch); /* printing sum of distance d1 and d2 */ return 0; } Output 1st distance Enter feet: 12 Enter inch: 7.9 2nd distance Enter feet: 2 Enter inch: 9.8 Sum of distances= 15'-5.7" Keyword typedef while using structure Programmer generally use typedef while using structure in C language. For example: typedef struct complex{ int imag; float real; }comp; Inside main: comp c1,c2; Here, typedef keyword is used in creating a type comp(which is of type as struct complex). Then, two structure variables c1 and c2 are created by this comp type. Structures within structures Structures can be nested within other structures in C programming. struct complex { int imag_value; float real_value; }; struct number{ struct complex c1; int real; }n1,n2; Suppose you want to access imag_value for n2 structure variable then, structure member n1.c1.imag_value is used.
http://www.programiz.com/c-programming/c-structures
CC-MAIN-2014-10
en
refinedweb
django-errorstack A Django reusable application for logging errors to the ErrorStack service. Installation Install from PyPI with easy_install or pip: pip install django-errorstack or get the in-development version: pip install django-errorstack==tip Usage To use django-errorstack in your Django project: - Add 'errorstack' to your INSTALLED_APPS setting. - Set the ERRORSTACK_STACK_KEY setting. - Add errorstack.middleware.ErrorStackMiddleware to the end of your MIDDLEWARE_CLASSES setting. When DEBUG is False, all unhandled view exceptions will be logged to ErrorStack. Error handling will otherwise proceed as it would otherwise: django-errorstack does not disable or modify Django's usual error handling. Logging errors manually You may want to log some errors to ErrorStack in your own code, without raising an unhandled exception or displaying a 500 page to your user. django-errorstack uses a named logger from the Python standard library logging module. The name of the logger is defined by the ERRORSTACK_LOGGER_NAME setting (defaults to "errorstack"). Assuming you don't change the setting, you could log errors yourself like this: import logging logger = logging.getLogger("errorstack") try: #... some code that raises an exception except: logger.error("Something bad happpened.", exc_info=True) This logger only sends errors or critical errors (not warnings or info or debug messages) to ErrorStack. Attaching the ErrorStack handler to your own logger Your application may already use the stdlib logging module with your own named loggers. If you want to attach the ErrorStack logger handler to your own loggers, you can do the following: import logging from errorstack.handlers import errorstack_handler logger = logging.getLogger("my_logger") logger.addHandler(errorstack_handler) Again, this handler only listens for errors or critical errors. Settings ERRORSTACK_STACK_KEY The key of the error stack you want to send errors to. This option is required. ERRORSTACK_CATCH_404 Log Http404 exceptions to ErrorStack if this is True. False by default. ERRORSTACK_LOGGER_NAME The logger name to use. Defaults to "errorstack".
https://bitbucket.org/carljm/django-errorstack/src
CC-MAIN-2014-10
en
refinedweb
the project is about a debate, and there are 4 candicates in the debate, and we need to group them into 4 different dict and count the word frequence they said. the debate is line by line, and we should group the sentences by name tage, like PAUL: and then all lines after needs to be his dict until another name tage appears. I just done with the file open part and Ive been stuck on the grouping for hours import string debate_line=open('debate.txt','rU') big_list=[] stop_word=open('stopWords.txt','rU') word_set=set() word_list=[] name=['romney:','santorum:','gingrich:','paul:'] for line in debate_line: line=line.lower() line=line.strip(string.punctuation) big_list.append(line.split()) for item in big_list: if len(item)<1: big_list.remove(item) for item in big_list: if item[0]=='paul': for word in item: if word in paul_dict: paul_dict[word]+=1 else: paul_dict[word]=1 the last part just doesnt work at all Start with the simple basics; print big_list and make sure it contains what you think it does and is in the form you expect to be in. You can also add a print statement after for item in big_list: to print the item, but it is basically the same thing. Assuming the data is correct (and I'm not sure it is), try something along these lines name_list=['romney','santorum','gingrich','paul'] found=False for item in big_list: if item[0] == "paul": found=True ## if another name then stop processing elif item[0] in ['romney','santorum','gingrich']: found=False if found: for word in item: if word in paul_dict: paul_dict[word]+=1 else: paul_dict[word]=1
http://www.daniweb.com/software-development/python/threads/416953/just-start-python-need-help-with-project
CC-MAIN-2014-10
en
refinedweb
Cookbook:FAQ Contents What is the Cookbook?[edit] The cookbook is a collaborative effort to document all aspects of cooking from recipes to culinary techniques. As a Wikibook, anyone is free to add, edit, or change content. A wiki is an ideal forum for communicating information such as recipes because it allows users to give feedback about recipes they have tried themselves. Consult the Wikibook help page for a well-organized and comprehensive overview of Wikibooks. How is the Cookbook organized?[edit] The Cookbook is organized around Categories and types. Category pages are useful as tables of contents, but do not have additional content written about them. When a new recipe is created, a category, e.g., Italian_Recipes, can be added to the bottom of the new recipe page. By doing so, this new recipe is added to that category page, which is simply an automatically generated listing of all pages referring to that Category. Cookbook entries are also organized by types. Types are groupings that are substantial enough to have additional content written about them. For example, the page for the type Cookbook:Cuisine_of_Italy has information about Italian cooking techniques, historical information, and a selective listing of the most important Italian recipes. When a new Italian recipe is created, its type is entered into the top of its page and the user has the option of manually linking to that recipe from the type page if they deem the new recipe important enough. How can I add a recipe?[edit] Consult the Policy page for an explanation of how pages are formatted. How do I keep track of recent changes to the Cookbook?[edit] First, select the recent changes module in the left-hand navigation. By default, the module displays changes made to all of the Wikibooks. You can then filter the listing by namespace, such as Cookbook or Cookbook talk, using the drop-down list and then clicking on the Go button. Alternatively, you can use the watchlist to keep track of a particular entry. On the top of the page, when you are logged in, there is a tab that says "watch". When you click that button, the page will go onto your personal watch list. Then, to see your watchlist, you can click the "My Watchlist" link in the upper right-hand corner (near your user name). Alternatively, when you edit a page, there is a check box labelled "Watch this page", which has the same effect. If you want to automatically watch every page you edit, you could click on the "preferences" link (right next to "my watchlist"), and under the "editing" button, click the checkbox called "Add pages you edit to your watchlist". Then, every time you edit a page in the cookbook, it will add that page to your watchlist.
http://en.wikibooks.org/wiki/Cookbook:FAQ
CC-MAIN-2014-10
en
refinedweb
thanks - JSP-Servlet thanks thanks sir i am getting an output...Once again thanks for help thanks - Development process thanks thanks for sending code for connecting jsp with mysql. I have completed j2se(servlet,jsp and struts). I didn't get job then i have learnt.... please help me. thanks in advance thanks - JSP-Servlet thanks thanks sir its working Please help need quick!!! Thanks (); ^ 6 errors any help would be appreciated guys. Thanks so...Please help need quick!!! Thanks hey i keep getting stupid compile errors and don't understand why. i'm supposed to use abstract to test a boat race Thanks Thanks This is my code.Also I need code for adding the information on the grid and the details must be inserted in the database. Thanks in advance Need help in completing a complex program; Thanks a lot for your help Need help in completing a complex program; Thanks a lot for your help ... it? Thanks a ton for your help... no output. So please help me with this too. And also, I am using Runtime function Begineer Help Help Please Thanks A million ) I am using Jcreator Begineer Help Help Please Thanks A million ) I am using Jcreator System.out.println(" Income Statement"); System.out.print("Year jsp help - JSP-Servlet :// Thanks...jsp help In below code value got in text box using 'ID' Attribute ... I want to use that value in query to fetch related values in same page please help in jsp - JSP-Servlet please help in jsp i have two Jsp's pages. on main.jsp have some... data. here some data of Jsp's. main.jsp... please help. Hi Friend, Try Please Help - JSP-Servlet . Thanks for your response.. You told me that its difficult to handle the problem.. Ok,Let me try my hands on it.. The help i need is can u please tell me... for u, i will continue to next step. Thanks Sreenivas Help in Struts2 Help in Struts2 Hi, in struts 2 how to get the values from db and show in jsp page using display tag or iterator tag thanks in advance Help! thanks for ur code, I'd like to ask a question: after press "c" or "C", timer starts and after every delay ms, it'll print "This line... once. oh, I see my problem. Thanks Programming Help URGENT - JSP-Servlet TO ROSEINDIA TEAM< IF I GET THIS HELP IN TIME.... Thanks/Regards...:// Thanks...Programming Help URGENT Respected Sir/Madam, I am to the user) please tell me how could i design that. Please help me asap Thanks a lot ;"); } </script> </html> Thanks Hi Friend, If you want...; System.out.println(i+" "+sq); } } } Thanks help!!!!!!!!!!!!!!!!!! import java.awt.; import java.sql.*; import...+"',"+t6+",'"+t7+"','"+t8+"')"); JOptionPane.showMessageDialog(null,"Thanks...,"Thanks for creating an account."); } catch(Exception e){} } });   Help me Help me HI I am using Tomcat6.0 this is the problem i got wen i run.../jsp/login.jsp"); }else{ out.println("<html>... a clear resolution to this vexing issue? Thanks in advance. Hi Friend JSP help JSP help Hi i am using jsp,html and mysql. I am displaying one question & their 4 options per page. For that i have one label for question &... do this? Please Help Help me Help me HI I am using Tomcat6.0 this is the problem i got wen i run the code , i am using login.html ,login .jsp,login.java and web.xml code...;quot;/Simple/jsp/login.jsp"); }else{ out.println(" method returning null on JSP page.Plz HELP!!! method returning null on JSP page.Plz HELP!!! public String... to Java, so please help me as it could also because of some silly mistake. Thanks...); return sAddress; } When I am calling this method on the jsp page How to create own help forum - JSP-Servlet How to create own help forum Hi All, My client given requirements, they need to create their own help forum, I need to do case study for, how... give me suggestions. thanks in advance. -- Rajkumar Programming help Very Urgent - JSP-Servlet Programming help Very Urgent Respected Sir/Madam, Actually my code... Please please its very urgent.. Thanks/Regards, R.Ragavendran.. Hi friend, Read for more information, Help Very Very Urgent - JSP-Servlet /jsp/ Thanks. function trim(stringToTrim...Help Very Very Urgent Respected Sir/Madam, I am sorry..Actually... requirements.. Please please Its Very very very very very urgent... Thanks please help me. please help me. Please send me the validation of this below link. the link is Thanks Trin Java Programming Help with controls .. I Just want to use jsp and applet in my project . Please help me as soon as fast .. :( Thanks You In Advance... need your help to complete my java project. I going to make a site like youtube jsp jsp hi sir i have a problem in jsp sir please help me in this case... then, the first label value should be optional sir. please help me in this casae.its urgent please reply me soon thanks inadvance help me - JSP-Servlet help me how to open one compiled html file by clicking one button from jsp help on project - JSP-Servlet help on project Need help on Java Project JSP report program. Thanks Hi, You many also use Jasper Assistant from the Eclipse IDE. This will help you in generating the report xml file. Thanks...JSP Hi , I am working in JSP. In my project i have to generate my JSP JSP How to retrieve the dynamic html table content based on id and store it into mysql database? How to export the data from dynamic html table content to excel?Thanks in Advance.. Plz help me its urgent jsp . For more information, visit the following link: JSP Tutorials Thanks.... Apache Tomcat/5.0.28 please help me. its urgent....... Have you... api.jar file inside the lib folder. 4)Now create a jsp file:'hello.jsp' < Regular Expression Help Help HELP!!!! appreciated Thanks in advance!!!!! Please Help!! harish...Regular Expression Help Help HELP!!!! HI all I am very new to java... could help me to give a solution of how to retrieve the name and email add jsp , database: MS Access. Please kindly help me ASAP. Thanks Re:Need Help for Editable Display table - JSP-Servlet Re:Need Help for Editable Display table Hi Genius i need a help in jsp to display editable display tag. I able to show the datagrid in jsp... and edit it in the same grid.. Thanks in advance Eswaramoorthy Hi Java and JSP help Java and JSP help I have a website, on my website i have made a form which allows the user to enter a question, this question is then saved...;title>JSP Form</title> <style> </style> help me help me HI. Please help me for doing project. i want to send control from one jsp page to 2 jsp pages... is it possible? if possible how to do Editor help required. - Java Server Faces Questions Editor help required. I am having problem with editor used to design JSP page in JSF applications. I want to open JSP page with Web Page Editor... are they? Please Help me.... Thanks In advance help me help me how to print from a-z, A-Z with exact order using for loop? Thanks for all concern jsp code - JSP-Servlet jsp code Can anyone help me in writing jsp/servlet code to retrieve files and display in the browser from a given directory. Hi Friend, Try the following code: Thanks Looking for help Looking for help I am looking for a valid helper to solve flex 4 problems I have found after switching from flex 3. We would work directly on my code with team viewer in the beginning. Thanks for your help Paolo JSP Date & Time - JSP-Servlet JSP Date & Time Hi! How to compare a String with System time in JSP.... pls... help me... Thanks in advance jsp - JSP-Servlet jsp hai everybody how to pass vlaue from jsp to jsp give me one example i tried with like this i tried please anyone help me its very urgent thanks in advance Hi friend help me help me hi sir pls tell me how to use ajax form validatin from very simple way with two ot three text field pls help me use ajax in php my email id... visit the following link: Thanks JSP - JSP-Servlet /connect_jsp_with_mysql.shtml Thanks...JSP Hi! Thank you very much for your help regarding XML reading in JSP. I have a small doubt. Is it possible to write a database help please help please hi i am done with register application using jsps... file.. Or atleast help me with code here.. I tried checking session alive and all didn worked ...will be waiting Thanks in advance help - Struts help, thans! information: struts.xml HelloWorld.jsp... : Thanks  .../struts/struts2/struts-2-hello-world-files... friend, Read for more information. Thanks-Servlet JSP How to store selected combo value in a String variable.. in JSP without AJAX. pls.... help me.... Hi friend, Using Jquery to store selected combo value in jsp : JSP - JSP-Servlet :// Thanks...JSP This is the error which i got in my JSP page. "The value for the useBean class attribute SQLBean.DbBean is invalid." please help me java help? java help? Write a program, where you first ask values to an array with 6 integer values and then count the sum and average of the values in methods...("Average of Array Elements: "+average(array)); } } Thanks
http://www.roseindia.net/tutorialhelp/comment/95232
CC-MAIN-2014-10
en
refinedweb
Safe to remove fields that are nulls? Xolani Nkosi Ranch Hand Joined: Apr 29, 2009 Posts: 32 posted Dec 16, 2010 08:34:37 0 I have some serialised objects from a class that looks like: public class SomeClass { private static final long serialVersionUID = 201012160001L; private Integer number; public Integer getNumber() { return number; } public void setNumber(Integer number) { this.number = number; } } I have since decided that number needs to be a Long. I know that I can't just change it, as that will break deserialisation for my existing objects. So I do the following: public class SomeClass { private static final long serialVersionUID = 201012160001L; @Deprecated private Integer number; private Long newNumber; public Long getNumber() { if(newNumber == null) { if(number != null) { newNumber = new Long(number.longValue()); number = null; } } return newNumber; } public void setNumber(Long number) { this.newNumber = number; this.number = null; } } So now, newly made objects will exclusively use newNumber to store the value, and leave number null, and existing classes that I deserialise, get/set from, and then serialise again, will have their value copied over to newNumber. My question is... is it safe to remove the Integer number field, once I know that all my stored objects have been migrated over to use the new field? e.g. does deserialision break even if the value it's attempting to set is null? Paul Clapham Bartender Joined: Oct 14, 2005 Posts: 17743 8 I like... posted Dec 16, 2010 10:31:52 0 Seems to me it shouldn't take more than 15 minutes to do that experiment. Why not try it and see what happens? Edit: and let us know what happens. Others may know the answer to your question but I don't and I'm sure many others don't either. Greg Charles Sheriff Joined: Oct 01, 2001 Posts: 2757 10 I like... posted Dec 16, 2010 11:03:33 0 From what I know of serialization, Any changes to the fields will change the serialVersionUID, and so make serialization impossible from "old" instances to "new", unless ... You explicitly set the serialVersionUID, as you did, which effectively disables this check. By the way, you don't have to set it to such a cryptic number, unless you're trying to match it with a version of the class that didn't explicitly set the value. Normally, you can just set it to 0 or 1 or whatever. Not everyone knows that. So, now we can serialize between different versions of the code: Any member data that is present in the class available to the deserializer, but not in the serialized object will be set to a default value. (null, 0, or false) Any values present in the serialized object, but not in the member data will be discarded. So, I think that answers your question, but I agree with Paul that you should just run it through some tests. After all, my memory could be faulty, or serialization might have changed in the 14 years since I last looked into in that level of detail. Incidentally, you might look into the weird private methods readObject() and writeObject(). They can be useful for converting between different object versions. I'm not sure if they could help you in this case though. I agree. Here's the link: subject: Safe to remove fields that are nulls? Similar Threads nikos thread question Niko's mock exam question mismatch in printing the value of a variable Struts2 QUERY Regarding Built in Type Conversions in Struts2 Framework Validate method not completing All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter JForum | Paul Wheaton
http://www.coderanch.com/t/520675/java-io/java/Safe-remove-fields-nulls
CC-MAIN-2014-10
en
refinedweb
setAttribute('style', ...) workaround for IE 08 January 2007 JavaScript I knew had I heard it before but I must have completely missed it anyway and forgotten to test my new Javascript widget in IE. None of the stylesheet worked in IE and it didn't make any sense. Here's how I did it first: var closer = document.createElement('a'); a.setAttribute('style', 'float:left; font-weight:bold'); a.onclick = function() { ... That worked in Firefox of course but not in IE. The reason is that apparently IE doesn't support this. This brilliant page says that IE is "incomplete" on setAttribute(). Microsoft sucked again! Let's now focus on the workaround I put in place. First I created a function to would take "font-weight:bold;..." as input and convert that to "element.style.fontWeight='bold'" etc: function rzCC(s){ // thanks\ // retrieving-css-styles-via-javascript/ for(var exp=/-([a-z])/; exp.test(s); s=s.replace(exp,RegExp.$1.toUpperCase())); return s; } function _setStyle(element, declaration) { if (declaration.charAt(declaration.length-1)==';') declaration = declaration.slice(0, -1); var k, v; var splitted = declaration.split(';'); for (var i=0, len=splitted.length; i<len; i++) { k = rzCC(splitted[i].split(':')[0]); v = splitted[i].split(':')[1]; eval("element.style."+k+"='"+v+"'"); } } I hate having to use eval() but I couldn't think of another way of doing it. Anybody? Anyhow, now using it is done like this: var closer = document.createElement('a'); //a.setAttribute('style', 'float:left; font-weight:bold'); _setStyle(a, 'float:left; font-weight:bold'); a.onclick = function() { ... and it works in IE! node.style.cssText = "..." usually does the trick for me Really? I'll give that a try. Hooray! Thank-you. In my case, involving styles of a div element, this worked only after I append the div to the body node, but yes! Yes, this is a really short solution! Thank you all for not giving up on this topic. By the way - it's not possible to code a lot of JavaScript for HTML using the DOM only, is it? Nice !!! Thx thnx...it worked!!! thanks, it works well! BEFORE var closer = document.createElement('a'); //a.setAttribute('style', 'float:left; font-weight:bold'); _setStyle(a, 'float:left; font-weight:bold'); a.onclick = function() { ... } ---------------------- AFTER var closer = document.createElement('a'); //closer.setAttribute('style', 'float:left; font-weight:bold'); _setStyle(closer, 'float:left; font-weight:bold'); closer.onclick = function() { ... } If type 'closer' it's work Thanks Peter :D Just what I was looking for. Thanks a lot! Wow that was great buddy ! You saved me a lot of weeks. I need to personally thanks you too. Hi, it helped me to fix appending of new style values, without overwritting all previously declared ones (just those that are meant to change). Thanks. If you still don't like eval(), try this: element.style[k]= v; You know objects, arrays, objects... Thanks a lot! perfect code!!! This is great! I've improved it just a bit: _setStyle: function (aElement /* object */, aDeclaration /* CSS Declaration */) { try { if (aElement) { aDeclaration = aDeclaration.replace(/\s+/g,''); // remove all white spaces if (document.all) { // IE Hack if (aDeclaration.charAt(aDeclaration.length-1)==';') aDeclaration = aDeclaration.slice(0, -1); var k, v; var splitted = aDeclaration.split(';'); for (var i=0, len=splitted.length; i<len; i++) { k = rzCC(splitted[i].split(':')[0]); v = splitted[i].split(':')[1]; eval("aElement.style."+k+"='"+v+"'"); } return (true); } else { // The clean way aElement.setAttribute ('style', aDeclaration); return (true); } } } catch (e) { return (false); } } Hope you like it. Good job mate ;) I forgot to tell why I decided to "improve" it: if you put a white space in the css declaratio, such: background-color: #FFFFFF; the original code will miss it. You had to put it together for it to work, like: background-color:#FFFFFF; Oh, and the function declaration in my version is for prototype. If you don't use this technique just change the declaration to: function _setStyle (aElement /* object */, aDeclaration /* CSS Declaration */) That's it. Cheers! I found myself having issues with this same problem today and have found out a few interesting things. In IE (they just have to be different don't they) the style attribute is actually treated as an Element. You can set the different style properties by using the syntax shown below. oNewDiv = createElement('div'); oNewDiv.style.setAttribute('border', '1px solid #000'); oNewDiv.style.setAttribute('backgroundColor', '#fff'); Of course, this fails terribly in firefox :( However, I have always been able to set styles without the setAttribute function in a cross browser supported way like: oNewDiv.style.backgroundColor = '#fff'; This won't work at all for me, using IE 7 or 8.. eval() is devil. this workaround is not going to help. infact it will hang your IE and fill your memory with bunch of variables. If you code little smart using conditions if(document.all) { code here }else{ code here } then everything will be cool. I've tried and it's working in all browsers. Try using cssText for ie. Element.style.setAttribute('cssText', 'left:150px;......... you could create function if you wanted. thanks very very very much! I have added this code: if(k=='class') { eval("element.className='"+v+"'"); } @ivo van der Wijk=You're a genius man!!! I know it sounds very exagerrated but what the hell... u just saved me a couple of hours of searching Hi, Try this: var closer = document.createElement('a'); a.style.float="left"; a.style.fontWeight="bold"; a.onclick = function() { ... It works on all browsers !! Enjoy it !! Hi Quiquelie, Your code is cool thanks :) i was literally searching for onclick cross browser functionality Hi, how is this? element.style[k]= v; instead of eval(...) Cool!! thxs! Works like a charm! I definitely needed this dynamic!! Thanks so much! I like how you automatically escaped the newline in the commented code ;-P set one or more objects to one or more styles {obj1,obj2...},{"color":"red","fontSize":"small","fontFamily":"Cursive"...} works in FF,IE,Safari function a_obj_setstyle(a_obj,a_prop){ for (ko in a_obj){for(kp in a_prop){ eval('a_obj[ko].style.'+kp+'="'+a_prop[kp]+'"'); }} } OMG, your a very smart, you just saved my ass, my client was going to kill me ,, lol Thanks a lot body ;) This is how it works in IE oImg.style.cssText="float:left;margin-right:7px;margin-bottom:7px"; The simple solutions are always the best. Thanks NICE! THAAAAANXXXXXX!!!! You're the best web programmer!!!!! I hate IE... Thanks a lot!!!! Hello guys, If you have short form in your style like : font: normal normal bold xx-small verdana, serif; This cut function will cut the spaces and mix the css --> font:normalnormalboldxx-smallverdana,serif; Oh thats work great... thankssssssss..... I had a similar issue with setAttribute not working on IE. I put it in a try block, and in the catch block I used outerHTML for the IE version. outerHTML is read/write, so my function could dynamically get the code of the existing control, and then replace whatever had to change. One quirk is that IE rewrites the control's code in outerHTML, so I had to work around that a little, but it worked. thanks ur code, but if i want to remove one of css that i added, how can i do that???? document.getElementById('name').className = "yourClass"; People, DO NOT USE eval(). Especially not in such an easy cases. eval("element.style."+k+"='"+v+"'"); is almost identical (I'll explain) to this: element.style[k] = v; When you create an object: var obj = { a: 1, b: 2, c: 3 }; You can (get or) set the values like: obj.a = 10 which is identical to: obj["a"] = 10 As to where that eval("element.style."+k+"='"+v+"'"); differs from the direct method is that if you'd try to set for example a background image, this'd be the css: background-image: url('/images/someImage.png') If you use that in the eval, this is the code that'll be evaluated: element.style.backgroundImage='url('/images/someImage.png')' Which obviously results in a syntax error because of the single quotes. Of course that could be solved by first replacing \ into \\ and then ' into \'. Eval is evil, there are rarely ever situations where there's need for eval, and even if there are try your absolute best to find a way around. Such a small change avoids: 1. The performance hit you have from using eval() 2. Making your code less secure (for example, if some 3rd party code executes: _setStyle(someElement, "width: 10px' alert('My evil message, muauauauaua') var rndDump = '; height: 10px;"), it would of course run the injected code) 3. Spreading bad code like this across other people's sites, possibly harming the identity and privacy of people browsing the web. It's been many years since I wrote that but I think the point is that the stupid eval was necessary because of IE. Then again, I've stopped caring about it working in IE. Unless you're doing commercial work that's always a good choice :P. Nevertheless even in IE this eval wasn't necessary :). And I also know that this is an old article, but these are still the articles beginners find when they run into this issue, and that's why I made the comment. Event at my old company where I had co-workers who all finished collage for web development, and they still didn't know how to write proper javascript and had all sorts of hacky scripts like this one in their code.
http://www.peterbe.com/plog/setAttribute-style-IE/
CC-MAIN-2014-10
en
refinedweb
Model card error There’s an error in the yaml metadata in this model card. If you’re the model author, please log in to check the list of errors and warnings. t5-weighter_cnndm-en Model description This model is a Classifier model based on T5-small, that predicts if a answer / question couple is considered as important fact or not (Is this answer enough relevant to appear in a plausible summary?). It is actually a component of QuestEval metric but can be used independently as it is. How to use from transformers import T5Tokenizer, T5ForConditionalGeneration tokenizer = T5Tokenizer.from_pretrained("ThomasNLG/t5-weighter_cnndm-en") model = T5ForConditionalGeneration.from_pretrained("ThomasNLG/t5-weighter_cnndm-en") You can play with the model using the inference API, the text input format should follow this template (accordingly to the training stage of the model): text_input = "{ANSWER} </s> {QUESTION} </s> {CONTEXT}" Training data The model was trained on synthetic data as described in Questeval: Summarization asks for fact-based evaluation. Citation info @article{scialom2021 - 395
https://huggingface.co/ThomasNLG/t5-weighter_cnndm-en
CC-MAIN-2022-05
en
refinedweb
Multilingual Content This article helps collect all the resources you need to utilize Prismic's multi-language and localization feature when building a Gatsby website. Go to your Dashboard, select your Prismic repository. Then go to Settings > Translations and Locales, and add all the languages you need. Prismic offers a robust library of locale codes, but you can create a custom locale if yours isn't on the list. Once you have your locales configured, you can create documents and translations, manage the locales and locales, navigate the locales, copy the content, and more. Create a Link Resolver to generate the localized routes for your site and declare it in your gatsby plugin configuration. In this example, we have a repository with two locales. English (en-us) which is the master locale, and French (fr-fr). Here's an example of how we want the URLs to look like: - Home type: /en-us & /fr-fr - Page type: /en-us/about-us & /fr-fr/a-propos-de-nous This would be the Link Resolver that generates localized routes. For the Home Custom Type we use lang as the language code and for the Page type and the lang and the uid of the document: // Example LinkResolver.js file exports.linkResolver = (doc) => { switch (doc.type) { case 'home': { return `/${doc.lang}` } case 'page': { return `/${doc.lang}/${doc.uid}` } default: return '/' } } The Link Resolver will generate the correct routes that we'll use to dynamically create pages with Gatsby Node APIs or with the File System Route API. Once you have set up your dynamic routes and created all of your documents and translations in your repository, you'll need to query the documents by language. You'll use the lang value to query the documents by language. Here's an example of a page.js template. We query the documents of the type Page. It will determine the language of the documents by the $lang: String variable in the query: // Example page.js file import * as React from 'react' import { graphql } from 'gatsby' const Page = ({ data }) => { if (!data) return null const pageContent = data.prismicPage return ( <div> <h1>{pageContent.data.title.text}</h1> </div> ) } export const query = graphql` query pageQuery($id: String, $lang: String) { prismicPage(id: { eq: $id }, lang: { eq: $lang }) { lang alternate_languages { id type lang uid } data { title { text } } } } ` export default Page Learn more about querying using metadata values: Now that you've built dynamic localized pages and routes, you need to create a navigation button so users can select to switch between languages on your website. This can be anything from a <select> element if you have many languages, a button, or a boolean toggle switch if you only have two. We'll show you how to build a selection component that lists the current and alternative languages in this example. The first step is to get the current lang and the alternate_languages from the query to pass it to the language switcher. Please take a look at our example. After retrieving these values from the query, we pass them as props to a LanguageSwitcher component that we'll create in the next step. import * as React from 'react' import { graphql } from 'gatsby' import { LanguageSwitcher } from '../components/LanguageSwitcher' const Page = ({ data }) => { if (!data) return null const pageContent = data.prismicPage return ( <div> <h1>{pageContent.data.title.text}</h1> <LanguageSwitcher lang={pageContent.lang} altLangs={pageContent.alternate_languages} /> </div> ) } export const query = graphql` query pageQuery($id: String, $lang: String) { prismicPage(id: { eq: $id }, lang: { eq: $lang }) { lang alternate_languages { id type lang uid } data { title { text } } } } ` export default Page In the 〜/src/components folder, create a LangSwitcher.js file. Get the lang and altLangs values that we previously passed as props. We'll use Gatsby's navigate function to resolve the navigation of the links between routers in the <select> element and the Link Resolver to direct to the correct URL. import * as React from 'react' import { navigate } from 'gatsby' import { linkResolver } from '../utils/linkResolver' export const LanguageSwitcher = ({ lang, altLang }) => { // Render the current language const currentLangOption = ( <option value={lang}>{lang.slice(0, 2).toUpperCase()}</option> ) // Render all the alternate language options const alternateLangOptions = altLang.map( (altLang, index) => ( <option value={linkResolver(altLang)} key={`alt-lang-${index}`}> {altLang.lang.slice(0, 2).toUpperCase()} </option> ), ) // Trigger select change event const handleLangChange = (event) => { navigate(event.target.value) } return ( <li className="language-switcher"> <select value={lang} onChange={handleLangChange}> {currentLangOption} {alternateLangOptions} </select> </li> ) } Now you'll have a selection component that lists all the available locales in your repository so your visitors can quickly switch between locales. Take a look at this multi-language example so you can see how it looks all put together. Was this article helpful? Can't find what you're looking for? Get in touch with us on our Community Forum.
https://prismic.io/docs/technologies/multilingual-content-gatsby
CC-MAIN-2022-05
en
refinedweb
User talk:Fkmclane From Gentoo Wiki Overlay Hi Fkmclane! I read your user page and I thought you could be interested by the Overlay namespace! --Feng (talk) 15:54, 26 March 2017 (UTC) - I'm a bit new to the wiki; thanks for the tip! --Foster McLane (talk) 15:24, 27 March 2017 (UTC)
https://wiki.gentoo.org/wiki/User_talk:Fkmclane
CC-MAIN-2022-05
en
refinedweb
How to install and use Exchangelib Python Try a faster and easier way to work with Python packages like Exchangelib. Use Python 3.9 by ActiveState and build your own runtime with the packages and dependencies you need. Get started for free by creating an account on the ActiveState Platform or logging in with your GitHub account. Exchangelib is a Python client library that provides an interface for accessing and working with Microsoft Exchange Web Services (EWS). EWS is both a messaging protocol and an Application Programming Interface (API) for locating and connecting with EWS/Exchange Server hosts, and provides a library of functions for working with host applications and user data. If you’re not familiar with Microsoft Exchange Server, it provides organizations with email and calendaring services for their users. Although EWS and Exchange Servers are Windows-only, Exchangelib is a Python cross-platform tool. Exchangelib Package Installation The simplest way to create an exchangelib project, is to install Python 3.9 from ActiveState and then run: state install exchangelib This will build all components from source code, and then install Python 3.9 in a virtual directory along with exchangelib and all it’s dependencies, ready to be worked with. If you have already have Python 3 installed, the Exchangelib package can be installed from the Python Package Index (PyPI) by entering the following command in a terminal or command window: pip install exchangelib or Python3 -m pip install exchangelib Or you can install the latest version directly from GitHub: pip install git+ You’ll also need to install either Kerberos or SSPI (required on Windows only): pip install exchangelib[kerberos] pip install exchangelib[sspi] Exchangelib Python: Getting Started Exchangelib Python includes: - Services for locating EWS/Exchange Server hosts - Protocols for establishing a secure connection with host applications - Functions for accessing, searching, creating, updating, deleting, exporting and uploading data to user accounts Before connecting to EWS and Exchange Server mail and calendaring applications, you’ll first need to import the packages required for interoperability with EWS/Exchange Server: # Import Exchangelib into Python: Import exchangelib # Packages required by Exchangelib Python: from datetime import datetime, timedelta import pytz from exchangelib import DELEGATE, IMPERSONATION, Account, Credentials, EWSDateTime, EWSTimeZone, Configuration, NTLM, GSSAPI, CalendarItem, Message, Mailbox, Attendee, Q, ExtendedProperty, FileAttachment, ItemAttachment, HTMLBody, Build, Version, FolderCollection Use Exchangelib to Connect to Exchange Server - First establish your credentials. Your username is usually in WINDOMAIN\username format but may be in PrimarySMTPAddress (‘myusername@example.com’) format (ie., Office365 requires this). For example: credentials = Credentials(username='MYWINDOMAIN\\myusername', password='topsecret') Establish a connection with your EWS user account. For example: my_account = Account(primary_smtp_address='myusername@example.com', credentials=credentials, autodiscover=True, access_type=DELEGATE) Where: - ‘Account’ can be your account or (if access_type=DELEGATE) any other account on the server that you have been granted access to. - ‘primary_smtp_address’ is the primary SMTP address assigned to the account. - autodiscover=True performs an autodiscover lookup to find the target EWS endpoint - You can also set access_type=IMPERSONATION in order to gain impersonation access to the target account You can set the auth method and version explicitly using config = Configuration(). For example: config = Configuration( server='example.com', credentials=credentials, version=version, auth_type=NTLM To enable Kerberos authentication, you can use: credentials = Credentials('', '') config = Configuration(server='example.com', credentials=credentials, auth_type=GSSAPI) Here, Kerberos is supported via the ‘GSSAPI’ authentication type. Exchangelib – Proxies and Custom TLS Validation If proxy support or custom TLS validation is needed, you can supply a custom ‘requests’ transport adapter class. # Example of using different custom root certificates depending on the server to connect to: from urllib.parse import urlparse import requests.adapters from exchangelib.protocol import BaseProtocol class RootCAAdapter(requests.adapters.HTTPAdapter): # An HTTP adapter that uses a custom root CA certificate at a hard coded location: def cert_verify(self, conn, url, verify, cert): cert_file = { 'example.com': '/path/to/example.com.crt', 'mail.internal': '/path/to/mail.internal.crt', ... }[urlparse(url).hostname] super(RootCAAdapter, self).cert_verify(conn=conn, url=url, verify=cert_file, cert=cert) # Tell Exchangelib Python to use this adapter class instead of the default: BaseProtocol.HTTP_ADAPTER_CLS = RootCAAdapter # Example of adding proxy support: class ProxyAdapter(requests.adapters.HTTPAdapter): def send(self, *args, **kwargs): kwargs['proxies'] = { 'http': '', 'https': '', } return super(ProxyAdapter, self).send(*args, **kwargs) # Tell Exchangelib Python to use this adapter class instead of the default: BaseProtocol.HTTP_ADAPTER_CLS = ProxyAdapter # Exchangelib Python provides a sample adapter which ignores TLS validation errors. (Use at your own risk): from exchangelib.protocol import NoVerifyHTTPAdapter # Tell Exchangelib Python to use this adapter class instead of the default BaseProtocol.HTTP_ADAPTER_CLS = NoVerifyHTTPAdapter Exchangelib – How to Access Folders There are multiple ways to navigate and search the folder tree. Be aware that if your folder names contain slashes, then globbing and absolute path may create unexpected results. (globs are patterns that specify sets of filenames with wildcard characters. Eg. Unix bash cmd: mv *.txt textfiles/). You can use some_folder.root to return the root of the folder structure, at any level. For example: print(Account.root) Other examples include: - print(account.root.children) which returns child folders - print(account.root.absolute)which returns the absolute path - print(account.root.walk) which is a generator returning all subfolders - print(account.root.parts) which returns some_folder and all its parents Or else you can use UNIX globbing syntax. For example: # Return child folders that match the pattern, using the foo placeholder:: print(account.root.glob('foo*')) # Return subfolders named ‘foo’ in any child folder: print(account.root.glob('*/foo')) # Return subfolders named ‘foo’ at any depth: print(account.root.glob('**/foo')) # Works like pathlib.Path: some_folder / 'sub_folder' / 'even_deeper' / 'leaf' Exchangelib – How to Use Dates, Datetimes and Timezones EWS has special requirements on datetimes and timezones. You need to use the EWSDate, EWSDateTime and EWSTimeZone classes when working with dates. For example: # You can use the local timezone defined in your OS: tz = EWSTimeZone.localzone() # EWSDATE, EWSDATETIME and DATETIME.DATETIME, datetime.date are # similar. Always localize time zones, by creating timezone-aware datetimes # with EWSTimeZone.localize(): localized_dt = tz.localize(EWSDateTime(2017, 9, 5, 8, 30)) right_now = tz.localize(EWSDateTime.now()) # Add datetime: two_hours_later = localized_dt + timedelta(hours=2) two_hours = two_hours_later - localized_dt two_hours_later += timedelta(hours=2) Exchangelib – Create, Update, Delete, Send & Move Data Python applications can be used to create, update, delete, send and move data to user accounts. In this example, a calendar item is created in the user’s standard calendar: # Create, update and delete single items: from exchangelib.items import SEND_ONLY_TO_ALL, SEND_ONLY_TO_CHANGED item = CalendarItem(folder=account.calendar, subject='foo') # Give the item an ‘id’ and a ‘changekey’ value: item.save() item.save(send_meeting_invitations=SEND_ONLY_TO_ALL) # Send a meeting invitation to attendees # Update a field. All fields have a corresponding Python type that must be used: item.subject = 'bar' # Print all available fields on the CalendarItem class: print(CalendarItem.FIELDS) # Items with item_id, are updated with save(): item.save() # Only update certain fields: item.save(update_fields=['subject']) # Send invites only to attendee changes: item.save(send_meeting_invitations=SEND_ONLY_TO_CHANGED) # Hard deletion: item.delete() # Send cancellations to all attendees: item.delete(send_meeting_cancellations=SEND_ONLY_TO_ALL) # Delete, but keep a copy in the recoverable items folder: item.soft_delete() # Move to the trash folder: item.move_to_trash() # Also move item to the account.trash folder: item.move(account.trash) # Create a copy of item in the account.trash folder: item.copy(account.trash) folder # Send emails without local copies: m = Message( account=a, subject='Daily motivation', body='All bodies are beautiful', to_recipients=[ Mailbox(email_address='anne@example.com'), Mailbox(email_address='bob@example.com'), ], # Simple strings also work: cc_recipients=['carl@example.com', 'denice@example.com'], bcc_recipients=[ Mailbox(email_address='erik@example.com'), 'felicity@example.com', ], # Or a mix of both ) m.send() # Or send emails, and get local copies, eg. in the ‘Sent’ folder: m = Message( account=a, folder=a.sent, subject='Daily motivation', body='All bodies are beautiful', to_recipients=[Mailbox(email_address='anne@example.com')] ) m.send_and_save() # You can reply to and forward messages: m.reply( subject='Re: foo', body='I agree', to_recipients=['carl@example.com', 'denice@example.com'] ) m.reply_all(subject='Re: foo', body='I agree') m.forward( subject='Fwd: foo', body='Hey, look at this!', to_recipients=['carl@example.com', 'denice@example.com'] ) # EWS distinquishes between plain text and HTML body contents. # To send HTML body content, use the HTMLBody helper. # Clients will see this as HTML and display the body correctly: item.body = HTMLBody('<html><body>Hello happy <blink>OWA user!</blink></body></html>') Exchangelib – Bulk Operations In this example, a bulk list of calendar items is built:, for when you have a list of item IDs and want the full objects. # Returns a generator: calendar_ids = [(i() Exchangelib – Searching Searching is modeled after the Django QuerySet API. In fact a large part of the API is supported in Exchangelib Python. As. In this example, the Django QuerySet API is used to query the calendaring application (that has been located and accessed using Exchanglib protocols and web services): # Get the calendar items created in the previous Bulk Operations section: Django QuerySet API # Get everything # Get everything, but don’t cache: all_items_without_caching = my_folder.all().iterator() # Chain multiple modifiers ro refine the query: filtered_items = my_folder.filter(subject__contains='foo').exclude(categories__icontains='bar') # Delete the items returned by the QuerySet: status_report = my_folder.all().delete() ‘-‘ to reverse the sorting: ordered_items = my_folder.all().order_by('subject') reverse_ordered_items = my_folder.all().order_by('-subject') # Indexed properties can be ordered on their individual components: sorted_by_home_street = my_contacts.all().order_by('physical_addresses__Home__street') dont_do_this = my_huge_folder.all().order_by('subject', 'categories')[:10] Exchangelib – Working with Meetings The CalendarItem class allows you to send out requests for meetings that you initiate, or to cancel meetings that you set out previously. It is also possible to process MeetingRequest messages that are received. You can reply to these messages using the AcceptItem, TentativelyAcceptItem and DeclineItem classes. If you receive a cancellation for a meeting (class MeetingCancellation) that you already accepted, then you can also process these by removing the entry from the calendar. import datetime from exchangelib import Account, CalendarItem from exchangelib.items import MeetingRequest, MeetingCancellation, \ SEND_TO_ALL_AND_SAVE_COPY credentials = Credentials(username='MYWINDOMAIN\\myusername', password='topsecret') a = Account(primary_smtp_address='john@example.com', credentials=credentials, autodiscover=True, access_type=DELEGATE) # Create and send out a meeting request: item = CalendarItem( account=a, folder=a.calendar, start=datetime.datetime(2019, 1, 31, 8, 15, tzinfo=a.default_timezone), end=datetime.datetime(2019, 1, 31, 8, 45, tzinfo=a.default_timezone), subject="Subject of Meeting", body="Please come to my meeting", required_attendees=['anne@example.com', 'bob@example.com'] ) item.save(send_meeting_invitations=SEND_TO_ALL_AND_SAVE_COPY) # Cancel a meeting that was sent out using the CalendarItem class: for calendar_item in a.calendar.all().order_by('-datetime_received')[:5]: # Only the organizer of a meeting can cancel it: if calendar_item.organizer.email_address == a.primary_smtp_address: calendar_item.cancel() # Processing an incoming MeetingRequest: for item in a.inbox.all().order_by('-datetime_received')[:5]: if isinstance(item, MeetingRequest): item.accept(body="Sure, I'll come") # Or: item.decline(body="No way!") # Or: item.tentatively_accept(body="Maybe...") # Meeting requests can also be handled from the calendar, # e.g. decline the meeting that was received last: for calendar_item in a.calendar.all().order_by('-datetime_received')[:1]: calendar_item.decline() # Process an incoming MeetingCancellation # and delete from calendar: for item in a.inbox.all().order_by('-datetime_received')[:5]: if isinstance(item, MeetingCancellation): if item.associated_calendar_item_id: calendar_item = a.inbox.get( id=item.associated_calendar_item_id.id, changekey=item.associated_calendar_item_id.changekey ) calendar_item.delete() item.move_to_trash() Exchangelib Troubleshooting If you are having trouble using Exchangelib Python, the first thing to try is to enable debug logging. This will output information about what is going on, most notably the actual XML documents at the source of the problem. import logging from exchangelib.util import PrettyXmlHandler from exchangelib import CalendarItem # Handler that pretty-prints and syntax highlights # request and response XML documents: logging.basicConfig(level=logging.DEBUG, handlers=[PrettyXmlHandler()]) # Most class definitions have a docstring containing # a URL to the MSDN page for the corresponding XML element. # Your code that uses Exchangelib Python, and needs debugging goes here: print(CalendarItem.__doc__) .
https://www.activestate.com/resources/quick-reads/how-to-install-and-use-exchangelib-python/
CC-MAIN-2022-05
en
refinedweb
Is There a Consensus Web Services Stack? February 12, 2003 Hegel says somewhere that all great events and personalities in world history reappear in one fashion or another. He forgot to add: the first time as tragedy, the second as farce. -- Karl Marx, The Eighteenth Brumaire of Louis Bonaparte What Marx said of world history -- that it occurs the first time as tragedy, the second as farce -- is increasingly true of conversations in the XML development community. Conversation among XML developers has grown increasingly ossified. Permanent topics of conversation return -- never, it appears, to be fully repressed -- over and over: the ins and outs of namespaces, the nature of resources and representations, why SOAP is sweetness-and-light or pure evil, the ideal simplifying refactor of XML itself, and so on. And, each time the cycle repeats itself, the positions grow more shrill, more caricatured, and less interesting. It's possible that someone will eventually learn something from all of this; more likely, people give up the hope of learning something and stop paying attention. The lucky journalist, whose job it is to cover these conversations, has one of two options: either mine the ossified flows of information for the occasional nugget or get things so wrong that the community is roused to fury by sheer (perhaps even intentional) incompetence. In this week's column, I maintain my hopes of steering toward the former option and away from the latter. A Short Stack or Tall? The web services "stack" is a semimythical creature, composed in equal parts of technical specification, running code, and marketing campaign. Since the global IT budgetary funk is unlikely to brighten during 2003 (or even 2004), the proliferation of web services specifications and technologies is as much wishful thinking as it is anything else. It is fairly uncontroversial that the core of the web services stack rests on the Internet infrastructure (TCP/IP, HTTP, and, arguably, URIs), followed by the XML layer, the SOAP layer, and the WSDL layer. Even though the composition of this segment of the web services stack reflects a rough industry consensus, that doesn't mean it necessarily works. Several people have reported interoperability problems in the SOAP-WSDL layers. As Don Box said, "many interop problems are a result of various stacks...trying to mask the existence of XML altogether. That combined with a WSDL specification (1.1) that invented far more than it needed to has made life harder than would otherwise be necessary." In short, even with a rough consensus, interoperation can be messy across different implementations of the web services stack; this is the case, in part, because people still aren't sure whether XML is a data model, just a syntax, or both. And so various groups try to bury XML beneath WSDL layers of, as Don Box said, "goop". After that, things get even trickier. Where does UDDI go? And, more to the point, what are its chances of success? Does the world really need -- to use Don Box's pithy explanation of UDDI, an "RDF-esque version of LDAP over SOAP"? As Paul Brown put it, "'free love' on the business internet is a long way off". Microsoft, for one, has a rather wild and woolly welter of high-level elements in the web services stack: coordination, inspection, referral, routing, policy, transaction. What about the various, competing service coordination specifications: BPEL, BTP, WSCI, and on it goes. Again, Paul Brown said it best, "The answer to the question 'Is there a royalty-free specification of web services choreography that legitimately combines and acknowledges the established body of knowledge on long-running transaction models, business process semantics, and cross-domain implementation realities?' is 'No.'" Another Turn in the Patent Wars Moving from the ridiculous to the sublimely ridiculous, it was reported that Microsoft has applied for a wide-ranging patent for many of its .NET APIs, including XML. The patent claims that Microsoft has developed "a software architecture for a distributed computing system comprising: an application configured to handle requests submitted by remote devices over a network; and an [API] to present functions used by the application to access network and computing resources of the distributed computing system". As is often the case in these cases, Microsoft's goal is probably to keep up with IBM, the patent wars being a kind of ghostly analogue of the Cold War's arms race. As for obvious prior art, Rich Salz opined that "[i]t seems pretty obvious that OSF DCE...[is] prior art that invalidate[s]" Microsoft's primary patentable claim. OSF DCE had, in Salz's view, "several APIs that were 'transparently remote'". While it is certainly important that the existence of prior art be communicated to the USPTO, Microsoft is likely to be aiming this patent at IBM rather than at, say, Mono or the free software community in general. Despite Microsoft recently admitting, in SEC filings, that free software could negatively impact its financial position, the mutually defensive patent struggle with IBM is not to be overlooked. Dennis Sosnoski put the matter this way: "The open source world looks especially vulnerable to this type of ploy, since there's no single entity that's likely to step up and bear the legal load if companies start making claims against open source programs. On the other side, it's very difficult for a small company to collect on valid patents being violated by large corporation for the same reason". Free software communities are at risk in principle, which makes it all the more surprising that none of the big companies have used patents offensively against them yet. If that is what actually motivates these patent applications, what is Microsoft, for example, waiting for? Free software developers and users should have learned by now that, jokes about Bill Gates and the devil to the contrary, neither IBM nor Microsoft have any inherent interest in avoiding doing harm to free software. The only reason Microsoft patents are more troublesome now is because Microsoft hasn't bet on free software in the way IBM has done. Thus, it's hard to imagine that IBM would use the patent system as a way to harm free software. Not only because IBM makes serious revenue from its patents (and has since well before anyone thought of free software as an economic threat), which provides a more likely motivation for its unending patent barrage, but IBM has also bet a serious slice of its business on free software, which includes its ability to work with free software developers. It's far more likely that IBM would use its legal resources to defend against patent moves designed to harm free software, since such moves could seriously imperil its own business. Having set out to find something new to report, I was drawn to two classic topics of discussion in the XML development community, web services and patents. Giving the journalists something new to talk about isn't motivation enough for anyone to break new XML ground, but would it kill ya?
https://www.xml.com/pub/a/2003/02/12/deviant.html
CC-MAIN-2022-05
en
refinedweb
On Thu, Jul 30, 2015 at 5:49 PM, Michael Niedermayer <michael at niedermayer.cc> wrote: > On Thu, Jul 30, 2015 at 02:43:01PM +0200, Michael Niedermayer wrote: >> On Wed, Jul 29, 2015 at 05:28:16PM -0400, Ganesh Ajjanagadde wrote: >> > On Wed, Jul 29, 2015 at 3:27 PM, Michael Niedermayer >> > <michael at niedermayer.cc> wrote: >> > > On Wed, Jul 29, 2015 at 02:43:52PM -0400, Ganesh Ajjanagadde wrote: >> > >> On Mon, Jul 27, 2015 at 9:56 AM, Ganesh Ajjanagadde >> > >> <gajjanagadde at gmail.com> wrote: >> > >> > This fixes Ticket2964 >> > >> > >> > >> > Signed-off-by: Ganesh Ajjanagadde <gajjanagadde at gmail.com> >> > >> > --- >> > >> > ffmpeg.c | 2 +- >> > >> > 1 file changed, 1 insertion(+), 1 deletion(-) >> > >> > >> > >> > diff --git a/ffmpeg.c b/ffmpeg.c >> > >> > index 751c7d3..98f812e 100644 >> > >> > --- a/ffmpeg.c >> > >> > +++ b/ffmpeg.c >> > >> > @@ -372,7 +372,7 @@ void term_init(void) >> > >> > struct termios tty; >> > >> > int istty = 1; >> > >> > #if HAVE_ISATTY >> > >> > - istty = isatty(0) && isatty(2); >> > >> > + istty = isatty(0); >> > >> > #endif >> > >> > if (istty && tcgetattr (0, &tty) == 0) { >> > >> > oldtty = tty; >> > >> >> > >> ping >> > > >> > > i dont mind applying this but i dont remember why it was there >> > > so this might break somethig and someone might then have to revert >> > >> > See the long discussion I had (with my initial patch series) for full details. >> > A short summary is as follows: >> > in order to accept "q" and other stuff, ffmpeg has to change the terminal mode. >> > Once terminal mode is changed, on event of "hard" signal like SIGSEGV, >> > it is not the responsibility of ffmpeg to clean up and restore the >> > terminal state >> > that now appears as messed up. >> > I had a patch to do this, but this requires registering signal handler >> > for such signals, >> > and others had valid objections since the core dump is no longer clean. >> > Thus, terminal restoration should be handled by the shell. >> > Fortunately, zsh has such functionality (thanks Nicolas for pointing >> > this out!) via "ttyctl -f" >> > to "freeze" terminal, i.e prevent any process from damaging the >> > terminal state on exit. >> > In bash it is harder to do this; AFAIK requires manual intervention. >> > >> > Unless fate tests redirect 2(stderr) and do not redirect 0(stdin), >> > functionality is identical. >> > Even otherwise, by above argument, I think this is the right thing to do. >> >> patch applied >> >> note, if something breaks, ill revert this one, but hopefully it >> will work fine > > any failure in fate trashes the terminal, thus reverted > > To reproduce, add a abort() into wav_read_header() > run make fate-acodec-adpcm-ima_wav Yes, but the trashing cleanup is not ffmpeg's job; the shell should do > > _______________________________________________ > ffmpeg-devel mailing list > ffmpeg-devel at ffmpeg.org > >
http://ffmpeg.org/pipermail/ffmpeg-devel/2015-July/176460.html
CC-MAIN-2022-05
en
refinedweb
Barcode Software vb.net print barcode labels Estimated lesson time: 60 minutes in .NET Maker Denso QR Bar Code in .NET Estimated lesson time: 60 minutes HKCU\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer\ NoPropertiesRecycleBin HKCU\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer\ NoNetHood HKCU\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer\ NoInternetIcon HKCU\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer\ NoRecentDocsNetHood generate, create barcode bind none for java projects BusinessRefinery.com/barcode rdlc barcode report use rdlc reports net barcode generator to draw bar code with .net objective BusinessRefinery.com/ bar code In this exercise, you compile and test the permissions of a sample assembly in a restricted My_Computer zone. 1. Log on to your computer as an Administrator. using dot.net visual studio .net to print barcode on asp.net web,windows application BusinessRefinery.com/ barcodes use birt barcodes development to develop bar code in java dynamically BusinessRefinery.com/barcode 18 c# code to generate barcode generate, create barcode support none on visual c# projects BusinessRefinery.com/barcode using barcode integrating for excel spreadsheets control to generate, create barcode image in excel spreadsheets applications. clarity, BusinessRefinery.com/barcode Implementing RAID qrcode data contact with word documents BusinessRefinery.com/qr codes to assign qr code 2d barcode and qr-codes data, size, image with .net barcode sdk additional BusinessRefinery.com/QR Code ISO/IEC18004 Value-setting controls allow the user to set values or pick options from a preset list in the user interface. The CheckBox control allows a user to select or deselect particular options in a non-exclusive manner, while the RadioButton allows you to present a range of options to the user, only one of which can be selected. The TrackBar control allows the user to rapidly set a value in a graphical interface. to integrate qrcode and qr-codes data, size, image with visual basic.net barcode sdk assembly BusinessRefinery.com/qr-codes add qr code to ssrs report generate, create denso qr bar code numbers none in .net projects BusinessRefinery.com/qr barcode Services namespace allows you to set a default application name at assembly level: to receive qr code and qr-codes data, size, image with .net barcode sdk adjust BusinessRefinery.com/Quick Response Code to draw quick response code and quick response code data, size, image with c sharp barcode sdk attachment BusinessRefinery.com/QR Code 2d barcode Do you know what these key terms mean You can check your answers by looking up the terms in the glossary at the end of the book. using consideration excel to compose barcode pdf417 in asp.net web,windows application BusinessRefinery.com/pdf417 java itext barcode code 39 use java code-39 implementation to incoporate 39 barcode for java update BusinessRefinery.com/3 of 9 barcode CodeAccessPermission.Assert is nothing like the assert function in C or C++. use excel data matrix encoder to produce data matrix ecc200 with excel source BusinessRefinery.com/ECC200 vb.net generate data matrix barcode generate, create ecc200 profile none in visual basic projects BusinessRefinery.com/gs1 datamatrix barcode Msisaund.ini Parameters rdlc code 128 use rdlc reports net code 128b integrated to assign code 128 on .net string BusinessRefinery.com/Code128 how to use code 39 barcode font in crystal reports generate, create code 39 extended action none in .net projects BusinessRefinery.com/Code 3/9 Create a Shared Schedule winforms code 39 use winforms 3 of 9 barcode printing to compose bar code 39 with .net bitmap BusinessRefinery.com/ANSI/AIM Code 39 using coder asp.net aspx to embed datamatrix in asp.net web,windows application BusinessRefinery.com/Data Matrix 2d barcode 3. Northwind Traders wants to open a satellite office in Burlington, but it does not want this new office to host any zones. The satellite office users are expected to use the Internet heavily for marketing and research. What can you do to improve DNS name resolution for users in this satellite office 9 Replication A global group is defined in the domain naming context. The group object, including the member attribute, is replicated to all domain controllers in the domain. Membership A global group can include as members users, computers, and other global groups in the same domain only. Availability A global group is available for use by all domain members as well as by all other domains in the forest and all trusting external domains. A global group can be a member of any domain local or universal group in the domain or in the forest. It can also be a member of any domain local group in a trusting domain. Finally, a global group can be added to ACLs in the domain, in the forest, or in trusting domains. Table 2-5 When Windows Vista runs normally, it displays either 16-bit or 32-bit color. Sixteen-bit color means that the monitor displays 65,536 colors, and 32-bit color means that the monitor displays 16,777,216 colors. Almost all modern monitors display 32-bit color, and generally speaking it is better to have your monitor configured to display as many colors as possible. There are some situations in which you might have to switch from 32-bit color to 16-bit color. For example, your monitor might fail, and you cannot afford a new one for a couple of weeks. As an alternative, you have a 10-year-old monitor in the garage that you hook up to your Windows Vista computer. The monitor cannot display very high resolutions and can display only a diminished number of colors, but this will be an acceptable solution until you can acquire a replacement monitor. To create a component like the one described, you would start by creating a new form that contains a PrintPreviewControl that would be used to display the document. By adding a Timer component, you can change the PrintPreviewControl.StartPage prop erty at regular intervals to cycle through the pages. One way of implementing page skipping would be to subclass the PrintPreviewControl and add a property that indi cated the step to take when skipping pages. Design a strategy for Group Policy implementation. Summary The SQL Server Agent -memberof GroupDN;... ROLLBACK TRAN; How would you work within BIDS to create SSIS project structures, packages, project data sources, and package connections What transformations would you use, and how would you implement the data flow that loads dimension tables What transformations would you use, and how would you implement the data flow that loads fact tables This section begins by stating a problem and then shows you how to troubleshoot it using one or more of the tools. More QR Code on .NET Articles you may be interested generate barcode vb.net: Using WinDiff in .NET Encoder DataMatrix in .NET Using WinDiff qr code generator vb.net 2010: Answers in visual basic.net Integration QR Code ISO/IEC18004 in visual basic.net Answers vb.net generate ean 128 barcode vb.net: Common Connectivity Problems in VB.NET Render QR Code in VB.NET Common Connectivity Problems zxing qr code c# example: Mail in C#.net Encode QR Code JIS X 0510 in C#.net Mail zxing c# qr code sample: Objective 3.2 in C# Render QR Code ISO/IEC18004 in C# Objective 3.2 upc internet: Using a Disconnected Model with ADO.NET in .NET Draw UPC Symbol in .NET Using a Disconnected Model with ADO.NET create barcode image using c#: Configure message compliance. Configure transport rules. in .NET Development Quick Response Code in .NET Configure message compliance. Configure transport rules. create qr barcode c#: Implementing and Conducting Administration of Resources in C#.net Deploy QR in C#.net Implementing and Conducting Administration of Resources qr code generator vb.net 2010: Using Profiler to Display Query Plan Information in VB.NET Incoporate QR Code ISO/IEC18004 in VB.NET Using Profiler to Display Query Plan Information create qr barcode c#: Configure RAID-5 Volumes in .NET Implement QR in .NET Configure RAID-5 Volumes .net barcode library: Note in .NET Writer Denso QR Bar Code in .NET Note free barcode generator asp.net c#: Getting and Setting Sensor Properties in visual basic.net Generator QR in visual basic.net Getting and Setting Sensor Properties create qr barcode c#: sole against the remote stand-alone servers, hence no way to alter their domain membership. in .NET Creation QR in .NET sole against the remote stand-alone servers, hence no way to alter their domain membership. vb.net code 39 generator in vb.net: Organize My Data: Libraries in Windows 7 in visual basic.net Generating QR Code JIS X 0510 in visual basic.net Organize My Data: Libraries in Windows 7 create 2d barcode c#: Lesson 2 in .NET Integration Quick Response Code in .NET Lesson 2 how to create qr code vb.net: C. Incorrect: Windows 2000 Professional workstations come with Terminal Services in .NET Creation qr-codes in .NET C. Incorrect: Windows 2000 Professional workstations come with Terminal Services barcode vb.net free: Using Service Recovery Options to Diagnose and in .NET Create barcode 128 in .NET Using Service Recovery Options to Diagnose and vb.net code to generate barcode: Review in .NET Creation PDF 417 in .NET Review c# qr code library: Configuring Network and Internet Connections in C#.net Integrated qrcode in C#.net Configuring Network and Internet Connections convert string to barcode c#: F01NS15 in .NET Implementation Quick Response Code in .NET F01NS15
http://www.businessrefinery.com/yc2/289/117/
CC-MAIN-2022-05
en
refinedweb
SYNOPSIS#include <sys/types.h> #include "lfc_api.h" int lfc_setratime (const char *sfn) DESCRIPTIONlfc_setratime set the replica last access (read) date to the current time and increments the counter of accesses to the replica. This function should be called everytime a file replica is accessed. - sfn - is the Physical File Name for the replica. RETURN VALUETh.
https://manpages.org/lfc_setratime/3
CC-MAIN-2022-05
en
refinedweb
{username} Short URLs or catchall (Facebook-style) Splash › Forums › PrettyFaces Users ›{username} Short URLs or catchall (Facebook-style) This topic contains 34 replies, has 5 voices, and was last updated by Christian Kaltepoth 9 years, 11 months ago. - AuthorPosts I’d like to rewrite “{username}” where username is a shortname (slug) of any valid mapped entity. However other paths still work (e.g.) So this rewrite acts more like a catchall, and if still not found then it passes to the next handler in the chain (ultimately giving a 404). I tried the following but got an infinite loop: <!– Slug –> <url-mapping id=”slug”> <pattern value=”/#{ slug : slugBean.slug }”> <validate index=”0″ validator=”#{slugBean.validateSlug}”/> </pattern> <view-id value=”#{slugBean.getViewPath}” /> </url-mapping> SlugBean.java : public String getViewPath() { return “/people/” + slug; } public void validateSlug(FacesContext context, UIComponent component, Object value) { log.debug(“Validating slug: {}”, value); try { Integer.parseInt((String) value); } catch (NumberFormatException e) { throw new ValidatorException(new FacesMessage(“Cannot parse “+ value), e); } } This is almost like but different than The best real-world example of this is{username} URLs Sorry, I missed where you said that. I see it now. That’s strange. Any chance you could post the rest of your pretty-config.xml, web.xml, and any annotations you’re using to configure PrettyFaces? Thanks, ~Lincoln Perhaps it would also be a good idea to give 3.3.3-SNAPSHOT a try. We recently fixed some issues that MAY be relevant to this. @lincoln, This is the non-working entire pretty-config as you requested: When I access, say /hendy.irawan, it goes into infinite loop like this: at org.apache.catalina.core.ApplicationHttpRequest.setAttribute(ApplicationHttpRequest.java:303) [jbossweb-7.0.7.Final.jar:] at org.apache.catalina.core.ApplicationHttpRequest.setAttribute(ApplicationHttpRequest.java:303) [jbossweb-7.0.7.Final.jar:] … All I need to fix is change the pattern here: <url-mapping id=”slug”> <pattern value=”/#{ slug : slugBean.slug }”> <validate index=”0″ validator=”#{slugBean.validateSlug}”/> </pattern> <view-id value=”#{slugBean.getViewPath}” /> </url-mapping> to here: <pattern value=”/slug/#{ slug : slugBean.slug }”> Now I can access both: * /people/hendy.irawan * /slug/hendy.irawan What I want is to have a catchall /#{slug} where it can “forward” to /people/#{slug} or /interests/#{slug} depending on the looked up slug. Thank you. I agree with @chkal. It looks like you might want to try 3.3.3-SNAPSHOT ~Lincoln After thinking a bit more about this “catch all” requirement I’m not really sure any more if something like this is currently possible with PrettyFaces. I think PrettyFaces identifies the mapping for an URL only using the <pattern> of the mappings (including the optional custom regular expressions for path parameters within the pattern). The validation happens at a much later time of the request processing (especially after the request has been forwarded to the viewId). The validation can currently only be used to abort processing of the request and prevent the execution of the URL action method and the page rendering. To be more specific, this is the order of execution: 1. Identify the mapping for the URL using the patterns 2. Forward the request to the viewId of the matching mapping 3. Enter the JSF lifecycle 4. Process the validators for the path parameters 5. Inject the values of the path parameters 6. Execute the page action 7. Render the page You see that the validation happens AFTER the request has been forwarded to the viewId of the mapping. Therefore there is currently no way to use some other mapping in case of a validation error because the the request has already been forwarded. Thoughts on this? Christian I believe you can also specify another “#{method.expression}” or “mapping:id” in the <validate onError=”…” /> element. @Christian: I guess we need to hook into #1 in your PrettyFaces lifecycle above. Or should I write my own servlet filter/listener? (after PrettyFaces, so will be handled when it fails before going to the 404). Yeah, you are right. I forgot about that. That’s possible too. But I don’t think this helps for the usecase ceefour describes, doesn’t it? I have one other idea but I’m not sure if this can work. You could try to use a custom rewrite processor like this: <rewrite match="/.*" processor="com.example.MyProcessor" redirect="chain"/> And this Processor implementation: public class MyProcessor implements Processor { public String processInbound(HttpServletRequest request, HttpServletResponse response, RewriteRule rule, String url) { // parse slug name from the URL String slug = parseUrl(url); // if it is a known people slug, forward to the correct view if( isPeopleSlug(slug) ) { return "/people/"+slug; } // no slug, just continue processing else { return url; } } } But as I said. That’s just an idea. I don’t know if it works. And you should definitively use 3.3.3-SNAPSHOT if you want to try this because we recently fixed some interaction issues between URL mappings and rewrite rules. I think this is an issue that Rewrite could solve. Perhaps it has solved it already. I don’t know. Essentially the problem is that that mappings/rules with path parameters overlap. Like in this example: <-- Simple mapping without path parameters <-- Simple mapping without path parameters <-- Mapping with path parameter: /#{username} The problem here is that whether “chkal” is a valid user name can only be checked at a very late point in time (validation phase). Does something like this work in Rewrite? Ah, well that should work with PrettyFaces as well, but yes, this most definitely works in Rewrite And… So you can see the order is what matters here, and the usage of the .isRequest() condition. This is a fairly complex example, but it shows that it works, and generally how to use many features. ~Lincoln Yeah, I see! Now as I think more about my example I think it should work with both PrettyFaces and Rewrite. You are completely right! However if I understood @ceefour correctly, his problem is a bit different. My example was misleading. Let me try to describe another example that is more similar to his use case. Imagine the following two mappings: /project/#{projectName} /user/#{username} So you have URLs like: /project/prettyfaces /user/chkal Now what @ceefour is trying to achieve is some kind of composite mapping: /#{name} Some code has to look into the database and find out if the name identifies a project or a user and then forwards/redirects to the correct URL: /chkal -> /user/chkal /prettyfaces -> /project/prettyfaces @ceefour: Is this description correct? I think something like this could be implemented with PrettyFaces 3.x either with a custom rewrite processor (like described above) or perhaps using dynaview? - AuthorPosts The forum ‘PrettyFaces Users’ is closed to new topics and replies.
https://www.ocpsoft.org/support/topic/httpdomain-comusername-short-urls-or-catchall-facebook-style/
CC-MAIN-2022-05
en
refinedweb
In this article you’ll learn how to get started with KendoReact. First, you’ll learn the installation steps necessary to get KendoReact up and running. Next, you’ll see how to use multiple KendoReact components by completing a short tutorial. And finally, you’ll learn about a few helping. Installation: Add KendoReact to a React app 1. Set Up the React Project The easiest way to start with React is to use create-react-app. To scaffold your project structure, follow the installation instructions. npx create-react-app my-app --use-npm cd my-app npm start or yarn create react-app my-app cd my-app yarn start Before you start playing with KendoReact, let's clean up the sample app a bit. Here is a list of suggested edits, with the resulting src/App.js code below: - src/App.js - Remove everything inside the App container div: <div className="App"> ... </div> - Remove the logo.svg import - Import {Component}in addition to React - Remove the contents of src/App.css - Delete src/logo.svg import React, {Component} from 'react'; import './App.css'; class App extends Component { render() { return ( <div className="App"> <h1>Hello KendoReact!</h1> </div> ); } } export default App; 2. Import the KendoReact CSS Styles KendoReact includes three gorgeous themes, which are all available as separate npm packages. The available theme packages are @progress/kendo-theme-default, @progress/kendo-theme-bootstrap and @progress/kendo-theme-material. Let’s take the Default theme and install it: npm install --save @progress/kendo-theme-default or yarn add @progress/kendo-theme-default Next, import the CSS file from the package in src/App.js. (Add this import before your existing App.css import.) import '@progress/kendo-theme-default/dist/all.css'; The KendoReact UI components are architected in such a way that the components themselves are not tightly coupled to a specific theme. While you need to include one of these three themes, or your own custom theme, this also allows you to change the look and feel by modifying a sass or CSS file, or even swap themes for your entire application by changing a single import. If needed, any additional custom styles can go in the empty src/App.css. 3. Using KendoReact Components KendoReact is a library of 100+ UI components. In this section, we’ll use one of those components, the Calendar, to show how easy it is to install and use KendoReact components in your applications. A first step to using any component is installing its package, and KendoReact is distributed as multiple npm packages, scoped to @progress. For example, the Calendar component is part of the @progress/kendo-react-dateinputs package. First, let's install the dateinputs package and its dependencies: npm install --save @progress/kendo-react-dateinputs @progress/kendo-react-intl @progress/kendo-licensing or yarn add @progress/kendo-react-dateinputs @progress/kendo-react-intl @progress/kendo-licensing Then we have to import it inside the component where it will be used: import { Calendar } from '@progress/kendo-react-dateinputs' Finally add the Calendar component to your markup, and voila—you have a fully functioning calendar in two lines of code! render() { return ( <div className="App"> <h1>Hello KendoReact!</h1> <Calendar/> </div> ); } Using the many other KendoReact components is just as easy as the Calendar—all you have to do is install the appropriate npm package, import the component, and use the component’s markup in your apps. As a final step to getting KendoReact up and running, let’s next look at how to handle licensing. 4. Activate Your Trial or Commercial License KendoReact is a professionally developed library distributed under a commercial license. Starting from version 4.0.0, to follow the tutorial below for an example of how multiple KendoReact components can work together. Tutorial: Integrate multiple KendoReact components KendoReact is a rich suite of many modular components. In this tutorial you’ll use three of these components, the Grid, the Window and the DropDownList, to build a small demo application. Before continuing with the tutorial, let’s first remove the Calendar from the page so that you again have a blank app to work with. 1. Add a KendoReact Data Grid The KendoReact Grid provides 100+ ready-to-use features, covering everything from paging, sorting, filtering, editing and grouping, to row and column virtualization and Excel export. In this section you’ll try out several of these features, but let’s start by installing, importing the component and adding some sample data. Install the Grid package and its dependencies: npm install --save or yarn add Next, import the installed components into your source code. Add the following to src/App.js: import { process } from '@progress/kendo-data-query'; import { Grid, GridColumn } from '@progress/kendo-react-grid'; Create a src/products.jsonfile and copy-paste this content from GitHub inside, then import it in src/App.js. import products from './products.json'; Add the code below to create a Grid bound to your list of products. (Add it right after the <p>that contains the DropDownList.) <Grid data={products}> <GridColumn field="ProductName" /> <GridColumn field="UnitPrice" /> <GridColumn field="UnitsInStock" /> <GridColumn field="Discontinued" /> </Grid> When your browser refreshes, you’ll see your first Grid! Pretty simple, but not quite real-world yet. To fill out this example, let’s use the Grid APIs to add the list of features below. Read through the features, and then grab the updated App.js code (below) to try the updated Grid for yourself. - Add a height style to the Grid to activate scrolling. - Add user-friendly column titles. - Format the numbers in the Price column. - Enable paging and sorting. This will require a few additions to the application code, explained below. - Display the boolean values in the Discontinued column as checkboxes. For this purpose, we will customize the table cell rendering via the cell property and a custom component. The Grid is databound to client-side data, so we will enable local data operations. This is how we do it: - Enable each data operation separately in the Grid declaration ( pageable={true}and sortable={true}). - Configure data operation settings and the initial state of the Grid data. For example: - The initial page ( skip) will be the first one. - The page size ( take) will be 10. - The Grid will be initially sorted by Product Name. - We will save all these settings in the App state as this.state.gridDataStateand apply them to the Grid in bulk with {...this.state.gridDataState}. - Define an onDataStateChangehandler. Its purpose is to update this.state.gridDataStateafter each user interaction. In turn, this will cause the Grid to refresh and display the expected data. - To display the correct Grid data, we will bind the Grid to the output of a function, rather than the productsarray directly. We will use the imported processfunction, which is part of the kendo-data-querypackage. - Finally, we will add Grid filtering via the DropDownList. To do that, we will use the existing handleDropDownChangefunction and add a filter descriptor to gridDataState. We also need to reset the page index ( skip) to zero, as the number of data items and pages will decrease. To try all this out, copy in this version of App.js, which has all these features implemented:, gridDataState: { sort: [ { field: "ProductName", dir: "asc" } ], skip: 0, take: 10 } } handleDropDownChange = (e) => { let newDataState = { ...this.state.gridDataState } if (e.target.value.CategoryID !== null) { newDataState.filter = { logic: 'and', filters: [{ field: 'CategoryID', operator: 'eq', value: e.target.value.CategoryID }] } newDataState.skip = 0 } else { newDataState.filter = [] newDataState.skip = 0 } this.setState({ dropdownlistCategory: e.target.value.CategoryID, gridDataState: newDataState }); } handleGridDataStateChange = (e) => { this.setState({gridDataState: e.dataSt> <Grid data={process(products, this.state.gridDataState)} pageable={true} sortable={true} {...this.state.gridDataState} onDataStateChange={this.handleGridDataStateChange} style={{ height: "400px" }}> <GridColumn field="ProductName" title="Product Name" /> <GridColumn field="UnitPrice" title="Price" format="{0:c}" /> <GridColumn field="UnitsInStock" title="Units in Stock" /> <GridColumn field="Discontinued" cell={checkboxColumn} /> </Grid> </div> ); } } class checkboxColumn extends Component { render() { return ( <td> <input type="checkbox" checked={this.props.dataItem[this.props.field]} </td> ); } } export default App; In this section you were able to add a robust grid to your application—complete with paging, filtering, and sorting—and you were able to do so using React APIs. Not a bad accomplishment for a few minutes' worth of work! Feel free to explore the KendoReact Grid documentation page to get a sense of just how many things the Grid can do. For now though, to wrap up, let’s look at one more powerful KendoReact component: the Window. 2. Add a KendoReact DropDownList Now lets add the KendoReact DropDownList and display all avaialbe categories of products. We already have the package installed as it is one of the Grid dependencies. We only have to import it. import { DropDownList } from '@progress/kendo-react-dropdowns'; We can create src/categories.json file and copy-paste this content from GitHub inside. We will use this data for the DropDownList. Now we have to import it: import categories from './categories.json'; Use the code below to bind a DropDownList to a list of categories. <p> <DropDownList data={categories} </p> The data property of the DropDownList points to an array of objects or primitive values. In this case, you’re using an array of objects, and therefore specify both dataItemKey and textField properties. You can also use the defaultItem property to display a hint for the users when no item is selected. The default item should have a field that matches the textField name. To show a little more of the DropDownList in action, update your code to use the version of src/App.js below: } handleDropDownChange = (e) => { this.setState({ dropdownlistCategory: e.target.value.Category> </div> ); } } export default App; This code additionally renders the ID of the selected category next to the DropDownList. You do this by defining a dropdownlistCategory field in the application state and implementing an onChange handler to set it. Now that you’ve seen what a basic KendoReact component looks like, let’s next implement something more complex with the KendoReact Grid. 3. Add a KendoReact Window The products array contains some fields which are not displayed in the Grid. In this section, you’ll use the KendoReact Window to display those additional product details when users select a Grid row. This will give us a chance to see a very common interaction with the KendoReact Data Grid: responding to user interactions and displaying information from the Grid in other React components. Here are the required steps: Install the required packages and import the Window component: npm install --save @progress/kendo-react-dialogs @progress/kendo-licensing or yarn add @progress/kendo-react-dialogs @progress/kendo-licensing import { Window } from '@progress/kendo-react-dialogs'; Then, define new windowVisibleand gridClickedRowfields in your application state. state = { // ... windowVisible: false, gridClickedRow: {} } Next, add a row click handler to the Grid. <Grid onRowClick={this.handleGridRowClick}> </Grid> After that, add the handleGridRowClickfunction below, which will set the windowVisibleflag to true, and save the Grid data item in the application state. You’ll use the data item values to render the Window's content. handleGridRowClick = (e) => { this.setState({ windowVisible: true, gridClickedRow: e.dataItem }); } Next, add the following Window declaration. (Add it immediately after the </Grid>.) Notice how the Window will be rendered only if the windowVisibleflag value is true. {this.state.windowVisible && <Window title="Product Details" onClose={this.closeWindow} height={250}> <dl style={{textAlign:"left"}}> <dt>Product Name</dt> <dd>{this.state.gridClickedRow.ProductName}</dd> <dt>Product ID</dt> <dd>{this.state.gridClickedRow.ProductID}</dd> <dt>Quantity per Unit</dt> <dd>{this.state.gridClickedRow.QuantityPerUnit}</dd> </dl> </Window> } Finally, add the following Window close handler, which will set the windowVisibleflag to falsewhen the user closes the Window. closeWindow = (e) => { this.setState({ windowVisible: false }); } With this code in place, try tapping on a row in the grid. You should see a custom window appear with additional product information. Once again, note how simple this functionality was to implement. With KendoReact, you get a collection of React components that are easy to drop in and solve hard problems—in this case, building a customizable cross-browser-friendly Window. That’s the power of KendoReact! You can learn more about the Window component and what it can do on the KendoReact Window documentation page. 4. Complete get you excited about becoming more a productive React developer and building complex UI in a short time through our professional UI library. Let’s look at a few more tips and tools that can help get started with KendoReact. Resources 1. TypeScript Support All KendoReact components are natively written with TypeScript and provide all of the benefits of TypeScript, like typings, intellisense and many others. We have made the full getting started example available in TypeScript and you can check it out here. 2. VS Code Extension To help you create projects even faster we have introduced the Kendo UI VS Code Template Wizard. To learn more about this awesome extension please check Introducing the Kendo UI Template Wizard for Visual Studio Code. 3. UI Kits for Figma KendoReact comes with three UI Kits for Figma: Material, Bootstrap, and Kendo UI Default. They provide the designers of your application with a building block that matches the UI components available in the KendoReact suite. Having matching building blocks guarantees the smooth implementation of the design. Sample Applications If you want to see more KendoReact components in action, please check our cool and interesting sample applications: Next Steps We are sure that you are looking for more—browse the components section and discover the amazing features that KendoReact brings to the table. Happy coding!
https://www.telerik.com/kendo-react-ui/getting-started/
CC-MAIN-2022-05
en
refinedweb
Student's t-distribution. Inherits From: Distribution, AutoCompositeTensor tfp.distributions.StudentT( df, loc, scale, validate_args=False, allow_nan_stats=True, name='StudentT' ) This distribution has parameters: degree of freedom df, location loc, and scale. Mathematical details The probability density function (pdf) is, pdf(x; df, mu, sigma) = (1 + y**2 / df)**(-0.5 (df + 1)) / Z where, y = (x - mu) / sigma Z = abs(sigma) sqrt(df pi) Gamma(0.5 df) / Gamma(0.5 (df + 1)) where: loc = mu, scale = sigma, and, Zis the normalization constant, and, Gammais the gamma function. The StudentT distribution is a member of the location-scale family, i.e., it can be constructed as, X ~ StudentT(df, loc=0, scale=1) Y = loc + scale * X Notice that scale has semantics more similar to standard deviation than variance. However it is not actually the std. deviation; the Student's t-distribution std. dev. is scale sqrt(df / (df - 2)) when df > 2. Samples of this distribution are reparameterized (pathwise differentiable). The derivatives are computed using the approach described in the paper Michael Figurnov, Shakir Mohamed, Andriy Mnih. Implicit Reparameterization Gradients, 2018 Examples Examples of initialization of one or a batch of distributions. import tensorflow_probability as tfp tfd = tfp.distributions # Define a single scalar Student t distribution. single_dist = tfd.StudentT(df=3) # Evaluate the pdf at 1, returning a scalar Tensor. single_dist.prob(1.) # Define a batch of two scalar valued Student t's. # The first has degrees of freedom 2, mean 1, and scale 11. # The second 3, 2 and 22. multi_dist = tfd.StudentT(df=[2, 3], loc=[1, 2.], scale=[11, 22.]) # Evaluate the pdf of the first distribution on 0, and the second on 1.5, # returning a length two tensor. multi_dist.prob([0, 1.5]) # Get 3 samples, returning a 3 x 2 tensor. multi_dist.sample(3) Arguments are broadcast when possible. # Define a batch of two Student's t distributions. # Both have df 2 and mean 1, but different scales. dist = tfd.StudentT(df=2, loc=1, scale=[11, 22.]) # Evaluate the pdf of both distributions on the same point, 3.0, # returning a length 2 tensor. dist.prob(3.0) Compute the gradients of samples w.r.t. the parameters: df = tf.constant(2.0) loc = tf.constant(2.0) scale = tf.constant(11.0) dist = tfd.StudentT(df=df, loc=loc, scale=scale) samples = dist.sample(5) # Shape [5] loss = tf.reduce_mean(tf.square(samples)) # Arbitrary loss function # Unbiased stochastic gradients of the loss function grads = tf.gradients(loss, [df, loc, scale]). Additional documentation from StudentT: The mean of Student's T equals loc if df > 1, otherwise it is NaN. If self.allow_nan_stats=True, then an exception will be raised rather than returning NaN.. Additional documentation from StudentT: The variance for Student's T equals df / (df - 2), when df > 2 infinity, when 1 < df <= 2 NaN, when df <=__()
https://www.tensorflow.org/probability/api_docs/python/tfp/distributions/StudentT?hl=nb-NO
CC-MAIN-2022-05
en
refinedweb
crypto deverictives trading in the usa Singapore bitcoin trading fees comparison South Africa crypto trading platform no fees South Africa bynari Singapore fx lite for mt4 binary options trading Singapore binary option trader forum South Africa simona weinglass binary options South Africa the best place to invest in bitcoin Malaysia best day trading platform with paper trading Singapore investing & trading in crypto South Africa bitcoin crypto forex binary trading Malaysia chicago firm drw to open bitcoin trading desk India learn forex trading before bitcoin trading South Africa binary options refund India forex grand trading platform expalanation South Africa trading crypto correlations India volume price crypto trading bot Singapore option league broker Malaysia bitcoin investment article South Africa crypto margin trading for us residents Singapore bitcoin investment ideas Malaysia efutures trading platform Singapore what is the difference between binary options and forex Malaysia invest in bitcoin technology Singapore should i invest in bitcoin september 2020 India ema strategy for binary options Malaysia where is bitcoin currently trading South Africa crypto trading under 18 Singapore best way to invest in bitcoin from phone India bitcoin investment trust prospectus India bitcoin investment website script Singapore top ten binary options sites India trading bitcoin against eth India cfd crypto trading India crypto trading bot cryptopia India binary options legal India when does robin hood start trading bitcoin Malaysia binary options jim South Africa top bitcoin trading platforms Singapore best btc trading platform Malaysia binary options to stock trading Malaysia trading binary options: strategies and tactics, second edition India all i need to know about binary options South Africa binary options chart setup South Africa binary options south africa Singapore best trading platform review South Africa best us trading bitcoin India crypto day trading success stories South Africa olymp trade binary options app Singapore bitcoin live trading in india Singapore bitcoin day trading indicators Singapore the next bitcoin type investment 2019 India us trading platform South Africa mt4 binary options demo Malaysia crypto trading tips twitter South Africa bitcoin investment in qatar Malaysia bitcoin trading site shut down Singapore bitcoin investment trust registered shares South Africa binary options robot wiki South Africa day trading platform lagging India is bitcoin trading taxed Malaysia intro to bitcoin trading India is it right time to invest in bitcoin India download binary option shark ye Malaysia 1 minute binary options indicators 2019 South Africa double up binary options Singapore multi exchange crypto trading platform Singapore binary options trading methods South Africa free binary option tools Malaysia best legit binary options trading platforms South Africa trading platform that can buy at your desired price quora India trading bitcoin best setting bolinger bands 1 minute scalping Malaysia can you make a living day trading crypto Malaysia are binary options legal in singapore South Africa bitcoin investment numbers South Africa dragons den investment into bitcoin India best binary options guide Singapore momentum binary options India day & after hours hours trading platform Singapore crypto trending trading meetup Singapore free download trading platform South Africa cursos gratuitos de trading bitcoin South Africa comission free trading platform India binary cent reviews Malaysia non deposit binary options South Africa free demo binary options platform Malaysia best monero trading platform South Africa binary options pro signals performance India th investing bitcoin Singapore cfibo binary options South Africa binary options ervaringen South Africa binary options advice Singapore how much should you invest in bitcoin stock Singapore bitcoin trading master simulator review youtube India how to make money trading bitcoin online Malaysia what is the best day trading platform for mac Malaysia free binary options course Singapore señales para hoy bitcoin trading Singapore bitcoin trading hours in usa Singapore stock trading using bitcoin India binary options israel news India who really making money nadex binary options Singapore best cryptocurrency trading app buy bitcoins Malaysia binary options trading academy Singapore aurora cannabis trading platform Singapore insider trading crypto South Africa nadex verses raceoption for trading binary options India como investir bitcoin brasil Singapore can you make money with bitcoin trading India chase stock trading platform Malaysia the next bitcoin type investment 2019 India binary options probability calculator India binary options indicator 95 accurate India player told financial advisor to invest in bitcoin Singapore when i win on binary options whose money is thst Singapore crypto trading volume my month Singapore what schools are invested in bitcoin India how to make money day trading crypto step-by-step binary options trading course ebook India best oil futures trading platform South Africa best binary options broker for nigeria Singapore binary options via olymp trade South Africa guide to algorithmic crypto trading India bitcoin binary Malaysia invest in bitcoin now reddit Singapore trading platform diagram South Africa risks in investing in bitcoin South Africa comparing different bitcoin trading platforms India ripple bitcoin trading symbol India binary option delta increase India professional trading strategies: what real traders need to succeed South Africa using macd and bollinger bands for binary options hourly trade India bitcoin trading through wechat china South Africa why do some states not allow bitcoin trading India mr. millionaire binary options Singapore best online trading platform for day traders veterans who invest in binary options Singapore non binary option employment california South Africa how to invest long term in bitcoin Singapore how to make money trading bitcoin day 3 South Africa best 5 minute binary options indicator Singapore the best bitcoin trading site India investing in bitcoin guide India best open source trading platform South Africa is binary options a good investment Malaysia free bitcoin trading Singapore investing in bitcoin funny India binary options us tax laws South Africa if you invested in bitcoin in 2020 India best crypto trading bot for beginners Malaysia best binary options review sites Malaysia how to trade bitcoin on nadex binary options India instant trading bitcoin game Malaysia i want to invest 1000 in bitcoin South Africa bitcoin trading chart history South Africa python github algorithmic trading crypto India earn free bitcoin daily with no investments South Africa how much bitcoin do i invest Singapore 60 second binary options review South Africa bitcoin trading united states Malaysia 60 second binary options mt4 broker Singapore which exchanges are trading bitcoin cash Malaysia trading crypto currency with vpn India shiva krishnan binary options Malaysia youtube bitcoin investment platforms Malaysia best binary option indicator mt4 download South Africa bitcoin trading with mt4 for usa India four markets binary options Malaysia how do binary options pay India are binary options taxable in australia Singapore binary options trading compaines India how mych can you earn trading crypto vurency South Africa binary options arrow tradeview India binary options trading signals affiliate Singapore investopedia trading platform South Africa funny cartoon about crypto trading Singapore robinhood crypto trading down Malaysia what is the lowest amount to invest in bitcoin India make bitcoins daily investment binary option recovery specialist India can you qualify as daytrader with irs trading bitcoin Singapore binary options market pull strategy South Africa what are the symbols for binary options South Africa best trading account for bitcoin South Africa bitcoin wealth auto trading system Singapore how many people invest in bitcoin South Africa binary options any good India possible to hedge a nadex binary option Singapore hehmeyer trading crypto Singapore spotoption trading platform Singapore what is bitcoin and how to invest in it hardy frame hfx price South Africa dukascopy binary options spread Singapore bitcoin hyip script investment daily interest bitcoin trading on etrade Malaysia bitcoin inception investment value South Africa best tools for day trading crypto Malaysia best predictive trading software crypto India how much is the minimum you can invest in bitcoin Singapore is it too late to invest in bitcoin now India binary options strategy system India bitcoin trading volume by day South Africa does optionsxpress offer binary options Singapore crypto trading training India crypto ma trading strategy Malaysia bitcoin pools firms invest India investing bitcoin index Malaysia impulse signal binary options India bitcoin options trading reddit first binary option отзывы South Africa binary options 5 minutes ea Malaysia investing on bitcoin trading wallet to buy India social trading platform South Africa education i really need to be successful at trading 5 minute binary options India quartz a guide to paying taxes on bitcoin investments India top bitcoin investment sites 2016 South Africa l7 trading platform South Africa does buy mean yes in binary options Singapore bitcoin mining investment scam Singapore static replicatin of binary options Singapore trading platform that costs 400$ for 2 years South Africa express trading technology bitcoin.de Singapore iq option us traders Malaysia import crypto trading data into sheets for free Singapore binary option price action pdf South Africa binary option strategy 5 min South Africa trading platform source code South Africa fidessa trading platform delivery test questions Singapore binary option payoff function India binary option trade and bitcoin mining mark donald India trading platform at millennium trust India too late invest bitcoin Singapore did mark cuban invested bitcoin India right time to invest in bitcoin Malaysia bitcoin good investment or not Singapore crypto trading simulator with technical indicators Malaysia fidelity to start bitcoin trading India best trading platform forex for beginners usa Singapore trading crypto mining for ad blocking South Africa too late to invest in bitcoin India day trading bitcoin with coinbase South Africa quant crypto trading platform South Africa currency option broker India itm binary options alerts Malaysia best currency to invest in bitcoin Singapore virtual trading platform us South Africa new bitcoin similar investments India ct option binary trading South Africa binary option is in usa South Africa charles scwab trading platform Malaysia ehy invest on crypto other than bitcoin South Africa best bitcoin trading paypal South Africa eu regulated binary options brokers Singapore sample options trade South Africa paccoin is not trading to bitcoin Singapore multilateral instrument 91-102 prohibition of binary options India best binary options affiliate programs Singapore trading viewer bitcoin Singapore trading binary options strategies and tactics ebook Singapore crypto trading chat room India iq binary options strategy 2020 Singapore ghost binary options India dark pool stock trading platform Singapore 24 option.com India bianery India crypto trading ewallet India difference between investing and trading bitcoin Singapore zenbot crypto trading South Africa crypto coin trading cheap site India richard branson bitcoin trading platform India what is double up in binary options Malaysia binary options minimum investment India binary options screenerz South Africa emoney invest bitcoin Singapore best crypto day trading platform reddit India awesome binary options strategy India binary options watchdog copy buffett India bitcoin forex cfd trading Singapore best binary options signals com Malaysia what are binary options? India binary options venezuelan currency trading Singapore crypto tradings hiring manager India who is successfully algo trading bitcoin Singapore broker binary option terbaik 2019 Malaysia 3 binary options trading strategies for beginners India learn how to do binary options South Africa working strategies on binary options India invest in blockchain without bitcoin South Africa td bitcoin trading desk Malaysia best binary traders bitcoin trading hoax trading futures Malaysia what is a career in binary option India where can i trading bitcoin in usa Singapore how much money do you have invested in bitcoin India trading in bitcoin for cash Malaysia best bitcoin trading days South Africa bitcoin trading tools Malaysia fibonacci trading bitcoin Malaysia trading platform and "binary options trading signals scam" Singapore best app for bitcoin trading in india Malaysia como hacer trading con bitcoin pdf binary trading app Singapore binary options trading strategies for beginners pdf South Africa bitcoin trading without transation fees South Africa automated binary options trading South Africa touch or no touch binary options South Africa make money trading bitcoin reddit South Africa how little can i invest in bitcoin Malaysia binary options that accept usa players Singapore banks warned about binary option scam South Africa first rule of investing dont invest in bitcoin South Africa strategy runner trading platform reviews Malaysia binary options range strategy South Africa adx strategy for binary options Malaysia binary options strategies for directional and volatility trading Singapore binary options trading using price action Singapore e futures international trading platform India legitimate bitcoin investment uk Malaysia crypto junkies day trading mt4 trading platform in bulgaria Singapore white paper on bitcoin ark investment Malaysia if you had invested in bitcoin Singapore etf investing in bitcoin South Africa how to make money from crypto trading Singapore where to trade binary options usa Singapore binary options trading demo account without deposit Malaysia is it worth investing in bitcoin right now Singapore how safe is an invest in bitcoin Singapore delta trading group complaints Malaysia how to trade forex binary options successfully South Africa how to start a binary options company Malaysia bitcoin investment trust is an open-ended investment fund Malaysia binary options millionaires India web based stock trading platform Malaysia should i use mt4 to trading platform Malaysia binary options minimum investment India best strategy for binary options Singapore best crypto trading platform with api South Africa resolute crypto trading calgary Malaysia binary option prediction Malaysia globes binary options India binary options official site Singapore how to trade 15 minute binary options South Africa binary option robot best option trading site Singapore is ripple a better investment than bitcoin India can i invest 1000 rs in bitcoin Singapore binary options affiliate commission Malaysia bitcoin trading platform cdax bdax Singapore how do i dowload ninja trading platform India best stock trading platform for short term trading India trading bitcoin foxnews South Africa start a new crypto currency trading platform Malaysia quantitative trading platform India trading bitcoin menurut islam Malaysia is crypto bot trading profitable India successful 60 second binary options strategy India binary options assets index Singapore bitcoin invest now or wait Singapore best binary options platform 2014 Malaysia oanda copier from mt4 to desktop trading platform India schwab trading platform setup Malaysia what is the best trading platform for cryptocurrency India should i invest 10000 in bitcoin South Africa iq binary options usa Singapore binary options calendar India free bitcoin trading charts Singapore scottrade trading platform Malaysia how to invest in bitcoin and ethereum Malaysia hong kong trading platform Singapore best legit bitcoin investment site India option indonesia.com Singapore global advisors bitcoin investment fund video youtube Singapore trade genius binary options Singapore overseas trading platform scams austrailia lawyer India do not trade binary options South Africa tradency mirror trading platform Malaysia best legit binary options trading platforms Singapore top 5 crypto trading exchanges Singapore aurora trading platform скачать India binary options arbitrage Singapore bitcoin trading affiliate Singapore bitcoin cloud mining vs trading Malaysia striker9 pro binary options trading system India safest way to invest in bitcoin uk Singapore learning about day trading crypto Malaysia bitcoin trading workshop Singapore bitcoin commodity vs trading Singapore binary options attorneys Malaysia asic regulated binary options brokers Singapore merrill edge stock trading platform Singapore how to start otc trading desk for bitcoin software Singapore crypto trading chicago South Africa qual moeda bitcoin investir 2018 South Africa key binary options South Africa bitcoin trading rich Malaysia russia bitcoin investment Malaysia finpro trading bitcoin Singapore titan bitcoin trading South Africa bitcoin exchange high frequency trading India living off my bitcoin investments South Africa best indicators to be successful in binary options Malaysia what is rvi binary options Malaysia tools of trade meaning Malaysia keep investing in bitcoin Malaysia 10 minute millionaire scam Singapore 60 seconds binary options strategy 2014 Malaysia binary options daily Malaysia binary tree print options South Africa how to read bitcoin trading South Africa roland wolf trading platform India ichimoku trading platform Singapore bitcoin investment products South Africa former marine harvest exec plans fundraising for trading platform Singapore bitcoin trading offices Malaysia trade binary options on bitcoin to usd India automated bitcoin trading platform dragons den Malaysia crypto currency oss trading platform India binary options trading times Singapore how to know when to invest in bitcoin Singapore binary options or penny stocks Singapore fbi binary options warning India should you join binary option South Africa binary options israel companies India the best plan investment bitcoin Singapore bitcoin investment co-op Malaysia binary options trading strategy 60 seconds South Africa comprehensive guide to recover money lost to binary options India best crypto futures trading India why bitcoin trading was not halted on coinbase Malaysia bitcoin trading value today South Africa bitcoin trading business opportunity Malaysia binary options system best day trading charts India rbc crypto trading platform India investing in bitcoin long term South Africa how to play options Malaysia systematic trading platform Singapore best day trading futures trading platform Malaysia binary option broker ratings India autobot crypto trading India can i really make money trading binary options Singapore new trading platform architecture ntpa Malaysia guaranteed binary options strategy South Africa binary options srategyquant South Africa edtrade trading platform India how to use adx indicator in binary options South Africa how to live of bitcoin trading India open source crypto trading bot reddit India google invest in bitcoin South Africa high frequency trading platform occean Malaysia should i invest 500 in bitcoin Singapore bitcoin trading group Malaysia i invested in bitcoin in 2010 India binary options that accept paypal 2020 Malaysia top binary options trading platforms Malaysia fusion stock trading platform Malaysia launched bitcoin trading services India invest in bitcoin ebook Malaysia online binary options trading platform India binary options legal Singapore compare option trading platform prices South Africa bitcoin trading in nigeria South Africa nadex binary options brokers Malaysia best bitcoin trading platform europe Singapore bitcoin investment sites list South Africa binary options mobile trading Malaysia barron's trading platform reviews 2015 Singapore largest options exchange South Africa bitcoin iota trading fee profit calculator Singapore best crypto trading platform for new zealand Malaysia future of investment in bitcoin chicago stock exchange bitcoin trading India bitcoin trading strategy python India broker dealer trading platform Malaysia nadex trading platform tools South Africa investing everything in bitcoin reddit binary options that are not scams binary options full time Malaysia top 10 binary options signals providers Singapore best online forex trading platform Malaysia why do you invest in bitcoin Singapore wwd tour's binary options trading course South Africa the underlying investment thesis of bitcoin South Africa how to invest in bitcoin ethereum reddit Singapore bitcoin gold future trading India crypto trading red candles Malaysia can one be consistent trading 5 minute binary options Singapore forex investopedia South Africa modern forex trading platform Singapore thinkorswim trading platform stop order and limit sell order at the same time India bitcoin trading news live India us binary options brokers 2020 reasons for investing in bitcoin India when will it be too late to invest in bitcoin South Africa is an electronic trading platform the same as an exchange India quartz bitcoin invest 1 South Africa can losses on bitcoin investments be deducted Malaysia robo de opções binarias gratis iq option India binary options start up business South Africa day trading crypto is hard Singapore can you invest in bitcoin cash Singapore regulated & legal for us residents nadex binary options India binary options real time graphs South Africa best investment options gold vs bitcoin vs stocks India best us trading platform Singapore how to invest in bitcoin revolution South Africa investing in crypto mining of bitcoins a scam India live bitcoin trading signals Singapore is cantor binary options accepting us customers South Africa highest earning trading bitcoins Malaysia what are the benefits of investing in bitcoin India lightning trading platform South Africa binary options trading signal providers can we invest 1000 rs in bitcoin Malaysia cheap binary options signals South Africa bitcoin cutrent trading South Africa best crypto trading wallet India taxes invovled in crypto day trading Singapore otc trading platform Singapore making a living out of binary options stocks and shares trading platform Malaysia assets international complaints India list of binary options trading platforms India quora day trading crypto South Africa how to trade 60 second binary options profitably South Africa colmex trading platform India is investing in bitcoin legal in india Singapore crypto currency codecanyon trading script India good platform for bitcoin trading carts South Africa ally invest bitcoin Singapore live bitcoin trading show South Africa best online bond trading platform South Africa what is binary option trading scam Singapore how to invest invest in bitcoin South Africa apps with binary options South Africa icon crypto krw trading India binary trading uk India response trading platform Malaysia global trading solutions llc bitcoin South Africa best bitcoin trading platform philippines Singapore binary options illegal in canada Malaysia github crypto trading bot site reddit.com Singapore bitcoin profit trading Singapore list of best binary options brokers India free forex binary options trading system India malaysia online trading platform Singapore should i keep investing to bitcoin Malaysia what is rvi binary options South Africa america's trading platform wiki Singapore build a binary options website invest bitcoin 24 hours India cmc binary options India using price action to trade binary options India never too late to invest bitcoin India advanced guide to binary options Singapore imagej binary options iterations Singapore crypto asian trading times Singapore start trading bitcoin today India algo binary options Malaysia binary options money management pdf South Africa tiger trading platform India profitable crypto trading bot Malaysia crypto trading volume my month South Africa crypto trading volume 2018 Malaysia bitcoin trading stock exchange Singapore bitcoin trading volume by country 2018 South Africa crypto bridge trading volume South Africa scanner binary option South Africa wave runner crypto trading software Malaysia fc stone trading platform Singapore receive seed invest bitcoin Singapore best spreads for trading crypto cheapest fees day trading platform Malaysia automated binary options trading signals South Africa invest bitcoins india South Africa binary options under 18 Malaysia crypto trading millionaires Singapore live bitcoin trading server Malaysia is bitcoin a long term investment binary option chart to use how much to trade binary options India best currency to trade in binary options Malaysia binary options journaling software Malaysia como hacer operaciones binarias en iq option en estados unidos Singapore electron flexibility trading platform South Africa i want to invest in bitcoin uk Malaysia arbitrage trading bitcoin india Singapore binary options that accept paypal South Africa how to trade binary options in the uk India bitcoin investment fail Singapore do banks trade binary options South Africa top 10 bitcoin trading sites South Africa green room academy binary options Malaysia what is a binary call option Singapore how to set up bitcoin trading account Singapore bitcoin trading jobs london Singapore largest volume bitcoin trading India crypto trading advisor India what is bitcoin and how do you invest in it Singapore does binary option really work Singapore swing trading crypto reddit Singapore is it wise to invest in bitcoin Singapore how to use binary options indicators India software for bitcoin trading Malaysia how to get your money from binary options Singapore 2 minute binary options South Africa crypto trading bot machine learning Malaysia how to make money trading crypto currencies South Africa best stock trading platform 2016 India how many trades in a day in binary options India structured credit trading platform Singapore bitcoin suisse trading desk India lightspeed trading platform alerts India us citizen trading bitcoin futures with a regulated broker Malaysia best android forex trading platform Singapore sma binary options binary option broker malaysia Malaysia trading terms illegal trading crypto Singapore fidelity investments and bitcoin India are there any legit binary options Singapore what is the bitcoin investment trust Malaysia can i trading crypto currencies in the usa Malaysia define binary options market South Africa binary trading system Malaysia best way to invest 3000 in bitcoin Singapore discord bitcoin trading room Malaysia litecoin vs bitcoin forex trading account funding South Africa pro trader strategies review Malaysia trading bitcoin usa weekends India how safe is an invest in bitcoin Malaysia day & after hours hours trading platform Malaysia best youtube crypto trading phiakone South Africa binary options pro signals pdf India best australian binary options South Africa wallstreet trading platform India jane wayne binary options India how to trade binary options successfully by meir liraz Malaysia how to invest ira money in bitcoin South Africa how to use awesome oscillator in binary options South Africa free binary options indicator 95 accurate South Africa how many on schwab trading platform nadex.com Singapore trading platform in dubai Malaysia bitcoin futures and options trading platform Malaysia commodity futures trading commission bitcoin futures data Singapore bitcoin trading tips reddit South Africa like investing one's life savings in bitcoin crossword clue Malaysia binary options online university South Africa what is binary options fraud Singapore forex trading vs bitcoin trading Malaysia get rich quick binary options Malaysia is bitcoin a good way to invest your money Singapore einstein buy bitcoin free cryptocurrency trading Malaysia pay taxes with nadex binary options South Africa binary option video investopedia India practice stock trading platform Malaysia elijah oyefeso binary options Malaysia binary options industry scam Singapore swing trading crypto- stratagy Singapore how to make money with forex binary options South Africa nadex trading platform tools Malaysia what trading platform does motley fool use India greeks invest in bitcoins Singapore new binary options brokers 2020 South Africa индикатор без перерисовки binary option arrows Malaysia altilly crypto trading market list India no fee crypto trading India what forex trading platform is legal in the usac South Africa bitcoin trading & Malaysia which investment banking have crypto trading South Africa if you invested in bitcoin in 2010 Singapore investing in bitcoin in a bad idea India investing money in bitcoin trackid sp-006 Malaysia crypto trading signals bundle Singapore binary options osc South Africa charles schwa online trading platform Malaysia binary option live signal service Singapore best obline trading platform canada South Africa marijuana bitcoin investment South Africa paper trading platform example India bitcoin day trading boca raton South Africa signals united scam Singapore options trading bot India people who have lost money on binary options South Africa cheapest overall trading platform online South Africa no loss binary option indicator free download India panda binary options Malaysia what year was the year to invest in bitcoin South Africa tablet trading platform South Africa et binary options India crystal trading platform crypto South Africa where to invest 0.0001 bitcoin South Africa is it safe to invest in bitcoin in 2018 India best binary options brokers sri lanka India best options to buy South Africa best options trading platform reddit Singapore safe binary options trading strategy Singapore bitcoin cash as an investment Singapore cboe binary options spx South Africa binary options teacha review Malaysia binary options brokers list Singapore best trading platform for e currency Singapore bitcoin futures trading view South Africa former marine harvest exec plans fundraising for trading platform India python build svm for binary options crypto trading team South Africa investing money in bitcoin trackid sp-006 South Africa trading and selling bitcoin South Africa what are nadex binary options Singapore how to play binary options Singapore binary options traders choice indicator South Africa bitcoin investment stories Malaysia icon crypto krw trading India crypto trading chat telegram South Africa best legit binary options Singapore bitcoin investing classes Malaysia stock trading platform design Malaysia trading bitcoin to friends coinbase app Singapore ainda vale a pena investir em bitcoin 2019 India should i trade binary options in the night Malaysia binary options strategy iq option Singapore where to trade binary options usa India margin trading bot for crypto currencies Singapore open a binary option account South Africa dubai bitcoin trading India cfd crypto trading South Africa is there a free forex trading platform Malaysia gold trading platform 40 weeks Malaysia what is a stock pair trading platform India crypto trading bot code Malaysia iq option binary trading tips South Africa country that allow binary option robot Malaysia bitcoin trading signals telegram South Africa youtube bitcoin live trading India best binary options software reviews Malaysia gail mercer trading nadex binary options keeping it simple strategies South Africa zerodha trading platform South Africa how to win binary options binary for beginners Malaysia bitcoin trading sites australia South Africa ask options binary India binary options fixed odds financial bets hamish raw Malaysia binary option edge backtest South Africa best margin trading crypto South Africa binary options trading fundamental basics 101. part 1 Singapore easy bitcoin trading India city option binary Malaysia social signals binary options Singapore binary options trading nifty India binary options bot for mac South Africa will bitcoin trading be open on christmas day South Africa how report taxes in binary options Malaysia investing.com in bitcoin India teach me to trade binary options bitcoin market trend trading software South Africa mark zuckerberg investment in bitcoin India day trader trading platform Singapore invest 100 dollars into bitcoin South Africa binary option trade meaning in hindi Malaysia bittrix trading platform South Africa 24 crypto trading South Africa binary option 英文 South Africa uk options trading platform South Africa trading platform for young people Malaysia bitcoin trading php code in github Singapore cboe binary options s&p 500 index India construction mertial trading platform India invest in bitcoin 10.00 dollars get 10 000 South Africa monthly investing in bitcoin India how to create an online trading platform Singapore capital one binary options Singapore colmex trading platform price Malaysia trading platform better than thinkorswim backtest software Malaysia binary options using stochastics India binary options audio version South Africa plateforme de trading crypto South Africa vanguard options trading platform South Africa trading platform open energy trading utility Singapore the rock trading company bitcoin South Africa crypto trading algortihim Singapore trading platform for mac South Africa nader binary options South Africa binary options watchdog insured profits Malaysia day trading crypto tutorial India become a binary options broker India best ema and sma for 5 minute binary options South Africa does thinkorswim have binary options India binary options allowed in usa Singapore binary options strategy bots prt trading platform Malaysia bitcoin gold investing.com South Africa best robotic trading platform South Africa teachaz binary options Malaysia binary option pricing Malaysia can i invest in bitcoin cash Malaysia write crypto trading bot South Africa how to invest into bitcoin 2.0 South Africa how to get money to invest in bitcoin Singapore cash fx trading platform how to build a trading platform for cryptocurrency Malaysia what is the best bitcoin trading site Singapore binary options.com.au Singapore trading platform at millennium trust Singapore crypto trading discord India day & after hours hours trading platform Malaysia binary options on iml India communtiy crypto trading platform Singapore first binary option service review India best way to invest in bitcoin cash Singapore u.s accepted binary options robots South Africa binary options emails Singapore what trading platform is whole foods traded on touch no touch binary option brokers Malaysia binary options guardian South Africa binomo usa India como investir em bitcoin cash Singapore 60 second binary options brokers for u.s. traders South Africa how bank in hong kong wire money to online trading platform mike auto trader binary options Malaysia binary options demo account low deposit Malaysia best forex web trading platform Singapore impact of futures trading on bitcoin South Africa investing in bitcoin gambling sites Singapore binary options trading systems that work South Africa trading view crypto tickers South Africa api algo trading crypto decentralized exchange India 60 seconds binary options strategy download India bitcoin trading bot codecanyon Singapore best forex trading platform for wimdows India bitcoin trading will stop trading hours ahead of fork Singapore how to trade nadex binary options Singapore e-trade bitcoin trading South Africa how does the cash app bitcoin investment work Singapore cbot binary options South Africa best robotic trading platform South Africa investing in crypto bitcoin Malaysia bitcoin is trading in real-time South Africa best way to invest in bitcoin in canada Singapore best place to invest in bitcoin South Africa how little can you invest in bitcoin South Africa minimum investment into bitcoin India conseil trading crypto monnaie South Africa roland wolf best trading platform Malaysia belajar trading bitcoin pemula Singapore binary options.com.au Singapore wealthclvb trading platform Malaysia algobit binary options South Africa binary options training london South Africa binary option delta South Africa bitcoin futures trading strategy Singapore investopied trading platform tools definition Singapore download nadex trading platform Singapore how do i invest money in bitcoin South Africa bitcoin value investing.com Malaysia investtoo.com binary option brokers Malaysia what is otc in binary options South Africa how much can crypto exchanges make from trading fees Singapore binary options outlawed India how to test trading platform Malaysia boat binary options autotrader South Africa best futures trading platform reddit Malaysia sinais opções binárias iq option Singapore greg marks binary options South Africa bitcoin trading iphone application Singapore binary option brokers accepting us clients Malaysia trading crypto eith chromebook Malaysia learn binary options trading free how to invest in bitcoin gold Singapore best stock trading platform for begginers Singapore what time do options start trading South Africa cahrt for binary options trades calculator South Africa trading vs lending bitcoin Malaysia binary options platforms that offer api India bitcoin cme trading time South Africa invest all your money in bitcoin Malaysia nadex binary options strategies forex Malaysia bitcoin exchange forex vs crypto trading profitability India best trading platform pdt South Africa doc/print_options: cannot execute binary file Singapore best python websites for trading platform India binary options trading etrade India binary options post India best bitcoin investing app for beginners Malaysia andrew feldstein binary options South Africa globes binary options Singapore best strategy for bitcoin trading faily India north american carbon trading platform world bank Malaysia best binary options advice India is it safe to invest money on bitcoin Singapore paypal billioniare investing in bitcoin Singapore mathematics of binary options India cwe trading bitcoin trading India south korea insider trading crypto Malaysia low cost bitcoin trading Singapore full time crypto trading jobs India fxcitizen binary option India 50 in binary Malaysia 50 invest into bitcoin mining Malaysia 404 Recipe not found Back to home X Open chat
https://conscioussupplements.in/tosmde/3ite2237560.htm
CC-MAIN-2022-05
en
refinedweb
Tips & Tricks of Deploying Deep Learning Webapp on Heroku Cloud Learn model deployment issues and solutions on deploying a TensorFlow-based image classifier Streamlit app on a Heroku server. Image by Author. Heroku Cloud is famous among web developers and machine learning enthusiasts. The platform provides easy ways to deploy and maintain the web application, but if you are not familiar with deploying deep learning applications, you might struggle with storage and dependence issues. This guide will make your deployment process smoother so that you can focus on creating amazing web applications. We will be learning about DVC integration, Git & CLI-based deployment, error code H10, playing around with Python packages, and optimizing storage. Git & CLI-based Deployment The Streamlit app can be deployed with git, GitHub integration, or using Docker. The git-based approach is by far a faster and easier way to deploy any data app on Heroku server. Simple Git-based The Streamlit app can be deployed using: git remote add heroku:[email protected]/.git git push -f heroku HEAD:master For this to work, you need: - Heroku API Key - Heroku App: either by CLI or using the website. - Git-based project - Procfile CLI-based CLI-based deployment is basic and easy to learn. Image by Author. - Create a free Heroku account here. - Install Heroku CLI using this link. - Either clone remote repository or use git init - Type heroku login and heroku create dagshub-pc-app. This will log you into the server and create an app on a web server. - Now create Procfile containing the commands to run the app: web: streamlit run --server.port $PORT streamlit_app.py - Finally, commit and push code to heroku server git push heroku master PORT If you are running the app with streamlit run app.py it will produce an error code H10 which means $PORT assigned by the server was not used by the Streamlit app. You need to: - Set PORT by using Heroku CLI heroku config:set PORT=8080 - Make changes in your Procfile and add server port in arguments. web: streamlit run --server.port $PORT app.py Tweaking Python Packages This part took me 2 days to debug as Heroku cloud comes with a 500MB limitation, and the new TensorFlow package is 489.6MB. To avoid dependencies and storage issues, we need to make changes in the requirements.txt file: - Add tensorflow-cpu instead of tensorflow which will reduce our slug size from 765MB to 400MB. - Add opencv-python-headless instead of opencv-python to avoid installing external dependencies. This will resolve all the cv2 errors. - Remove all unnecessary packages except numpy, Pillow, andstreamlit. DVC Integration Image by Author. There are a few steps required for successfully pulling data from the DVC server. - First, we will install a buildpack that will allow the installation of apt-files by using Heroku API heroku buildpacks:add --index 1 heroku-community/apt - Create a file name Aptfile and add the latest DVC version - In your app.py file add extra lines of code: import os if "DYNO" in os.environ and os.path.isdir(".dvc"): os.system("dvc config core.no_scm true") if os.system(f"dvc pull") != 0: exit("dvc pull failed") os.system("rm -r .dvc .apt/usr/lib/dvc") After that, commit and push your code to Heroku server. Upon successful deployment, the app will automatically pull the data from DVC server. Optimizing Storage There are multiple ways to optimize storage, and the most common is to use Docker. By using the docker method, you can bypass the 500MB limit, and you also have the freedom to install any third-party integration or packages. To learn more about how to use docker, check out this guide. For optimizing storage: - Only add model inference python libraries in requiremnets.txt - We can pull selective data from DVC by using dvc pull {model} {sample_data1} {sample_data2}.. - We only need a model inference file, so add the rest of the files to .slugignore, which works similarly to .gitignore. To learn more, check out Slug Compiler. - Remove .dvc and .apt/usr/lib/dvc directories after successfully pulling the data from the server. Outcomes The initial slug size was 850MB, but with storage and package optimizations, the final slug size was reduced to 400MB. We have solved error code H10 with a simple command and added opencv-python-headless package to solve dependency issues. This guide was created to overcome some of the common problems faced by beginners on Heroku servers. The Docker-based deployment can solve a lot of storage problems, but it comes with complexity and a slow deployment process. You can use heroku container:push web, but before that, you need to build the docker, test it, and resolve all the issues locally before you can push it. This method is preferred by advanced Heroku users. The next challenge is to deploy your web application with webhook. This will allow us to automate the entire machine learning ecosystem from any platform. The automation process will involve creating a simple Flask web server that will run shell commands. Additional Resources
https://www.kdnuggets.com/2021/12/tips-tricks-deploying-dl-webapps-heroku.html
CC-MAIN-2022-05
en
refinedweb
Weaver-testWeaver-test A test-framework built on cats-effect and fs2, with zio and monix interop. InstallationInstallation Weaver-test is currently published for Scala 2.12 and 2.13 SBTSBT Refer yourself to the releases page to know the latest released version, and add the following (or scoped equivalent) to your build.sbt file. libraryDependencies += "com.disneystreaming" %% "weaver-cats" % "x.y.z" % Test testFrameworks += new TestFramework("weaver.framework.CatsEffect") // optionally (for ZIO usage) libraryDependencies += "com.disneystreaming" %% "weaver-zio" % "x.y.z" % Test testFrameworks += new TestFramework("weaver.framework.ZIO") // optionally (for Monix usage) libraryDependencies += "com.disneystreaming" %% "weaver-monix" % "x.y.z" % Test testFrameworks += new TestFramework("weaver.framework.Monix") // optionally (for Monix BIO usage) libraryDependencies += "com.disneystreaming" %% "weaver-monix-bio" % "x.y.z" % Test testFrameworks += new TestFramework("weaver.framework.MonixBIO") // optionally (for Scalacheck usage) libraryDependencies += "com.disneystreaming" %% "weaver-scalacheck" % "x.y.z" % Test // optionally (for specs2 interop) libraryDependencies += "com.disneystreaming" %% "weaver-specs2" % "x.y.z" % Test MotivationMotivation Weaver aims at providing a nice experience when writing and running tests : - tests within a suite are run in parallel by default for quickest results possible - expectations (ie assertions) are composable values. This forces developers to separate the scenario of the test from the checks they perform, which generally keeps tests cleaner / clearer. - failures are aggregated and reported at the end of the run. This prevents the developer from having to "scroll up" forever when trying to understand what failed. - a lazy logger is provided for each test, and log statements are only displayed in case of a test failure. This lets the developer enrich their tests with clues and works perfectly well with parallel runs APIAPI Example suites (cats-effect)Example suites (cats-effect) SimpleIOSuiteSimpleIOSuite The suite that is most familiar to developers : import weaver.SimpleIOSuite import cats.effect._ // Suites must be "objects" for them to be picked by the framework object MySuite extends SimpleIOSuite { pureTest("non-effectful (pure) test"){ expect("hello".size == 6) } private val random = IO(java.util.UUID.randomUUID()) test("test with side-effects") { for { x <- random y <- random } yield expect(x != y) } loggedTest("test with side-effects and a logger"){ log => for { x <- random _ <- log.info(s"x : $x") y <- random _ <- log.info(s"y : $y") } yield expect(x != y) } } IOSuiteIOSuite The IOSuite constructs the given resource once for all tests in the suite. import weaver.IOSuite import cats.effect._ object MySuite extends IOSuite { type Res = Int def sharedResource : Resource[IO, Int] = Resource .make( IO(println("Making resource")) .as(123) )(n => IO(println(s"Closing resource $n"))) test("test, but resource not visible"){ IO(expect(123 == 123)) } test("test with resource"){ n => IO(expect(n == 123)) } test("test with resource and a logger"){ (n, log) => log.info("log was available") *> IO(expect(n == 123)) } } Other suitesOther suites Weaver also includes support for ZIO-based suites via the optional weaver-ziodependency Monix-based suites via the optional weaver-monixdependency Monix BIO-based suites via the optional weaver-monix-biodependency Expectations (assertions)Expectations (assertions) Building expectationsBuilding expectations The various test functions have in common that they expect the developer to return a value of type Expectations, which is just a basic case class wrapping a cats.data.Validated value. The most convenient way to build Expectations is to use the expect function. Based on Eugene Yokota's excellent expecty, it captures the boolean expression at compile time and provides useful feedback on what goes wrong when it does : Nothing prevents the user from building their own expectations functions to resemble what they're used to. Composing expectationsComposing expectations Something worth noting is that expectations are not throwing, and that if the user wants to perform several checks in the same test, he needs to compose the expectations via the and or the or methods they carry. Filtering testsFiltering tests When using the IOSuite variants, the user can call sbt's test command as such: > testOnly -- -o *foo* This filter will prevent the execution of any test that doesn't contain the string "foo" in is qualified name. For a test labeled "foo" in a "FooSuite" object, in the package "fooPackage", the qualified name of a test is: fooPackage.FooSuite.foo Running suites in standaloneRunning suites in standalone It is possible to run suites outside of your build tool, via a good old main function. To do so, you can instantiate the weaver.Runner, create a fs2.Stream of the suites you want to run, and call runner.run(stream). This is useful when you consider your tests (typically end-to-end ones) as a program of its own and want to avoid paying the cost of compiling them every time you run them. Scalacheck (property-based testing)Scalacheck (property-based testing) Weaver comes with basic scalacheck integration. import weaver._ import weaver.scalacheck._ import org.scalacheck.Gen // Notice the Checkers mix-in object ForallExamples extends SimpleIOSuite with Checkers { // CheckConfig can be overridden at the test suite level override def checkConfig: CheckConfig = super.checkConfig.copy(perPropertyParallelism = 100) test("Gen form") { // Takes an explicit "Gen" instance. There is only a single // version of this overload. If you want to pass several Gen instances // at once, just compose them monadically. forall(Gen.posNum[Int]) { a => expect(a > 0) } } test("Arbitrary form") { // Takes a number of implicit "Arbitrary" instances. There are 6 overloads // to pass 1 to 6 parameters. forall { (a1: Int, a2: Int, a3: Int) => expect(a1 * a2 * a3 == a3 * a2 * a1) } } test("foobar") { // CheckConfig can be overridden locally forall.withConfig(super.checkConfig.copy(perPropertyParallelism = 1, initialSeed = Some(7L))) { (x: Int) => expect(x > 0) } } } ContributingContributing Contributions are most welcome ! Development requirementsDevelopment requirements git checkout to work properly. To install for Mac using brew: brew install git-lfs git lfs install If you want to build and run the website then you will need yarn installed: brew install yarn Building the websiteBuilding the website If you're changing documentation, here's how you can check your changes locally: sbt docs/docusaurusCreateSite cd website yarn start If you're only changing .md files, you can run sbt '~docs/mdoc'. Note that the site will look a tiny bit different because to build a versioned website we have some machinery in the script running on CI - but you don't have to worry about that. IntelliJ pluginIntelliJ plugin The code of the IntelliJ plugin lives there PR GuidelinesPR Guidelines Please: - Sign the CLA - Write positive and negative tests - Include documentation InspirationInspiration A HUGE thank you to Alexandru Nedelcu, author of Monix and contributor to cats-effect, as he wrote the minitest framework which got this framework started.
https://index.scala-lang.org/disneystreaming/weaver-test/weaver-cats/0.7.3?target=_sjs1.x_3.x
CC-MAIN-2022-05
en
refinedweb
. This section provides you an example of the abstract class. To create an abstract class, just use the abstract keyword before the class keyword, in the class declaration. /* File name : Employee.java */ in the following way − /* File name : AbstractDemo.java */ public class AbstractDemo { public static void main(String [] args) { /* Following is not allowed and would raise error */ Employee e = new Employee("George W.", "Houston, TX", 43); System.out.println("\n Call mailCheck using Employee reference--"); e.mailCheck(); } } When you compile the above class, it gives you the following error − Employee.java:46: Employee is abstract; cannot be instantiated Employee e = new Employee("George W.", "Houston, TX", 43); ^ 1 error We can inherit the properties of Employee class just like concrete class in the following way − /*; } } Here, you cannot instantiate the Employee class, but you can instantiate the Salary Class, and using this instance you can access all the three fields and seven methods of Employee class as shown below. /* File name : AbstractDemo.java */ public class Abstract produces the following result − Constructing an Employee Constructing an Employee Call mailCheck using Salary reference -- Within mailCheck of Salary class Mailing check to Mohd Mohtashim with salary 3600.0 Call mailCheck using Employee reference-- Within mailCheck of Salary class Mailing check to John Adams with salary 2400.0 If you want a class to contain a particular method but you want the actual implementation of that method to be determined by child classes, you can declare the method in the parent class as an abstract. abstract keyword is used to declare the method as abstract. You have to place the abstract keyword before the method name in the method declaration. An abstract method contains a method signature, but no method body. Instead of curly braces, an abstract method will have a semoi colon (;) at the end. Following is an example of the abstract method. public abstract class Employee { private String name; private String address; private int number; public abstract double computePay(); // Remainder of class definition } Declaring a method as abstract has two consequences − The class containing it must be declared as abstract. Any class inheriting the current class must either override the abstract method or declare itself as abstract. Note − Eventually, a descendant class has to implement the abstract method; otherwise, you would have a hierarchy of abstract classes that cannot be instantiated. Suppose Salary class inherits the Employee class, then it should implement the computePay() method as shown below − /* File name : Salary.java */ public class Salary extends Employee { private double salary; // Annual salary public double computePay() { System.out.println("Computing salary pay for " + getName()); return salary/52; } // Remainder of class definition } 16 Lectures 2 hours 19 Lectures 5 hours 25 Lectures 2.5 hours 126 Lectures 7 hours 119 Lectures 17.5 hours 76 Lectures 7 hours
https://www.tutorialspoint.com/java/java_abstraction.htm
CC-MAIN-2022-05
en
refinedweb
nvm_hal.c File Reference Non-Volatile Memory Wear-Leveling driver HAL implementation. - Version - 5.6.0 License (C) Copyright 2015 Silicon Labs, This file is licensed under the Silabs License Agreement. See the file "Silabs_License_Agreement.txt" for details. Before using this software for any purpose, you must agree to the terms of that agreement. Definition in file nvm_hal.c. #include <stdbool.h> #include " em_msc.h" #include " nvm.h" #include " nvm_hal.h" Function Documentation Calculate checksum according to CCITT CRC16. This function calculates a checksum of the supplied buffer. The checksum is calculated using CCITT CRC16 plynomial x^16+x^12+x^5+1. This functionality is also present internally in the API, but is duplicated here to allow for much more efficient calculations specific to the hardware. - Parameters - Definition at line of file nvm_hal.c. References MSC_ErasePage(). Referenced by NVM_Erase(). Read data from NVM. This function is used to read data from the NVM hardware. It should be a blocking call, since the thread asking for data to be read cannot continue without the data. Another requirement is the ability to read unaligned blocks of data with single byte precision. - Parameters - Definition at line 158 of file nvm_hal.c. Referenced by NVM_Erase(), NVM_Init(), NVM_Read(), and NVM_Write(). Write data to NVM. This function is used to write data to the NVM. This is a blocking function. - Parameters - - Returns - Returns the result of the write operation. Definition at line 195 of file nvm_hal.c. References MSC_WriteWord(), and mscReturnOk. Referenced by NVM_Erase(), and NVM_Write().
https://docs.silabs.com/mcu/5.6/efm32tg/nvm-hal-c
CC-MAIN-2022-05
en
refinedweb
With the release of Microsoft Exchange Server 2007 Service Pack 1 you can programmatically override the default routing for message recipients on a per-recipient basis. This can be done by using the SetRoutingOverride method on the recipient for which you want to override the default routing. Let's assume that you have an Exchange 2007 server with just one send connector "Internet Connector"" using DNS for the address space *. With this configuration all messages leaving the organization will use this connector. Let's further assume that you want to route messages from certain senders to a smarthost instead of using DNS. This can be done as follows: - Create an additional send connector "Smarthost Connector" pointing to the smarthost - Specify a non-existing domain (e.g. nexthopdomain.com) as address space of the new connector - Write, install and enable a routing agent which registers for the OnResolvedMessage event and overwrites the default routing for the recipient. The sample agent of this article shows you how to route messages from administrator@contoso.com over the new connector, the routing for all other sender's won't be changed. 1.) Create a C# project (dll/library type) 2.) Copy the following DLLs from the C:\Program Files\Microsoft\Exchange Server\Public directory of an Exchange 2007 server to the debug directory of your new C# project: a. Microsoft.Exchange.Data.Common.dll b. Microsoft.Exchange.Data.Transport.dll 3.) Add references to the two DLLs to the C# project using the Visual Studio solution explorer 4.) Add the following code to your project: using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Exchange.Data.Transport; using Microsoft.Exchange.Data.Transport.Email; using Microsoft.Exchange.Data.Transport.Smtp; using Microsoft.Exchange.Data.Transport.Routing; using Microsoft.Exchange.Data.Common; namespace RoutingAgentOverride { public class SampleRoutingAgentFactory : RoutingAgentFactory { public override RoutingAgent CreateAgent(SmtpServer server) { RoutingAgent myAgent = new ownRoutingAgent(); return myAgent; } } } public class ownRoutingAgent : RoutingAgent { public ownRoutingAgent() { base.OnResolvedMessage += new ResolvedMessageEventHandler(ownRoutingAgent_OnResolvedMessage); } void ownRoutingAgent_OnResolvedMessage(ResolvedMessageEventSource source, QueuedMessageEventArgs e) { try { // For testing purposes we do not only check the sender address but the subject line as well // If the subject contains the substring "REDIR" then the default routing is overwritten. // // Instead of hard-coding the sender you could also perform an LDAP-query, read the information // from a text file, etc. // if (e.MailItem.FromAddress.ToString() == "administrator@contoso.com" { // Here we set the address space we want to use for the next hop. Note that this doesn't change the recipient address. // Setting the routing domain to "nexthopdomain.com" only means that the routing engine chooses a suitable connector // for nexthopdomain.com instead of using the recpient's domain. RoutingDomain myRoutingOverride = new RoutingDomain("nexthopdomain.com"); foreach (EnvelopeRecipient recp in e.MailItem.Recipients) { recp.SetRoutingOverride(myRoutingOverride); } } } catch // (Exception except) { } } } 5.) Compile the DLL 6.) Copy the DLL to the HT server 7.) Install the transport agent using the Exchange Management Shell: Install-TransportAgent "OwnTestAgent" -TransportAgentFactory "RoutingAgentOverride.SampleRoutingAgentFactory" -AssemblyPath "Path to DLL" 8.) Enable the transport agent using the Exchange Management Shell: Enable-TransportAgent "OwnTestAgent" 9.) IMPORTANT: Exit Powershell 10. IMPORTANT: Restart the MSExchangeTransport service 11.) Verify that the agent was successfully enabled / registered by running Get-Transportagent Tips: - To live debug the dll you need to attach to edgetransport.exe. - To recompile after a change - detach from edgetransport - stop the transport service (otherwise Visual studio won't be able to overwrite the file) (only if you registered the dll from the \debug folder) - Sometimes messages remain in the outbox until the mail submission service is restarted Sorry to ask again, but why should internal mail go to a smarthost? If you create a connector pointing to a smarthost and specify an address space like nexthopdomain.com then ONLY messages sent directly to this domain and messages for which the agent sets nexthopdomain.com as ‘RoutingOverride’ will go through this connector. If this is still not clear then you need to describe your problem in more details: Topology (servers, roles, connectors, address spaces, …) You could add a header field (e.g. X-already-processed). to matty-uk Attach a debugger and check if the agent fires. If yes then step through the code and see verify that SetRoutingOverride is called for the recipient(s). It does'nt work, if I compile the sourcecode. I think the problem is my .net framework. Can anyone compile the source-code from above and then load the .dll file up, so I can test my exceptation? Thanks. Hello, I am trying to write a custom transport agent for the first time using the steps above, however when i pasted the supplied code into my Visual Studio project, and then try to save and build the project to compile the DLL, the build fails. I see several errors within the code, but don't have the programming background to troubleshoot and resolve them. Is there anything additional besides the code above that I would need? Right now, I only have "Public Class Class1" at the very top, and "End Class" at the very bottom, with the code from above in between. Thanks. What happens if you move the DLL to another location and try to register it from there? Do you get the same error? I don’t understand the question. If you specify a certain address space like nexthopdomain.com – why should internal messages be routed over this connector? The address space should be a dummy-address-space which is NOT used as proxy address and which does NOT match any accepted domain. Hi there, I have written a RoutingAgent(installed on HUB) to override the default outbound routing to another send connector for messages that have secure in the subject. THe send connector then sends the mail back to the HUB server, here the RoutingAgent should ignore this message , otherwise it goes in a loop. How do we achieve the same. Can i use e.MailItem.OriginatingDomain to do the same. Thanks!! Hello there First up, thanks for this, works like a charm… However.. In the section: if (e.MailItem.FromAddress.ToString() == "administrator@contoso.com" Is there a way to select multiple users or a group from AD? I’m guessing LDAP wouldn’t work by itself… Oh and sorry for my lack of C# knowledge incase it’s a really simple answer. I just cant find anywhere that explains what I would need to do here. Thanks in advance Nevermind, cracked it using: if (e.MailItem.FromAddress.DomainPart.Contains("secure.contoso.com")) We have put the dll we created in the same folder as the other dlls and tried to install it. We are getting an error that the Transport Agent assembly file does not exist. Here is the command we used and the output: [PS] C:Windowssystem32>Install-TransportAgent "OwnTestAgent" -TransportAgentFactory "RoutingAgentOverride.SampleRoutin gAgentFactory" -AssemblyPath "C:Program FilesMicrosoftExchange ServerV14PublicExchangeRouter.dll" The Transport Agent assembly file "C:Program FilesMicrosoftExchange ServerV14PublicExchangeRouter.dll" doesn’t ex ist. Parameter name: AssemblyPath + CategoryInfo : InvalidArgument: (:) [Install-TransportAgent], ArgumentException + FullyQualifiedErrorId : 77AF4613,Microsoft.Exchange.Management.AgentTasks.InstallTransportAgent I moved the DLL to a new location, but still get the error. I should also mention that this is Exchange 2010. [PS] C:Windowssystem32>Install-TransportAgent "OwnTestAgent" -TransportAgentFactory "RoutingAgentOverride.SampleRoutin gAgentFactory" -AssemblyPath "C:Exchange_DLL/ExchangeRouter.dll" The Transport Agent assembly file "C:Exchange_DLL/ExchangeRouter.dll" doesn’t exist. Parameter name: AssemblyPath + CategoryInfo : InvalidArgument: (:) [Install-TransportAgent], ArgumentException + FullyQualifiedErrorId : 77AF4613,Microsoft.Exchange.Management.AgentTasks.InstallTransportAgent Actually, I have found there is an issue connecting the ems to that server. Likely this is why. Thank you for the response. hi, Thank you very much for your solution which worked for me.. But my internal mails are also getting routed through the samrt host.Kindly help me to overcome this behaviour as i don’t have much knowledge in programming.. We also are having all mail (including internal) going to the smart host. Example: UserA@usa.com sends an email to UserB@usa.com The mail is sent to the smart host and then tries to route back to Exchange. Exchange also rejects it. Is there a way to make it check internally before seeing if it should use the smart host? We are still having the same behavior when using the routing agent. We had to go back to sending all mail out the smart host until we can resolve this. We had thought of putting a check in there that would not use the smarthost connector if the mail sending domain was the same as the recipient. Not sure how that would handle mail that had some internal and some external address though. Any thoughts on another way to get the routing agent to keep the local mail local? I too have no idea why internal mail would be going out this way instead of just being delivered locally. I should mention that this is Exchange 2010. We have one hub, one cas, and two mb servers in a dag. We have two send connectors. One has the nexthopdomain address space, and one has *. Anything that gets marked as being from a domain that should use the nexthop connector sends out that way, including internal mail. The smarthost also then passes the back, but Exchange just sends it back to the smarthost, in an endless loop. Anything not marked for nexthop goes to the other connector, sends internal and external mail properly. If there is an email address I could send you more info to as well, that would be great. We fixed the issue by adding some code. Eric, would you be able to post the additional code you needed? I would like to try this but looking at the example it seems that the behaviour you describe is unavoidable as it stands. The example says that any email from administrator@contoso.com with REDIR in the subject will go over the connector so it looks like internal email would do the same. Does anyone know how to intercept Meeting Types? Great article by the way. Cheers John Does anyone know how to intercept Meeting Requests? We need something similar but we need to check for a Meeting Request, look at the receipients and if there are flagged email on the request, trash the request. We've search for days and posted on various blogs but it seems nobody has an answer. Surely you can do with by writing you own Agent, as above. Can anyone help out there!? Thanks in advance John" I do not see that this was explicitly mentioned anywhere, but it looks like that dummy adrress space such as "nexthopdomain.com" cannot be used with send connectors which use DNS to route mail. For example, if I sent a message to anyuser@gmail.com and my transport agent set routing override with the domain nexthopdomain.com, NDR is generated with the error message '554 5.4.4 SMTPSEND.DNS.NonExistentDomain; nonexistent domain'. This did not look obvious to me, but after testing I realized that the Exchange server was trying to find the MX record for nexthopdomain.com in order to deliver the message for anyuser@gmail.com. I know this code has problems with trying to route internal mail through the dummy 'nexthopdomain' connector however I would like to understand how to insert an exception in this code to ignore messages intended for internal use only. A little help on this would be much appreciated. Would something like this resolve this issue of forwarding internal mail through the send connector?? RoutingDomain myRoutingOverride = new RoutingDomain("nexthopdomain.com"); foreach (EnvelopeRecipient recp in e.MailItem.Recipients) { if (!recp.Address.DomainPart.Contains("internal-domain-name-here")) { recp.SetRoutingOverride(myRoutingOverride); } } } } catch // (Exception except) { } } } I've tested this addition to the code which finally works! Basically this custom transport rule is ignored if the message recipient address contains the internal domain name (or contains part of), therefore all internal messages are routed normally. After installing SP1 to 2010 on the HUB we had issues with this. Taking out the custom routing agent resolved the issue, but the mail is not routing the way we would like of course. When We try to reinstall the agent, the error is: The TransportAgentFactory type "RoutingAgentOverride.SampleRoutingAgentFactory" doesn't exist. The TransportAgentFactory type must be the Microsoft .NET class type of the transport agent factory. Parameter name: TransportAgentFactory + CategoryInfo : InvalidArgument: (:) [Install-TransportAgent], ArgumentException + FullyQualifiedErrorId : 779E4613,Microsoft.Exchange.Management.AgentTasks.InstallTransportAgent Any ideas on this? Hi Jimmy, Yes, I too have experiencing the same issues with "Transport Agent Factory Type" – still not sure of the root cause of this problem, however try this….. copy the code into notepad. Create a new project in VS and then build solution and build the agent. Try to do this on the local domain and copy the agent directly to the Exch server via UNC. May sure you use the Exchange DLL from SP1 also (however I believe they haven't change during the SP1 update). Let me know how you get on. – Graham graham.hosking@fdean.gov.uk Graham, Yes, we also did have to use the new DLLs. Also found that the method we were using for internal mail to work had to be altered. The code must be complied with the correct common and transport DLL's for your system. If you say update your Exch2010 system to SP1 and/or Rollup 1 these DLL's will change. You then need to remove from your C# project and add the new DLL's (resources) in. I've uploaded my transport agent however this is complied for Exch2010 SP1 with Rollup1. rapidshare.com/…/agent.dll Use installer command: Install-TransportAgent "Myagent" -TransportAgentFactory "RoutingAgentOverride.gcRoutingAgentFactory" -AssemblyPath "Path to DLL" Hi I am getting problem installing 2007 routing agent; social.technet.microsoft.com/…/da9fc6bc-8449-42b0-a23f-0c8744b688c0 Regards Hi, I used this routing agent for a while and it works very good. But after installing service pack 2 I cannot send any mails. After deactivating the routing agent everything works fine again. anyone have the same problem and know a solution? Regards Sorry, I fixed the problem. 2 new dlls were installed with the sp2. I recompiled the routing agent and everything works fine. Thank you thank you thank you! That really saved me from spending money for a 3rd-Party application to route e-mails to different smarthosts by sender domain. Works like charm 🙂 Hi All I enhanced Grahams code so that it is externally configurable:…/index.html Regards, Martin I've tried this for Exchange 2007 and a test account. Mail is not being rerouted for the test account. What the bet way to troubleshoot it? Thanks Matt Here is my thought. 1. Create a Transport Rule with condition “If from address matches “specific sender” redirect to “contact(with different domain name)” 2. Create a Send connecter to forward email (having domain name of the contact) to specific gateway
https://blogs.technet.microsoft.com/appssrv/2009/08/26/how-to-control-routing-from-your-own-routing-agent/
CC-MAIN-2019-22
en
refinedweb
reggae 0.5.0 A build system in D To use this package, put the following dependency into your project's dependencies section: Reggae A build system written in the D programming language. This is alpha software, only tested on Linux and likely to have breaking changes made. Features - Write readable build descriptions in D, Python, Ruby, JavaScript or Lua - Out-of-tree builds - Backends for GNU make, ninja, tup and a custom binary executable. - User-defined variables like CMake in order to choose features before compile-time - Low-level DAG build descriptions + high-level convenience rules to build C, C++ and D - Automatic header/module dependency detection for C, C++ and D - Automatically runs itself if the build description changes - Rules for using dub build targets in your own build decription - use dub with ninja, add to the dub description, ... Not all features are available on all backends. Executable D code commands (as opposed to shell commands) are only supported by the binary backend, and due to tup's nature dub support and a few other features can't be supported. When using the tup backend, simple is better. The recommended backends are ninja and binary. Usage Reggae is actually a meta build system and works similarly to CMake or Premake. Those systems require writing configuration files in their own proprietary languages. The configuration files for Reggae are written in D, Python, Ruby, JavaScript or Lua From a build directory (usually not the same as the source one), type reggae -b <ninja|make|tup|binary> </path/to/project>. This will create the actual build system depending on the backend chosen, for Ninja, GNU Make, tup, or a runnable executable, respectively. The project path passed must either: Dub projects with no reggaefile.d will have one generated for them in the build directory. How to write build configurations The best examples can be found in the features directory. illustrate the low-level primitives. To build D apps with no external dependencies, this will suffice and is similar to using rdmd: import reggae; alias app = scriptlike!(App(SourceFileName("src/main.d"), BinaryFileName(. There is detailed documentation in markdown format. For C and C++, the main high-level rules to use are targetsFromSourceFiles and link, but of course they can also be hand-assembled from Target structs. Here is an example C++ build: import reggae; alias objs = objectFiles!(Sources!(["."]), // a list of directories Flags("-g -O0"), IncludePaths(["inc1", "inc2"])); alias app = link!(ExeName("app"), objs); Sources can also be used like so: Sources!(Dirs([/*directories to look for sources*/], Files([/*list of extra files to add*/]), Filter!(a => a != "foo.d"))); //get rid of unwanted files objectFiles isn't specific to C++, it'll create object file targets for all supported languages (currently C, C++ and!(".5.0 released 4 years ago - atilaneves/reggae - github.com/atilaneves/reggae - BSD 3-clause - Authors: - - Dependencies: - none - Versions: - Show all 45 versions - Download Stats: 0 downloads today 2 downloads this week 9 downloads this month 3716 downloads total - Score: - 1.5 - Short URL: - reggae.dub.pm
http://code.dlang.org/packages/reggae/0.5.0
CC-MAIN-2019-22
en
refinedweb
Do ifstream or istringstream have issues processing tabs? I'm trying to process fragments of a text file that look like this: 6 Jane Doe 1942 90089 3 1 5 12 Lines 2-5 begin with a tab. The last line will have an arbitrary number of integers separated by spaces. I'm store all of this information in appropriate variables, with the last line in a vector. Here's what I've tried so far: int id; ifile >> id; string name; getline(ifile, name); int year; ifile >> year; int zip; ifile >> zip; vector<int> friends; string friends_str; getline(ifile, friends_str); istringstream iss(friends_str); int x_id; while (iss >> x_id) { friends.push_back(x_id); } Am I missing anything about how tabs are dealt with? Is my approach with istringstream good for this situation, since the last line will have an unknown number of integers? Am I missing any trivial mistakes? See also questions close to this topic - CGAL 4.14 Bezier Arrangement crashes with two straight curves CGAL::insert on an Arrangement_2< Arr_Bezier_curve_traits_2 > will occasionally violate an assertion. I can't state certainly what the problematic scenarios have in common, but they often seem to involve one curve terminating in the middle of another. I've put together a minimal example. For me (Windows 8.1, MSVC2015 running in QtCreator, CGAL 4.14), this fails in debug mode at the assertion of line 234 in No_intersection_surface_sweep_2_impl.h: CGAL_assertion((m_statusLine.size() == 0)); In release mode, my whole system hangs until I can manage to kill the offending process. Can anyone reproduce this? Am I doing something wrong, or is this a bug? There have been bugs with inserting Bezier curves into arrangements before—see this thread concerning a since-fixed problem in an earlier CGAL version. main.cpp: #include <CGAL/Cartesian.h> #include <CGAL/CORE_algebraic_number_traits.h> #include <CGAL/Arr_Bezier_curve_traits_2.h> #include <CGAL/Arrangement_2.h> #include <sstream> using NtTraits = CGAL::CORE_algebraic_number_traits; using Rational = NtTraits::Rational; using Algebraic = NtTraits::Algebraic; using RationalKernel = CGAL::Cartesian< Rational >; using AlgebraicKernel = CGAL::Cartesian< Algebraic >; using ArrTraits = CGAL::Arr_Bezier_curve_traits_2< RationalKernel, AlgebraicKernel, NtTraits >; using BezierCurve2 = ArrTraits::Curve_2; using Arrangement = CGAL::Arrangement_2< ArrTraits >; int main() { // Change 10.1 to 10 and problem goes away. const std::string curvesData = "2 \ 2 -10 0 10.1 0 \ 2 10 10 10 0 "; std::istringstream stream( curvesData ); std::vector< BezierCurve2 > curvesToInsert; size_t numCurves = 0; stream >> numCurves; for( size_t i = 0; i < numCurves; i++ ) { BezierCurve2 curve; stream >> curve; curvesToInsert.push_back( curve ); } Arrangement arr; // Assertion violation here. CGAL::insert( arr, curvesToInsert.begin(), curvesToInsert.end() ); return 0; } - Read letters from the keyboard and insert them in a BST Read letters from the keyboard and insert them in a BST. The reading process stops when the user inserts the character 0 (zero) BST<string> *r= new BST<string>; string q1[MAX]; string n1; int a =0; cout<<"Enter the letter"<<"/n"; for(int i=0;i<MAX;i++) { cin>n1; q1[i]=n1; a++; if(q1[i] == "0"){ break; } } for(int j=0;j<a;j++){ t->insert(q1[j];)} }; The error messages appear for "cout", "i" and "j" and some expected unqualified-id before "for" ||=== Build: Debug in BIG HW 3 ex 1 (compiler: GNU GCC Compiler) ===| E:\CodeBlocks\BIG HW 3\main.cpp|151|error: 'cout' does not name a type| E:\CodeBlocks\BIG HW 3\main.cpp|152|error: expected unqualified-id before 'for'| E:\CodeBlocks\BIG HW 3\main.cpp|152|error: 'i' does not name a type| E:\CodeBlocks\BIG HW 3\main.cpp|152|error: 'i' does not name a type| E:\CodeBlocks\BIG HW 3\main.cpp|162|error: expected unqualified-id before 'for'| E:\CodeBlocks\BIG HW 3\main.cpp|162|error: 'j' does not name a type| E:\CodeBlocks\BIG HW 3\main.cpp|162|error: 'j' does not name a type| - How do I fix the balancing of the Red Black tree? This is the entire implementation which I have tried out for Red Black Trees using templates. Click here to download my code. The tree is printing fine. But it is not balancing itself after insertion and deletion. I feel the left rotate and right rotate functions are fine. Pls help me fix the error in insertfixup and delfixup function. - Can't read from text file using c++ using atom on MacOS I'm using atom on my mac(c++) to try to open a text file and read from it, but when I run it, it goes blank. [enter image description here][1] When it goes to the function copydata, nothing shows up even tho the text file has written words in it. #include <iostream> #include <string> #include <fstream> #include <algorithm> using namespace std; void copydata(string name , string x[]) { ifstream inFile; inFile.open(name); int i = 0; while (inFile >> x[i]) { i++; } } void displaynames(string x[]) { for (int i =0 ; i<4 ; i++) cout << x[i] << endl; } int main() { string names[10]; string filename = "datas.txt"; copydata(filename,names); displaynames(names); sort(names, names+10); displaynames(names); return 0; } - std::length_error at memory location 0x012FEC9C at string assignment I'm tring to read variables off of a binary file located in my PC based on a structure order of variables. when I try to assign the input string value to the structure array string value it breaks, and not at first but at the second iteration of the loop. here's my code: #include "pch.h" #include <iostream> #include <fstream> #include <string> #include <cstdlib> #include <vector> using namespace std; struct inputWord { string word; int value=0; bool did = false; }; void createFile(); static string filePath = "E:\\tmp\\wordArray.dat"; int main() { createFile(); //string filePath; ifstream file; string content; int value; cout << "enter input file path with double back slash each time instead of one with the file name and .dat extension" << endl; //cin >> filePath; inputWord *inputWordsArray = new inputWord[5]; int numberOfWords = 0; file.open(filePath, ios::in | ios::binary);//attempt to open file if (file.is_open()) {//check if file was opened file.seekg(0, ios::beg);//position file pointer int i = 0; while(!file.eof()) {//check if reached end of file if (i >= 5) break; file.read((char*)& content, sizeof(string)); file.read((char*)& value, sizeof(int)); inputWordsArray[i].word = content; inputWordsArray[i].value = value; numberOfWords++; i++; } file.close(); } else { cout << "Problem opening file" << endl;//report problem if file was not opened properly exit(0); } return 0; } void createFile() { inputWord inputArray1[30]; inputArray1[0].word = "ab"; inputArray1[0].value = 250; inputArray1[1].word = "abc"; inputArray1[1].value = 200; inputArray1[2].word = "abcd"; inputArray1[2].value = 150; inputArray1[3].word = "abcde"; inputArray1[3].value = 100; inputArray1[4].word = "abcdef"; inputArray1[4].value = 50; string filePath = "E:\\tmp\\wordArray.dat"; ofstream file1; file1.open(filePath, ios::out | ios::binary); if (file1.is_open()) { file1.seekp(0, ios::beg); for (int i = 0; i < 5; i++) { file1.write((char*)& inputArray1[i].word, sizeof(string)); file1.write((char*)& inputArray1[i].value, sizeof(int)); } file1.close(); } else { cout << "Problem occurred while opening the file"; exit(0); } } it breaks on: inputWordsArray[i].word = content; I'd really appreciate any help in understanding why is this happening? thnx anyway. - Severity Code Description Project File Line Suppression State Error C2676 binary '>>': 'std::ifstream' i am trying to define function in header file that takes 2 arguments, std::ifstream and char* .. function is going to check if char* type argument is in file then return true else it will return false. the compiler shows me the error message about ">>" operation with ifstream reference P.S Note that, i am defining function in external my own header file firstly i have passed parameter of fstream, then changed to ifstream but same error message bool check_for_valid_name(std::ifstream &file, char* name) { char data[sizeof(name)]; while (file.eof()) { file >> data; if (strcmp(data, name)) { return true; } } return false; } it should work fine, just return false or true but the compiler shows error: Severity Code Description Project File Line Suppression State Error C2676 binary '>>': 'std::ifstream' - Atoi function not returning int expected - C++ string number = " 9782123456803"; char buffer[256]; istringstream is_number(number); is_number.getline(buffer, 255); int n = atoi(buffer); Expected return from n : 9782123456903 And what i get is : 2147483647 I've used this code a few times but im not sure why its returning this weird int instead of the correct answer, any idea why? Thanks. - Using istringstream in C++ I have some code that utilizes fork, execlp, and wait to make two processes. The objective is to be able to repeatedly print a prompt and have the user enter a command with up to 4 arguments/options to the command. int main() { string command, argument; istringstream iss(argument); do { //prompt user for command to run cout << "Enter command: "; cin >> command >> argument; int pid, rs, status; //fork will make 2 processes pid = fork(); if(pid == -1) { perror("fork"); exit(EXIT_FAILURE); } if(pid == 0) { //Child process: exec to command with argument //C_str to get the character string of a string rs = execlp(command.c_str(), command.c_str(), argument.c_str(), (char*) NULL); . if (rs == -1) { perror("execlp"); exit(EXIT_FAILURE); } } else { //Parent process: wait for child to end wait(&status); } } while(command != "exit"); return 0; } I knew that the current code I have would be able to support only one argument to the command, but I wasn't sure about what to use in order to specify between 1 to 4 arguments. That's when I a friend mentioned to me about std::istringstream, but while looking into it, I didn't understand how to use it for input with the rest of the program. Is there a way to set it up or is there a different method to use to fulfill the requirements? - Stuck reading first line of a file over and over I'm trying to record lines of data from a text file and store them in variables so I can use those variables to create and object with those values. My text file is set up to have a string1 num1 num2 string2. They are separated by white space and there's 15 lines. For now, I'm just trying to print them so I can easily tell it's working. However, it's printing the first line 15 times, so I'm guessing that it's just reading the first line and not proceeding to the next line. I'm just learning about reading from files though so any help would be appreciated. Thanks. ifstream inFile; string line; inFile.open("CellValues.txt"); //Check for Error if (inFile.fail()) { cerr << "File does not exist!"; exit(1); } int index = 0, max_num = 0; string type, name; istringstream inStream; while (getline(inFile, line)) { inStream.str(line); inStream >> type >> index >> max_num >> name; cout << type << " / " << index << " of " << max_num << " / " << name << endl; }
http://quabr.com/53203048/do-ifstream-or-istringstream-have-issues-processing-tabs
CC-MAIN-2019-22
en
refinedweb
__thrsleep, __thrwakeup— #include <sys/time.h> int __thrsleep(const volatile void *id, clockid_t clock_id, const struct timespec *abstime, void *lock, const int *abort); int __thrwakeup(const volatile void *id, int count); __thrsleep() and __thrwakeup() functions provide thread sleep and wakeup primitives with which synchronization primitives such as mutexes and condition variables can be implemented. __thrsleep() blocks the calling thread on the abstract “wait channel” identified by the id argument until another thread calls __thrwakeup() with the same id value. If the abstime argument is not NULL, then it specifies an absolute time, measured against the clock_id clock, after which __thrsleep() should time out and return. If the specified time is in the past then __thrsleep() will return immediately without blocking. The lock argument, if not NULL, points to a locked spinlock that will be unlocked by __thrsleep() atomically with respect to calls to __thrwakeup(), such that if another thread locks the spinlock before calling __thrwakeup() with the same id, then the thread that called __thrsleep() will be eligible for being woken up and unblocked. The abort argument, if not NULL, points to an int that will be examined after unlocking the spinlock pointed to by lock and immediately before blocking. If that int is non-zero then __thrsleep() will immediately return EINTR without blocking. This provides a mechanism for a signal handler to keep a call to __thrsleep() from blocking, even if the signal is delivered immediately before the call. The __thrwakeup() function unblocks one or more threads that are sleeping on the wait channel identified by id. The number of threads unblocked is specified by the count argument, except that if zero is specified then all threads sleeping on that id are unblocked. __thrsleep() will return zero if woken by a matching call to __thrwakeup(), otherwise an error number will be returned to indicate the error. __thrwakeup() will return zero if at least one matching call to __thrsleep() was unblocked, otherwise an error number will be returned to indicate the error. __thrsleep() and __thrwakeup() will fail if: EINVAL] NULL. In addition, __thrsleep() may return one of the following errors: EWOULDBLOCK] EINTR] ECANCELED] EINVAL] __thrwakeup() may return the following error: ESRCH] __thrsleep() with the same id were found. __thrsleep() and __thrwakeup() functions are specific to OpenBSD and should not be used in portable applications. thrsleep() and thrwakeup() syscalls appeared in OpenBSD 3.9. The clock_id and abstime arguments were added in OpenBSD 4.9. The functions were renamed to __thrsleep() and __thrwakeup() and the abort argument was added in OpenBSD 5.1 thrsleep() and thrwakeup() syscalls were created by Ted Unangst <tedu@OpenBSD.org>. This manual page was written by Philip Guenther <guenther@OpenBSD.org>.
https://man.openbsd.org/__thrwakeup.2
CC-MAIN-2019-22
en
refinedweb
- Advertisement Jakob KrarupMember Content Count14 Joined Last visited Community Reputation159 Neutral About Jakob Krarup - RankMember Personal Information - Website spriteBatch.Draw slow? Jakob Krarup replied to Christian Thorvik's topic in General and Gameplay ProgrammingDo you only have a single SpriteBatch.Begin before and a single SpriteBatch.End after your drawing? Having many separate spritebatches with the begin/end will slow your drawing down a lot. - Hi Shippou You could fiddle a bit with the chunk sizes, to ensure that you would only read/dump files from and to disk every so often. If your maps are pretty simple, the amount of data in memory shouldn't be a problem. To my knowledge this is the same way Minecraft does it. You could also cache a bigger amount of chunks, say two concentric circles worth around the one the player is currently in. I can't see this becoming a problem on modern computers. Try the sample that's for download on my Blog - I haven't experienced any problems, and the chunks there are very small, to illustrate the concept. If you make 255x255 chunks you would load a lot less and the files would still be fast to read and not too much of a strain on memory. Kind regards - Jakob - Hi Mellkor A similar question popped up on the Microsoft XNA forums a while back, and I posted some graphics to visualize the theory and a code sample with class diagram. (scroll down to "I found some time yesterday, and coded a framework for making infinite worlds.") I hope it will prove useful to you Kind regards - Jakob - Yup - they are now :) Nice game! The gfx for the menu and introscreen is very nice. I like the concept, but I don't get the feeling that what I do changes very much in the game. If I move in a different direction all the small enemies quickly catch up to me, and the big enemy is very hard to outmaneuver. I would like small explosions as well when I hit or when I am hit, so I get the reward (feedback) for aiming well. A little sound for each shot being fired would be nice too. Overall a very good first game! :) Kind regards - Jakob Rotate sprites around a point in 2D Jakob Krarup replied to Christian Thorvik's topic in General and Gameplay ProgrammingGlad to hear it! :) Cudos on coming back with your solution for future reference :) /Jake - The links are down. Maybe it has to do with DropBox having trouble, but otherwise, if you could upload again? :) Rotate sprites around a point in 2D Jakob Krarup replied to Christian Thorvik's topic in General and Gameplay ProgrammingHi: Find the current rotation of and distance to the child object change the rotation by the wanted amount calculate the new position using cos and sin (you may want to read up on these) basically cos(angle) gives you the X coordinate of where to position something, and sin(angle) gives you the Y coordinate. Getting the rotation of a Vector2 is possible using the Atan2 function: private float Vector2ToRadian(Vector2 direction) { return (float)Math.Atan2(direction.X, -direction.Y); } XNA - Tile Engine With Collision Jakob Krarup replied to QuackTheDuck's topic in Graphics and GPU ProgrammingHi :) Here you can download codesamples for reading a map from a textfile. This code uses numeric values, but you can change what you do with the characters read to a SWITCH statement like you are mentioning in your question. Kind regards - Jakob Jakob Krarup replied to Daniel Costa's topic in Graphics and GPU ProgrammingHere's a code framework for infinite worlds implemented in XNA: You would have to make an implementation of IPermanentMapStorage which gets maps from a webservice. You can probably use the rest of the code as is /Jake P.S. in case you are interested in seeing the newest version, which uses Perlin noise for map generation (not a requirement for the framework), it is attached to this post. Static Creations and upcoming XNA Game Jakob Krarup replied to Rustystatic's topic in Your AnnouncementsCool :) Good luck! /Jake Problem displaying correct portion of a scene Jakob Krarup replied to tmccolgan88's topic in For Beginners's ForumHi tmccolgan88 What you need is a "camera". And I put "camera" in quotation marks, because it is merely a way of thinking about the concept. Whenever you are drawing the background, you are using the absolute coordinates, which makes them stay where they are, and your player move, as you point out. What you are looking for is a way to "translate the coordinates of the world into the screen, based on the player's position". This can be done by storing a Vector2 (yes - you may call it "_camera", to keep up the illusion that there *is* a real camera ;)), and updating the value of that vector based on the player's movements. Whenever you want to draw the background (world), you subtract the position of the camera from the position of the tiles/map-pieces/whatever, to make it the new origin for coordinates (it will be the top-left corner of the screen). Does that make sense? Otherwise Google "2D camera" or ask again Kind regards - Jakob Setting coordinates in map editor Jakob Krarup replied to ChristianFrantz's topic in For Beginners's ForumHi Burnt_casadilla You can change the line: builder.Append(separator + (map[x, y] > oceanLevel ? "X" : " ")); to builder.Append(separator + map[x, y]); This will look up the value in the double array at position x,y and add that to the StringBuilders buffer for later retrieval. EDIT: I added an extended version of the editor to the blogpost (at the bottom), which supports saving the heightmap (and you can look at the code for loading from the file as well, though the application doesn't support it). as for adding a border - you can do this with a for-loop, iterating through zero to max on both the Y and X axis, and setting the value there to 50 if either the X or the Y value is either zero or max. If that doesn't make sense, ask again Kind regards - Jakob Krarup ;-) Help with Worm Clone Draw() method Jakob Krarup replied to Manhattanisgr8's topic in For Beginners's ForumHi :) Kind regards - Jakob - Advertisement
https://www.gamedev.net/profile/210703-xnafan/
CC-MAIN-2019-22
en
refinedweb
A colleague recently asked me perform a time series analysis of gold prices and forecast future prices with the assumption that they would continue to decline. In this analysis with will not only forecast gold prices but also look at factors that may impact those prices. To conduct this analysis, I looked for leading economic indicators and not being an economist I turned to some of the Moody’s top economic indicators, namely consumer price index (CPI), inflation, U.S. gross domestic product (GDP-US), S&P 500, prime rate, and long interest rate. Since the gold prices are available in monthly increments from January 1950to June 2014, I wanted the other data to cover the same period. All of these including gold prices, except for prime rate, were found at GitHub,. Prime rate does not change every moth. In fact is can change several times within the same month or go several months without change. I obtained the prime rate data for Mortgage-X at. Then I filled in the missing data with the last previous value, except when there were multiple changes within a month. In those cases I averaged the changes for the month in question. To perform the analysis I used R and built both ARIMA and UCM models, using the following R packages: forecast, stlplus, and rucm. I also did the analysis using SAS Studio University Edition with PROC UCM. R Code I first load the libraries I intend to use. I use the function require(package) but you can just use library(package). Both load the namespace of the package with name package and attach it on the search list. require is designed for use inside other functions; it returns FALSE and gives a warning (rather than an error as library() does by default) if the package does not exist. Both functions check and update the list of currently attached packages and do not reload a namespace which is already loaded. require(forecast) require(stlplus) require(rucm) Next, I designate the file I want to load assigning it the name file, and the read it into the workspace. I used two different names here to show that there is a distinction between one or the other and I can use them interchangeably. Setup file = "C:/Users/Strickland/Documents/Python Scripts/gold_plus.csv" read.csv(file) -> gold read.csv(file) -> mygold Now, I set up the time series variable, which is the second column of the file. y_var<-mygold[,2] gold.ts <- ts(y_var, start=c(1950, 1), end=c(2014,6), frequency=12) plot(gold.ts,col=4) And the independent variables are the third through fourteenth columns. x_vars<-mygold[,3:14] plot(x_vars) Component Analysis Before we dive into modeling, we want to analyze the time series variable so we use the stlplus() function from the stlplus-package and make five plots, one for all components, one for seasonality analysis, one for trend analysis, one for cycle analysis, and one for remainder analysis. gold_stl <- stlplus(y_var, t = as.vector(time(y_var)), n.p = 12, l.window = 13, t.window = 19, s.window = 35, s.degree = 1, sub.labels = substr(month.name, 1, 3)) plot(gold_stl, ylab = "Gold Prices (USD)", xlab = "Time (months)") plot_seasonal(gold_stl) plot_trend(gold_stl) plot_cycle(gold_stl) plot_rembycycle(gold_stl) Plot of gold_stl Plot of seasonal Plot of trend Plot of cycle Plot of remainder By observation, I see no seasonality but do observe two distinct cycles occurring roughly at 376 months (Aug 1979, just before the 180 recession), and one after 693 months (Sep 2007, just before the 2008 recession). So, in my UCM model I take seasonality out by setting season equal to FALSE and set the cycle period to 376. Initial Model gold.model <- ucm(gold~cpi+inflation+SP500+dividend+earnings+lg_int_rate, data = gold, level = TRUE, slope = TRUE, season = FALSE, cycle = TRUE, cycle.period=376) gold.model Call: ucm(formula = gold ~ cpi + inflation + SP500 + dividend + earnings + lg_int_rate, data = gold, level = TRUE, slope = TRUE, season = FALSE, cycle = TRUE, cycle.period = 376) Parameter estimates: Estimate Approx.StdErr t.val p.value cpi 7.25700 1.82142 3.9843 7.408e-05 *** inflation 4.80970 2.44910 1.9639 0.04990 * SP500 -0.11200 NA NA NA dividend -9.77310 6.58572 -1.4840 0.13822 earnings 1.36070 0.73976 1.8394 0.06624 . lg_int_rate -6.25060 3.98984 -1.5666 0.11761 --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 Estimated variance: Irregular_Variance Level_Variance Slope_Variance 0.0002 0.0810 0.0000 Cycle_Variance 479.8603 It appears that CPI has the greatest effect on gold prices. However, I know that inflation is calculated using CPI, so I use its more relevant form, inflation and remodel, adding GDP-US and keeping S&P 500, which demonstrated no variance (technically, it could not be calculated). I also construct a forecast for 48 months into the future. gold.model2 <- ucm(gold~SP500+inflation+gdp_us, data = gold, level = TRUE, slope = TRUE, season = FALSE, cycle = TRUE, cycle.period=420) gold.model2 gold.for2<-forecast(gold.model2$s.cycle,h=48,lambda=NULL) plot(gold.for2) Call: ucm(formula = gold ~ SP500 + inflation + gdp_us, data = gold, level = TRUE, slope = TRUE, season = FALSE, cycle = TRUE, cycle.period = 420) Parameter estimates: Estimate Approx.StdErr t.val p.value SP500 -0.0971000 0.0334187 -2.9056 0.0037700 ** inflation 8.3858000 2.3025877 3.6419 0.0002886 *** gdp_us 0.0108000 0.0072548 1.4887 0.1369798 --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 Estimated variance: Irregular_Variance Level_Variance Slope_Variance 0.0015 0.1563 0.0000 Cycle_Variance 492.1741 Now, inflation shows its importance and S&P 500 is added with variance. GDP-US does not appear to be a factor. So, I keep this model and check the accuracy of its forecast. accuracy(gold.for2) ME RMSE MAE MPE Training set 0.4900831 22.78806 11.78584 11.84575 MAPE MASE ACF1 Training set 37.04665 0.9895334 0.1014228 Keying in on MAPE, this model does not produce a very accurate forecast. So, I develop another model to challenge it. In this instance I build. Challenger Model In this instance, I built. x_vars3<-mygold[,4:5] gold.model3<- Arima(y_var,order=c(1,1,1),lambda=0,xreg=x_vars3) gold.model3 gold.for3<-forecast(gold.model3$x,h=48,lambda=NULL) plot(gold.for3) accuracy(gold.for3) Series: y_var ARIMA(1,1,1) Box Cox transformation: lambda= 0 Coefficients: ar1 ma1 SP500 inflation -0.1389 0.4784 -1e-04 0.0061 s.e. 0.1127 0.1020 1e-04 0.0034 sigma^2 estimated as 0.001549: log likelihood=1415.32 AIC=-2820.64 AICc=-2820.56 BIC=-2797.34 ME RMSE MAE MPE Training set 0.7340026 22.82116 10.88003 0.1975731 MAPE MASE ACF1 Training set 2.400621 1.006989 0.01282057 Both inflation and S&P 500 are significant, but the latter contributes very little. The MAPE of 2.4 demonstrates an accurate forecast based on the historical data and model selection. Looking more closely at the forecast, we see the prices of gold continuing to go down but the starting to level off at the end of the forecast period (which is what it is actually doing). Variable Contribution Looking at the contribution of the components on gold prices, we see that inflation and S&P 500 both have negative effects, but the contribution of the S&P 500 does not appear until after the 2008 recession. GDP_US seems to make no contribution at all, which is why it was not significant in the model. Now, that is not to say that the world GDP or Western European GDP does not, because we did not include them in the model. Conclusion So the cycle for gold is to stay relatively constant untile just before a recession, then increase in vale only to fall after a recession. Once the price levels out, it behaves as it did before the recession untile the next recession and repeats the cycle. However, the price of gold after the recession is higher is higher that it was before. Also, there seems to be a delayed reaction to the recession. If you think of a recession as an intervention, how would you change the model?
https://bicorner.com/2016/03/23/whats-up-with-gold/
CC-MAIN-2019-22
en
refinedweb
ShadowCallStack¶ Introduction¶ ShadowCallStack is an instrumentation pass, currently only implemented for aarch64, that protects programs against return address overwrites (e.g. stack buffer overflows.) It works by saving a function’s return address to a separately allocated ‘shadow call stack’ in the function prolog in non-leaf functions and loading the return address from the shadow call stack in the function epilog. The return address is also stored on the regular stack for compatibility with unwinders, but is otherwise unused. The aarch64 implementation is considered production ready, and an implementation of the runtime has been added to Android’s libc (bionic). An x86_64 implementation was evaluated using Chromium and was found to have critical performance and security deficiencies–it was removed in LLVM 9.0. Details on the x86_64 implementation can be found in the Clang 7.0.1 documentation. Comparison¶ To optimize for memory consumption and cache locality, the shadow call stack stores only an array of return addresses. This is in contrast to other schemes, like SafeStack, that mirror the entire stack and trade-off consuming more memory for shorter function prologs and epilogs with fewer memory accesses. Return Flow Guard is a pure software implementation of shadow call stacks on x86_64. Like the previous implementation of ShadowCallStack on x86_64, it is inherently racy due to the architecture’s use of the stack for calls and returns. Intel Control-flow Enforcement Technology (CET) is a proposed hardware extension that would add native support to use a shadow stack to store/check return addresses at call/return time. Being a hardware implementation, it would not suffer from race conditions and would not incur the overhead of function instrumentation, but it does require operating system support. Compatibility¶ A runtime is not provided in compiler-rt so one must be provided by the compiled application or the operating system. Integrating the runtime into the operating system should be preferred since otherwise all thread creation and destruction would need to be intercepted by the application. Android, Darwin, Fuchsia and Windows) or be compiled with the flag -ffixed-x18. If absolutely necessary, code compiled without -ffixed-x18 may be run on the same thread as code that uses ShadowCallStack by saving the register value temporarily on the stack (example in Android) but this should be done with care since it risks leaking the shadow call stack address. Because of the use of register x18, the ShadowCallStack feature is incompatible with any other feature that may use x18. However, there is no inherent reason why ShadowCallStack needs to use register x18 specifically; in principle, a platform could choose to reserve and use another register for ShadowCallStack, but this would be incompatible with the AAPCS64. Special unwind information is required on functions that are compiled with ShadowCallStack and that may be unwound, i.e. functions compiled with -fexceptions (which is the default in C++). Some unwinders (such as the libgcc 4.9 unwinder) do not understand this unwind info and will segfault when encountering it. LLVM libunwind processes this unwind info correctly, however. This means that if exceptions are used together with ShadowCallStack, the program must use a compatible unwinder. Security¶ ShadowCallStack is intended to be a stronger alternative to -fstack-protector. It protects from non-linear overflows and arbitrary memory writes to the return address slot. The instrumentation makes use of the x18 register to reference the shadow call stack, meaning that references to the shadow call stack do not have to be stored in memory. This makes it possible to implement a runtime that avoids exposing the address of the shadow call stack to attackers that can read arbitrary memory. However, attackers could still try to exploit side channels exposed by the operating system [1] [2] or processor [3] to discover the address of the shadow call stack. Unless care is taken when allocating the shadow call stack, it may be possible for an attacker to guess its address using the addresses of other allocations. Therefore, the address should be chosen to make this difficult. One way to do this is to allocate a large guard region without read/write permissions, randomly select a small region within it to be used as the address of the shadow call stack and mark only that region as read/write. This also mitigates somewhat against processor side channels. The intent is that the Android runtime will do this, but the platform will first need to be changed to avoid using setrlimit(RLIMIT_AS) to limit memory allocations in certain processes, as this also limits the number of guard regions that can be allocated. The runtime will need the address of the shadow call stack in order to deallocate it when destroying the thread. If the entire program is compiled with -ffixed-x18, this is trivial: the address can be derived from the value stored in x18 (e.g. by masking out the lower bits). If a guard region is used, the address of the start of the guard region could then be stored at the start of the shadow call stack itself. But if it is possible for code compiled without -ffixed-x18 to run on a thread managed by the runtime, which is the case on Android for example, the address must be stored somewhere else instead. On Android we store the address of the start of the guard region in TLS and deallocate the entire guard region including the shadow call stack at thread exit. This is considered acceptable given that the address of the start of the guard region is already somewhat guessable. One way in which the address of the shadow call stack could leak is in the jmp_buf data structure used by setjmp and longjmp. The Android runtime avoids this by only storing the low bits of x18 in the jmp_buf, which requires the address of the shadow call stack to be aligned to its size. The architecture’s call and return instructions ( bl and ret) operate on a register rather than the stack, which means that leaf functions are generally protected from return address overwrites even without ShadowCallStack. Usage¶ To enable ShadowCallStack, just pass the -fsanitize=shadow-call-stack flag to both compile and link command lines. On aarch64, you also need to pass -ffixed-x18 unless your target already reserves x18. Low-level API¶ __has_feature(shadow_call_stack)¶ In some cases one may need to execute different code depending on whether ShadowCallStack is enabled. The macro __has_feature(shadow_call_stack) can be used for this purpose. #if defined(__has_feature) # if __has_feature(shadow_call_stack) // code that builds only under ShadowCallStack # endif #endif __attribute__((no_sanitize("shadow-call-stack")))¶ Use __attribute__((no_sanitize("shadow-call-stack"))) on a function declaration to specify that the shadow call stack instrumentation should not be applied to that function, even if enabled globally. Example¶ The following example code: int foo() { return bar() + 1; } Generates the following aarch64 assembly when compiled with -O2: stp x29, x30, [sp, #-16]! mov x29, sp bl bar add w0, w0, #1 ldp x29, x30, [sp], #16 ret Adding -fsanitize=shadow-call-stack would output the following assembly: str x30, [x18], #8 stp x29, x30, [sp, #-16]! mov x29, sp bl bar add w0, w0, #1 ldp x29, x30, [sp], #16 ldr x30, [x18, #-8]! ret
https://clang.llvm.org/docs/ShadowCallStack.html
CC-MAIN-2019-22
en
refinedweb
bps_set_domain_data() Sets domain specific data for the active channel. Synopsis: #include <bps/bps.h> BPS_API int bps_set_domain_data(int domain_id, void *new_data, void **old_data) Arguments: - domain_id - The domain ID to associate new_data with. - new_data - The service user data that should be stored in the active channel. - old_data - If a value of NULL is not provided, it is set to the previous data for the domain_id parameter. Library:libbps Description: Call the function when a service wants to set specific user data for the active channel. Often, a service has data that is particular to a channel. Since each service needs to call the bps_register_domain() function to create events, the same domain ID is used for a service to reference its data. The specifics of the type of data to store, however, is dependent on the implementation of each service. At minimum, most services pass a structure that contains a file descriptor. In most cases, this is the same file descriptor that was added using the bps_add_fd() function. Channels are thread-specific and a channel on one thread cannot be used by another thread. In addition, only active channels can retrieve data. To clear domain data from the channel, call this function with the new_data parameter set to a value of NULL. If old_data is not a NULL value, it is set to the previous data that was associated with same value of the domain_id parameter. If no data was previously set, it is set to a value of NULL. Returns: BPS_SUCCESS if the file descriptor was successfully removed from the channel, BPS_FAILURE with the errno value set otherwise.
http://developer.blackberry.com/playbook/native/reference/com.qnx.doc.bps.lib_ref/com.qnx.doc.bps.lib_ref/topic/bps_set_domain_data.html
CC-MAIN-2019-22
en
refinedweb
One could imagine a number of reasons for wanting to rewrite Busybox. Over time, that package has grown to the point that it's not quite the minimal-footprint tool kit that it once was. Android-based systems can certainly benefit from the addition of Busybox, but the Android world tends to be allergic to GPL-licensed software; a non-GPL Busybox might even find a place in the standard Android distribution. But the project page makes another reason abundantly clear: What seems to be happening in particular is that the primary Busybox litigant - the Software Freedom Conservancy (SFC) - has taken the termination language in GPLv2 to mean that somebody who fails to comply with the license loses all rights to the relevant software, even after they fix their compliance problems. (See Android and the GPLv2 death penalty for more information on this interpretation of the license, which is not universally held). Under this interpretation, they are withholding the restoration of a license to use and distribute Busybox based on conditions that are not directly related to Busybox; among other things, they require compliance for all other free software products shipped by that company, including the Linux kernel. Thus, according to Matthew Garrett: There is some truth to the notion that, on its own, license enforcement for Busybox is not hugely interesting. Encouraging compliance with the GPL is a good thing, but, beyond that, there is little to be gained by prying the source for a Busybox distribution from a vendor's hands. There just isn't anything interesting being added to Busybox by those vendors. Rob Landley, who was once one of the Software Freedom Law Center's plaintiffs (before the enforcement work moved to the Software Freedom Conservancy) once wrote: Rob has been working on the Toybox project, which happens to be the effort that would someday like to replace Busybox, since 2006. So, beyond the generation of bad publicity for a violator and some cash for the litigants, Busybox enforcement on its own could perhaps be said to achieve relatively little for the community. But a vendor that can't be bothered to provide a tarball for an unmodified Busybox distribution is highly unlikely to have its act together with regard to other projects, starting with the kernel. And that vendor's kernel code can often be the key to understanding their hardware and supporting it in free software. So it is not surprising that a group engaging in GPL enforcement would insist on the release of the kernel source as well. On its face, it does seem surprising that vendors would object to this requirement - unless they overtly wish to get away with GPL infringement. Tim Bird, who is promoting the Busybox replacement project, has stated that this is not the case. Instead, Tim says: Mistakes do happen. Companies are often surprisingly unaware of where their code comes from or what version they may have shipped in a given product. Often, the initial violation comes from upstream suppliers, with the final vendor being entirely unaware that they are shipping GPL-licensed software at all. What is being claimed here is that SFC's demands are causing the consequences of any such mistakes to be more than companies are willing to risk. What does the SFC require of infringers? The SFC demands, naturally enough, that the requirements of the GPL be met for the version of Busybox shipped by an infringer. There are also demands for an unknown amount of financial compensation, both to the SFC (The SFC's FY2010 IRS filings show just over $200,000 in revenue from legal settlements) and to the Busybox developer (Erik Andersen) that the SFC is representing. Then there are the demands for compliance for all other GPL-licensed products shipped by the vendor, demands that, it is alleged, extend to the source for binary-only kernel modules. The SFC also evidently demands that future products be submitted to them for a compliance audit before being shipped to customers. Such demands may well be appropriate for habitual GPL infringers; they are, arguably, a heavy penalty for a mistake. Whether the cases filed by the SFC relate to habitual behavior or mistakes is not necessarily clear; there have been plenty of allegations either way. One person's mistake is another person's intentional abuse. If Busybox is, for whatever reason, especially mistake-prone, then replacing it with a mistake-proof, BSD-licensed version might make sense. Not using the software at all is certainly a way to avoid infringing its license. What is a bit more surprising is that some developers are lamenting the potential loss of Busybox as a lever for the enforcement of conditions on the use of the kernel. There are a couple of concerns here: For such a developer to go to the SFC is exactly what Matthew is asking for in his post. Thus far, despite a search for plaintiffs on the SFC's part, that has not happened. Why that might be is not entirely clear. Perhaps kernel developers are not comfortable with how the SFC goes about its business, or perhaps it's something else. It's worth noting that most kernel developers are employed by companies these days, with the result that much of their output is owned by their employers. For whatever reason, companies have shown remarkably little taste for GPL enforcement in any form, so a lot of kernel code is not available to be put into play in an enforcement action. That last point is, arguably, a real flaw in the corporate-sponsored free software development model - at least, if the viability of copyleft licenses matters. The GPL, like almost any set of rules, will require occasional enforcement if its rules are to be respected; if corporations own the bulk of the code, and they are unwilling to be part of that enforcement effort, respect for the GPL will decrease. One could argue that scenario is exactly what is playing out now; one could also argue that it is causing Busybox, by virtue of being the only project for which active enforcement is happening, to be unfairly highlighted as the bad guy. If GPL enforcement were spread across a broader range of projects, it would be harder for companies to route around - unless, as some fear, that enforcement would drive companies away from GPL-licensed software altogether. Situations like this one show that there is an increasing amount of frustration building in our community. Some vendors and some developers are clearly unhappy with how some license enforcement is being done, and they are taking action in response. But there is also a lot of anger over the blatant disregard for the requirements of the GPL at many companies; that, too, is inspiring people to act. There are a number of undesirable worst-case outcomes that could result. On one side, GPL infringement could reach a point where projects like the kernel are, for all practical effect, BSD-licensed. Or GPL enforcement could become so oppressive that vendors flee to code that is truly BSD licensed. Avoiding these outcomes will almost certainly require finding a way to enforce our licenses that most of us can agree with. The classroom presents a special challenge to Linux and open source advocates. At first glance it seems like a slam dunk: free software lowers costs, and provides students with unique opportunities to learn. But even as FOSS adoption grows into big business for enterprises, start-ups, and mom-and-pop shops, it continues to be a minority player in public schools and universities. There are outreach efforts fighting the good fight, but progress is slow, and learning how to adapt the message to the needs of educators is far from a solved problem. Open Source Software In Education (OSSIE) was a dedicated Saturday track at SCALE 10X in Los Angeles. The sessions included talks about FOSS aimed at educators and talks about promoting open source usage in schools. The track was running concurrently with the rest of the conference, which made it difficult to attend every session, but the overlap between two of the talks raised more than enough questions for the open source community — namely, how to adapt outreach strategies for success in the often intransigent education sector. Elizabeth Krumbach's "Bringing Linux into Public Schools and Community Centers" was an overview of the Partimus project's work in the San Francisco Bay area (and similar efforts), setting up and maintaining computer labs for K-12 students. Sebastian Dziallas's "Undergraduate Education Strategies" was a look at the Red Hat-run Professors' Open Source Summer Experience (POSSE), which is a workshop for college professors interested in bringing open source to the classroom. Krumbach is both a volunteer and a board member with Partimus, a volunteer-driven nonprofit that accepts hardware donations, outfits them with free software, and provides them to San Francisco area schools. As she explained, Partimus's involvement includes not only the desktop systems used by students, but the network tools and system administration support required to keep the labs running. That frequently means setting up thin clients for the lab machines, plus network-mounted drives and imaging servers to provision or replace clients, and often setting up the infrastructure for the network itself: running Ethernet and power to all of the seats. The client software is based on Ubuntu, Firefox, and LibreOffice on the client side, plus OpenLDAP directory service and the DansGuardian filtering system — which fulfills a legal requirement for most schools. The talk examined three education deployments in depth, and the lessons interested projects could draw from each. The Mount Airy Learning Tree (MALT) is a community center in Philadelphia, and a Partimus-inspired effort by the Ubuntu Pennsylvania team worked with the center to build its first-ever computer lab. The deployment was initially a success, but it did not end well when MALT relocated to a new venue on the other side of the city. The volunteers who had been supporting the lab found it impossible to make the numerous trips required to support the new facility on an ongoing basis, and the new MALT staff were uninterested in the lab. Although community centers are often easier to work with than public schools, Krumbach said, the MALT experience underlines the necessity of having on-the-ground volunteers available, and of having buy-in by the community center staff itself. The Creative Arts Charter School (CACS) is a San Francisco charter school, meaning that it is publicly funded but can make autonomous decisions apart from the general school district. CACS is one of Partimus's flagship projects, an ongoing relationship that involves both labs and individual installs for various teachers. In the CACS case, Krumbach highlighted that supporting the computers required Partimus volunteers willing to go to the schools and inspect the machines in person. Teachers, being driven by the demands of the fixed academic calendar, rarely call in to report hardware or software failures: they simply work around them. The ASCEND charter school in Oakland is another Partimus effort, but one with a distinctly different origin story. Robert Litt, a teacher at ASCEND, learned about Linux and open source from an acquaintance, and sought out help himself. Partimus donated a server to the school, but acts more like a technology consultancy, providing help and educational resources, while the labs are run and maintained by Litt. Krumbach used the example as evidence of the value of a local champion: Litt is a forward-thinking, technology-aware teacher in other respects as well; he runs multiple blogs to communicate with and provide assignments to his elementary-age classes. A successful school deployment is not primarily a technological challenge, Krumbach said: the software is all there, and getting modern hardware donations is relatively easy. Instead, the challenges center around the individuals. She called attention to the "enthusiastic" leadership of Partimus director Christian Einfeldt, who is an effective advocate for the software and motivator of the volunteers. But on-the-ground supporters and strong allies at the school themselves are vital as well. Finally, she emphasized that "selling" schools on open source software required demonstrating it and providing training classes so that the teachers could gain firsthand experience — not merely enumerating a list of benefits. The audience in the session included many who either worked in education or who had firsthand experience advocating open source software in the classroom, which at times made for impassioned discussion. The topic that occupied the most time was how to respond when a Linux lab is challenged by the sudden appearance of a grant-funded (or corporate-donated) rival lab built on Windows. Apparently, in those situations it is common for the donation or the grant to stipulate that the new hardware be used only in a particular way — which precludes installing another operating system. Krumbach said that Partimus had encountered such a dilemma, and quoted Einfeldt as saying "it's wrong, but it sort of makes me glad when I walk into that lab and one third of the Windows computers don't boot. And they call us back in when half of them don't boot." Grants and corporate-sponsored donations relate to another important issue, which is that public schools do not deal with budgets like businesses do. They do have a budget (even a technology budget), Krumbach said, but the mindset is completely different: a school's budget is fixed, it is determined by outsiders, and the school has very little input into the process. In other words, schools don't deal with income and expenses like businesses do, and thus the "you'll start saving money now" argument common in the small business and enterprise market simply carries no weight. A better strategy is to directly connect open source software to opportunities to do new things: a new course, an optional extra-curricular activity, or a faster and simpler way to teach a particular subject. That approach makes charter schools an especially viable market, she said; anyone interested in promoting open source software would do well to pay attention to when local charter schools are in the planning stages. While Partimus is interested in the primary and secondary education market (and generally only at the desktop-user level), Red Hat's POSSE targets college professors who teach computer science and software engineering. It has been run both as a week-long boot camp and as a weekend experience, but in either case, the professors are split into groups and learn about the open source development model by immersion: getting familiar with wikis, distributed source code management, and communicating only by online means. Dziallas mentioned that (in at least one case) the professors were instructed to only communicate with each other over IRC during the project; IRC like other tools common in open source projects is rarely used in academia. At the end of a POSSE training course, the expectation is that the professors will use real-world open source projects as exercises and learning opportunities in their own classes — anywhere from serving as source material to assigning semester-long projects that get the students involved in actual development. In addition, the professors leave POSSE with valuable contacts in the open source community, including people who they can turn to when they have questions or when something goes wrong (such as a project delaying its next release to an inopportune time of year). Dziallas is currently a student at Olin College, and had worked as an intern at Red Hat in the summer of 2011. Based on that internship and his experience with POSSE, he presented his insights on the cultural differences between open source software and academia, and how understanding them could help bridge the gap. For starters, he pointed out that open source and academia have radically different timing on a number of fronts. Many Linux-related open source projects now operate on steady, six-month release cycles, while universities typically only re-evaluate their curriculum every four years. Planning is also different: open source projects vary from those with completely ad-hoc roadmaps to those that plan a year in advance — but academia thinks in two-to-five-year cycles for everything from hardware refreshes to accreditation. The "execution time" of the two worlds differs, too, with the lifecycle of a typical software release being six to twelve months, but the lifespan of a particular degree taking four to five years. As a result, he said, from the open source perspective the academic world seems glacially slow, but from academia's vantage point, open source is chaotic and unpredictable. But the differences do not stop there. In open source, jumping in and doing something without obtaining permission first is the preferred technique — while in academia it is anathema. Open source is always preoccupied with the problem of finding and recruiting more contributors, he said, while academia is currently interested in "mentoring," "portfolio material," and the "workplace readiness" of students. Industry has been quick to connect with universities, recruiting interns and new employees, but open source has so far not been as successful. POSSE is Red Hat's effort to bridge the gap and find common ground between open source in the wild and academia. The professors are encouraged to find an existing project that they care about, not to simply pick one at random, in the hopes of building a sustainable relationship. The "immersion" method of learning the open source methodology is supposed to be a quicker path to understanding it than any written explanation can provide. But ultimately, building connections between the interested professors and actual developers is one of the biggest benefits of the program. Dziallas calculated that of all of the college professors with an interest in learning more about open source, only 50% can make it to a POSSE event (for budgetary or time reasons). In addition, about 30% have some sort of "institutional blocker" that precludes their attendance beyond just logistical issues, and a tiny percentage drop out for loss of interest or other reasons. Thus POSSE is only reaching a fraction of the educators it would like to, but the challenge does not stop there. Among POSSE alumni, the challenge is maintaining a long-term relationship. The amount of support a professor receives after POSSE corresponds to the success rate. Although some are able to use institutional funds to further their involvement with open source (such as travel support to attend a conference, or to bring in a developer to give a guest lecture), most are not. POSSE has only been in operation since 2009, so its long-term sustainability has yet to be proven. But, Dziallas noted, regardless of whether or not the current formula is sustainable, "we must keep trying." As was the case with Krumbach's talk, the audience question-and-answer segment of the session was taken up largely by the question of how to make inroads into institutions where there is currently no Linux or open source presence. At the college level, of course, the specifics are different. One audience member asked how to combat purchasing decisions that locked out open source, to which Dziallas replied that there is a big difference between the software that students use to do their homework, and what shapes the education experience: if understanding open source and participating in the community is the goal, that goal can be accomplished on a computer running Microsoft software. Another audience member weighed in on the topic by suggesting that open source advocates take a closer look at the community colleges and technical colleges in their area, not just the four year, "liberal arts" institutions. In the United States, "community" and "technical" colleges typically have a different mandate, the argument went, and one that puts more emphasis on job training and on learning real-world skills. As a result, they move at a different pace than traditional institutions and respond to different factors. In both sessions, then, the speakers shared their successes, but the audience expressed an ongoing frustration with cracking into the educational computing space. Of course, selling Linux on the desktop has always been a tougher undertaking than selling it in the server room, but it is clear from the conversations at OSSIE that advocating open source in education is far more complicated than substituting "administrator" for "executive" and "classroom" for "office." Both Partimus and POSSE are gaining valuable insights through their own work about the distinct expectations, timing, and interaction it takes to present a compelling case to educators. They still have more information to gather, but even now other open source projects can learn from their progress.. Page editor: Jonathan Corbet Security A recent sudo advisory described a "format string vulnerability" that could be used for privilege escalation. Since sudo runs as setuid-root, that means that it could potentially be used by a regular user—not just one listed in the /etc/sudoers file—to compromise the system. As with many security flaws, format string vulnerabilities are the result of improper handling of user-supplied input. Given this latest report, it's probably worth taking a look at how these kind of vulnerabilities come about. For those who aren't C programmers, a little background may be in order. The standard C library function for printing things to stdout is printf()—other functions in the same family can be used to print to stderr, character buffers, or other files. That function takes a string as its first argument which can contain special formatting characters that describe the types of the rest of the arguments. For example: printf("hello, world\n"); printf("%s\n", "hello, world"); printf("%s, %s\n", "hello", "world");would all print the canonical string to stdout. The "%s" is the format specifier for a string, so the function expects the corresponding argument to be a pointer to a null-terminated array of characters. Members of the printf() family use the "varargs" (variable arguments) facility of the C language to take an arbitrary number of arguments. When the formatting string is parsed, values are popped off the stack in the order they are listed. Those values are expected to be there by the function, but, given the existing ABI, the compiler does not (in fact cannot) enforce that they be placed there by caller. That's where the problem can occur. In the easy case, compilers can and do warn when there is a mismatch between the format string and arguments. A call like: printf("hello, %s\n");will cause a warning if the warning level is set high enough (like -Wall for GCC). But those kinds of problems are relatively easily found. A trickier problem occurs with something like: printf(str);which is perfectly legal as long as str contains no formatting characters. If it does, however, the function will happily pop things off the stack that don't correspond to the arguments in that formatting string. For GCC, the "-Wformat -Wformat-nonliteral" flags can be used to detect this kind of thing. In the "best" case, having format specifiers in str will lead to a program crash, in the worst, it could end up executing code. If str comes from user-supplied input, an attacker may be able to arrange just the right formatting string to execute code of their choosing. That may be bad enough for a program run as an unprivileged user (as the attacker's code might be the equivalent of "rm -rf $HOME"), but it is far worse if the program has root privileges as sudo does. According to Wikipedia, format string bugs were noted in 1990, but were not recognized as a security problem until a researcher auditing proftpd reported a way to exploit the bug. That exploit used the "%n" format, which stores the number of characters printed so far to an integer pointer it pops off the stack. By arranging just the right format string, the exploit would overwrite the current user ID. In the sudo case, the program name (which is stored in argv[0] for C programs) was being printed as part of an error message. As the advisory from the finder describes, the program name was "printed" into a buffer (using a variant of sprintf()), and that buffer was then handed off to a vfprintf() as the format string. That meant that the user-controlled program name—which could certainly contain format specifiers—was used as the format string for the vfprintf(). The fix for sudo is to ensure that the program name is printed with a "%s" specifier in the final print statement, rather than building it into the earlier buffer. How can the user control the program name, especially for a setuid binary like sudo? That's not very hard either: $ ln -s /usr/bin/sudo %n The sudo advisory notes that building sudo with -D_FORTIFY_SOURCE=2 will prevent these kinds of exploits, though the advisory from the finder notes an article in Phrack that may make it possible to bypass that protection. The problem in sudo was introduced relatively recently, for version 1.8.0 released at the end of February 2011. It has now been fixed in 1.8.3p2 and affected distributions are starting to get updates out. These kinds of bugs are yet another lesson in the need for great care when handling user-controlled input. Brief items Full Story (comments: none) New vulnerabilities Page editor: Jake Edge Kernel development Brief items Stable updates: there have been no stable updates in the last week. The 2.6.32.56, 3.0.19, and 3.2.3 stable updates are in the review process as of this writing; they can be expected on or after February 3. Full Story (comments: none) Kernel development news An explanation of the problem requires just a bit of background, and, in particular, the definition of a couple of terms. "Readahead" is the process of speculatively reading file data into memory with the idea that an application is likely to want it soon. Reasonable performance when reading a file sequentially depends on proper readahead; that is the only way to ensure that reading and consuming the data can be done in parallel. Without readahead, applications will spend more time than necessary waiting for data to be read from disk. "Plugging," instead, is the process of stopping I/O request submissions to the low-level device for a period of time. The motivation for plugging is to allow a number of I/O requests to accumulate; that lets the I/O scheduler sort them, merge adjacent requests, and apply any sort of fairness policy that might be in effect. Without plugging, I/O requests would tend to be smaller and more scattered across the device, reducing performance even on solid-state disks. Now imagine that we have a process about to start reading through a long file, as indicated by your editor's unartistic rendering here: Once the application starts reading from the beginning of the file, the kernel will set about filling the first readahead window (which is 128KB with larger files) and submit I/O for the second window, so the situation will look something like this: Once the application reads past 128KB into the file, the data it needs will hopefully be in memory. The readahead machinery starts up again, initiating I/O for the window starting at 256KB; that yields a situation that looks something like this: This process continues indefinitely with the kernel running to always stay ahead of the application and have the data there by the time that application gets around to reading it. The 2.6.39 kernel saw some significant changes to how plugging is handled, with the result that the plugging and unplugging of queues is now explicitly managed in the I/O submission code. So, starting with 2.6.39, the readahead code will plug the request queue before it submits a batch of read operations, then unplug the queue at the end. The function that handles basic buffered file I/O (generic_file_aio_read()) also now does its own plugging. And that is where the problems begin. Imagine a process that is doing large (1MB) reads. As the first large read gets into generic_file_aio_read(), that function will plug the request queue and start working through the file pages already in memory. When it gets to the end of the first readahead window (at 128KB), the readahead code will be invoked as described above. But there's a problem: the queue is still plugged by generic_file_aio_read(), which is still working on that 1MB read request, so the I/O operations submitted by the readahead code are not passed on to the hardware; they just sit in the queue. So, when the application gets to the end of the second readahead window, we see a situation like this: At this point, everything comes to a stop. That will cause the queue to be unplugged, allowing the readahead I/O requests to be executed at last, but it is too late. The application will have to wait. That wait is enough to hammer performance, even on solid-state devices. The fix is to simply remove the top-level plugging in generic_file_aio_read() so that readahead-originated requests can get through to the hardware. Developers who have been able to reproduce the slowdown report that this patch makes the problem go away, so this issue can be considered solved. Look for this fix to appear in a stable kernel release sometime soon. Cyrill Gorcunov has been working to fill in some of the gaps with a preparatory patch set for user-space checkpointing/restore with the "CRIU" tool set. There are a number of small additions to the kernel ABI to be found here: Perhaps the most significant new feature, though, is the addition of a new system call: long kcmp(pid_t pid1, pid_t pid2, int type, unsigned long idx1, unsigned long idx2); Checkpoint/restore is meant to work as well on a tree of processes as on a single process. One challenge in the way of meeting that goal is that some of those processes may share resources - files, say, or, perhaps, a whole lot more. Replicating that sharing at restore time is relatively easy; the clone() system call provides a nice set of flags controlling the sharing of resources. The harder part is knowing, at checkpoint time, whether that sharing is taking place. One way for user space to determine whether, for example, two processes are sharing the same open file would be to query the kernel for the address of the associated struct file and see if they are the same in both processes. That kind of functionality sets off alarms among those concerned about security, though; learning where data structures live in kernel space is often an important precondition to an attack. There was talk for a while of "obfuscating" the pointers - through an exclusive-OR with a random value, for example - but the risk was still seen as being too high. So the compromise is kcmp(), which simply answers the question of whether resources found in two processes are the same or not. kcmp() takes two process ID parameters, indicating the processes of interest; both processes must be in the same PID namespace as the calling process. The type parameter tells the kernel the specific item that is being compared: The return value from kcmp() is zero if the two items are equal, one if the first item is "less" than the second, or two if the first is "greater" than the second. The ordered comparison may seem a little strange, especially when one looks at the implementation and sees that the pointers are obfuscated before comparison within the kernel. The result is, thus, an ordering that (by design) does not match the ordering of the relevant data structures in kernel space. It turns out that even a reshuffled (but consistent) "ordering" is useful for optimizing comparisons in user space when large numbers of open files are present. This patch set has been through a few cycles of review and seems to have addressed most of the concerns raised by reviewers. It may just find its way in through the next merge window. Meanwhile, people who want to see how the user-space side works can find the relevant code at criu.org. CRIU is not the only user-space checkpoint/restore implementation out there; the DMTCP (Distributed MultiThreaded CheckPointing) project has been busy since about 2.6.9. DMTCP differs somewhat from CRIU, though; in particular, it is able to checkpoint groups of processes connected by sockets - even across different machines - and it requires no changes to the kernel at all. These features come with a couple of limitations, though. Checkpoint/restore with DMTCP requires that the target process(es) be started with a special script; it is not possible to checkpoint arbitrary processes on the system. That script uses the LD_PRELOAD mechanism to place wrappers around a number of libc and (especially) system call implementations. As a result, DMTCP has no need to ask the kernel whether two processes are sharing a specific resource; it has been watching the relevant system calls and knows how the processes were created. The disadvantage to this approach - beyond having to run checkpointable process in a special environment - is that, as can be seen in the table of supported applications, not all programs can be checkpointed. The recent 1.2.4 release improves support, though, to the point that everything a wide range of users care about should be checkpointable. The system has been integrated with Open MPI and is able to respond to MPI-generated checkpoint and restore requests. DMTCP is available with the openSUSE, Debian Testing, and Ubuntu distributions. DMTCP may offer something good enough today for many users, who may not need to wait for one of the other projects to be ready sometime in the future. One of the many structures used by the btrfs filesystem, defined in fs/btrfs/ctree.h, is: struct btrfs_block_rsv { u64 size; u64 reserved; struct btrfs_space_info *space_info; spinlock_t lock; unsigned int full:1; }; Jan Kara recently reported that, on the ia64 architecture, the lock field was occasionally becoming corrupted. Some investigation revealed that GCC was doing a surprising thing when the bitfield full is changed: it generates a 64-bit read-modify-write cycle that reads both lock and full, modifies full, then writes both fields back to memory. If lock had been modified by another processor during this operation, that modification will be lost when lock is written back. The chances of good things resulting from this sequence of events are quite small. One can imagine that quite a bit of work was required to track down this particular surprise. It is also not hard to imagine the dismay that results from a conversation like this: Unsurprisingly, Linus was less than impressed by this response. Language standards are not written for the unique needs of kernels, he said, and can never "guarantee" the behavior that a kernel needs: But sometimes compilers do stupid things. Using 8-byte accesses to a 4-byte entity is *stupid*, when it's not even faster, and when the base type has been specified to be 4 bytes! As it happens, the problem is a bit worse than non-specified behavior. Linus suggested running a test with a structure like: struct example { volatile int a; int b:1; }; In this case, if an assignment to b causes a write to a, the behavior is clearly buggy: the volatile keyword makes it explicit that a may be accessed from elsewhere. Jiri Kosina gave it a try and reported that GCC is still generating 64-bit operations in this case. So, while the original problem is technically compliant behavior, it almost certainly results from the same decision-making that makes the second example go wrong. Knowing that may give the kernel community more ammunition to flame the GCC developers with, but it is not necessarily all that helpful. Regardless of the source of the problem, this behavior exists in versions of the compiler that, almost certainly, are being used outside of the development community to build the kernel. So some sort of workaround is likely to be necessary even if GCC's behavior is fixed. That could be a bit of a challenge; auditing the entire kernel for 32-bit-wide bitfield variables in structures that may be accessed concurrently will not be a small job. But, then, nobody said that kernel development was easy. Patches and updates Kernel trees Architecture-specific Core kernel code Development tools Device drivers Filesystems and block I/O Memory management Networking Security-related Virtualization and containers Page editor: Jonathan Corbet Distributions On January 16, John Kozubik posted to the FreeBSD-hackers list and expressed his disappointment in some of the recent trends in the project. Namely, an increasingly-slow release cycle, too many overlapping "production" releases, and an estrangement between the core developers and end users when it comes to support issues like bug fixes. The list has since debated Kozubik's assessment of the situation in a heroically long thread, but while the majority agree that FreeBSD would benefit from refocusing its energies and polishing its processes, it has not yet developed a concrete plan of action. Kozubik himself is not a FreeBSD developer; he manages enterprise production environments (including rsync.net) that run almost 1,000 FreeBSD machines. As he explained in his initial message, he was disappointed to hear that the next point release of the OS, 8.3, has been pushed back to March 2012 — more than a year after 8.2. Such a long stretch between minor releases makes maintaining a stable server farm difficult, but paradoxically FreeBSD has also complicated the lives of its end users by simultaneously pushing out multiple "production releases" with different major numbers — at present including versions 7.4, 8.2, and 9.0. Once a new "major" version is in development, he said, important patches to the previous major version start to languish, as developers lose interest in donating their time to the old code and to less-than-exciting maintenance tasks. As a result, enterprise users face a difficult choice: either go without new features and fixes in the "old" production release, or risk the instability of the "new" production release. He worries that FreeBSD may be "becoming an operating system by, and for, FreeBSD developers" — to the ultimate alienation of users. Kozubik then outlined five underlying causes that contribute to the alienation problem, and proposes three fixes. First, there is a "widening gap of understanding" between the developers and end users, caused by developers frequently jumping between bleeding-edge snapshots of the code, rather than running the releases tagged as stable for production use. The disconnect makes discussing maintenance issues difficult. Second, maintaining multiple "production releases" simultaneously dilutes developer focus, which keeps the releases from ever truly maturing. Third, the simultaneous production releases drive away potential paid investment from enterprise customers, because they view each FreeBSD release with uncertainty. Fourth, the slow pace of minor releases means that important fixes often sit unreleased long after they have been verified by maintainers. That not only hurts end users (by depriving them of regression fixes and security updates), but downstream projects as well. Finally, when the slow pace of minor releases is coupled with the multiple-major-releases problem, new code and fixes increasingly get bumped from the "old production" release to the "new production release," solely because the new release is what developers are interested in working on. This traps enterprise users in "the same bad choice again: make major investments in testing and people and processes every two years, or just limp along with old, buggy drivers and no support." Kozubik called this "the culture of 'that's fixed in CURRENT' or 'we built those changes into (insert next major release)'." He suggested that the project take three steps to ameliorate the trouble. First, intentionally consider the processes and costs incurred by large FreeBSD deployments. "Think about the logistics of major upgrades and the difficulty of running snapshot releases, etc. Remember - if it's not fixed in the production release, it's NOT FIXED. Serious (large) end users have very little use for CURRENT." Second, the project should focus on just one production release at a time, and commit to a definite support schedule (Kozubik suggests five years as a production release, followed by five years as a "legacy" release). Third, in concert with the predictable major release schedule, the project should commit to doing smaller, more frequent minor updates, around three times per year. A majority of the people who joined in the discussion agreed that something like what Kozubik proposed would be beneficial. Opinion varied, however, on what the underlying causes are, and whether or not they can be fixed in the short term. Rich Healey observed that there are very few paid FreeBSD developers, and while volunteers have little motivation to undertake the unexciting maintenance tasks, the paid developers that exist are often contracted to implement specific new features. Warner Losh said that no corporate sponsor has been pushing the project to keep the release process on schedule since the demise of Walnut Creek. Julian Elischer responded by suggesting that interested high-volume customers and downstream vendors could pool their resources and pay a developer to work specifically on release management — a suggestion that was met with approval. FreeBSD release engineer Robert Watson described the dilemma as a release engineering problem — with several causes — that he and the other release team members could address. Historically, he said, the FreeBSD base and ports collection were on a single, tightly-coupled release cycle — which often resulted in ports getting very little attention. In the early days, he added, the project used CVS version control, which made branching very expensive. Last but not least, the project has come to rely on a single "head release engineer" to steer all of the release schedules, which results in bottlenecks and slipping release dates. The CVS problem has been addressed by moving to Subversion, he said, and there is growing support for de-coupling the base and ports releases, but the project still needs to fix the single-release-engineer issue. Watson suggested mentoring-in new release managers from the developer community, each of whom would take responsibility for one minor release. On the other hand, Igor Mozolevsky argued that the FreeBSD Problem Report (PR) patch system is broken, because it effectively requires end users to undertake a nagging campaign to even get a patch examined by a developer. That drives away users and is clearly sub-optimal for the project. Not everyone agreed with that assessment, although Matthew Fuller cited an example of a manpage fix collecting dust for three years. Adam Vande More speculated that a bounty system would motivate quicker PR merges — but Matt Olander from iXsystems pointed out that he has set one up already. Watson again suggested changes that the project could make to its existing processes, starting with replacing the GNATS issue-tracker that no one seems to like, and adopting a more formal policy for trawling PRs and triaging bug reports. Not everyone was on board with Kozubik's reading of the situation, however. Ivan Voras disagreed completely, saying that "the situation is actually quite good," and that "nobody would mind" if there were no more stable releases at all. "The 'releases' are for many people simply a periodical annoyance due to freezes," he said. Kozubik replied that "I could not have illustrated my point better, RE: FreeBSD becoming an OS by, and for, FreeBSD developers," and explained that most businesses will simply not use software that is not "officially" released. Andriy Gapon defended the concept of a "by the developers, for the developers" mindset as the equivalent to being a community project. Projects that exist "for the users," he argued, tend to exist for commercial purposes, and be backed by profit-driven corporations. FreeBSD is more akin to the Debian project, he said, which is very much a "for the developers" effort, but still quite successful. Adrian Chadd took issue with the question being raised at all, saying: But Doug Barton quickly responded "let's do away with the whole, 'If you step up to help, your help will be accepted with open arms' myth. That's only true if the project leadership agrees with your goals." The FreeBSD project needs to do some serious thinking about things like the role of "committer" and the meaning of "release," he said, including the difference between major and minor releases, all of which are terms with no formal definition. "We also need to take a step back and ask if throwing more person-hours at the problem is the right solution, or if redesigning the system to better meet the needs of the users *as a first step* is the right answer." Barton suggested defining minor "point releases" as updates only to the FreeBSD base, not the ports collection or documentation. "The other thing I think has been missing (as several have pointed out in this thread already) is any sort of planning for what should be in the next release," he added. The current release schedule is a hold-over from the trouble-filled days the project experienced in the FreeBSD 5.x era, he said, but "the pendulum has swung *way* too far in the wrong direction, such that we are now afraid to put *any* kind of plan in place for fear that it will cause the release schedule to slip." Watson concurred, adding that ""here's been an over-swing caused by the diagnosis 'it's like herding cats' into 'cats can't be herded, so why try?'" — and asking list members if they could come up with a tentative release schedule. The debate continues, without a consensus yet on a release schedule. For his part, Kozubik favored immediately declaring FreeBSD 7.z end-of-life, marking 8.x as "legacy," and tagging 9.x as the only production release. Not everyone agrees with Kozubik's five-production-years-plus-five-legacy-years timetable; though there is support for a five-year total support life, and most developers seem to think that making minor releases every four months is doable. Such a schedule would be roughly in line with what the commercial Linux distributors offer, and as Freddie Cash observed, the maintenance of a production release alongside a legacy release is similar to the process used by Debian. The big question remains whether the project will be able to hash out all of the details in time to commit to a concrete release schedule for 9.x itself — or whether the new release process will have to wait for FreeBSD 10.0. Brief items When reboots don’t go horribly wrong. Despite the privation we have all endured, please find strength to stop this nightmarish ravaging of our once-pure filesystems. For if he’s not stopped now, what hope for /usr/sbin vs /usr/bin? Full Story (comments: none) Distribution News Ubuntu family Full Story (comments: none) Newsletters and articles of interest Page editor: Rebecca Sobol Development Turning an on-screen session into a video is a widely used technique for a number of different uses, but one of its main use-cases is for education. One can find any number of "screencasts" on YouTube or elsewhere that show how to do particular tasks using various tools like Gimp or Blender. Depending on the task, it's generally much easier to show people how to do something rather than to try to explain in words the steps required. There are a few different Linux tools available for doing screen recording. Perhaps the best-known choice is recordMyDesktop, which is actually a command-line tool that provides a means to turn a region of the desktop into a video—in Ogg-Theora-Vorbis format. As the man page describes, there are lots of different options that can be used to control the area that will be recorded, the video format and frame rate, sound options, and so on. But, since screen recording is an inherently visual task, there are both GTK and Qt front-ends available. Both of the front-ends are written in Python using either pyGtk or pyQt4, and both, not surprisingly, provide a GUI interface to the recordMyDesktop command line. As one might guess, the front-ends pretty much look and act the same (the Qt version is seen at right). In the simplest case, one simply indicates the region of interest on the preview pane. Once the region is selected, hitting the "Record" button starts the video capture. Amusingly, because the preview pane shows the entire window, including the qt-recordMyDesktop window itself, one gets an "infinite" regression in the pane. One can also choose a particular window, rather than a region, by using the "Select Window" option. But, in either case, it is really the rectangular region of the visible screen that is being recorded. If another window is moved into the region, or a different virtual desktop is chosen, that's what goes into the video. Depending on the use, that may be exactly what is called for, but, for other uses, like recording an online lecture or webcast, it may require extra care. Popping up an email client or web browser to quickly check something may result in unwanted video artifacts. Audio can also be recorded, either from the audio that accompanies the content or from a local microphone. For the specific recording I was doing (a Go class lecture on the KGS Go Server), it required switching the sound source in recordMyDesktop from "DEFAULT" to "pulse" and using pavucontrol to change the recording source for the application to the "Monitor" of my sound card. It was a little non-obvious, at least to me, but there were multiple solutions that Google led me to, including this. The "Advanced" settings allow changing things like the sound source mentioned above, but also frame rate, on-the-fly encoding, mouse cursor settings, and more. As with video in general, files can get fairly large for a 90-minute class, so reducing the size of the recording area and the frame rate will produce smaller video while still capturing the information needed. A 2 frames per second (fps) setting, for example, may be fine for showing human-initiated screen changes and can make a big reduction in size from the default 30fps. The recording is stopped from a panel applet (or a signal to the recordMyDesktop process), which will then start the encoding process (unless on-the-fly encoding is chosen). The end result is a out.ogv file that can be played in Totem, Dragon Player, or other video players. Sadly, sharing Ogg format video with much of the rest of the world is difficult, so transcoding to WebM (maybe) or H.264 is probably required. Transmageddon or Arista (for those not running the GStreamer bleeding edge) fit the transcoding bill nicely. Another option for recording is Istanbul, which has a minimal "GUI" via the menu from its panel applet. It lacks many of the advanced features of recordMyDesktop, including the ability to directly record audio. One can use a separate audio recorder and try to synchronize the audio and video (as the Fedora wiki suggests), but that may prove somewhat painful. Another option is Byzanz, which is a command-line-only tool that also lacks audio support (and, seemingly, a home page). From discussions with other students who use OS X or Windows, the choices there are more varied, but generally not free (in either sense of the term). I found recordMyDesktop to be more than adequate for the task at hand, and it would seem that lots of others are using it as well. If audio is not required (or can be recorded separately, perhaps by narrating while watching the video for example), Istanbul or Byzanz may suit as well. Foolishly, I set out on this task thinking that Linux options might be difficult to find or use—video applications for Linux have had that reputation in the past—but was happily surprised to find that it wasn't the case. Brief items Full Story (comments: none) Newsletters and articles Page editor: Jonathan Corbet Announcements Brief items Full Story (comments: none) Full Story (comments: none)
https://lwn.net/Articles/477349/bigpage
CC-MAIN-2017-30
en
refinedweb
Clears an instance of a Slapi_RDN structure. #include "slapi-plugin.h" void slapi_rdn_done(Slapi_RDN *rdn); This function takes the following parameter: Pointer to the structure to be cleared. This function clears the contents of a Slapi_RDN structure. It frees both the RDN value and the array of split RDNs. Those pointers are then set to NULL.
http://docs.oracle.com/cd/E19424-01/820-4810/aailh/index.html
CC-MAIN-2017-30
en
refinedweb
#include <time.h> char *ctime(const time_t *clock); struct tm *localtime(const time_t *clock); struct tm *gmtime(const time_t *clock); char *asctime(const struct tm *tm); extern time_t timezone, altzone; extern int daylight; extern char *tzname[2]; void tzset(void); char *ctime_r(const time_t *clock, char *buf, int buflen); struct tm *localtime_r(const time_t *restrict clock, struct tm *restrict res); struct tm *gmtime_r(const time_t *restrict clock, struct tm *restrict res); char *asctime_r(const struct tm *restrict tm, char *restrict buf, int buflen); cc [ flag... ] file... –D_POSIX_PTHREAD_SEMANTICS [ library... ] char *ctime_r(const time_t *clock, char *buf); char *asctime_r(const struct tm *tm, char *buf);time_r() function has the same functionality as ctime() except that the caller must supply a buffer buf with length buflen to store the result; buf must be at least 26 bytes. The standard-conforming ctime_r()time_r() and gmtime_r(). The asctime_r() function has the same functionality as asctime() except that the caller must supply a buffer buf with length buflen for the result to be stored. The buf argument must be at least 26 bytes. The standard-conforming, 60] */ /*, conversion for various time periods for the U.S. (specifically, the years 1974, 1975, and 1987). They start handling the new daylight savings time starting with the first Sunday in setting,)). Upon successful completion, the gmtime() and localtime() functions return a pointer to a struct tm. If an error is detected, gmtime() and localtime() return a null pointer. Upon successful completion, the gmtime_r() and localtime_r() functions return the address of the structure pointed to by the res argument. If an error is detected, gmtime_r() and localtime_r() return a null pointer and set errno to indicate the error. The ctime_r() and asctime_r() functions will fail if: The length of the buffer supplied by the caller is not large enough to store the result. The gmtime(), gmtime_r(), localtime(), and localtime_r() functions will fail if: The result cannot be represented. historical records. positive.. See attributes(5) for descriptions of the following attributes: The asctime(), ctime(), gmtime(), and localtime() functions are safe to use in multithread applications because they employ thread-specific data. However, their use is discouraged because standards do not require them to be thread-safe. The asctime_r() and gmtime_r() functions are MT-Safe. The ctime_r(), localtime_r(),(). time(2), Intro(3), getenv(3C), mktime(3C), printf(3C), putenv(3C), setlocale(3C), strftime(3C), TIMEZONE(4), attributes(5), environ(5), standards(5)time_r(), localtime_r(), gmtime_r(), and asctime_r() functions as specified in POSIX.1c Draft 6. The final POSIX.1c standard changed the interface for ctime_r() and asctime_r(). >= 199506L. In Solaris 10, gmtime(), gmtime_r(), localtime(), and localtime_r() were updated to return a null pointer if an error is detected. This change was based on the SUSv3 specification. See standards(5).
http://docs.oracle.com/cd/E36784_01/html/E36874/localtime-3c.html
CC-MAIN-2017-30
en
refinedweb
Getting Started With GraphQL in Angular with Apollo Apollo is a GraphQL client that makes it very easy to develop GraphQL applications with the likes of React and Angular. All you need to get started is a few dependencies and a client configuration, and you’ll be off to the races running queries and mutations against your GraphQL endpoints. You can refer to our intro to GraphQL queries if you're new to GraphQL in general. Let’s get started by installing the required packages (apollo-client, apollo-angular and graphql-tag) with Yarn or NPM: # Yarn $ yarn add apollo-client apollo-angular graphql-tag # NPM $ npm i -S apollo-client apollo-angular graphql-tag - apollo-client is the client library that works for any platform. - apollo-angular is the Angular integration for the Apollo client. - graphql-tag is the tag that parses your GraphQL queries/mutations. Client Configuration Let’s create a file called client.ts in the root of our application and include the following: client.ts import { ApolloClient, createNetworkInterface } from 'apollo-client'; const clientConfig = new ApolloClient({ networkInterface: createNetworkInterface({ uri: '' }) }); export function client(): ApolloClient { return clientConfig; } Note how we used createNetworkInterface to define our API endpoint. In the example we put a sample Graphcool endpoint. Graphcool is a popular GraphQL backend as a service. The client would default to an endpoint of /graphql if the network interface wasn’t specified. The Apollo module’s forRoot method takes a function that returns a client configuration, hence our client function in client.ts. In your app module, import the ApolloModule, your client configuration file and add the module to your @NgModule ‘s imports: app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; import { ApolloModule } from 'apollo-angular'; import { client } from './client'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, ApolloModule.forRoot(client) ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } You’re now ready to start using the client in your components and services. Using the Client Let’s see an example of using our newly configured client, here let’s imagine that our GraphQL endpoint on Graphcool has a Post type that can be queried: app.component.ts import { Component, OnInit } from '@angular/core'; import { Apollo } from 'apollo-angular'; import gql from 'graphql-tag'; @Component({ ... }) export class AppComponent implements OnInit { loading = true; data: any; constructor(private apollo: Apollo) {} ngOnInit() { this.apollo.query({ query: gql`query getAllPosts { posts: allPosts { title url } }` }).subscribe(({data, loading}) => { this.data = data; this.loading = loading; }); } } We injected Apollo in our constructor and then ran our query in the ngOnInit lifecycle hook. Notice how Apollo queries return an observable that we can subscribe to, and also how we get loading, which evaluates to true when the query starts and false when it’s resolved. This makes it easy to create loading indicators when getting data from an endpoint. We could also refactor and have our query strings defined outside of our component class, like this: import { Component, OnInit } from '@angular/core'; import { Apollo } from 'apollo-angular'; import gql from 'graphql-tag'; const allPosts = gql`query getAllPosts { posts: allPosts { title url } }`; @Component({ ... }) export class AppComponent implements OnInit { loading = true; data: any; constructor(private apollo: Apollo) {} ngOnInit() { this.apollo.query({ query: allPosts }).subscribe(({data, loading}) => { this.data = data; this.loading = loading; }); } } Template Access And in the template we can access our data with something like the following: <ul * <li *{{ post.title }} - {{ post.url }}</li> </ul> <ng-template #loadingMsg> Loading your posts... </ng-template> We used the else clause that’s available since Angular 4 to show a loading message while our data is being retrieved. Mutations Let’s give you an example of how we would create a new post with a mutation when the user clicks a button that’s bound to an newPost method: newPost() { this.apollo.mutate({ mutation: gql`mutation($title: String, $url: String) { createPost(title: $title, url: $url) { title url } } `, variables: { title: this.someForm.get('title'), url: this.someForm.get('url')' } }).subscribe(data => { console.log('New post created!', data); }); } 🌈 That's it for now. Go on and query that graph!
https://alligator.io/angular/getting-started-graphql-apollo/
CC-MAIN-2017-30
en
refinedweb
Static, by application programs. And, it is performed by programs called linkers. Linkers are also called link editors. Linking is performed as the last step in compiling a program. In this tutorial static and dynamic linking with C modules will be discussed. Linker is system software which plays crucial role in software development because it enables separate compilation. Instead of organizing a large application as one monolithic source file, you can decompose it into smaller, more manageable chunks that can be modified and compiled separately. When you change one of the modules, you simply recompile it and re-link the application, without recompiling the other source files. During static linking the linker copies all library routines used in the program into the executable image. This of course takes more space on the disk and in memory than dynamic linking. But static linking is faster and more portable because it does not require the presence of the library on the system where it runs. At the other hand, in dynamic linking shareable library name is placed in the executable image, while actual linking takes place at run time when both the executable and the library are placed in memory. Dynamic linking serves the advantage of sharing a single shareable library among multiple programs. Linker as a system program takes relocatable object files and command line arguments in order to generate an executable object file. To produce an executable file the Linker has to perform the symbol resolution, and Relocation. Note: Object files come in three flavors viz Relocatable, Executable, and Shared. Relocatable object files contain code and data in a form which can be combined with other object files of its kind at compile time to create an executable object file. They consist of various code and data sections. Instructions are in one section, initialized global variables in another section, and uninitialized variables are yet in another section. Executable object files contain binary code and data in a form which can directly be copied into memory and executed. Shared object files are files those can be loaded into memory and linked dynamically, at either load or run time by a linker. Through this article, static and dynamic linking will be explained. While linking, the linker complains about missing function definitions, if there is any. During compilation, if compiler does not find a function definition for a particular module, it just assumes that the function is defined in another file, and treats it as an external reference. The compiler does not look at more than one file at a time. Whereas, linker may look at multiple files and seeks references for the modules that were not mentioned. The separate compilation and linking processes reduce the complexity of program and gives the ease to break code into smaller pieces which are better manageable. Static linking is the process of copying all library modules used in the program into the final executable image. This is performed by the linker and it is done as the last step of the compilation process. The linker combines library routines with the program code in order to resolve external references, and to generate an executable image suitable for loading into memory. Let's see static linking by example. Here, we will take a very simple example of adding two integer quantities to demonstrate the static linking process. We will develop an add module and place in a separate add.c file. Prototype of add module will be placed in a separate file called add.h. Code file addDemo.c will be created to demonstrate the linking process. To begin with, create a header file add.h and insert the add function signature into that as follows: int add(int, int); Now, create another source code file viz addDemo.c, and insert the following code into that. #include <add.h> #include <stdio.h> int main() { int x= 10, y = 20; printf("\n%d + %d = %d", x, y, add(x, y)); return 0; } Create one more file named add.c that contains the code of add module. Insert the following code into add.c int add(int quant1, int quant2) { return(quant1 + quant2); } After having created above files, you can start building the executable as follows: [root@host ~]# gcc -I . -c addDemo.c The -I option tells GCC to search for header files in the directory which is specified after it. Here, GCC is asked to look for header files in the current directory along with the include directory. (in Unix like systems, dot(.) is interpreted as current directory). Note: Some applications use header files installed in /usr/local/include and while compiling them, they usually tell GCC to look for these header files there. The -c option tells GCC to compile to an object file. The object file will have name as *.o. Where * is the name of file without extension. It will stop after that and won't perform the linking to create the executable. As similar to the above command, compile add.c to create the object file. It is done by following command. [root@host ~]# gcc -c add.c This time the -I option has been omitted because add.c requires no header files to include. The above command will produce a new file viz add.o. Now the final step is to generate the executable by linking add.o, and addDemo.o together. Execute the following command to generate executable object file. [root@host ~]# gcc -o addDemo add.o addDemo.o Although, the linker could directly be invoked for this purpose by using ld command, but we preferred to do it through the compiler because there are other object files or paths or options, which must be linked in order to get the final executable. And so, ld command has been explained in detail in How to Compile a C Program section. Now that we know how to create an executable object file from more than one binary object files. It's time to know about libraries. In the following section we will see what libraries are in software development process? How are they created? What is their significance in software development? How are they used, and many things which have made the use of libraries far obvious in software development? Static and shared libraries are simply collections of binary object files they help during linking. A library contains hundreds or thousands of object files. During the demonstration of addDemo we had two object files viz add.o, and addDemo.o. There might be chances that you would have ten or more object files which have to be linked together in order to get the final executable object file. In those situations you will find yourself enervate, and every time you will have to specify a lengthy list of object files in order to get the final executable object file. Moreover, fenceless object files will be difficult to manage. Libraries solve all these difficulties, and help you to keep the organization of object files simple and maintainable. Static libraries are explained here, dynamic libraries will be explained along with dynamic linking. Static libraries are bundle of relocatable object files. Usually they have .a extension. To demonstrate the use of static libraries we will extend the addDemo example further. So far we have add.o which contains the binary object code of add function which we used in addDemo. For more explanatory demonstration of use of libraries we would create a new header file heymath.h and will add signatures of two functions add, sub to that. int add(int, int); //adds two integers int sub(int, int); //subtracts second integer from first Next, create a file sub.c, and add the following code to it. We have add.c already created. int sub(int quant1, int quant2) { return (quant1 - quant2); } Now compile sub.c as follows in order to get the binary object file. [root@host ~]# gcc -c sub.c Above command will produce binary object file sub.o. Now, we have two binary object files viz add.o, and sub.o. We have add.o file in working directory as we have created it for previous example. If you have not done this so far then create the add.o from add.c in similar fashion as sub.o has been created. We will now create a static library by collecting both files together. It will make our final executable object file creation job easier and next time we will have not to specify two object files along with addDemo in order to generate the final executable object file. Create the static library libheymath by executing the following command: [root@host ~]# ar rs libheymath.a add.o sub.o The above command produces a new file libheymath.a, which is a static library containing two object files and can be used further as and when we wish to use add, or sub functions or both in our programs. To use the sub function in addDemo we need to make a few changes in addDemo.c and will recompile it. Make the following changes in addDemo.c. #include <heymath.h> #include <stdio.h> int main() { int x = 10, y = 20; printf("\n%d + %d = %d", x, y, add(x, y)); printf("\n%d + %d = %d", x, y, sub(x, y)); return 0; } If you see, we have replaced the first statement #include <add.h> by #include <heymath.h>. Because heymath.h now contains the signatures of both add and sub functions and added one more printf statement which is calling the sub function to print the difference of variable x, and y. Now remove all .o files from working directory (rm will help you to do that). Create addDemo.o as follows: [root@host ~]# gcc -I . -c addDemo.c And link it with heymath.a to generate final executable object file. [root@host ~]# gcc -o addDemo addDemo.o libheymath.a You can also use the following command as an alternate to link the libheymath.a with addDemo.o in order to generate the final executable file. [root@host ~]# gcc -o addDemo -L . addDemo.o -lheymath In above command -lheymath should be read as -l heymath which tells the linker to link the object files contained in lib<library>.a with addDemo to generate the executable object file. In our example this is libheymath.a. The -L option tells the linker to search for libraries in the following argument (similar to how we did for -I). So, what we created as of now is a static library. But this is not the end; systems use a lot of dynamic libraries as well. It is the right time to discuss them. Dynamic linking defers much of the linking process until a program starts running. It performs the linking process "on the fly" as programs are executed in the system. During dynamic linking the name of the shared library is placed in the final executable file while the actual linking takes place at run time when both executable file and library are placed in the memory. The main advantage to using dynamically linked libraries is that the size of executable programs is dramatically reduced because each program does not have to store redundant copies of the library functions that it uses. Also, when DLL functions are updated, programs that use them will automatically obtain their benefits. A shared library (on Linux) or a dynamic link library (dll on Windows) is a collection of object files. In dynamic linking, object files are not combined with programs at compile time, also, they are not copied permanently into the final executable file; therefore, a shared library reduces the size of final executable. Shared libraries or dynamic link libraries (dlls) serve a great advantage of sharing a single copy of library among multiple programs, hence they are called shared libraries, and the process of linking them with multiple programs is called dynamic linking. Shared libraries are loaded into memory by programs when they start. When a shared library is loaded properly, all programs that start later automatically use the already loaded shared library. Following text will demonstrate how to create and use shared library on Linux. Let's continue with the previous example of add, and sub modules. As you remember we had two object files add.o, and sub.o (compiled from add.c and sub.c) that contain code of add and sub methods respectively. But we will have to recompile both add.c and sub.c again with -fpic or -fPIC option. The -fPIC or -fpic option enable "position independent code" generation, a requirement for shared libraries. Use -fPIC or -fpic to generate code. Which option should be used, -fPIC or -fpic to generate code that is target-dependent. The -fPIC choice always works, but may produce larger code than -fpic.. So, while creating shared library you have to recompile both add.c, and sub.c with following options: [root@host ~]# gcc -Wall -fPIC -c add.c [root@host ~]# gcc -Wall -fPIC -c sub.c Above commands will produce two fresh object files in current directory add.o, and sub.o. The warning option -Wall enables warnings for many common errors, and should always be used. It combines a large number of other, more specific, warning options which can also be selected individually. For details you can see man page for warnings specified. Now build the library libheymath.so using the following command. [root@host ~]# gcc -shared -o libheymath.so add.o sub.o This newly created shared library libheymath.so can be used as a substitute of libheymath.a. But to use a shared library is not as straightforward as static library was. Once you create a shared library you will have to install it. And, the simplest approach of installation is to copy the library into one of the standard directories (e.g., /usr/lib) and run ldconfig command. Thereafter executing ldconfig command, the addDemo executable can be built as follows. I recompile addDemo.c also. You can omit it if addDemo.o is already there in your working directory. [root@host ~]# gcc -c addDemo.c [root@host ~]# gcc -o addDemo addDemo.o libheymath.so or [root@host ~]# gcc -o addDemo addDemo.o -lheymath You can list the shared library dependencies which your executable is dependent upon. The ldd <name-of-executable> command does that for you. [root@host ~]# ldd addition libheymath.so => /usr/lib/libheymath.so (0x00002b19378fa000) libc.so.6 => /lib64/libc.so.6 (0x00002b1937afb000) /lib64/ld-linux-x86-64.so.2 (0x00002b19376dd000) In this tutorial we discussed how static and dynamic linking in C is performed for static and shared libraries (Dynamic Link Libraries - DLLs).
http://cs-fundamentals.com/c-programming/static-and-dynamic-linking-in-c.php
CC-MAIN-2017-30
en
refinedweb
I was wondering if there is an optimization in gcc that can make some single-threaded code like the example below execute in parallel. If no, why? If yes, what kind of optimizations are possible? #include <iostream> int main(int argc, char *argv[]) { int array[10]; for(int i = 0; i < 10; ++ i){ array[i] = 0; } for(int i = 0; i < 10; ++ i){ array[i] += 2; } return 0; } The compiler can try to automatically parallelise your code, but it wont do it by creating threads. It may use vectorised instructions (intel intrinsics for an intel CPU, for example) to operate on multiple elements at a time, where it can detect that using those instructions is possible (for example when you perform the same operation multiple times on consecutive elements of a correctly aligned data structure). You can help the compiler by telling it which intrinsic instruction set your CPU supports ( -mavx, -msse4.2 ... for example). You can also use these instructions directly, but it requires a non-trivial amount of work for the programmer. There are also libraries which do this already (see the vector class here Agner Fog's blog). You can get the compiler to auto-parallelise using multiple threads by using OpenMP (OpenMP introducion), which is more instructing the compiler to auto-parallelise, than the compiler auto-parallelising by itself.
https://codedump.io/share/8brepCphS0uj/1/can-gcc-make-my-code-parallel
CC-MAIN-2017-30
en
refinedweb
Django app which makes easy to create sports team website. # django-league Django app which makes easy to create sports team website ## Requirements Django == 1.9.7 Python >= 3 ## Installation Download app to your project and enable it in INSTALLED_APPS Then include urls in urls.py `url(r'^league/', include('league.urls', namespace='league')),` Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/django-league/
CC-MAIN-2017-30
en
refinedweb
Amazingly, it still hangs with --no-window-system. I still have to `unset DISPLAY` before running makepkg. Maybe `env -i octave` could be a solution. Also, the compile still fails with the same problem (octave/base-lu.h isn't included in extra/octave anymore). Search Criteria Package Details: octave-communications 1.2.1-3 Dependencies (2) - octave-signal>=1.1.3 - octave>=3.4.0 (octave-hg) Required by (0) Sources (1) Latest Comments Calimero commented on 2017-01-20 11:32 Amazingly, it still hangs with --no-window-system. I still have to `unset DISPLAY` before running makepkg. Calimero commented on 2017-01-16 10:39 Found the problem. /usr/bin/octave is the graphical interface by default since a few months on Arch. If I unset DISPLAY, the build doesn't hang anymore. Aren't package building systems supposed to sanitize environment variables, though!? Now the compile fails (but the package gets built, with empty contents): In file included from galois-def.cc:21:0: galois.h:25:28: fatal error: octave/base-lu.h : No such file or directory #include <octave/base-lu.h> extra/octave doesn't include the file anymore, but it used to. Calimero commented on 2017-01-04 16:13 The compile hangs for me, on "checking for Octave HDF5 preprocessor flags... " drizzd commented on 2016-12-21 20:21 Known issue: No workaround available other than patching Octave source. j605 commented on 2016-12-19 17:15 The package fails to compile with the latest release, "galois.h:25:28: fatal error: octave/base-lu.h: No such file or directory".
https://aur.archlinux.org/packages/octave-communications/
CC-MAIN-2017-30
en
refinedweb
Parallel execution with Python With Python it is relatively easy to make programs go faster by running things in parallel on multiple cores. This article shows you how. We sill concentrate on a type of problem that is easy to parallelize. Problem description Suppose you have a huge number of files and a program that has to be run on each of them. This could be e.g. a collection of holiday videos that has to be converted to a different format. Or a bunch of photos that need gamma correction. A first attempt to solve this problem could be a shell-script that compiles a list of files and then runs the program in question them. This will work but will convert the files one at a time. All but one of the cores of your shiny multi-core machine are doing nothing and the run will take ages. With modern multi-core machines it has become possible to make scripts that perform the same action on different files faster by using more processes. Let’s see how this would work in Python 3. Solutions in Python Using multiprocessing.Pool directly A proper way to run jobs in multiple processed in Python is to run Python code in the worker processes of a Pool. The following example uses the ImageMagick binding module wand to convert DICOM images to PNG format. from multiprocessing import Pool import os import sys from wand.image import Image def convert(filename): """Convert a DICOM file to a PNG file, removing the blank areas from the Philips detector. Arguments: filename: name of the file to convert. Returns: Tuple of (input filename, output filename) """ outname = filename.strip() + '.png' with Image(filename=filename) as img: with img.convert('png') as converted: converted.units = 'pixelsperinch' converted.resolution = (300, 300) converted.crop(left=232, top=0, width=1568, height=2048) converted.save(filename=outname) return filename, outname def main(argv): """Main program. Arguments: argv: command line arguments """ if len(argv) == 1: binary = os.path.basename(argv[0]) print("{} ver. {}".format(binary, __version__), file=sys.stderr) print("Usage: {} [file ...]\n".format(binary), file=sys.stderr) print(__doc__) sys.exit(0) del argv[0] # Remove the name of the script from the arguments. es = 'Finished conversion of {} to {}' p = Pool() for infn, outfn in p.imap_unordered(convert, argv): print(es.format(infn, outfn)) if __name__ == '__main__': main(sys.argv) Since the work is done in separate processes, the Python GIL is not a factor. This is a good example of using a multiprocessing.Pool. Using multiprocessing.Pool with subprocess A simple solution to launch programs would be to use a combination of the subprocess and multiprocessing modules. We compile a list of files to be worked on and define a function that uses subprocess.call to execute an external utility on a file. This function is used in the imap_unordered method of a multiprocessing.Pool. In [3]: data = """chkmem.py mkhistory.py property.py softwareinfo.py verbruik.py markphotos.py passphrase.py pull-git.py texspell.py weer-ehv.py""" In [4]: files = data.split() In [5]: import subprocess In [6]: def runwc(path): rv = subprocess.check_output(['wc', path], universal_newlines=True) lines, words, characters, name = rv.split() return (name, int(lines), int(words), int(characters)) ...: In [7]: from multiprocessing import Pool In [8]: p = Pool() In [9]: p.map(runwc, files) Out[9]: [('chkmem.py', 33, 112, 992), ('mkhistory.py', 70, 246, 1950), ('property.py', 87, 373, 2895), ('softwareinfo.py', 84, 280, 2517), ('verbruik.py', 132, 585, 4476), ('markphotos.py', 97, 330, 3579), ('passphrase.py', 51, 191, 1916), ('pull-git.py', 82, 237, 2217), ('texspell.py', 343, 1480, 20631), ('weer-ehv.py', 71, 254, 2403)] This method works and is relatively easy to implement. But it is somewhat wasteful. The Pool starts a number of Python worker processes. Each of those receives items from the files list by IPC, runs the runwc function on those files which starts a process to run wc. The output of each wc is converted to a tuple, pickled and sent back to the parent process. If large amounts of data have to be transferred to and from the worker processes, performance will suffer. Managing subprocesses directly A different approach to using multiple subprocesses is it start a bunch of subprocesses directly. We must do this with care, though. Blindly starting a process for every file in a long list could easily exhaust available memory and processing resources. In general it does not make sense to have more concurrent processes running than you CPU has cores. That would lead to processes fighting over available cores. The following example defines the following function to start ffmpeg to convert a video file to Theora/Vorbis format. It returns a Popen object for each started subprocess. def startencoder(iname, oname, offs=None): args = ['ffmpeg'] if offs is not None and offs > 0: args += ['-ss', str(offs)] args += ['-i', iname, '-c:v', 'libtheora', '-q:v', '6', '-c:a', 'libvorbis', '-q:a', '3', '-sn', oname] with open(os.devnull, 'w') as bb: p = subprocess.Popen(args, stdout=bb, stderr=bb) return p In the main program, a list of Popen objects representing running subprocesses is maintained like this. outbase = tempname() ogvlist = [] procs = [] maxprocs = cpu_count() for n, ifile in enumerate(argv): while len(procs) == maxprocs: manageprocs(procs) ogvname = outbase + '-{:03d}.ogv'.format(n + 1) procs.append(startencoder(ifile, ogvname, offset)) ogvlist.append(ogvname) while len(procs) > 0: manageprocs(procs) So a new process is only started when there are less running subprocesses than cores. Code that is used multiple times is separated into the manageprocs function. def manageprocs(proclist): for pr in proclist: if pr.poll() is not None: proclist.remove(pr) sleep(0.5) This approach avoids starting unneeded processes. But it is more complicated to implement. Using ThreadPoolExecutor.map Since Python 3.2, the concurrent.futures module has made parallelizing a bunch of subprocesses easier. We can use a ThreadPoolExecutor to combine the convenience of a map method without the process overhead of a multiprocessing.Pool. The main part of such a program looks like this. errmsg = 'conversion of track {} failed, return code {}' okmsg = 'finished track {}, "{}"' num = len(data['tracks']) with concurrent.futures.ThreadPoolExecutor(max_workers=os.cpu_count()) as tp: for idx, rv in tp.map(partial(runflac, data=data), range(num)): if rv == 0: logging.info(okmsg.format(idx+1, data['tracks'][idx])) else: logging.error(errmsg.format(idx+1, rv)) This programs calls the flac program to convert WAV music to FLAC format. def runflac(idx, data): """Use the flac(1) program to convert a music file to FLAC format. Arguments: idx: track index (starts from 0) data: album data dictionary Returns: A tuple containing the track index and return value of flac. """ num = idx + 1 ifn = 'track{:02d}.cdda.wav'.format(num) args = ['flac', '--best', '--totally-silent', '-TARTIST=' + data['artist'], '-TALBUM=' + data['title'], '-TTITLE=' + data['tracks'][idx], '-TDATE={}'.format(data['year']), '-TGENRE={}'.format(data['genre']), '-TTRACKNUM={:02d}'.format(num), '-o', 'track{:02d}.flac'.format(num), ifn] rv = subprocess.call(args, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) return (idx, rv) A property of the map method is that it returns the results in the same order as the inputs. If it is to be expected that some subprocess calls take significantly longer than others it would be nicer to handle the returns from the subprocesses as they finish. Using Futures To handle subprocesses as they are completed we create a list of Future objects, and use the as_completed function. This returns futures in the sequence that they finish. starter = partial(runencoder, vq=args.videoquality, aq=args.audioquality) errmsg = 'conversion of {} failed, return code {}' with concurrent.futures.ThreadPoolExecutor(max_workers=os.cpu_count()) as tp: fl = [tp.submit(starter, t) for t in args.files] for fut in concurrent.futures.as_completed(fl): fn, rv = fut.result() if rv == 0: logging.info('finished "{}"'.format(fn)) elif rv < 0: ls = 'file "{}" has unknown extension, ignoring it.' logging.warning(ls.format(fname)) else: logging.error(errmsg.format(fn, rv)) The runencoder function is given below. def runencoder(fname, vq, aq): """ Use ffmpeg to convert a video file to Theora/Vorbis streams in a Matroska container. Arguments: fname: Name of the file to convert. vq : Video quality. See ffmpeg docs. aq: Audio quality. See ffmpeg docs. Returns: (fname, return value) """ basename, ext = os.path.splitext(fname) known = ['.mp4', '.avi', '.wmv', '.flv', '.mpg', '.mpeg', '.mov', '.ogv', '.mkv', '.webm'] if ext.lower() not in known: return (fname, -1) ofn = basename + '.mkv' args = ['ffmpeg', '-i', fname, '-c:v', 'libtheora', '-q:v', str(vq), '-c:a', 'libvorbis', '-q:a', str(aq), '-sn', '-y', ofn] rv = subprocess.call(args, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) return fname, rv This is slightly more complicated that using a map, but will not be held up by a single subprocess.
http://rsmith.home.xs4all.nl/programming/parallel-execution-with-python.html
CC-MAIN-2017-30
en
refinedweb
Apocalypse 12: Objects Larry Wall <larry@wall.org> Maintainer: Larry Wall <larry@wall.org> Date: 13 Apr 2004 Last Modified: 25 May 2006 Number: 12 Version: 8 The official unofficial slogan of Perl 6 is "Second System Syndrome Done Right!". After you read this Apocalypse you will at least be certain that we got the "Second System" part down pat. But we've also put in a little bit of work on the "Done Right" part, which we hope you'll recognize. The management of complexity is complex, but only if you think about it. The goal of Perl 6 is to discourage you from thinking about it unnecessarily. Speaking of thinking unnecessarily, please don't think that everything we write here is absolutely true. We expect some things to change as people point out various difficulties. That's the way all the other Apocalypses have worked, so why should this one be different? When I say "we", I don't just mean "me". I mean everyone who has participated in the design, including the Perl 6 cabal, er, design team, the readers (and writers) of the perl6-language mailing list, and all the participants who wrote or commented on the original RFCs. For this Apocalypse we've directly considered the following RFCs: RFC PSA Title === === ===== 032 abb A method of allowing foreign objects in perl 067 abb Deep Copying, aka, cloning around. 092 abb Extensible Meta-Object Protocol 095 acc Object Classes 101 bcc Apache-like Event and Dispatch Handlers 126 aaa Ensuring Perl's object-oriented future 137 bdd Overview: Perl OO should I<not> be fundamentally changed. 147 rr Split Scalars and Objects/References into Two Types 152 bdd Replace invocant in @_ with self() builtin 163 bdd Objects: Autoaccessors for object data structures 171 rr my Dog $spot should call a constructor implicitly 174 bdd Improved parsing and flexibility of indirect object syntax 187 abb Objects : Mandatory and enhanced second argument to C<bless> 188 acc Objects : Private keys and methods 189 abb Objects : Hierarchical calls to initializers and destructors 190 acc Objects : NEXT pseudoclass for method redispatch 193 acc Objects : Core support for method delegation 223 bdd Objects: C<use invocant> pragma 224 bdd Objects : Rationalizing C<ref>, C<attribute::reftype>, and C<builtin:blessed> 244 cdr Method calls should not suffer from the action on a distance 254 abb Class Collections: Provide the ability to overload classes 256 abb Objects : Native support for multimethods 265 abc Interface polymorphism considered lovely 277 bbb Method calls SHOULD suffer from ambiguity by default 307 rr PRAYER - what gets said when you C<bless> something 335 acc Class Methods Introspection: what methods does this object support? 336 bbb use strict 'objects': a new pragma for using Java-like objects in Perl These RFCs contain many interesting ideas, and many more "cries for help". Usually in these Apocalypses, I discuss the design with respect to each of the RFCs. However, in this case I won't, because most of these RFCs fail in exactly the same way--they assume the Perl 6 object model to be a set of extensions to the Perl 5 object model. But as it turns out, that would have been a great way to end up with Second System Syndrome Done Wrong. Perl 5's OO system is a great workbench, but it has some issues that have to be dealt with systematically rather than piecemeal. It has often been claimed that Perl 5 OO was "bolted on", but that's inaccurate. It was "bolted through", at right angles to all other reference types, such that any reference could be blessed into being an object. That's way cool, but it's often a little too cool. It's too hard to treat built-in types as objects when you want to. Perl 5's tie interface helps, but is suboptimal in several ways, not the least of which is that it only works on variables, not values. Because of the ability to turn (almost) anything into an object, a derived class had to be aware of the internal data type of its base class. Even after convention settled on hashes as the appropriate default data structure, one had to be careful not to stomp on the attributes of one's base class. Some people will be surprised to hear it, but Perl is a minimalist language at heart. It's just minimalistic about weird things compared to your average language. Just as the binding of parameters to @_ was a minimalistic approach, so too the entire Perl 5 object system was an attempt to see how far you could drive a few features. But many of the following difficulties stem from that. In Perl 5, a class is just a package, a method is just a subroutine, and an object is just a blessed referent. That's all well and good, and it is still fundamentally true in Perl 6. However, Perl 5 made the mistake of reusing the same keywords to express similar ideas. That's not how natural languages work--we often use different words to express similar ideas, the better to make subtle distinctions. Because Perl 5 reused keywords and treated parameter binding as something you do via a list assignment at run-time, it was next to impossible for the compiler to tell which subroutines were methods and which ones were really just subroutines. Because hashes are mutable, it was difficult to tell at compile time what the attribute names were going to be. The Perl 5 solution to the previous problem was to declare more things at compile time. Unfortunately, since the main way to do things at compile time was to invoke use, all the compile-time interfaces were shoehorned into use's syntax, which, powerful though it may be, is often completely inside-out from a reasonable interface. For instance, overloading is done by passing a list of pairs to use, when it would be much more natural to simply declare appropriate methods with appropriate names and traits. The base and fields pragmas are also kludges. Because of the flexibility of the Perl 5 approach, there was never any "obvious" way to do it. So best practices had to be developed by each group, and of course everyone came up with a slightly different solution. Now, we're not going to be like some folks and confuse "obvious" with "the only way to do it". This is still Perl, after all, and the flexibility will still be there if you need it. But by convention, there needs to be a standard look to objects and classes so that they can interoperate. There's more than one way to do it, but one of those is the standard way. The use of arrow where most of the rest of the world uses dot was confusing. The upshot of the previous problems was that, while Perl 5 made it easy to use objects and classes, it was difficult to try to define classes or derive from them. While there are plenty of problems with Perl 5's OO system, there are some things it did right. One of the big advances in Perl 5 was that a program could be in charge of its own compilation via use statements and BEGIN blocks. A Perl program isn't a passive thing that a compiler has its way with, willy nilly. It's an active thing that negotiates with the compiler for a set of semantics. In Perl 6 we're not shying away from that, but taking it further, and at the same time hiding it in a more declarative style. So you need to be aware that, although many of the things we'll be talking about here look like declarations, they trigger Perl code that runs during compilation. Of such methods are metaclasses made. (While these methods are often triggered by grammar rule reductions, remember from Apocalypse 5 that all these grammar rules are also running under the user's control. You can tweak the language without the crude ax of source filtering.) In looking for an "obvious" way to conventionalize Perl's object system, we shouldn't overlook the fact that there's more than one obvious way, and different approaches work better in different circumstances. Inheritance is one way (and typically the most overused), but we also need good support for composition, delegation, and parametric types. Cutting across those techniques are issues of interface, implementation, and mixtures of interface and implementation. There are multiple strategies for ambiguity resolution as well, and no single strategy is always right. (Unless the boss says so.) In making it easier to define and derive classes, we must be careful not to make it harder to use classes. So to summarize this summary, what we're proposing to develop is a set of conventions for how object orientation ought to work in Perl 6--by. There's still a bless method, and you can still pretend that an object is a hash--though it isn't anymore. However, as with all the rest of the design of Perl 6, the overriding concern has been that the language scale well. That means Perl has to scale down as well as up. Perl has to work well both as a first language and as a last language. We believe our design fulfills this goal--though, of course, only time will tell. One other note: if you haven't read the previous Apocalypses and Exegeses, a lot of this is going to be complete gobbledygook to you. (Of course, even if you have read them, this might still be gobbledygook. You take your chances in life...) Before we start talking about all the hard things that should be possible, let's look at an example of some of the easy things that should be easy. Suppose we define a Point object that (for some strange reason) allows you to adjust the y-axis but not the x-axis. class Point { has $.x; has $.y is rw; method clear () { $.x = 0; $.y = 0; } } my $point = Point.new(x => 2, y => 3); $a = $point.y; # okay $point.y = 42; # okay $b = $point.x; # okay $point.x = -1; # illegal, default is read-only $point.clear; # reset to 0,0 If you compare that to how it would have to be written in Perl 5, you'll note a number of differences: classand methodrather than packageand sub. [Update: The " ." form of the attribute syntax is now construed to always be a virtual dispatch to the accessor, so you can use that syntax in any of the child classes too. To refer to the private storage you now use " !" in place of the " .". Within the lexical scope of the class you may omit even that.] clearmethod is implicit. .instead of ->to dereference an object. Now suppose we want to derive from Point, and add a z-axis. That's just class Point3d is Point { has $:z = 123; method clear () { $:z = 0; next; } } my $point3d = Point3d.new(x => 2, y => 3, z => 4); $c = $point3d.z; # illegal, $:z is invisible The implicit constructor automatically sorts out the named arguments to the correct initializers for you. If you omit the z value, it will default to 123. And the new clear method calls the old clear method merely by invoking next, without the dodgy "super" semantics that break down under MI. We also declared the $:z attribute to be completely private by using a colon instead of a dot. No accessor for it is visible outside the class. (And yes, OO purists, our other attributes should probably have been private in the first place...that's why we're making it just as easy to write a private attribute as a public one.) [Update: It's now easier to write a private attribute than a public one. We've change the : twigil to !, and made it optional, so you can just declare it as has $z, or as has $!z if you wish to emphasize the privateness of it.] If any of that makes your head spin, I'm sure the following will clear it right up. :-) A class is what provides a name and a place for the abstract behavior of a set of objects said to belong to the class. As in Perl 5, a class is still "just a funny package", structurally speaking. Syntactically, however, a class is now distinct from a package or a module. And the body of a class definition now runs in the context of a metaclass, which is just a way of saying that it has a metaclass instance as its (undeclared) invocant. (An "invocant" is what we call the object or class on behalf of which a method is being called.) Hence class definitions, though apparently declarative, are also executing code to build the class definition, and the various declarations within the class are also running bits of code. By convention classes will use a standard metaclass, but that's just convention. (A very strong convention, we hope.) The primary role of a class is to manage instances, that is, objects. So a class must worry about object creation and destruction, and everything that happens in between. Classes have a secondary role as units of software reuse, in that they can be inherited from or delegated to. However, because this is a secondary role, and because of weaknesses in models of inheritance, composition, and delegation, Perl 6 will split out the notion of software reuse into a separate class-like entity called a "role". Roles are an abstraction mechanism for use by classes that don't care about the secondary aspects of software reuse, or that (looking at it the other way) care so much about it that they want to encapsulate any decisions about implementation, composition, delegation, and maybe even inheritance. Sounds fancy, but just think of them as includes of partial classes, with some safety checks. Roles don't manage objects. They manage interfaces and other abstract behavior (like default implementations), and they help classes manage objects. As such, a role may only be composed into a class or into another role, never inherited from or delegated to. That's what classes are for. [Update: In reality things are a little looser than that. If you use a role as if it were a class, it autoinstantiates an anonymous class for you that just does that role. If you use a class as if it were a role, it takes a role-like snapshot of the current state of the class and freezes it into an anonymous role.] Classes are arranged in an inheritance hierarchy by their "isa" relationships. Perl 6 supports multiple inheritance, but makes it easy to program in a single-inheritance style, insofar as roles make it easy to mix in (or delegate, or parameterize) private implementation details that don't belong in the public inheritance tree. In those cases where MI is used, there can be ambiguities in the pecking order of classes in different branches. Perl 6 will have a canonical way to disambiguate these, but by design the dispatch policy is separable from inheritance, so that you can change the rules for a given set of classes. (Certainly the rules can change when we call into another language's class hierarchy, for instance.) Where possible, class names are treated polymorphically, just as method names are. This powerful feature makes it possible to inherit systems of classes in parallel. (These classes might be inner classes, or they might be inner aliases to outer classes.) By making the class names "virtual", the base classes can refer to the appropriate derived classes without knowing their full name. That sounds complicated, but it just means that if you do the normal thing, Perl will call the right class instead of the one you thought it was going to call. :-) (As in C++ culture, we use the term "virtual" to denote a method that dispatched based on the actual run-time type of the object rather than the declared type of the variable. C++ classes have to declare their methods to be virtual explicitly. All of Perl's public methods are virtual implicitly.) You may derive from any built-in class. For high-level object classes such as Int or Num there are no restrictions on how you derive. For low-level representational classes like int or num, you may not change the representation of the value; you may only add behaviors. (If you want to change the representation, you should probably be using composition instead of inheritance. Or define your own low-level type.) Apart from this, you don't need to worry about the difference between int and Int, or num and Num, since Perl 6 will do autoboxing. Class declarations may be either file scoped or block scoped. A file-scoped declaration must be the first thing in the file, and looks like this: class Dog is Mammal; has Limb @.paws; method walk () { .paws».move() } That has the advantage of avoiding the use of one set of braces, letting you put everything up against left margin. It is otherwise identical to a block-scoped class, which looks like this: class Dog is Mammal { has Limb @.paws; method walk () { .paws».move() } } [Update: That .paws would have to be write @.paws these days unless you put the invocant into $_.] An incomplete class definition makes use of the ... ("yada, yada, yada") operator: class Dog is Mammal {...} The declaration of a class name introduces the name as a valid bare identifier or name. In the absence of such a declaration, the name of a class in an expression must be introduced with the :: class sigil, or it will be considered a bareword and rejected, since Perl 6 doesn't allow barewords. Once the name is declared however, it may be used as an ordinary term in an expression. Unlike in Perl 5, you should not view it as a bareword string. Rather, you should view it as a parameterless subroutine that returns a class object, which conveniently stringifies to the name of the class for Perl 5 compatibility. But when you say Dog.new() the invocant of new is an object of type Class, not a string as in Perl 5. [Update: There is no Class class now. The Dog object is of type Dog, the same type as any of its instances. It's just not a real Dog. It's an abstract Dog.] Unmodified, a class declaration always declares a global name. But if you prefix it with our, you're defining an inner class: class Cell { our class Golgi {...} ... } The full name of the inner class is Cell::Golgi, and that name can be used outside of Cell, since Golgi is declared in the Cell package. (Classes may be declared private, however. More later.) [Update: Bare class declarations now always default to our. The top level class ends up in the global space merely because files start out being parsed in the * package (aka GLOBAL::), so that's where the first class declaration puts its name.]. Now, the usual thing to do to a class's metadata is to insert another class into its ISA metadata. So we use trait notation to install a superclass: class Dog is Mammal {...} To specify multiple inheritance, just add another trait: class Dog is Mammal is Pet {...} But often you'll want a role instead, specified with does: class Dog is Mammal does Pet {...} More on that later. But remember that traits are evil. You can have traits like: class Moose is Mammal is stuffed is really(Hatrack) is spy(Russian) {...} So what if you actually want to derive from stuffed? That's a good question, which we will answer later. (The short answer is, you don't.) Now as it happens, you can also use is from within the class. You can also put the does inside to include various roles: class Dog { is Mammal; does Pet; does Servant; does Best::Friend[Man]; does Drool; ... } In fact, there's no particular reason to put any of these outside the braces except to make them more obvious to the casual reader. If we take the view that inheritance is just one form of implementation, then a simple class Dog {...} is sufficient to establish that there's a Dog class defined out there somewhere. We shouldn't really care about the implementation of Dog, only its interface--which is usually pretty slobbery. That being said, you can know more about the interface at compile time once you know the inheritance, so it's good to have pulled in a definition of the class as well as a declaration. Since this is typically done with use, the inheritance tree is generally available even if you don't mark your class declaration externally with the inheritance. (But in any event, the actual inheritance tree doesn't have to be available till run time, since that's when methods are dispatched. (Though as is often the case, certain optimizations work better when you give them more data earlier...)) A class is used directly by calling class methods, and indirectly by calling methods of an object of that class (or of a derived class that doesn't override the methods in question). Classes may also be used as objects in their own right, as instances of a metaclass, the class MetaClass by default. When you declare class Dog, you're actually calling a metaclass class method that constructs a metaclass instance (i.e. the Dog class) and then calls the associated closure (i.e the body of the class) as a method on the instance. (With a little grammatical magic thrown in so that Dog isn't considered a bareword.) The class Dog is an instance of the class MetaClass, but it's also an instance of the type Class when you're thinking of it as a dispatcher. That is, a class object is really allomorphic. If you treat one as an instance of Class, it behaves as if it were the user's view of the class, and the user thinks the class is there only to dispatch to the user's own class and instance methods. If, however, you treat the object as an instance of MetaClass, you get access to all its metaclass methods rather than the user-defined methods. Another way to look at it is that the metaclass object is a separate object that manages the class object. In any event, you can get from the ordinary class object to its corresponding metaclass object via the .meta method, which every object supports. [Update: Every Dog object (class or instance) just points to its metaclass instance. The Dog class object isn't either a Class or a MetaClass object. Perhaps it does a Class role though.] By the way, a Class is a Module which in turn is a Package which in turn is an Object. Or something like that. So a class can always be used as if it were a mere module or package. But modules and packages don't have a .dispatch method... [Update: The preceding paragraph is really only true if you take it as talking about the metaclasses, not the classes. A Dog is not a Module. Dog.meta is a metaclass instance that can do modular and package operations as well as class operations, and all these metaobjects use packages as their global storage. That is, the metaclass "does" the Package interface, on some level or other, if it wants to make global names visible through the package interface.] By default, classes in Perl are left open. That is, you can add more methods later. (However, an application may close them.) For discussion of this, see the section on "Open vs Closed Classes". Class names (and module names) are just package names. Unlike in Perl 5, when you mention a package name in Perl 6 it doesn't always mean a global name, since Perl 6 knows about inner classes and lexically scoped packages and such. As with other entities in Perl such as variables and methods, a scan is made for who thinks they have the best definition of the name, going out from lexical scopes to package scope to global scope in the case of static class names, and via method inheritance rules in the case of virtual class names. Note that ::MyClass and MyClass mean the same thing. In Perl 6, an initial :: is merely an optional sigil for when the name of the package would be misconstrued as something else. It specifically does not mean (as it does in Perl 5) that it is a top-level package. To refer to the top-level package, you would need to say something like ::*MyClass (or just *MyClass in places where the * unary operator would not be expected.) But also note that the * package in Perl is not the " main" package in the Perl 5 sense. Likewise, the presence of :: within a package name like Fish::Carp does not make it a global package name necessarily. Again, it scans out through various scopes, and only if no local scopes define package Fish::Carp do you get the global definition. And again, you can force it by saying ::*Fish::Carp. (Or just *Fish::Carp in places where the * unary operator is not expected.) GLOBAL::Fish::Carp means the same thing. You can interpolate a parenthesized expression within a package name after any ::. So these are all legal package names (or module names, or class names): ::($alice) ::($alice)::($bob) ::($alice::($bob)) ::*::($alice)::Bob ::('*')::($alice ~ '_misc')::Bob ::(get_my_dir()) ::(@multilevel) And any of those package names could be part of a variable or sub name: $::($alice)::name @::($alice)::($bob)::elems[1,2,3] %::*::($alice)::Bob::map{'xyz'} &::('*')::($alice ~ '_misc')::Bob::doit(1,2,3) $::(get_my_dir())::x $::(@multilevel) Note in the last example that the final element of @multilevel is taken to be the variable name. This may be illegal under use strict refs, since it amounts to a symbolic reference. (Not that the others aren't symbolic, but the rules may be looser for package names than for variable names, depending on how strict our strictures get.) [Update: There is no "strict refs" anymore, since we have a separate syntax for when we explicitly want symbolic references.] A class named with a single initial colon is a private class name: class :MyPrivateClass {...} It is completely ignored outside of the current class. Since the name is useful only in the current package, it makes no sense to try to qualify it with a package name. While it's an inner class of sorts, it does not override any class name from any other class because it lives in its own namespace (a subnamespace of the current package), and there's no way to tell if the class you're deriving from declares its own private class of the same name (apart from digging through the reflection interfaces). The colon is orthogonal to the scoping. What's actually going on in this example is that the name is stored in the package with the leading colon, because the colon is part of the name. But if you declared " my class :Golgi" the private name would go into the lexical namespace with the colon. The colon functions a bit like a "private" trait, but isn't really a trait. Wherever you might use a private name, the colon in the name effectively creates a private subspace of names, just as if you'd prefixed it with "_" in the good old days. But if were only that, it would just be encapsulation by convention. We're trying to do a little better than that. So the language needs to actively prevent people from accessing that private subspace from outside the class. You might think that that's going to slow down all the dispatchers, but probably not. The ordinary dispatch of Class.method and $obj.method don't have to worry about it, because they use bare identifiers. It's only when people start doing ::($class) or $obj.$method that we have to trap illegal references to colonic names. Even though the initial colon isn't really a trait, if you interrogate the " .private" property of the class, it will return true. You don't have to parse the name to get that info. We'll make more of this when we talk about private methods and attributes. Speaking of methods... [Update: Private attributes are now marked with ! rather than :, but nowadays you should just use a lexically scoped class if you want a private class.] Methods are the actions that a class knows how to invoke on behalf of an object of that type (or on behalf of itself, as a class object). But you knew that already. As in Perl 5, a method is still "just a funny subroutine", but in Perl 6 we use a different keyword to declare it, both because it's better documentation, and because it captures the metadata for the class at compile time. Ordinary methods may be declared only within the scope of a class definition. (Multimethods are exempt from this restriction, however.) To declare a method, use the method keyword just as you would use sub for an ordinary subroutine. The declaration is otherwise almost identical: method doit ($a, $b, $c) { ... } The one other difference is that a method has an invocant on behalf of which the method is called. In the declaration above, that invocant is implicit. (It is implicitly typed to be the same as the current surrounding class definition.) You may, however, explicitly declare the invocant as the first argument. The declaration knows you're doing that because you put a colon between the invocant and the rest of the arguments: method doit ($self: $a, $b, $c) { ... } In this case, we didn't specify the type of $self, so it's an untyped variable. To make the exact equivalent of the implicit declaration, put the current class: method doit (MyClass $self: $a, $b, $c) { ... } or more generically using the ::_ "current class" pronoun: method doit (::_ $self: $a, $b, $c) { ... } [Update: The current lexical class is now named via ::?CLASS. To capture the actual class of the invocant, use a type variable like ::RealClass in the declaration, with or without the $self.] In any case, the method sets the current invocant as the topic, which is also known as the $_ variable. However, the topic can change depending on the code inside the method. So you might want to declare an explicit invocant when the meaning of $_ might change. (For further discussion of topics see Apocalypse 4. For a small writeup on sub signatures see Apocalypse 6.) [Update: Methods do not set the topic now unless you declare the invocant with the name $_.] A private method is declared with a colon on the front: method :think (Brain $self: $thought) Private methods are callable only by the class itself, and by trusted "friends". More about that when we talk about attributes. [Update: Private methods are marked with ! now rather than :.] As in Perl 5, there are two notations for calling ordinary methods. They are called the "dot" notation and the "indirect object" notation. Perl 6's "dot" notation is just the industry-standard way to call a method these days. (This used to be -> in Perl 5.) $object.doit("a", "b", "c"); If the object in question is the current topic, $_, then you can use the unary form of the dot operator: for @objects { .doit("a", "b", "c"); } A simple variable may be used for an indirectly named method: my $dosomething = "doit"; $object.$dosomething("a", "b", "c"); As in Perl 5, if you want to do anything fancier, use a temporary variable. The parentheses may also be omitted when the following code is unambiguously a term or operator, so you can write things like this: @thumbs.each { .twiddle } # same as @thumbs.each({.twiddle}) $thumb.twiddle + 1 # same as $thumb.twiddle() + 1 .mode 1 # same as $_.mode(1) [Update: This is retracted. Parens are always required if there are arguments.] [Update: As an alternative to parens, you can turn any otherwise legal method call into a list operator by appending a :.] (Parens are always required around the argument list when a method call with arguments is interpolated into a string.) The parser will make use of whitespace at this point to decide some things. For instance $obj.method + 1 is obviously a method with no arguments, while $obj.method +1 is obviously a method with an argument. However, the dwimmery only goes as far as the typical person's visual intuition. Any construct too ambiguous is simply rejected. So $obj.method+1 produces a parse error. [Update: The preceding is also retracted. None of those would be interpreted as arguments now. However, most of the following is still true.] In particular, curlies, brackets, or parens would be interpreted as postfix subscripts or argument lists if you leave out the space. In other words, Perl 6 distinguishes: $obj.method ($x + $y) + $z # means $obj.method(($x + $y) + $z) [Update: That's illegal now.] from $obj.method($x + $y) + $z # means ($obj.method($x + $y)) + $z Yes, this is different from Perl 5. And yes, I know certain people hate it. They can write their own grammar. While it's always possible to disambiguate with parentheses, sometimes that is just too unsightly. Many methods want to be parsed as if they were list operators. So as an alternative to parenthesizing the entire argument list, you can disambiguate by putting a colon between the method call and the argument list: @thumbs.each: { .twiddle } # same as @thumbs.each({.twiddle}) $thumb.twiddle: + 1 # same as $thumb.twiddle(+ 1) .mode: 1 # same as $_.mode(1) $obj.for: 1,2,3 -> $i { ... } [Update: There is no colon disambiguator any more. Use parens if there are arguments. (However, you can pass an adverbial block using :{} notation with a null key. That does not count as an ordinary argument.)] [Update: The colon disambiguator is back again. The problem with precedence is now solved by requiring that a bare closure in the list is always interpreted as the final argument unless followed by a comma or comma surrogate.] If a method is declared with the trait " is rw", it's an lvalue method, and you can assign to it just as if it were an ordinary variable: method mystate is rw () { return $:secretstate } $object.mystate = 42; print $object.mystate; # prints 42 In fact, it's a general rule that you can use an argumentless " rw" method call anywhere you might use a variable: temp $state.pi = 3; $tailref = \$fido.tail; (Though occasionally you might need to supply parentheses to disambiguate, since the compiler can't always know at compile time whether the method has any arguments.) [Update: The parens (or a colon) are required if there are arguments.] Method calls on container objects are obviously directed to the container object itself, not to the contents of the container: $elems = @array.elems; @keys = %hash.keys; $sig = &sub.signature; However, with scalar variables, methods are always directed to the object pointed to by the reference contained in the scalar: $scalar = @array; # (implied \ in scalar context) $elems = $scalar.elems; # returns @array.elems or for value types, the appropriate class is called as if the value were a reference to a "real" object. $scalar = "foo"; $chars = $scalar.chars; # calls Str::chars or some such In order to talk to the scalar container itself, use the tied() pseudo-function as you would in Perl 5: if tied($scalar).constant {...} (You may recall, however, that in Perl 6 it's illegal to tie any variable without first declaring it as tieable, or (preferably) tying it directly in the variable's declaration. Otherwise the optimizer would have to assume that every variable has semantics that are unknowable in advance, and we would have to call it a pessimizer rather than an optimizer.) [Update: The function is now called variable() instead of tied() to avoid that confusion.] The other form of method call is known as the "indirect object" syntax, although it differs from Perl 5's syntax in that a colon is required between the indirect object (the invocant) and its arguments: doit $object: "a", "b", "c" The colon may be omitted if there are no arguments (besides the invocant): twiddle $thumb; $x = new X; Note that indirect object calls may not be directly interpolated into a string, since they don't start with a sigil. You can always use the $() expression interpolater though: say "$(greet $lang), world!"; [Update: The $() notation means something else now. Use say "{greet $lang}, world!"; instead.] As in Perl 5, the indirect object syntax is valid only if you haven't declared a subroutine locally that overrides the method lookup. That was a bit of a problem in Perl 5 since, if there happened to be a new constructor in your class, it would call that instead dispatching to the class you wanted it to. That's much less of a problem in Perl 6, however, because Perl 6 cannot confuse a method declaration with a subroutine declaration. (Which is yet another reason for giving methods their own keyword.) Another factor that makes indirect objects work better in Perl 6 is that the class name in " new X" is a predeclared object, not a bare identifier. (Perl 5 just had to guess when it saw two bare identifiers in a row that you were trying to call a class method.) The indirect object syntax may not be used with a variable for the methodname. You must use dot notation for that. Because of precedence, the indirect object notation may not be used as an lvalue unless you parenthesize it: (mystate $object) = 42; (findtail Dog: "fido") = Wagging::on; You may parenthesize an argumentless indirect object method to make it look like a function: mystate($object) = 42; twiddle($thumb); The dispatch rules for methods and global multi subs conspire to keep these unambiguous, so the user really doesn't have to worry about whether close($handle); is implemented as a global multi sub or a method on a $handle object. In essence, the multimethod dispatching rules degenerate to ordinary method dispatch when there are no extra arguments to consider (and sometimes even when there are arguments). This is particularly important because Perl uses these rules to tell the difference between print "Howdy, world!\n"; # global multi sub and print $*OUT; # ordinary filehandle method However, you must still put the colon after the invocant if there are other arguments. The colon tells the parser whether to look for the arguments inside: doit($object: "a", "b", "c") or outside: doit($object): "a", "b", "c" If you do say doit($object, "a", "b", "c") the first comma forces it to be interpreted as a sub call rather than a method call. (We could have decided to say that whenever Perl can't find a doit() sub definition at run time, it should assume you meant the entire parenthesized list to be the indirect object, which, since it's in scalar context would automatically generate a list reference and call [$object,"a","b","c"].doit(), which is unlikely to be what you mean, or even work. (Unless, of course, that's how you really meant it to work.) But I think it's much more straightforward to simply disallow comma lists at the top level of an indirect object. The old "if it looks like a function" rule applies here. Oddly, though, function syntax is how you call multisubs in Perl 6. And as it happens, the way the multisub/multimethod dispatch rules are defined, it could still end up calling $object.doit("a", "b", "c") if that is deemed to be the best choice among all the candidates. But syntactically, it's not an indirect object. More on dispatch rule interactions later.) The comma still doesn't work if you go the other way and leave out the parens entirely, since doit $object, "a", "b", "c"; would always (in the absence of a prior sub declaration) be parsed as (doit $object:), "a", "b", "c"; So a print with both an indirect object and arguments has to look like one of these: print $*OUT: "Howdy, world!\n"; print($*OUT: "Howdy, world!\n"); print($*OUT): "Howdy, world!\n"; Note that the old Perl 5 form using curlies: print {some_hairy_expression()} "Howdy, world!\n"; should instead now be written with parentheses: print (some_hairy_expression()): "Howdy, world!\n"; though, in fact, in this case the parens are unnecessary: print some_hairy_expression(): "Howdy, world!\n"; You'd only need the parens if the invocant expression contained operators lower in precedence than comma (comma itself not being allowed). Basically, if it looks confusing to you, you can expect it to look confusing to the compiler, and to make the compiler look confused. But it's a feature for the compiler to look confused when it actually is confused. (In Perl 5 this was not always so.) Note that the disambiguating colon associates with the closest method call, whether direct or indirect. So print $obj.meth: "Howdy, world!\n"; passes " Howdy, world!\n" to $obj.meth rather than to print ($obj.meth): "Howdy, world!\n"; A private method does not participate in normal method dispatch. It is not listed in the class's public methods. The .can method does not see it. Calling it via normal dispatch raises a "no such method" exception. It is, in essence, invisible to the outside world. It does not hide a base class's method of the same name--even in the current class! It's fair to ask for warnings about name collisions, of course. But we're not following the C++ approach of making private methods visible but uncallable, because that would violate encapsulation, and in particular, Liskov substitutability. Instead, we separate the namespaces completely by distinguishing the public dot operator from the private dot-colon operator. That is: $mouth.say("Yes!") # always calls public .say method .say("Yes!") # unary form $brain.:think("No!") # always calls private :think method .:think("No!") # unary form [Update: We now use ! instead of .: and there is no unary form.] The inclusion of the colon prevents any kind of "virtual" behavior. Calling a private method is illegal except under two very specific conditions. You can call a private method :think on an object $brain only if: $brainis explicitly declared, and the declared class is either the class definition that we are in or a class that has explicitly granted trust to our current class, and the declared class contains a private :thinkmethod. Or... $brainis not declared, and the current class contains a private :thinkmethod. The upshot of these rules is that a private method call is essentially a subroutine call with a method-like syntax. But the private method we're going to call can be determined at compile time, just like a subroutine. Class methods are called on the class as a whole rather than on any particular instance object of the class. They are distinguished from ordinary methods only by the declared type of the invocant. Since an implicit invocant would be typed as an object of the class and not as the class itself, the invocant declaration is not optional in a class method declaration if you wish to specify the type of the invocant. (Untyped explicit invocants are allowed to "squint", however.) [Update: Squinting is no longer necessary now that we've defined class objects to merely be uninstantiated prototypes of the same type as the instances in the class.] To declare an ordinary class method, such as a constructor, you say something like: method new (Class $class: *@args) { ... } Such a method may only be called with an invocant that "isa" Class, that is, an object of type Class, or derived from type Class. [Update: No Class class exists.] It is possible to write a method that can be called with an invocant that is either a Class or an object of that current class. You can declare the method with a type junction: method new (Class|Dog $classorobj: *@args) { ... } Or to be completely non-specific, you can leave out the type entirely: method new ($something: *@args) { ... } That's not as dangerous as it looks, since almost by definition the dispatcher only calls methods that are consistent with the inheritance tree. You just can't say: method new (*@args) { ... } which would be the equivalent of method new (Dog $_: *@args) { ... } Well, actually, you could say that, but it would require that you have an existing Dog-compatible object in order to create a new one. And that could present a little bootstrapping problem... [Update: We simply made Dog a Dog-compatible object.] (Though it could certainly cure the boot chewing problem...) But in fact, you'll rarely need to declare new method at all, because Perl supplies a default constructor to go with your class. Some methods are intended to be inherited by derived classes. Others are intended to be reimplemented in every class, or in every class that doesn't want the default method. We call these "submethods", because they work a little like subs, and a little like methods. (You can also read the "sub" with the meaning it has in words like "subhuman".) Typically these are (sub)methods related to the details of construction and destruction of the object. So when you call a constructor, for instance, it ends up calling the BUILDALL initialization routine for the class, which ends up calling the BUILD submethod: submethod BUILD ($a, $b, $c) { $.a = $a; $.b = $b; $.c = $c; } Since the submethod is doing things that make sense only in the context of the current class (such as initializing attributes), it makes no sense for BUILD to be inherited. Likewise DESTROY is also a submethod. Why not just make them ordinary subs, then? Ordinary subs can't be called by method invocation, and we want to call these routines that way. Furthermore, if your base class does define an ordinary method named BUILD or DESTROY, it can serve as the default BUILD or DESTROY for all derived classes that don't declare their own submethods. (All public methods are virtual in Perl, but some are more virtual than others.) You might be saying to yourself, "Wait, private methods aren't virtual. Why not just use a private method for this?" It's true that private methods aren't virtual, because they aren't in fact methods at all. They're just ordinary subroutines in disguise. They have nothing to do with inheritance. By contrast, submethods are all about presenting a unified inherited interface with the option of either inheriting or not inheriting the implementation of that interface, at the discretion of the class doing the implementing. So the bottom line is that submethods allow you to override an inherited implementation for the current class without overriding the default implementation for other classes. But in any case, it's still using a public interface, called as an ordinary method call, from anywhere in your program that has an object of your type. Or a class of your type. The default new constructor is an ordinary class method in class Object, so it's inherited by all classes that don't define their own new. But when you write your own new, you need to decide whether your constructor should be inherited or not. If so, that's good, and you should declare it as a method. But if not, you should declare it as a submethod so that derived classes don't try to use it erroneously instead of the default Object.new(). In Perl 6, "attributes" are what we call the instance variables of an object. (We used that word to mean something else in Perl 5--we're now calling those things "traits" or "properties".) As with classes and methods, attribute declarations are apparently declarative. Underneath they actually call a method in the metaclass to install the new definition. The Perl 6 implementation of attributes is not based on a hash, but on something more like a symbol table. Attributes are stored in an opaque datatype rather like a struct in C, or an array in Perl 5--but you don't know that. The datatype is opaque in the sense that you shouldn't care how it's laid out in memory (unless you have to interface with an outside data structure--like a C struct). Do not confuse opacity with encapsulation. Encapsulation only hides the object's implementation from the outside world. But the object's structure is opaque even to the class that defines it. One of the large benefits of this is that you can actually take a C or C++ data structure and wrap accessor methods around it without having to copy anything into a different data structure. This should speed up things like XML parsing. In order to provide this opaque abstraction layer, attributes are not declared as a part of any other data structure. Instead, they are modeled on real variables, whose storage details are implicitly delegated to the scope in which they are declared. So attributes are declared as if they were normal variables, but with a strange scope and lifetime that is neither my nor our. (That scope is, of course, the current object, and the variable lives as long as the object lasts.) The class will implicitly store those attributes in a location distinct from any other class's attributes of the same name, including any base or derived class. To declare an attribute variable, declare it within the class definition as you would a my variable, but use the has declarator instead of my: class Dog is Mammal { has $.tail; has @.legs; ... } The has declarator was chosen to remind people that attributes are in a "HASA" relationship to the object rather than an "ISA" relationship. The other difference from normal variables is that attributes have a secondary sigil that indicates that they are associated with methods. When you declare an attribute like $.tail, you're also implicitly declaring an accessor method of the same name, only without the $ on the front. The dot is there to remind you that it's also a method call. As with other declarations, you may add various traits to an attribute: has $.dogtag is rw; If you want all your attributes to default to " rw", you can put the attribute on the class itself: class Coordinates is rw { has int $.x; has int $.y; has int $.z; } Essentially, it's now a C-style struct, without having to introduce an ugly word like "struct" into the language. Take that, C++. :-) You can also assign to a declaration: has $.master = "TheDamian"; Well, actually, this looks like an assignment, but it isn't. The effect of this is to establish a default; it is not executed at run time. (Or more precisely, it runs when the class closure is executed by the metaclass, so it gets evaluated only once and the value is stored for later use by real instances. More below.) The attribute behaves just like an ordinary variable within the class's instance methods. You can read and write the attributes just like ordinary variables. (It is, however, illegal to refer to an instance attribute variable (that is, a " has" variable) from within a class method. Class methods may only access class attributes, not instance attributes. See below.) [Update: Class methods are no longer distinguished from instance methods by the compiler, except insofar as the compiler can tell that a method refers to instance variables in the body. It's a run-time error to ask for an attribute of a class object, but that's because the class object doesn't have the attribute, not because it's a class object.] Bare attributes are automatically hidden from the outside world because their sigiled names cannot be seen outside the class's package. This is how Perl 6 enforces encapsulation. Outside the class the only way to talk about an attribute is through accessor methods. Since public methods are always virtual in Perl, this makes attribute access virtual outside the class. Always. (Unless you give the optimizer enough hints to optimize the class to "final". More on that later.) In other words, only the class itself is allowed to know whether this attribute is, in fact, implemented by this class. The class may also choose to ignore that fact, and call the abstract interface, that is, the accessor method, in which case it might actually end up calling some derived class's overriding method, which might in turn call back to this class's accessor as a super method. (So in general, an accessor method should always refer to its actual variable name rather than the accessor method name to avoid infinite recursion.) [Update: All public $.foo variables are now virtual, and the actual private storage is represented by $!foo.] You may write your own accessor methods around the bare attributes, but if you don't, Perl will generate them for you based on the declaration of the attribute variable. The traits of the generated method correspond directly to the traits on the variable. By default, a generated accessor is read-only (because by default any method is read-only). If you mark an attribute with the trait " is rw" though, the corresponding generated accessor will also be marked " is rw", meaning that it can be used as an lvalue. In any event, even without " is rw" the attribute variable is always writable within the class itself (unless you apply the trait is constant to it). As with private classes and methods, attributes are declared private using a colon on the front of their names. As with any private method, a private accessor is completely ignored outside its class (or, by extension, the classes trusted by this class). To carry the separate namespace idea through, we incorporate the colon as the secondary sigil in declarations of private attributes: has $:x; Then we can get rid of the verbose is private altogether. Well, it's still there as a trait, but the colon implies it, and is required anyway.) And we basically force people to document the private/public distinction every place they reference $:x instead of $.x, or $obj.:meth instead of $obj.meth. We've seen secondary sigils before in earlier Apocalypses. In each case they're associated with a bizarre usage of some sort. So far we have: $*foo # a truly global global (in every package) $?foo # a regex-scoped variable $^foo # an autodeclared parameter variable $.foo # a public attribute $:foo # a private attribute [Update: A regex-scoped variable now looks like $<foo> instead. A $?foo variable is now a compiler variable, and a $=foo variable is a POD variable. A private attribute is $!foo. By the way, lately we've been calling the secondary sigils "twigils".] As a form of the dreaded "Hungarian notation", secondary sigils are not introduced lightly. We define secondary sigils only where we deem instant recognizability to be crucial for readability. Just as you should never have to look at a variable and guess whether it's a true global, you should never have to look at a method and guess which variables are attributes and which ones are variables you just happen to be in the lexical scope of. Or which attributes are public and which are private. In Perl 6 it's always obvious--at the cost of a secondary sigil. We do hereby solemnly swear to never, never, ever add tertiary sigils. You have been warned. You can set default values on attributes by pseudo-assignment to the attribute declaration: has Answer $.ans = 42; These default values are associated as " build" traits of the attribute declaration object. When the BUILD submethod is initializing a new object, these prototype values are used for uninitialized attributes. The expression on the right is evaluated immediately at the point of declaration, but you can defer evaluation by passing a closure, which will automatically be evaluated at the actual initialization time. (Therefore, to initialize to a closure value, you have to put a closure in a closure.) Here's the difference between those three approaches. Suppose you say: class Hitchhiker { my $defaultanswer = 0; has $.ans1 = $defaultanswer; has $.ans2 = { $defaultanswer }; has $.ans3 = { { $defaultanswer } }; $defaultanswer = 42; ... } When the object is eventually constructed, $.ans1 will be initialized to 0, while $.ans2 will be initialized to 42. (That's because the closure binds $defaultanswer to the current variable, which still presumably has the value 42 by the time the BUILD routine initializes the new object, even though the lexical variable " $defaultanswer" has supposedly gone out of scope by the time the object is being constructed. That's just how closures work.) And $.ans3 will be initialized not to 42, but to a closure that, if you ever call it, will also return 42. So since the accessor $obj.ans3() returns that closure, $obj.ans3().() will return 42. The default value is actually stored under the " build" trait, so this: has $.x = calc($y); is equivalent to this: has $.x is build( calc($y) ); and this: has $.x = { calc($y) }; is equivalent to either of these: has $.x is build( { calc($y) } ); has $.x will build { calc($y) }; As with all closure-valued container traits, the container being declared (the $.x variable in this case) is passed as the topic to the closure (in addition to being the target that will be initialized with the result of the closure, because that's what build does). In addition to the magical topic, these build traits are also magically passed the same named arguments that are passed to the BUILD routine. So you could say has $.x = { calc($^y) }; to do a calculation based on the :y(582) parameter originally passed to the constructor. Or rather, that will be passed to the constructor someday when the object is eventually constructed. Remember we're really still at class construction time here. As with other initializers, you can be more specific about the time at which the default value is constructed, as long as that time is earlier than class construction time: has $.x = BEGIN { calc() } has $.x = CHECK { calc() } has $.x = INIT { calc() } has $.x = FIRST { calc() } has $.x = ENTER { calc() } which are really just short for: has $.x is build( BEGIN { calc() } ) has $.x is build( CHECK { calc() } ) has $.x is build( INIT { calc() } ) has $.x is build( FIRST { calc() } ) has $.x is build( ENTER { calc() } ) In general, class attributes are just package or lexical variables. If you define a package variable with a dot or colon, it autogenerates an accessor for you just as it does for an ordinary attribute: our $.count; # generates a public read-only .count accessor our %:cache is rw; # generates a private read-write .:cache accessor The implicit invocant of these implicit accessors has a "squinting" type--it can either be the class or an object of the class. (Declare your own accessors if you have a philosophical reason for forcing the type one way or the other.) [Update: Squinting no longer necessary.] The disadvantage of using " our" above is that that both of these are accessible from outside the class via their package name (though the private one is Officially Ignored, and cannot be named simply by saying %MyClass:::cache because that syntax is specifically disallowed). If on the other hand you declare your class variables lexically: my $.count; # generates a read-only .count accessor my %:cache is rw; # generates a read-write .:cache accessor then the same pair of accessors are generated, but the variables themselves are visible only within the class block. If you reopen the class in another block, you can only see the accessors, not the bare variables. This is probably a feature. Generally speaking, though, unless you want to provide public accessors for your class attributes, it's best to just declare them as ordinary variables (either my or state variables) to prevent confusion with instance attributes. It's a good policy not to declare any public accessors until you know you need them. They are, after all, part of your contract with the outside world, and the outside world has a way of holding you to your contracts. The basic idea here is to remove the drudgery of creating objects. In addition we want object creation and cleanup to work right by default. In Perl 5 it's possible to make recursive construction and destruction work, but it's not the default, and it's not easy. Perl 5 also confused the notions of constructor and initializer. A constructor should create a new object once, then call all the appropriate initializers in the inheritance tree without recreating the object. The initializer for a base class should be called before the initializer for any class derived from it. The initializer for a class is always named BUILD. It's in uppercase because it's usually called automatically for you at construction time. As with Perl 5, a constructor is only named " new" by convention, and you can write a constructor with any name you like. However, in Perl 6, if you do not supply a " new" method, a generic one will be provided (by inheritance from Object, as it happens). The default new constructor looks like this: multi method new (Class $class: *%_) { return $class.bless(0, *%_); } [Update: Now that we have parametric types it's more like: method new (::T: *%_) { return T.bless(*%_); } That binds the class type of the invocant regardless of how instantiated the invocant is. Also, the candidate argument need not be supplied.] The arguments for the default constructor are always named arguments, hence the *%_ declaration to collect all those pairs and pass them on to bless. You'll note also that bless is no longer a subroutine but a method call, so it's now impossible to omit the class specification. This makes it easier to inherit constructors. You can still bless any reference you could bless in Perl 5, but where you previously used a function to do that: # Perl 5 code... return bless( {attr => "hi"}, $class ); in Perl 6 you use a method call: # Perl 6 code... return $class.bless( {attr => "hi"} ); However, if what you pass as the first argument isn't a reference, bless is going to construct an opaque object and initialize it. In a sense, bless is the only real constructor in Perl 6. It first makes sure the data structure is created. If you don't supply a reference to bless, it calls CREATE to create the object. Then it calls BUILDALL to call all the initializers. The signature of bless is something like: method bless ($class: $candidate, *%_) The 0 candidate indicates the built-in opaque type. If you're really strange in the head, you can think of the " 0" as standing for " 0paque". Or it's the "zero" object, about which we know zip. Whatever tilts your windmill... In any event, strings are reserved for other object layouts. We could conceivably have things like: return $class.bless("Cstruct", *%_); So as it happens, 0 is short for the layout "P6opaque". [Update: There is no 0 argument. Just leave it out if you wish to declare a P6opaque object. If you wish to pass some other representation name to CREATE, just call CREATE first and pass the result of that as your candidate to bless,] Any additional arguments to .bless are automatically passed on to CREATE and BUILDALL. But note that these must be named arguments. It could be argued that the only real purpose for writing a .new constructor in Perl 6 is to translate different positional argument signatures into a unified set of named arguments. Any other initialization common to all constructors should be done within BUILD. Oh, the invocant of .bless is either a class or an object of the class, but if you use an object of the class, the contents of that object are not automatically used to prototype the new object. If you wish to do that, you have to do it explicitly by copying the attributes: $obj.bless(0, *%$obj) (That is just a specific application of the general principle that if you treat any object like a hash, it will behave like one, to the extent that it can. That is, %$obj turns the attributes into key/value pairs, and passes those as arguments to initialize the new object. Note that %$obj includes the private attributes when used inside the class, but not outside.) [Update: These days the * would be replaced by a [,] reduction.] Just because .bless allows an object to be used for a class doesn't mean your new constructor has to do the same. Some folks have philosophical issues with mixing up classes and objects, and it's fine to disallow that on the constructor level. In fact, you'll note that the default .new above requires a Class as its invocant. Unless you override it, it doesn't allow an object for the constructor invocant. Go thou and don't likewise. [Update: Sorry, the new ::T parametric type syntax doesn't care whether the invocant is a class or an object. It does, however, document that you're only interested in the type of the invocant.] Another good reason not to overload .new to do cloning is that Perl will also supply a default .clone routine that works something like this: multi method clone ($proto: *%_) { return $proto.bless(0, *%_, *%$proto); } Note the order of the two hash arguments to bless. This gives the supplied attribute values precedence over the copied attribute values, so that you can change some of the attributes en passant if you like. That's because we're passing the two flattened hashes as arguments to .bless and Perl 6's named argument binding mechanism always picks the first argument that matches, not the last. This is opposite of what happens when you use the Perl 5 idiom: %newvals = (%_, %$proto); In that case, the last value (the one in %$proto) would "win". [Update: We now do "last wins" semantics for named args, unless the argument in question is declared as an array, in which case it gets all the arguments of that name.] submethod CREATE ($self: *%args) {...} CREATE is called when you don't want to use an existing data structure as the candidate for your object. In general you won't define CREATE because the default CREATE does all the heavy magic to bring an opaque object into existence. But if you don't want an opaque object, and you don't care to write all your constructors to create the data structure before calling .bless, you can define your own CREATE submethod, and it will override the standard one for all constructors in the class. [Update: The $self here should probably read ::T.] submethod BUILDALL ($self: *%args) {...} [Update: But this one actually is the new self, the candidate created by CREATE above. It's just not entirely instantiated until BUILDALL is done.] After the data structure is created, it must be populated by each of the participating classes (and roles) in the proper order. The BUILDALL method is called upon to do this. The default BUILDALL is usually correct, so you don't generally have to override it. In essence, it delegates the initialization of parent classes to the BUILDALL of the parent classes, and then it calls BUILD on the current class. In this way the pieces of the object are assembled in the correct order, from least derived to most derived. For each class BUILDALL calls on, if the arguments contain a pair whose key is that class name, it passes the value of the pair as its argument to that class's BUILDALL. Otherwise it passes the entire list. (There's not much ambiguity there--most classes and roles will start with upper case, while most attribute names start with lower case.) submethod BUILD ($self: *%args) {...} That is the generic signature of BUILD from the viewpoint of the caller, but the typical BUILD routine declares explicit parameters named after the attributes: submethod BUILD (+$tail, +@legs, *%extraargs) { $.tail = $tail; @:legs = @legs; ... } [Update: That would be (:$tail, :@legs, *%extraargs) now, but you don't really need the colons since positional declarations can still be set by name.] That occurs so frequently that there's a shorthand available in the signature declaration. You can put the attributes (distinguished by those secondary sigils, you'll recall) right into the signature. The following means essentially the same thing, without repeating the names: submethod BUILD (+$.tail, +@:legs, *%extraargs) {...} [Update: @!legs now. The ! may not be omitted in this case.] It's actually unnecessary to declare the *%extraargs parameter. If you leave it out, it will default to *%_ (but only on methods and submethods--see the section on Interface Consistency later). You may use this special syntax only for instance attributes, not class attributes. Class attributes should generally not be reinitialized every time you make a new object, after all. If you do not declare a BUILD routine, a default routine will be supplied that initializes any attributes whose names correspond to the keys of the argument pairs passed to it, and leaves the other attributes to default to whatever the class supplied as the default, or undef otherwise. In any event, the assignment of default attribute values happens automatically. For any attribute that is not otherwise initialized, the attribute declaration's " build" property is evaluated and the resulting value copied in to the newly created attribute slot. This happens logically at the end of the BUILD block, so we avoid running initialization closures unnecessarily. This implicit initialization is based not on whether the attribute is undefined, but on whether it was initialized earlier in BUILD. (Otherwise we could never explicitly create an attribute with an undefined value.) If you say: my Dog $spot = Dog.new(...) you have to repeat the type. That's not a big deal for a small typename, but sometime typenames are a lot longer. Plus you'd like to get rid of the redundancy, just because it's, like, redundant. So there's a variant on the dot operator that looks a lot like a dot assignment operator: my Dog $spot .= new(...) It doesn't really quite fit the assignment operator rule though. If it did, it'd have to mean my Dog $spot = $spot.new(...) which doesn't quite work, because $spot is undefined. What probably happens is that the my cheats and puts a version of undef in there that knows it should dispatch to the Dog class if you call .self:new() on it. Anyway, we'll make it work one way or another, so that it becomes the equivalent of: my Dog $spot = Dog.new(...) The alternative is to go the C++ route and make new a reserved word. We're just not gonna do that. Note that an attribute declaration of the form has Tail $wagger .= new(...) might not do what you want done when you want it done, if what you want done is to create a new Dog object each time an object is built. For that you'd have to say: has Tail $wagger = { .new(...) } or equivalently, has Tail $wagger will build { .new(...) } But leaving aside such timing issues, you should generally think of the .= operator more as a variant on . than a variant on +=. It can, for instance, turn any non-mutating method call into a mutating method: @array.=sort; # sort @array in place .=lc; # lowercase $_ in place This presumes, of course, that the method's invocant and return value are of compatible types. Some classes will wish to define special in-place mutators. The syntax for that is: method self:sort (Array @a is rw) {...} [Update: That's now self:<sort> instead.] It is illegal to use return from such a routine, since the invocant is automatically returned. If you do not declare the invocant, the default invocant is automatically considered " rw". If you do not supply a mutating version, one is autogenerated for you based on the corresponding copy operator. Object destruction is no longer guaranteed to be "timely" in Perl 6. It happens when the garbage collector gets around to it. (Though there will be ways to emulate Perl 5 end-of-scope cleanup.) As with object creation, object destruction is recursive. Unlike creation, it must proceed in the opposite order. The DESTROYALL routine is the counterpart to the BUILDALL routine. Similarly, the default definition is normally sufficient for the needs of most classes. DESTROYALL first calls DESTROY on the current class, and then delegates to the DESTROYALL of any parent classes. In this way the pieces of the object are disassembled in the correct order, from most derived to least derived. As with Perl 5, all the memory deallocation is done for you, so you really only need to define DESTROY if you have to release external resources such as files. Since DESTROY is the opposite of BUILD, if any attribute declaration has a " destroy" property, that property (presumably a closure) is evaluated before the main block of DESTROY. This happens even if you don't declare a DESTROY. (The " build" and " destroy" traits are the only way for roles to let their preferences be made known at BUILD and DESTROY time. It follows that any role that does not define an attribute cannot participate in building and destroying except by defining a method that BUILD or DESTROY might call. In other words, stateless roles aren't allowed to muck around with the object's state. This is construed as a feature.) Perl 6 supports both single dispatch (traditional OO) and multiple dispatch (also known as "multimethod dispatch", but we try to avoid that term). Single dispatch looks up which method to run solely on the basis of the type of the first argument, the invocant. A single-dispatch call distinguishes the invocant syntactically (unlike a multiple-dispatch call, which looks like a subroutine call, or even an operator.) Basically, anything can be an invocant as long as it fills the Dispatch role, which provides a .dispatcher method. This includes ordinary objects, class objects, and (in some cases) even varieties of undef that happen to know what class of thing they aren't (yet). [Update: It is unlikely that there will be a .dispatcher method. This is all delegated to the .meta object now, at least in the abstract.] Simple single dispatch is specified with the dot operator, or its indirect object equivalent: $object.meth(@args) # always calls public .meth .meth(@args) # unary form meth $object: @args # indirect object form There are variants on the dot form indicated by the character after the dot. (None of these variants allows indirect object syntax.) The private dispatcher only ever dispatches to the current class or its proxies, so it's really more like a subroutine call in disguise: $object.:meth(@args) # always calls private :meth .:meth(@args) # unary form [Update: Uses ! now, no unary form.] It is an error to use .: unless there is a correspondingly named "colon" method in the appropriate class, just as it is an error to use . when no method can be found of that name. Unlike the .: operator, which can have only one candidate method, the . operator potentially generates a list of candidates, and allows methods in that candidate list to defer to subsequent methods in other classes until a candidate has been found that is willing to handle the dispatch. In addition to the .: and .= operators, there are three other dot variants that can be used if it's not known how many methods are willing to handle the dispatch: $object.?meth(@args) # calls method if there is one .?meth(@args) # unary form $object.*meth(@args) # calls all methods (0 or more) .*meth(@args) # unary form $object.+meth(@args) # calls all methods (1 or more) .+meth(@args) # unary form The .* and .+ versions are generally only useful for calling submethods, or methods that are otherwise expected to work like submethods. They return a list of all the successful return values. The .? operator either returns the one successful result, or undef if no appropriate method is found. Like the corresponding regex modifiers, ? means "0 or 1", while * means "0 or more", and + means "1 or more". Ordinary . means "exactly one". Here are some sample implementations, though of course these are probably implemented in C for maximum efficiency: # Implements . (or .? if :maybe is set). sub CALLONE ($obj, $methname, +$maybe, *%opt, *@args) { my $startclass = $obj.dispatcher() // fail "No dispatcher: $obj"; METHOD: for WALKMETH($startclass, :method($methname), %opt) -> &meth { return meth($obj, @args); } fail qq(Can't locate method "$methname" via class "$startclass") unless $maybe; return; } With this dispatcher you can continue by saying " next METHOD". This allows methods to "failover" to other methods if they choose not to handle the request themselves. # Implements .+ (or .* if :maybe is set). # Add :force to redispatch in every class sub CALLALL ($obj, $methname, +$maybe, +$force, *%opt, *@args) { my $startclass = $obj.dispatcher() // fail "No dispatcher: $obj"; my @results = gather { if $force { METHOD: for WALKCLASS($startclass, %opt) -> $class { take $obj.::($class)::$methname(*@args) # redispatch } } else { METHOD: for WALKMETH($startclass, :method($methname), %opt) -> &meth { take meth($obj,*@args); } } } return @results if @results or $maybe; fail qq(Can't locate method "$methname" via class "$startclass"); } This one you can quit early by saying " last METHOD". Notice that both of these dispatchers cheat by calling a method as if it were a sub. You may only do that by taking a reference to the method, and calling it as a subroutine, passing the object as the first argument. This is the only way to call a virtual method non-virtually in Perl. If you try to call a method directly as a subroutine, Perl will ignore the method, look for a subroutine of that name elsewhere, probably not find it, and complain bitterly. (Or find the wrong subroutine, and execute it, after which you will complain bitterly.) We snuck in an example the new gather/ take construct. It is still somewhat conjectural. Perl 5 supplies a pseudoclass, SUPER::, that redirects dispatch to a parent class's method. That's often the wrong thing to do, though, in part because under MI you may have more than one parent class, and also because you might have sibling classes that also need to have the given method triggered. Even if SUPER is smart enough to visit multiple parent classes, and even if all your classes cooperate and call SUPER at the right time, the depth first order of visitation might be the wrong order, especially under diamond inheritance. Still, if you know that your parent classes use SUPER, or you're calling into a language with SUPER semantics (such as Perl 5) then you should probably use SUPER semantics too, or you'll end up calling your parent's parents in duplicate. However, since use of SUPER is slightly discouraged, we Huffman code it a bit longer in Perl 6. Remember the *%opt parameters to the dispatchers above? That comes in as a parameterized pseudoclass called WALK. $obj.*WALK[:super]::method(@args) That limits the call to only those immediate super classes that define the method. Note the star in the example. If you really want the Perl 5 semantics, leave the star out, and you'll only get the first existing parent method of that name. (Why you'd want that is beyond me.) Actually, we'll probably still allow SUPER:: as a shorthand for WALK[:super]::, since people will just hack it in anyway if we don't provide it... If you think about it, every ordinary dispatch has an implicit WALK modifier on the front that just happens to default to WALK[:canonical]. That is, the dispatcher looks for methods in the canonical order. But you could say WALK[:depth] to get Perl 5's order, or you could say WALK[:descendant] to get an order approximating the order of construction, or WALK[:ascendant] to get an order approximating the order of destruction. You could say WALK[:omit(SomeClass)] to call all classes not equivalent to or derived from SomeClass. For instance, to call all super classes, and not just your immediate parents, you could say WALK[:omit(::_)] to skip the current lexical class or anything derived from it. [Update: The lexical class is now named ::?CLASS.] But again, that's not usually the right thing to do. If your base classes are all willing to cooperate, it's much better to simply call $obj.method(@args) and then let each of the implementations of the method defer to the next one when they're done with their part of it. If any method says " next METHOD", it automatically iterates the loop of the dispatcher and finds the next method to dispatch to, even if that method comes from a sibling class rather than a parent class. The next method is called with the same arguments as originally supplied. That presupposes that the entire set of methods knows to call "next" appropriately. This is not always the case. In fact, if they don't all call next, it's likely that none of them does. And maybe just knowing whether or not they do is considered a violation of encapsulation. In any case, if you still want to call all the methods without their active cooperation, then use the star form: $obj.*method(@args) Then the various methods don't have to do anything to call the next method--it happens automatically by default. In this case a method has to do something special if it wants to stop the dispatch. Naturally, that something is to call " last METHOD", which terminates the dispatch loop early. Now, sometimes you want to call the next method, but you want to change the arguments so that the next method doesn't get the original argument list. This is done with deep magic. If you use the call keyword in an ordinary (nonwrapper) method, it steals the rest of the dispatch list from the outer loop and redispatches to the next method with the new arguments: @retvals = call(@newargs) return @retvals; And unlike with " next METHOD", control returns to this method following the call. It returns the results of the subsequent method calls, which you should return so that your outer dispatcher can add them to the return values it already gathered. Note that " next METHOD" and " last METHOD" can typically be spelt " next" and " last" unless they are in an inner loop. By default the various dot operators call a method on a single object, even if it ends up calling multiple methods for that object. Since a method call is essentially a unary postfix operator, however, you can use it as a hyper operator on a list of objects: @object».meth(@args) # Call one for each or fail @object».?meth(@args) # Call one for each if available @object».*meth(@args) # Call all available for each @object».+meth(@args) # Call one or more for each Note that with the last two, if a method uses " last METHOD", it doesn't bomb out of the "hyper" loop, but just goes on to the next entry. One can always bomb out of the hyperloop with a real exception, of course. And maybe with " last HYPER", depending on how hyper's implicit iteration is implemented. If you want to use an array for serial rather than parallel method calling, see Delegation, which lets you set up cascading handlers. WALKCLASS generates a list of matching classes. WALKMETH generates a list of method references from matching classes. The WALKCLASS and WALKMETH routines used in the sample dispatch code need to cache their results so that every dispatch doesn't have to traverse the inheritance tree again, but just consult the preconstructed list in order. However, if there are changes to any of the classes involved, then someone needs to call the appropriate cache clear method to make sure that the inheritance is recalculated. WALKCLASS/ WALKMETH options include some that specify ordering: :canonical # canonical dispatch order :ascendant # most-derived first, like destruction order :descendant # least-derived first, like construction order :preorder # like Perl 5 dispatch :breadth # like multimethod dispatch and some that specify selection criteria: :super # only immediate parent classes :method(Str) # only classes containing method declaration :omit(Selector) # only classes that don't match selector :include(Selector) # only classes that match selector Note that :method(Str) selects classes that merely have methods declared, not necessarily defined. A declaration without a definition probably implies that they intend to autoload a definition, so we should call the stub anyway. In fact, Perl 6 differentiates an AUTOMETHDEF from AUTOLOAD. AUTOLOAD works as it does in Perl 5. AUTOMETHDEF is never called unless there is already a declaration of the stub (or equivalently, AUTOMETH faked a stub.) [Update: Those autoloaders are now called AUTODEF and CANDO.] It would be possible to just define everything in terms of WALKCLASS, but that would imply looking up each method name twice, once inside WALKCLASS to see if the method exists in the current class, and once again outside in order to call it. Even if WALKCLASS caches the cache list, it wouldn't cache the derived method list, so it's better to have a separate cache for that, controlled by WALKMETH, since that's the common case and has to be fast. (Again, this is all abstract, and is probably implemented in gloriously grungy C code. Nevertheless, you can probably call WALKCLASS and WALKMETH yourself if you feel like writing your own dispatcher.) Multiple dispatch is based on the notion that methods often mediate the relationships of multiple objects of diverse types, and therefore the first object in the argument list should not be privileged over other objects in the argument list when it comes to selecting which method to run. In this view, methods aren't subservient to a particular class, but are independent agents. A set of independent-minded, identically named methods use the class hierarchy to do pattern matching on the argument list and decide among themselves which method can best handle the given set of arguments. The Perl approach is, of course, that sometimes you want to distinguish the first invocant, and sometimes you don't. The interaction of these two approaches gets, um, interesting. But the basic notion is to let the caller specify which approach is expected, and then, where it makes sense, fall back on the other approach when the first one fails. Underlying all this is the Principle of Least Surprise. Do not confuse this with the Principle of Zero Surprise, which usually means you've just swept the real surprises under some else's carpet. (There's a certain amount of surprise you can't go below--the Heisenberg Uncertainty Principle applies to software too.) With traditional multimethods, all methods live in the same global namespace. Perl 6 takes a different approach--we still keep all the traditional Perl namespaces (lexical, package, global) and we still search for names the same way (outward through the lexical scopes, then the current package, then the global * namespace; or upward in the class hierarchy). Then we simply claim that, under multiple dispatch, the "long name" of any multi routine includes its signature, and that visibility is based on the long name. So an inner or derived multi only hides an outer or base multi of the same name and the same signature. (Routines not declared " multi" still hide everything in the traditional fashion.) To put it another way, the multiple dispatch always works when both the caller and the callee agree that that's how it should work. (And in some cases it also works when it ought to work, even if they don't agree--sort of a "common law" multimethod, as it were...) A callee agrees to the multiple dispatch "contract" by including the word " multi" in the declaration of the routine in question. It essentially says, "Ordinarily this would be a unique name, but it's okay to have duplicates of this name (the short name) that are differentiated by signatures (the long name)." Looking at it from the other end, leaving the " multi" out says "I am a perfect match for any signature--don't bother looking any further outward or upward." In other words, the standard non-multi semantics. You may not declare a multi in the same scope as a non-multi. However, as long as they are in different scopes, you can have a single non-multi inside a set of multis, or a set of multis inside a single non-multi. You can even have a set of multis inside a non-multi inside a set of multis. Indeed, this is how you hide all the outer multis so that only the inner multi's long names are considered. (And if no long name matches, you get the intermediate non-multi as a kind of backstop.) The same policy applies to both nested lexical scopes and derived subclasses. [Update: Now you can declare a "first multi" that is simulataneously an ordinary sub and the final arbiter of subsequent multi declarations in this scope. This is done with the " proto" keyword in place of the " multi" keyword". Oh, and the " sub" is optional with either " multi" or " proto".] Actually, up till now we've been oversimplifying the concept of "long name" slightly. The long name includes only that part of the signature up to the first colon. If there is no colon, then the entire signature is part of the long name. (You can have more colons, in which case the additional arguments function as tie breakers if the original set of long names is insufficient to prevent a tie.) [Update: The actual, most-unique "long name" is really till the last colon, not the first. But the tiebreaking still happens as described above.] So sometimes we'll probably slip and say "signature" when we mean "long name". We pray your indulgence. A multi sub in any scope hides any multi sub with the same "long name" in any outer scope. It does not hide subs with the same short name but a different signature. Er, long name, I mean... If you want a multi that is visible in all namespaces (that don't hide the long name), then declare the name in the global name space, indicated in Perl 6 with a *. Most of the so-called "built-ins" are declared this way: multi sub *push (Array $array, *@args) {...} multi sub *infix:+ (Num $x, Num $y) returns Num {...} multi sub *infix:.. (Int $x, Int $y: Int ?$by) returns Ranger {...} [Update: Those are now named infix:<+> and infix:<..>.] Note the use of colon in the last example to exclude $by as part of the long name. The range operator is dispatched only on the types of its two main arguments. If you declare a method with multi, then that method hides any base class method with the same long name. It does not hide methods with the same short name but a different signature when called as a multimethod. (It does hide methods when called under single dispatch, in which case the first invocant is treated as the only invocant regardless of where you put the colon. Just because a method is declared with multi doesn't make it invisible to single dispatch.) Unlike a regular method declaration, there is no implied invocant in the syntax of a multi method. A method declared as multi must declare all its invocants so that there's no ambiguity as to the meaning of the first colon. With a multi method, it always means the end of the long name. (With a non-multi, it always means that the optional invocant declaration is present.) Submethods may be declared with multi, in which case visibility works the same as for ordinary methods. However, a submethod has the additional constraint that the first invocant must be an exact class match. Which effectively means that a submethod is first single dispatched to the class, and then the appropriate submethod within that class is selected, ignoring any other class's submethods of the same name. [Update: Multi submethods are visible to both the single dispatch and multiple dispatcher. Multi methods are visible only within the constraints of single dispatch.] Since rules are just methods in disguise, you can have multi rules as well. (Of course, that doesn't do you a lot of good unless you have rules with different signatures, which is unusual.) It is not likely that Perl 6.0.0 will support multiple dispatch on named arguments, but only on positional arguments. Since all the extra arguments to a BUILD routine come in as named arguments, you probably can't usefully multi a BUILD (yet). However, we should not do anything that precludes multiple BUILD submethods in the future. Which means we should probably enforce the presence of a colon before the first named argument declaration in any multi signature, so that the semantics don't suddenly change if and when we start supporting multiple dispatch that includes named arguments as part of the long name. To the extent that you declare constructors (such as .new) with positional arguments, you can use multi on them in 6.0.0. As we mentioned, multiple dispatch is enabled by agreement of both caller and callee. From the caller's point of view, you invoke multiple dispatch simply by calling with subroutine call syntax instead of method call syntax. It's then up to the dispatcher to figure out which of the arguments are invocants and which ones are just options. (In the case where the innermost visible subroutine is declared non-multi, this degenerates to the Perl 5 semantics of subroutine calls.) This approach lets you refactor a simple subroutine into a more nuanced set of subroutines without changing how the subroutines are called at all. That makes this sort of refactoring drop-dead simple. (Or at least as simple as refactoring ever gets...) It's a little harder to refactor between single dispatch and multiple dispatch, but a good argument could be made that it should be harder to do that, because you're going to have to think through a lot more things in that case anyway. Anyway, here's the basic relationship between single dispatch and multiple dispatch. Single dispatch is more familiar, so we'll discuss multiple dispatch first. Whenever you make a call using subroutine call syntax, it's a candidate for multiple dispatch. A search is made for an appropriate subroutine declaration. As in Perl 5, this search goes outward through the lexical scopes, then through the current package and on to the global namespace (represented in Perl 6 with an initial * for the "wildcard" package name). If the name found is not a multi, then it's a good old-fashioned sub call, and no multiple dispatch is done. End of story. [Update: A "proto" counts as a "sub" here, not as a "multi".] However, if the first declaration we come to is a multi, then lots of interesting stuff happens. (Fortunately for our performance, most of this interesting stuff can happen at compile time, or upon first use.) The basic idea is that we will collect a complete list of candidates before we decide which one to call. So the search continues outward, collecting all sub declarations with the same short name but different long names. (We can ignore outer declarations that are hidden by an inner declaration with the same long name.) If we run into a scope with a non-multi declaration, then we're done generating our candidate list, and we can skip the next paragraph. After going all the way out to the global scope, we then examine the type of the first argument as if we were about to do single dispatch on it. We then visit any classes that would have been single dispatched, in most-derived to least-derived order, and for each of those classes we add into our candidate list any methods declared multi, plus all the single invocant methods, whether or not they were declared multi! In other words, we just add in all the methods declared in the class as a subset of the candidates. (There are reasons for this that we'll discuss below.) Anyway, just as with nested lexical scopes, if two methods have the same long name, the more derived one hides the less derived one. And if there's a class in which the method of the same short name is not declared multi, it serves as a "stopper", just as a non-multi sub does in a lexical scope. (Though that "stopper" method can of course redispatch further up the inheritance tree, just as a "stopper" lexical sub can always call further outward if it wants to.) [Update: We now have the "proto" keyword to specifically mark such a routine. It also lets the routine supply known argument names for any multis found in the lexical scope, so the compiler can be smart about mapping named args to positionals.] Now we have our list of candidates, which may or may not include every sub and method with the same short name, depending on whether we hit a "stopper". Anyway, once we know the candidate list, it is sorted into order of distance from the actual argument types. Any exact match on a parameter type is distance 0. Any miss by a single level of derivation counts as a distance of 1. Any violation of a hard constraint (such as having too many arguments for the number of parameters, or violating a subtype check on a type that does constraint checking, or missing the exact type on a submethod) is effectively an infinite distance, and disqualifies the candidate completely. Once we have our list of candidates sorted, we simply call the first one on the list, unless there's more than one "first one" on the list, in which case we look to see if one of them is declared to be the default. If so, we call it. If not, we die. So if there's a tie, the default routine is in charge of subsequent behavior: # Pick next best at random... multi sub foo (BaseA $a, BaseB $b) is default { next METHOD; } # Give up at first ambiguity... multi sub bar (BaseA $a, BaseB $b) is default { last METHOD; } # Invoke my least-derived ancestor multi sub baz (BaseA $a, BaseB $b) is default { my @ambiguities = WALKMETH($startclass, :method('baz')) or last METHOD; pop(@ambiguities).($a, $b); } # Invoke most generic candidate (often a good fall-back)... multi sub baz (BaseA $a, BaseB $b) is default { my @ambiguities = @CALLER::methods or last METHOD; pop(@ambiguities).value.($a, $b); } In many cases, of course, the default routine won't redispatch, but simply do something generically appropriate. [Update: We probably aren't using the "Manhattan" distance indicated above.] If you use the dot notation, you are explicitly calling single dispatch. By default, if single dispatch doesn't find a suitable method, it does a "failsoft" to multiple dispatch, pretending that you called a subroutine with the invocant passed as the first argument. (Multiple dispatch doesn't need to failsoft to single dispatch since all single dispatch methods are included as a subset of the multiple dispatch candidates anyway.) This failsoft behavior can be modified by lexically scoped pragma. If you say use dispatch :failhard then single dispatch will be totally unforgiving as it is in Perl 5. Or you can tell single dispatch to go away: use dispatch :multi in which case all your dot notation is treated as a sub call. That is, any $obj.method(1,2,3) in the lexical scope acts like you'd said: method($obj,1,2,3) If single dispatch locates a class that defines the method, but the method in question turns out to be a set of one or more multi methods, then, the single dispatch fails immediately and a multiple dispatch is done, with the additional constraint that only multis within that class are considered. (If you wanted the first argument to do loose matching as well, you should have called it as a multimethod in the first place.) If you use indirect object syntax with an explicit colon, it is exactly equivalent to dot notation in its semantics. However, one-argument subs are inherently ambiguous, because Perl 6 does not require the colon on indirect objects without arguments. That is, if you say: print $fh it's not clear whether you mean $fh.print or print($fh) As it happens, we've defined the semantics so that it doesn't matter. Since all single invocant methods are included automatically in multimethod dispatch, and since multiple dispatch degenerates to single dispatch when there's only one invocant, it doesn't matter which way you write it. The effect is the same either way. (Unless you've defined your own non-multi print routine in a surrounding lexical scope. But then, if you've done that, you probably did it on purpose precisely because you wanted to disable the default dispatch semantics.) Within the context of a multimethod dispatch, " next METHOD" means to try the next best match, if unambiguous, or else the marked default method. From within the default method it means just pick the next in the list even if it's ambiguous. The dispatch list is actually kept in @CALLER::methods, which is a list of pairs, the key of each indicating the "distance" rating, and the value of each containing a reference to the method to call (as a sub ref). [Update: A proto routine can't use " next METHOD" because the original dispatch list is exhausted. Maybe. If so, we can arrange for call() to propagate the call outward, as if the proto routine is a wrapper around the rest of the world.] If you want to directly access the attributes of a class, your multi must be declared within the scope of that class. Attributes are never directly visible outside a class. This makes it difficult to write an efficient multimethod that knows about the internals of two different classes. However, it's possible for private accessors to be visible outside your class under one condition. If your class declares that another class is trusted, that other class can see the private accessors of your class. If the other class declares that you are trusted, then you can see its private accessor methods. The trust relationship is not necessarily symmetrical. This lets you have an architecture where classes by and large don't trust each other, but they all trust a single well-guarded " multi-plexor" class that keeps everyone else in line. The syntax for trusting another class is simply: class MyClass { trusts Yourclass; ... } It's not clear whether roles should be allowed to grant trust. In the absence of evidence to the contrary, I'm inclined to say not. We can always relax that later if, after many large, longitudinal, double-blind studies, it turns out to be both safe and effective. [Update: The intent of the previous paragraph was to describe whether a role could grant trust on behalf of the composed class, but it was ambiguously stated, and sometimes misinterpreted. It seems to me that a role could grant trust to private routines in its own scope, however, since they're basically just sub calls anyway. On the other hand, the relationship of the role's package namespace to its eventual lexical namespace is perhaps problematic. At some point the object has to keep track of all its cloned role closures and provide the right one to private sub callers.] In Perl 5 overloading was this big special deal that had to have special hooks inserted all over the C code to catch various operations on overloaded types and do something special with them. In Perl 6, that just all falls out naturally from multiple dispatch. The only other part of the trick is to consider operators to be function calls in disguise. So in Perl 6 the real name of an operator is composed of a grammatical context identifier, a colon, and then the name of the operator as you usually see it. The common context identifiers are "prefix", "infix", "postfix", "circumfix", and "term", but there are others. So when you say something like $x = <$a++ * -@b.[...]>; you're really saying something like this: $x = circumfix:<>( infix:*( postfix:++($a), prefix:-( infix:.( @b, circumfix:[]( term:...(); ) ) ) ) ) [Update: All the operator names need to be quoted now as a hash subscript or slice. And instead of breaking .[] into . and [], there is now a postcircumfix grammatical category. So we have: $x = circumfix:«< >»( infix:<*>( postfix:<++>($a), prefix:<->( postcircumfix:<[ ]>( @b, term:<...>(); ) ) ) ) Except that circumfix <...> is a quoting operator these days. many of the examples using French quotes in this Apocalypse are now written with regular angles.] Perl 5 had special key names representing stringification and numification. In Perl 6 these naturally fall out if you define: method prefix:+ () {...} # what we do in numeric context method prefix:~ () {...} # what we do in string context [Update: Here and below, it's prefix:<+> etc.] Likewise you can define what to return in boolean context: method prefix:? () {...} # what we do in boolean context Integer context is, of course, just an ordinary method: method int () {...} # what we do in integer context These can be defined as normal methods since single-invocant multi subs degenerate to standard methods anyway. C++ programmers will tend to feel comfy defining these as methods. But others may prefer to declare them as multi subs for consistency with binary operators. In which case they'd look more like this: multi sub *prefix:+ (Us $us) {...} # what we do in numeric context multi sub *prefix:~ (Us $us) {...} # what we do in string context multi sub *prefix:? (Us $us) {...} # what we do in string context multi sub *prefix:int (Us $us) {...} # what we do in integer context Coercions to other classes can also be defined: multi sub *coerce:as (Us $us, Them ::to) { to.transmogrify($us) } Such coercions allow both explicit conversion: $them = $us as Them; as well as implicit conversions: my Them $them = $us; Binary operators should generally be defined as multi subs: multi sub infix:+ (Us $us, Us $ustoo) {...} multi sub infix:+ (Us $us, Them $them) is commutative {...} [Update: And these are infix:<+> now.] The " is commutative" trait installs an additional autogenerated sub with the invocant arguments reversed, but with the same semantics otherwise. So the declaration above effectively autogenerates this: multi sub infix:+ (Them $them, Us $us) {...} Of course, there's no need for that if the two arguments have the same type. And there might not actually be an autogenerated other subroutine in any case, if the implementation can be smart enough to simply swap the two arguments when it needs to. However it gets implemented, note that there's no need for Perl 5's "reversed arguments flag" kludge, since we reverse the parameter name bindings along with the types. Perl 5 couldn't do that because it had no control of the signature from the compiler's point of view. See Apocalypse 6 for much more on the definition of user-defined operators, their precedence, and their associativity. Some of it might even still be accurate. [Update: Nowadays see Synopsis 6 instead.] Objects have many kinds of relationships with other objects. One of the pitfalls of the early OO movement was to encourage people to model many relationships with inheritance that weren't really "isa" relationships. Various languages have sought to redress this deficiency in various ways, with varying degrees of success. With Perl 6 we'd like to back off a step and allow the user to define abstract relationships between classes without committing to a particular implementation. More specifically, we buy the argument of the Traits paper (see). This is necessary if we are to abstract out the delegation decision. We feel that the decision to delegate rather than compose a sub-object is a matter of implementation, and therefore that decision should be encapsulated (or at least be allowed to be encapsulated) in a role. This allows you to refactor a problem by redefining one or more roles without having to doctor all the classes that make use of those roles. This is a great way to turn your huge, glorious "god object" into a cooperating set of objects that know how to delegate to each other. As in the Traits paper, roles are composed at class construction time, and the class composer does some work to make sure the composed class is not unintentionally ambiguous. If two methods of the same name are composed into the same class, the ambiguity will be caught. The author of the class has various remedies for dealing with this situation, which we'll go into below. From the standpoint of the typical user, a role just looks like a "smart" include of a "partial class". They're smart in that roles have to be well behaved in certain respects, but most of the time the naive user can ignore the power of the abstraction. A role is declared much like a class, but with a role keyword instead: role Pet { method feed ($food) { $food.open_can(); $food.put_in_bowl(); .call(); } } [Update: That'd have to be self.call() or $.call() these days.] A role may not inherit from a class. It may be composed of other roles, however. In essence, a role doesn't know its own type yet, because it will be composed into another type. So if you happen to make any mention of its main type (available as ::_), that mention is in fact generic. Therefore the type of $self is generic. Likewise if you refer to SUPER, the role doesn't know what the parent classes are yet, so that's also generic. The actual types are instantiated from the generic types when the role is composed into the class. (You can use the role name (" Pet") directly, but only in places where a role name is allowed as a type constraint, not in places that declare the type of an actual object.) [Update: Instead of ::_ we have ::?CLASS to mean the generic class.] Just as the body of a class declaration is actually a method call on an instance of the MetaClass class, so too the body of a role declaration is actually a method call on an instance of the MetaRole class, which is like the MetaClass class, with some tweaks to manage Role objects instead of Class objects. For instance, a Role object doesn't actually support a dispatcher like a Class object. [Update: Just as there's no Class type anymore, there's also no Role type. The metaobject handles everything type related (except the name, which is a package name just like any other type).] MetaRole and MetaClass do not inherit from each other. More likely they both inherit from MetaModule or some such. A role's main type is generic by default, but you can also parameterize other types explicitly: role Pet[Type $petfood = TableScraps] { method feed (::($petfood) $food) {...} } [Update: With type sigils that would just be role Pet[::Petfood = TableScraps] { method feed (Petfood $food) {...} } now.] Unlike certain other languages you may be altogether too familiar with, Perl uses square brackets for parametric types rather than angles. Within those square brackets it uses standard signature notation, so you can also use the arguments to pass initial values, for instance. Just bear in mind that by default any parameters to a role or class are considered part of the name of the class when instantiated. Inasmuch as instantiated type names are reminiscent of multimethod "long names", you may use a colon to separate those arguments that are to be considered part of the name from those that are just options. Please note that these types can be as latent (or as non-latent) as you like. Remember that what looks like compile time to you is actually run time to the compiler, so it's free to bind types as early or late as you tell it to, including not at all. If a role merely declares methods without defining them, it degenerates to an interface: role Pet { method feed ($food) {...} method groom () {...} method scratch (+$where) {...} } When such a role is included in a class, the methods then have to be defined by the class that uses the role. Actually, each method is on its own--a role is free to define default implementations for any subset of the methods it declares. If a role declares private accessors, those accessors are private to the class, not the role. The class must define any private implementations that are not supplied by the role, just as with public methods. But private method names are never visible outside the class (except to its trusted proxy classes). [Update: See S12 for refinements of this.] Unlike in the Traits paper, we allow roles to have state. Which is fancy way of saying that the role can define attributes, and methods that act on those attributes, not just methods that act only on other methods. role Pet { has $.collar = { Collar.new(Tag.new) }; method id () { return $.collar.tag } method lose_collar () { undef $.collar } } By the way, I think that when $.collar is undefined, calling .tag on it should merely return undef rather than throwing an exception (in the same way that @foo[$x][$y][$z] returns undef when @foo[$x] is undefined, and for the same reason). The undef object returned should, of course, contain an unthrown exception documenting the problem, so that if the undef is ever asked to provide a defined value, it can explain why it can't do so. Or if the returned value is tested by //, it can participate in the resulting error message. If you want to parameterize the initial value of a role attribute, be sure to put a colon if you don't want the parameter to be considered part of the long name: role Pet[IDholder $id: $tag] { has IDholder $.collar .= new($tag); } class Dog does Pet[Collar, DogLicense("fido")] {...} class Pigeon does Pet[LegBand, RacerId()] {...} my $dog = new Dog; my $pigeon = new Pigeon; In which case the long names of the roles in question are Pet[Collar] and Pet[LegBand]. In which case all of these are true: $dog.does(Dog) $dog.does(Pet) $dog.does(Pet[Collar]) but this is false: $dog.does(Pet[LegBand]) Anyway, where were we. Ah, yes, encapsulated attributes, which leads us to... We can also have private attributes: has Nose $:sniffer .= new(); [Update: That's $!sniffer now.] And encapsulated private attributes lead us to... A role can abstract the decision to delegate: role Pet { has $:groomer handles «bathe groom trim» = hire_groomer(); } Now when the Dog or Cat class incorporates the Pet role, it doesn't even have to know that the .groom method is delegated to a professional groomer. (See section on Delegation below.) It gets worse. Since you can specify inheritance with an "is" declaration within a class, you can do the same with a role: role Pet { is Friend; } Note carefully that this is not claiming that a Pet ISA Friend (though that might be true enough). Roles never inherit. So this is only saying that whatever animal takes on the role of Pet gets some methods from Friend that just happen to be implemented by inheritance rather than by composition. Probably Friend should have been written as a role, but it wasn't (perhaps because it was written in Some Other Language that runs on Parrot), and now you want to pretend that it was written as a role to get your project out the door. You don't want to use delegation because there's only one animal involved, and inheritance will work good enough till you can rewrite Friend in a language that supports role playing. Of course, the really funny thing is that if you go across a language barrier like that, Perl might just decide to emulate the inheritance with delegation anyway. But that should be transparent to you. And if two languages manage to unify their object models within the Parrot engine, you don't want to suddenly have to rewrite your roles and classes. And the really, really funny thing is that Parrot implements roles internally with a funny form of multiple inheritance anyway... Ain't abstraction wonderful. Roles are most useful at compile time, or more precisely, at class composition time, the moment in which the MetaClass class is figuring out how to put together your Class object. Essentially, that's while the closure associated with your class is being executed, with a little extra happening before and after. [Update: That should read "put together your MetaClass object (and the package associated with the name, if any)".] A class incorporates a role with the verb "does", like this: class Dog is Mammal does Pet does Sentry {...} or equivalently, within the body of the class closure: class Dog { is Mammal; does Pet; does Sentry; ... } There is no ordering dependency among the roles, so it doesn't matter above if Sentry comes before Pet. That is because the class just remembers all the roles and then meshes them after the closure is done executing. Each role's methods are incorporated into the class unless there is already a method of that name defined in the class itself. A class's method definition hides any role definition of the same name, so role methods are second-class citizens. On the other hand, role methods are still part of the class itself, so they hide any methods inherited from other classes, which makes ordinary inherited methods third-class citizens, as it were. If there are no method name conflicts between roles (or with the class), then each role's methods can be installed in the class, and we're done. (Unless we wish to do further analysis of role interrelationships to make sure that each role can find the methods it depends on, in which case we can do that. But for 6.0.0 I'll be happy if non-existent methods just fail at run time as they do now in Perl 5.) If, however, two roles try to introduce a method of the same name (for some definition of name), then the composition of the class fails, and the compilation of the program blows sky high--we sincerely hope. It's much better to catch this kind of error at compile time if you can. And in this case, you can. There are several ways to solve conflicts. The first is simply to write a class method that overrides the conflicting role methods, perhaps figuring out which role method to call. It is allowed to use the role name to select one of the hidden role methods: method shake ($self: $arg) { given $arg { when Culprit { $self.Sentry::shake($arg) } when Paw { $self.Pet::shake($arg) } } } So even though the methods were not officially composed into the class, they're still there--they're not thrown away. That last example looks an awful lot like multiple dispatch, and in fact, if you declare the roles' methods with multi, they would be treated as methods with different "long names", provided their signatures were sufficiently different. An interesting question, though, is whether the class can force two role methods that weren't declared "multi" to behave as if they were. Perhaps this can be forced if the class declares a signatureless multi stub without defining it later in the class: multi shake {...} The Traits paper recommends providing ways of renaming or excluding one or the other of the conflicting methods. We don't recommend that, because it's better if you can keep both contracts through multiple dispatch to the role methods. However, you can force renaming or exclusion by pretending the role is a delegation: does Pet handles [ :myshake«shake», Any ]; does Pet handles { $^name !~ "shake" }; Or something that. (See the section on Delegation below.) If we can't get that to work right, you can always say something like: method shake { .Sentry::shake(@_) } # exclude Pet::shake method handshake { .Pet::shake(@_) } # rename Pet::shake In many ways that's clearer than trying to attach a selection syntax to "does". [Update: That'd have to be self.Sentry etc. now.] While roles are at their most powerful at compile time, they can also function as mixin classes at run time. The "does" binary operator performs the feat of deriving a new class and binding the object to it: $fido does Sentry Actually, it only does this if $fido doesn't already do the Sentry role. If it does already, this is basically a no-op. The does operator works on the object in place. It would be illegal to say, for instance, 0 does true The does operator returns the object so you can nest mixins: . (Do not confuse the binary does with the unary does that you use inside a class definition to pull in a role.) In contrast to does, the but operator works on a copy. So you can say: 0 but true and you get a mixin based on a copy of 0, not the original 0, which everyone shares. One other wrinkle is that "true" isn't, in fact, a class name. It's an enumerated value of a bit class. So what we said was a shorthand for something like: 0 but bit::true [Update: That's Bool::True these days.] In earlier Apocalypses we talked about applying properties with but. This has now been unified with mixins, so any time you say: $value but prop($x) you're really doing something more like $tmp = $value; # make a copy $tmp does SomeRole; # guarantee there's a rw .prop method $tmp.prop = $x; # set the prop method And therefore a property is defined by a role like this: role SomeRole { has SomeType $.prop is rw = 1; } This means that when you mention " prop" in your program, something has to know how to map that to the SomeRole role. That would often be something like an enum declaration. It's illegal to use an undeclared property. But sometimes you just want a random old property for which the role has the same name as the property. You can declare one with my property answer; and that essentially declares a role that looks something like my role answer { has $.answer is rw = 1; } Then you can say $a = 0 but answer(42) and you have an object of an anonymous type that "does" answer, and that include a .answer accessor of the same name, so that if you call $a.answer, you'll get back 42. But $a itself has the value 0. Since the accessor is " rw", you can also say $a.answer = 43; There's a corresponding assignment operator: $a but= tainted; That avoids copying $a before tainting it. It basically means the same thing as $a does taint::tainted For more on enumerated types, see Enums below. Here we're talking about Perl's traits (as in compile-time properties), not Traits (as in the Traits paper). Traits can be thought of as roles gone wrong. Like roles, they can function as straightforward mixins on container objects at compile time, but they can also cheat, and frequently do. Unlike roles, traits are not constrained to play fair with each other. With traits, it's both "first come, first served", and "he who laughs last laughs best". Traits are applied one at a time to their container victim, er, object, and an earlier trait can throw away information required by a later trait. Contrariwise, a later trait can overrule anything done by an earlier trait--except of course that it can't undestroy information that has been totally forgotten by the earlier trait. You might say that "role" is short for "role model", while "trait" is short for "traitor". In a nutshell, roles are symbiotes, while traits are parasites. Nevertheless, some parasites are symbiotic, and some symbiotes are parasitic. Go figure... All that being said, well-behaved traits are really just roles applied to declared items like containers or classes. It's the declaration of the item itself that makes traits seem more permanent than ordinary properties. The only reason we call them "traits" rather than "properties" is to continually remind people that they are, in fact, applied at compile time. (Well, and so that we can make bad puns on "traitor".) Even ill-behaved traits should add an appropriately named role to the container, however, in case someone wants to look at the metadata properties of the container. Traits are generally inflicted upon the "traitee" with the "is" keyword, though other modalities are possible. When the compiler sees words like "is" or "will" or "returns" or "handles", or special constructs like signatures and body closures, it calls into an associated trait handler which applies the role to the item as a mixin, and also does any other traitorous magic that needs doing. To define a trait handler for an "is xxx" trait, define one or more multisubs into a property role like this: role xxx { has Int $.xxx; multi sub trait_auxiliary:is(xxx $trait, Class $container: ?$arg) {...} multi sub trait_auxiliary:is(xxx $trait, Any $container: ?$arg) {...} } [Update: That's trait_auxiliary:<is> now.] Then it can function as a trait. A well-behaved trait handler will say $container does xxx($arg); somewhere inside to set the metadata on the container correctly. Then not only can you say class MyClass is xxx(123) {...} but you'll also be able to say if MyClass.meta.xxx == 123 {...} Since a class can function as a role when it comes to parameter type matching, you can also say: class MyBase { multi sub trait_auxiliary:is(MyBase $base, Class $class: ?$arg) {...} multi sub trait_auxiliary:is(MyBase $tied, Any $container: ?$arg) {...} } These capture control if MyBase wants to capture control of how it gets used by any class or container. But usually you can just let it call the generic defaults: multi sub *trait_auxiliary:is(Class $base, Class $class: ?$arg) {...} which adds $base to the "isa" list of $class, or multi sub *trait_auxiliary:is(Class $tied, Any $container: ?$arg) {...} which sets the "tie" type of the container to the implementation type in $tied. In any event, if the trait supplies the optional argument, that comes in as $arg. (It's probably something unimportant, like the function body...) Note that unlike "pair options" such as " :wag", traits do not necessarily default to the value 1 if you don't supply the argument. This is consistent with the notion that traits don't generally do something passive like setting a value somewhere, but something active like totally screwing up the structure of your container. Most traits are introduced by use of a "helping verb", which could be something like " is", or " will", or " can", or " might", or " should", or " does". We call these helping verbs "trait auxiliaries". Here's " will", which (being syntactic sugar) merely delegates to back to "is": multi sub *trait_auxiliary:will($trait, $container: &arg) { trait_auxiliary:is($trait, $container, &arg); } Note the declaration of the argument as a non-optional reference to a closure. This is what allows us to say: my $dog will eat { anything() }; rather than having to use parens: my $dog is eat({ anything() }); Other traits are applied with a single word, and we call one of those a "trait verb". For instance, the " returns" trait described in Apocalypse 6 is defined something like this: role returns { has ReturnType $.returns; multi sub trait_verb:returns($container: ReturnType $arg) { $container does returns($arg); } ... } [Update: Make that trait_verb:<returns> now.] Note that the argument is not optional on " returns". Earlier we defined the xxx trait using multi sub definitions: role xxx { has Int $.xxx; multi sub trait_auxiliary:is(xxx $trait, Class $container: ?$arg) {...} multi sub trait_auxiliary:is(xxx $trait, Any $container: ?$arg) {...} } This is one of those situations in which you may really want single-dispatch methods: role xxx { has Int $.xxx; method trait_auxiliary:is(xxx $trait: Class $container, ?$arg) {...} method trait_auxiliary:is(xxx $trait: Any $container, ?$arg) {...} } Some traits are control freaks, so they want to make sure that anything mentioning them comes through their control. They don't want something dispatching to another trait's trait_auxiliary:is method just because someone introduced a cute new container type they don't know about. That other trait would just mess things up. Of course, if a trait is feeling magnanimous, it should just go ahead and use multi subs. Since the multi-dispatcher takes into account single-dispatch methods, and the distance of an exact match on the first argument is 0, the dispatcher will generally respect the wishes of both the paranoid and the carefree. Note that we included "does" in our list of "helping verbs". Roles actually implement themselves using the trait interface, but the generic version of trait_auxiliary:does defaults to doing proper roley things rather than proper classy things or improper traitorous things. So yes, you could define your own trait_auxiliary:does and turn your nice role traitorous. That would be...naughty. But apart from how you typically invoke them, traits and roles are really the same thing. Just like the roles on which they're based, you may neither instantiate nor inherit from a trait. You may, however, use their names as type constraints on multimethod signatures and such. As with well-behaved roles, they should define attributes or methods that show up as metadata properties where that's appropriate. Unlike compile-time roles, which all flatten out in the same class, compile-time traits are applied one at a time, like mixin roles. You can, in fact, apply a trait to a container at run time, but if you do, it's just an ordinary mixin role. You have to call the appropriate trait_auxiliary:is() routine yourself if you want it to do any extra shenanigans. The compiler won't call it for you at run time like it would at compile time. When you define a helping verb such as "is" or "does", it not only makes it a postfix operator for declarations, but a unary operator within class and role closures. Likewise, declarative closure blocks like BEGIN and INIT are actually trait verbs, albeit ones that can add multiple closures to a queue rather than adding a single property. This implies that something like sub foo { LEAVE {...} ... } could (except for scoping issues) equivalently be written: sub foo LEAVE {...} { ... } Though why you'd want to that, I don't know. Hmm, if we really generalize trait verbs like that, then you could also write things like: sub foo { is signature ('int $x'); is cached; returns Int; ... } That's gettin' a little out there. Maybe we won't generalize it quite that far... Delegation is the art of letting someone else do your work for you. The fact that you consider it "your" work implies that delegation is actually a means of taking credit in advance for what someone else is going to do. In terms of objects, it means pretending that some other object's methods are your own. Now, as it happens, you can always do that by hand simply by writing your own methods that call out to another object's methods of the same name. So any shorthand for doing that is pure syntactic sugar. That's what we're talking about here. Delegation in this sugary sense always requires there to be an attribute to keep a reference to the object we're delegating to. So our syntactic relief will come in the form of annotations on a " has" declaration. We could have decided to instead attach annotations to each method declaration associated with the attribute, but by the time you do this, you've repeated so much information that you almost might as well have written the non-sugary version yourself. I know that for a fact, because that's how I originally proposed it. :-) is context(Lazy)) { $:tail.wag(*@args) } (It's necessary to specify a Lazy context for the arguments to a such a delegator method because the actual signature is supplied by the tail's .wag method, not your method.) [Update: Now you use Captures: method wag (\$args) { $!tail.wag([,]$args) } ] So as you can see, the delegation syntax already cuts our typing in half, not to mention the reading. The win is even greater when you specify multiple methods to delegate: has $:legs handles «walk run lope shake pee»; Or equivalently: has $:legs handles ['walk', 'run', 'lope', 'shake', 'pee']; You can also say things like my @legmethods := «walk run lope shake pee»; has $:legs handles (@legmethods); since the " has" declaration is evaluated at class construction time. Of course, it's illegal to call the outer method unless the attribute has been initialized to an object of a type supporting the method. So a declaration that makes a new delegatee at object build time might be specified like this: has $:tail handles 'wag' will build { Tail.new(*%_) }; or, equivalently, has $:tail handles 'wag' = { Tail.new(*%_) }; This automatically performs $:tail = Tail.new(*%_); when BUILD is called on a new object of the current class (unless BUILD initializes $:tail to some other value). Or, since you might want to declare the type of the attribute without duplicating it in the default value, you can also say has Tail $:tail handles 'wag' = { .new(*%_) }; or has Tail $:tail handles 'wag' will build { .new(*%_) }; Note that putting a Tail type on the attribute does not necessarily mean that the method is always delegated to the Tail class. The dispatch is still based on the run-time type of the object, not the declared type. So has Tail $:tail handles 'wag' = { LongTail.new(*%_) }; delegates to the LongTail class, not the Tail class. Of course, you'll get an exception at build time if you try to say: has Tail $:tail handles 'wag' = { Dog.new(*%_) }; since Dog is not derived from Tail (whether or not the tail can wag the dog). We declare $:tail as a private attribute here, but $.tail would have worked just as well. A Dog's tail does seem to be a public interface, after all. Kind of a read-only accessor. We've seen that the argument to " handles" can be a string or a list of strings. But any argument or subargument that is not a string is considered to be a smartmatch selector for methods. So you can say: has $:fur handles /^get_/; and then you can do the .get_wet or .get_fleas methods (presuming there are such), but you can't call the .shake or .roll_in_the_dirt methods. (Obviously you don't want to delegate the .shake method since that means something else when applied to the Dog as a whole.) If you say has $:fur handles Groomable; then you get only those methods available via the Groomable role or class. Wildcard matches are evaluated only after it has been determined that there's no exact match to the method name. They therefore function as a kind of autoloading in the overall pecking order. If the class also has an AUTOLOAD, it is called only if none of the wildcard delegations match. (An AUTOMETHDEF is called much earlier, since it knows from the stub declarations whether there is supposed to be a method of that name. So you can think of explicit delegation as a kind of autodefine, and wildcard delegation as a kind of autoload.) When you have multiple wildcard delegations to different objects, it's possible to have a conflict of method names. Wildcard method matches are evaluated in order, so the earliest one wins. (Non-wildcard method conflicts can be caught at class composition time.)» }; Perhaps that reads better with the old pair notation: has $:fur handles { shakefur => 'shake', scratch => 'get_fleas' }; You can do a wildcard renaming, but not with pairs. Instead do smartmatch with a substitution: has $:fur handles (s/^furget_/get_/); As always, the left-to-right mapping is from this class to the other one. The pattern matching is working on the method name passed to us, and the substituted method name is used on the class we delegate to. Ordinarily delegation is based on an attribute holding an object reference, but there's no reason in principle why you have to use an attribute. Suppose you had a Dog with two tails. You can delegate based on a method call: method select_tail handles «wag hang» {...} The arguments are sent to both the delegator and delegatee method. So when you call $dog.wag(:fast) you're actually calling $dog.select_tail(:fast).wag(:fast) If you use a wildcard delegation based on a method, you should be aware that it has to call the method before it can even decide whether there's a valid method call to the delegatee or not. So it behooves you not to get too fancy with select_tail(), since it might just have to throw all that work away and go on to the next wildcard specification. If your delegation object happens to be an array: has @:handlers handles 'foo'; then something cool happens. <cool rays> In this case Perl 6 assumes that your array contains a list of potential handlers, and you just want to call the first one that succeeds. This is not considered a wildcard match unless the "handles" argument forces it to be. Note that this is different from the semantics of a hyper method such as @objects».foo(), which will try to call the method on every object in @objects. If you want to do that, you'll just have to write your own method: has @:ears; method twitchears () { @:ears».twitch() } Life is hard. If your delegation object happens to be a hash: has %:objects handles 'foo'; then the hash provides a mapping from the string value of "self" to the object that should be delegated to: has %:barkers handles "bark" = (Chihauhau => $yip, Beagle => $yap, Terrier => $arf, StBernard => $woof, ); method prefix:~( return "$.breed" ) [Update: That's prefix:<~> now.] If the string is not found in the hash, a " next METHOD" is automatically performed. Again, this construct is not necessarily considered a wildcard. In the example above we know for a fact that there's supposed to be a .bark method somewhere, therefore a specific method can be autogenerated in the current class. Delegation is a means of including a set of methods into your class. Roles can also include a set of methods in your class, but the difference is that what a role includes happens at class composition time, while delegation is much more dynamic, depending on the current state of the the delegating attribute (or method). But there's no reason you can't have your cake and eat it too, because roles are specifically designed to allow you to pull in delegations without the class even being aware of the fact that it's delegating. When you include a role, you're just signing up for a set of methods, with maybe a little state thrown in. You don't care whether those methods are defined directly, or indirectly. The role manages that. In fact, this is one of the primary motivators for including roles in the design of Perl 6. As a named abstraction, a role lets you refactor all the classes using that role without changing any of the classes involved. You can turn your single "god" object into a set of nicely cooperating objects transparently. Well, you have to do the composition using roles first, and that's not transparent. Note that all statically named methods are dispatched before any wildcard methods, regardless of whether the methods came from a role or the class itself. (Inherited methods also come before wildcard methods because we order all the cachable method dispatches before all the non-cachable ones. But see below.) So the lookup order is: Note that any method that is stubbed (declared but not yet defined) in steps 1 or 2 skips straight to step 4, because it means this class thinks it "owns" a method of that name. (At this point Perl 5 would skip straight to step 5, but Perl 6 still wants to do wildcard delegation before falling back on inherited autoloading.) When you inherit from a class with a different layout policy, Perl has to emulate inheritance via anonymous delegation. In this case it installs a wildcard delegation for you. According to the list above, this gives precedence to all methods with the same layout policy over all methods with a different layout policy. This might be a feature, especially when calling cross-language. Then again, maybe it isn't. There is no " has" variable for such an anonymous delegation. Its delegated object is stored as a property on the class's entry in the ISA list, probably. (Or we could autogenerate an attribute whose name is related to the class name, I suppose.) Since one of the primary motivations for allowing this is to make it possible to call back and forth between Perl 5 and Perl 6 objects, we need to make that as transparent as possible. When a Perl 6 object inherits from a Perl 5 object, it is emulated with delegation. The invocant passed into the Perl 5 (Ponie) object looks like a Perl 5 object to Perl 5. However, if the Perl 5 object passes that as an invocant back into Perl 6, it has to go back to looking like a Perl 6 object to Perl 6, or our emulation of inheritance is suboptimal. When a Ponie object accesses its attributes through what it thinks is a hash reference, it really has to call the appropriate Perl 6 accessor function if the object comes from Perl 6. Likewise, when Perl 6 calls an accessor on a Perl 5 object, it has to translate that method call into a hash lookup--presuming that the Perl 5 object is implemented as a blessed hash. Other language boundaries may or may not do similar tricks. Python's attributes suffer from the same misdesign as Perl 5's attributes. (My fault for copying Python's object model. :-) So that'd be a good place for a similar policy. So we can almost certainly emulate inheritance with delegation, albeit with some possible misordering of classes if there are duplicate method names. However, the hard part is constructing objects. Perl 5 doesn't enforce a policy of named arguments for its constructors, so it is difficult for a Perl 6 BUILDALL routine to have any automatic way to call a Perl 5 constructor. It's tempting to install glue code into the Perl 6 class that will do the translation, but that's really not a good idea, because someday the Perl 5 class may eventually get translated to a Perl 6 class, and your glue code will be useless, or worse. So the right place to put the glue is actually back into the Perl 5 class. If a Perl 5 class defines a BUILD subroutine, it will be assumed that it properly handles named pairs in Perl 5's even/odd list format. That will be used in lieu of any predefined constructor named " new" or anything else. If there is no BUILD routine in the Perl 5 package, but there is a " use fields" declaration, then we can autogenerate a rudimentary BUILD routine that should suffice for most scalar attributes. I've always really liked the Ada distinction between types and subtypes. A type is something that adds capabilities, while a subtype is something that takes away capabilities. Classes and roles generally function as types in Perl 6. In general you don't want to make a subclass that, say, restricts your integers to only even numbers, because then you've violated Liskov substitutability. In the same way that we force role composition to be "before" classes, we will force subtyping constraints to be "after" classes. In both cases we force it by a declarator change so that you are unlikely to confuse a role with a class, or a class with a subtype. And just as you aren't allowed to derive a role from a class, you aren't allowed to derive a class from a constrained type. On the other hand, a bit confusingly, it looks like subtyping will be done with the "type" keyword, since we aren't using that word yet. To remind people that a subtype of a class is just a constrained alias for the class, we avoid the "is" word and declare a type using a ::= compile-time alias, like this: type Str_not2b ::= Str where /^[isnt|arent|amnot|aint]$/; The ::= doesn't create the type, nor in fact does the type keyword. It's actually the where that creates the type. The type keyword just marks the name as "not really a classname" so that you don't accidentally try to derive from it. [Update: I decided I don't like the forced use of ::=, nor do I like the confusion engendered by use the word "type" to mean "subtype", so the syntax is now any of: my subset Str_not2b of Str where /^[isnt|arent|amnot|aint]$/; my Str subset Str_not2b where /^[isnt|arent|amnot|aint]$/; .] Since a type is "post-class-ical", there's really no such thing as an object blessed into a type. If you try it, you'll just end up with an object blessed into whatever the underlying unconstrained class is, as far as inheritance is concerned. A type is not a subclass. A type is primarily a handy way of sneaking smartmatching into multiple dispatch. Just as a role allows you to specify something more general than a class, a type allows you to specify something more specific than a class. While types are primarily intended for restricting parameter types for multiple dispatch, they also let you impose preconditions on assignment. Basically, if you declare any container with a subtype, Perl will check the constraint against any value you might try to bind or assign to the container. type Str_not2b ::= Str where /^[isnt|arent|amnot|aint]$/; type EvenNum ::= perfectly legal to base one subtype on another. It merely adds an additional constraint. It's possible to use an anonymous subtype in a signature: use Rules::Common :profanity; multi sub mesg (Str where /<profanity>/ $mesg is copy) { $mesg ~~ s:g/<profanity>/[expletive deleted]/; print $MESG_LOG: $mesg; } multi sub mesg (Str $mesg) { print $MESG_LOG: $mesg; } Given a set of multimethods that would "tie" on the actual classes of the arguments, a multimethod with a matching constraint will be preferred over an equivalent one with no constraint. So the first mesg above is preferred if the constraint matches, and otherwise the second is preferred. However, if two multis with constraints match (and are otherwise equivalent), it's just as if you'd called any other set of ambiguous multimethods, and one of them had better be marked as the default, or you die. We say that types are "post-class-ical", but since you can base them off of any class including Any, they are actually rather orthogonal to the class system. [Update: Everywhere the preceding section says "type", change to "subtype", except for the keyword, which changes to "subset". And change ::= to of.] An enum functions as a subtype that is constrained to a single value. (When a subtype is constrained to a single value, it can be used for that value.) But rather than declaring it as: type DayOfWeek ::= Int where 0..6; type DayOfWeek::Sunday ::= DayOfWeek where 0; type DayOfWeek::Monday ::= DayOfWeek where 1; type DayOfWeek::Tuesday ::= DayOfWeek where 2; type DayOfWeek::Wednesday ::= DayOfWeek where 3; type DayOfWeek::Thursday ::= DayOfWeek where 4; type DayOfWeek::Friday ::= DayOfWeek where 5; type DayOfWeek::Saturday ::= DayOfWeek where 6; we allow a shorthand: type DayOfWeek ::= int enum «Sunday Monday Tuesday Wednesday Thursday Friday Saturday»; [Update: The syntax is now more like existing declarations: our int enum DayOfWeek <Sunday Monday Tuesday Wednesday Thursday Friday Saturday>; where int is usually omitted.] Type int is the default enum type, so that can be: type DayOfWeek ::= enum «Sunday Monday Tuesday Wednesday Thursday Friday Saturday»; [Update: Now just enum DayOfWeek <...>.] The enum installer inspects the strings you give it for things that look like pairs, so to number your days from 1 to 7, you can say: type DayOfWeek ::= enum «:Sunday(1) Monday Tuesday Wednesday Thursday Friday Saturday»; You can import individual enums into your scope where they will function like argumentless constant subs. However, if there is a name collision with a sub or other enum, you'll have to disambiguate. Unambiguous enums may be used as a property on the right side of a "but", and the enum type can be intuited from it to make sure the object in question has the right semantics mixed in. Two builtin enums are: type bool ::= bit enum «false true»; type taint ::= bit enum «untainted tainted»; [Update: Now just: our bit enum *Bool is <False True>; our bit enum *Taint is <Untainted Tainted>; .] By default, classes in Perl are left open. That is, you can add more methods to them, though you have to be explicit that that is what you're doing: class Object is extended { method wow () { say "Wow, I'm an object." } } Otherwise you'll get a class redefinition error. Likewise, a "final" class (to use the Java term) is one that you know will never be derived from, let alone mucked with internally. Now, it so happens that leaving all your classes open is not terribly conducive to certain kinds of optimization (let alone encapsulation). From the standpoint of the compiler, you'd like to be able to say, "I know this class will never be derived from or modified, so I can do things like access my attributes directly without going through virtual accessors." We were, in fact, tempted to make closed classes the default. But this breaks in frameworks like mod_perl where you cannot predict in advance which classes will want to be extended or derived from. Some languages solve this (or think they solve it) by letting classes declare themselves to be closed and/or final. But that's actually a bad violation of OO principles. It should be the users of a class that decide such things--and decide it for themselves, not for others. As such, there has to be a consensus among all users of a class to close or finalize it. And as we all know, consensus is difficult to achieve. Nevertheless, the Perl 6 approach is to give the top-level application the right to close (and finalize) classes. But we don't do this by simply listing the classes we want to close. Instead, we use the sneaky strategy of switching the default to closed and then list the classes we want to stay open. The benefit of this is that modules other than the top level can simply list all the classes that they know should stay open. In an open framework, these are, at worst, no-ops, and they don't cause classes to close that other modules might want to remain open. If any module requests a class to stay open, it stays open. If any module requests that a class remain available as a base class, it remains available. It has been speculated that optimizer technology in Parrot will develop such that a class can conjecturally be compiled as closed, and then recompiled as open should the need arise. (This is just a specific case of the more general problem of what you do whenever the assumptions of the optimizer are violated.) If we get such an on-the-fly optimizer/pessimizer, then our open class declarations are still not wasted--they will tell the optimizer which classes not to bother trying to close or finalize in the first place. Setting the default the other way wouldn't have the same benefit. Syntax? You want syntax? Hmm. use classes :closed :open«Mammal Insect»; [Update: Now more like " use opt :classes(:close :finalize);", since it's direct instruction to the optimizer. It doesn't directly change the meaning of the class keyword, so it shouldn't use class as the pragma name.] Or some such. Maybe certain kinds of class reference automatically request the class to be open without a special pragma. A module could request open classes without attempting to close everything with just: use classes :open«Mammal Insect»; [Update: Just " class" to match the keyword.] On the other hand, maybe that's another one of those inside-out interfaces, and it should just be options on the classes whose declarations you have to include anyway: use classes :closed; class Mammal is open {...} class Insect is open {...} Similarly, we can finalize classes by default and then "take it back" for certain classes: use classes :final; class Mammal is base {...} class Insect is base {...} In any event, even though the default is expressed at the top of the main application, the final decision on each class is not made by the compiler until CHECK time, when all the compiled code has had a chance to stake its claims. (A JIT compiler might well wait even longer, in case run-time evaluated code wishes to express an opinion.) In theory, a subclass should always act as a more specialized version of a superclass. In terms of design-by-contract theory, a subclass should OR in its preconditions and AND in its postconditions. In terms of Liskov substitutability, you should always be able to substitute a derived class object in where a base class object is expected, and not have it blow up. In terms of Internet policy, a derived class (compared to its base class) should be at least as lenient in what it accepts, and at least as strict in what it emits. So, while it would be lovely in a way to require that derived methods of the same name as a base method must use the same signature, in practice that doesn't work out. A derived class often has to be able to add arguments to the signature of a method so that it can "be more lenient" in what it accepts as input. But this poses a problem, insofar as the user of the derived object does not know whether all the methods of a given name support the same interface. Under SUPER semantics, one can at least assume that the derived class will "weed out" any arguments that would be detrimental to its superclass. But as we have already pointed out, there isn't a single superclass under MI, and each superclass might need to have different "detrimental arguments" weeded out. One could say that in that case, you don't call SUPER but rather call out to each superclass explicitly. But then you're back to the problem that SUPER was designed to solve. And you haven't solved SUPER's problem either. Under NEXT semantics, we assume that we are dispatching to a set of methods with the same name, but potentially different signatures. (Perl 6's SUPER implementation is really a limited form of NEXT, insofar as SUPER indicates a set of parent methods, unlike in Perl 5 where it picks one.) We need a way of satisfying different signatures with the same set of arguments. There are, in fact, two ways to approach this. One way is to say, okay everything is a multimethod, and we just won't call anything whose signature is irreconcilably inconsistent with the arguments presented. Plus there are varying degrees of consistency within the set of "consistent" interfaces, so we try them in decreasing order of consistency. A more consistent multi is allowed to fall back to a less consistent multi with " next METHOD". But as a variant of the "pick one" mentality, that still doesn't help the situation where you want to send a message to all your ancestor classes (like "Please Mr. Base Class, help me initialize this object."), but you want to be more specific with some classes than others ("Please Miss Derived Class, set your $.prim attribute to 1."). So the other approach is to use named arguments that can be ignored by any classes that don't grok the argument. So what this essentially comes down to is the fact that all methods and submethods of classes that might be derived from (which is essentially all classes, but see the previous section) must have a *% parameter, either explicitly or implicitly, to collect up and render harmless any unrecognized option pairs in the argument list. So the ruling is that all methods and submethods that do not declare an explicit *% parameter will get an implicit *%_ parameter declared for them whether they like it or not. (Subroutines are not granted this "favor".) It might be objected that this will slow down the parameter binding algorithm for all methods favored with an implicit *%_, but I would argue that the binding code doesn't have to do anything till it sees a named parameter it doesn't recognize, and then it can figure out whether the method even references %_, and if not, simply throw the unrecognized argument away instead of constructing a %_ that won't be used. And most of this "figuring out" can be done at compile time. Another counterargument is that this prevents a class from recognizing typos in argument names. That's true. It might be possible to ask for a warning that checks globally (at class-finalization time in the optimizer?) to see if there is any method of that name anywhere that is interested in a parameter of that name. But any class that gets its parameters out of a *% hash at run time would cause false positives, unless we assume that any *% hash makes any argument name legal, in which case we're pretty much back to where we started, unless we do analysis of the usage of all *% hash in those methods, and count things like %_«prim» as proper parameter declarations. And that can still be spoofed in any number of ways. Plus it's not a trivial warning to calculate, so it probably wouldn't be the default in a load-and-go interpreter. So I think we basically have to live with possible typos to get proper polymorphic dispatch. If something is frequently misspelled, then you could always put in an explicit test against %_ for that argument: warn "Didn't you mean :the(%_«teh»)?" if %_«teh»; And perhaps we could have a pragma: use signatures :exact; But it's possible that the correct solution is to differentiate two kinds of "isa", one that derives from "nextish" classes, and one that derives from "superish" classes. A " next METHOD" traversal would assume that any delegation to a super class would be handled explicitly by the current class's methods. That is, a "superish" inheritance hides the base class from .* and .+, as well as " next METHOD". On the other hand, if we marked the super class itself, we could refrain from generating *% parameters for its methods. Any "next" dispatcher would then have to "look ahead" to see if the next class was a "superish" class, and bypass it. I haven't a clue what the syntax should be though. We could mark the class with a "superish" trait, which wouldn't be inheritable. Or we could mark it with a Superish role, which would be inheritable, and a base class would have to override it to impose a Nextish role instead. (But then what if one parent class is Superish and one is Nextish?) Or we could even have two different metaclasses, if we decide the two kinds of classes are fundamentally different beasts. In that case we'd declare them differently using "class" and some other keyword. Of course, people will want to use "class" for the type they prefer, and the other keyword for the type they don't prefer. :-) But since we're attempting to bias things in favor of nextish semantics, that would be a "class", and the superish semantics might be a "guthlophikralique" or some such. :-) Seriously, if we mark the class, " is hidden" can hide the current class from " next METHOD" semantics. The problem with that is, how do you apply the trait to a class in a different language? That argues for marking the "isa" instead. So as usual when we can't make up our minds, we'll just have it both ways. To mark the class itself, use " is hidden". To mark the "isa", use " hides Base" instead of " is Base". In neither case will " next METHOD" traverse to such a class. (And no *%_ will be autogenerated.) For example, here are two base classes that know about " next METHOD": class Nextish1 { method dostuff() {...; next;} class Nextish2 { method dostuff() {...; next;} class MyClass is Nextish1 is Nextish2 { method dostuff () {...; next;} } Since all the base classes are "next-aware", MyClass knows it can just defer to "next" and both parent classes' dostuff methods will be called. However, suppose one of our base classes is old-fashioned and thinks it should call things with SUPER:: instead. (Or it's a class off in Python or Ruby.) Then we have to write our classes more like this: class Superish { method dostuff(...; .*SUPER::dostuff(); } class Nextish { method dostuff() {...; next;} class MyClass hides Superish is Nextish { method dostuff () { .Superish::dostuff(); # do Superish::dostuff() next; # do Nextish::dostuff() } } Here, MyClass knows that it has two very different base classes. Nextish knows about " next", and Superish doesn't. So it delegates to Superish::dostuff() differently than it delegates to Nextish::dostuff(). The fact that it declared " hides Superish" prevents next from visiting the Superish class. We'd like to be able to support virtual inner classes. You can't have virtual inner classes unless you have a way to dispatch to the actual class of the invocant. That says to me that the solution is bound up intimately with the method dispatcher, and the syntax of naming an inner class has to know about the invocant in whose context we have to start searching for the inner class. So we could have an explicit syntax like: class Base { our class Inner { ... } has Inner $inner; submethod BUILD { .makeinner; } method makeinner ($self:){ my Inner $thing .= $self.Inner.new(); return $thing; } } class Middle is Base { our class Inner is Base::Inner { ... } } class Derived is Middle { } When you say Derived.new(), it creates a Derived object, calls Derived::BUILDALL, which eventually calls Base::BUILD, which makes a Middle::Inner object (because that's what the virtual method $self.Inner returns) and puts it in a variable that of the Base::Inner type (which is fine, since Middle::Inner ISA Base::Inner. Whew! The only extra magic here is that an inner class would have to autogenerate an accessor method (of the same name) that returns the class. A class could then choose to access an inner class name directly, in which case it would get its own inner class of that name, much like $.foo always gets you your own attribute. But if you called the inner class name as a method, it would automatically virtualize the name, and you'd get the most derived existing version of the class. This would give us most of what RFC 254 is asking for, at the expense of one more autogenerated method. Use of such inner classes would take the connivance of a base class that doesn't mind if derived classes redefine its inner class. Unfortunately, it would have to express that approval by calling $self.Inner explicitly. So this solution does not go as far as letting you change classes that didn't expect to be changed. It would be possible to take it further, and I think we should. If we say that whenever you use any global class, it makes an inner class on your behalf that is merely an alias to the global class, creating the accessor method as if it were an inner class, then it's possible to virtualize the name of any class, as long as you're in a context that has an appropriate invocant. Then we'd make any class name lookup assume $self. on the front, basically. This may seem like a wild idea, but interestingly, we're already proposing to do a similar aliasing in order to have multiple versions of a module running simultaneously. In the case of classes, it seems perfectly natural that a new version might derive from an older version rather than redefining everything. The one fly in the ointment that I can see is that we might not always have an appropriate invocant--for instance, outside any method body, when we're declaring attributes. I guess when there's no dynamic context indicating what an "inner" classname should mean, it should default to the ordinary meaning in the current lexical and/or package context. Within a class definition, for instance, the invocant is the metaclass, which is unhelpful. So generally that means that a declared attribute type will turn out to be a superclass of the actual attribute type at run time. But that's fine, ain't it? You can always store a Beagle in a Dog attribute. So in essence, it boils down to this. Within a method, the invocant is allowed to have opinions about the meanings of any class names, and when there are multiple possible meanings, pick the most appropriate one, where that amounts to the name you'd find if the class name were a virtual method name. Here's the example from RFC 254, translated to Perl 6 (with Frog made into an explicit inner class for clarity (though it should work with any class by the aliasing rule above)): class Forest { our class Frog { method speak () { say "ribbit ribbit"; } method jump () {...} method croak () {...} # ;-) } has Frog $.frog; method new ($class) { my Frog $frog .= new; # MAGIC return $class.bless( frog => $frog ); } sub make_noise { .frog.speak; # prints "ribbit ribbit" } } Now we derive from Forest, producing Forest::Japanese, with its own kind of frogs: class Forest::Japanese is Forest { our class Frog is Forest::Frog { method speak () { say "kerokero"; } } } And finally, we make a forest of that type, and tell it to make a noise: $forest = new Forest::Japanese; $forest.make_noise(); # prints "kerokero" In the Perl 5 equivalent, that would have printed "ribbit ribbit" instead. How did it do the right thing in Perl 6? The difference is on the line marked " MAGIC". Because Frog was mentioned in a method, and the invocant was of type Forest::Japanese rather than of type Forest, the word " Frog" figured out that it was supposed to mean a Forest::Japanese::Frog rather than a Forest::Frog. The name was "virtual". So we ended up creating a forest with a frog of the appropriate type, even though it might not have occurred to the writer of Forest that a subclass would override the meaning of Frog. So one object can think that its Frog is Japanese, while another thinks it's Russian, or Mexican, or even Antarctican (if you can find any forests there). Base methods that talk about Frog will automatically find the Frog appropriate to the current invocant. This works even if Frog is an outer class rather than an inner class, because any outer class referenced by a base class is automatically aliased into the class as a fake inner class. And the derived class doesn't have to redefine its Frog by declaring an inner class either. It can just alias (or use) a different outer Frog class in as its fake inner class. Or even a different version of the same Frog class, if there are multiple versions of it in the library. And it just works. It's also possible to put a collection of classes into a module, but that doesn't buy you much except the ability to pull them all in with one use, and manage them all with one version number. Which has a lot to be said for it--in the next section. Way back at the beginning, we claimed that a file-scoped class declaration: class Dog; ... is equivalent to the corresponding block-scoped declaration: class Dog {...} While that's true, it isn't the whole truth. A file-scoped class (or module, or package) is the carrier of more metadata than a block-scoped declaration. Perl 6 supports a notion of versions that is file based. But even a class name plus a version is not sufficient to name a module--there also has to be a naming authority, which could be a URI or a CPAN id. This will be discussed more fully in Apocalypse 11, but for now we can make some predictions. The extra metadata has to be associated with the file somehow. It may be implicit in the filename, or in the directory path leading to the file. If so, then Perl 6 has to collect up this information as modules are loaded and associate it with the top level class or module as a set of properties. It's also possible that a module could declare properties explicitly to define these and other bits of metadata: author version 1.2.1 creator Joe Random description This class implements camera obscura. subject optics, boxes language ja_JP licensed Artistic|GPL Modules posted to CPAN or entered into any standard Perl 6 library are required to declare some set of these properties so that installations can know where to keep them, such that multiple versions by different authors can coexist, all of them available to any installed version of Perl. (This is a requirement for any Perl 6 installation. We're tired of having to reinstall half of CPAN every time we patch Perl. We also want to be able to run different versions of the Frog module simultaneously when the Frog requirements of the modules we use are contradictory.) It's possible that the metadata is supplied by both the declarations and by the file's name or location in the library, but if so, it's a fatal error to use a module for which those two sources contradict each other as to author or version. (In theory, it could also be a fatal error to use modules with incompatible licensing, but a kind warning might be more appreciated.) Likely there will also be some kind of automatic checksumming going on as well to prevent fraudulent distributions of code. It might simplify things if we make an identifier metadatum that incorporates all of naming authority, package name, and version. But the individual parts still have to be accessible, if only as components of identifier. However we structure it, we should make the identifier the actual declared full name of the class, yet another one of those "long names" that include extra parameters. The syntax of a versioned class declaration looks like this: class Dog-1.2.1-cpan:JRANDOM; class Dog-1.2.1-; class Dog-1.2.1-mailto:jrandom@some.com; Perhaps those could also have short forms, presuming we can distinguish CPAN ids, web pages, and email addresses by their internal forms. class Dog-1.2.1-JRANDOM; class Dog-1.2.1-; class Dog-1.2.1-jrandom@some.com; Or maybe using email addresses is a bad idea now in the modern Spam Age. Or maybe Spam Ages should be plural, like the Dark Ages... In any event, such a declaration automatically aliases the full name of the class (or module) to the short name. So for the rest of the scope, Dog refers to the longer name. (Though if you refer to Dog within a method, it's considered a virtual class name, so Perl will search any derived classes for a redefined inner Dog class (or alias) before it settles on the least-derived aliased Dog class.) We lied slightly when we said earlier that only the file-scoped class carries extra metadata. In fact, all of the classes (or modules, or packages) defined within your file carry metadata, but it so happens that the version and author of all your extra classes (or modules, or packages) are forced to be the same as the file's version and author. This happens automatically, and you may not override the generation of these long names, because if you did, different file versions could and would have version collisions of their interior components, and that would be catastrophic. In general you can ignore this, however, since the long names of your extra classes are always automatically aliased back down to the short names you thought you gave them in the first place. The extra bookkeeping is in there only so that Perl can keep your classes straight when multiple versions are running at the same time. Just don't be surprised when you ask for the name of the class and it tells you more than you expected. Since these long names are the actual names of the classes, when you say: use Dog; you're really asking for something like: use Dog-(Any)-(Any); And when you say: use Dog-1.2.1; you're really asking for: use Dog-1.2.1-(Any); Note that the 1.2.1 specifies an exact match on the version number. You might think that it should specify a minimum version. However, people who want stable software will specify an exact version and stick with it. They don't want 1.2.1 to mean a minimum version. They know 1.2.1 works, so they want that version nailed down forever--at least for now. To match more than one version, put a range operator in parens: use Dog-(1.2.1..1.2.3); use Dog-(1.2.1..^1.3); use Dog-(1.2.1...); [Update: An infinite range is now written (1.2.1..*). What goes inside the parens is in fact any valid smartmatch selector: use Dog-(1.2.1 | 1.3.4)-(/:i jrandom/); use Dog-(Any)-(/^cpan\:/) And in fact they could be closures too. These means the same thing: use Dog-{$^ver ~~ 1.2.1 | 1.3.4}-{$^auth ~~ /:i jrandom/}; use Dog-{$^ver ~~ Any}-{$^auth ~~ /"); (Again, if you refer to Dog within a method, it's a virtual class name, so Perl will search any derived classes for a redefined Dog class before it settles on the outermost aliased Dog class.) [Update: You can also prefix the module name with the language to borrow it from, like " use perl5:DBI;".] It's easy to specify what Perl 6 will provide for introspection: the union of what Perl 6 needs and whatever Parrot provides for other languages. ;-) In the particular case of class metadata, the interface should generally be via the class's metaclass instance--the object of type MetaClass that was in charge of building the class in the first place. The metamethods are in the metaobject, not in the class object. (Well, actually, those are the same object, but a class object ignores the fact that it's also a metaobject, and dispatches by default to its own methods, not the ones defined by the metaclass.) [Update: It's not true that the class object is the same as the metaobject.] To get to the metamethods of an ordinary class object you have to use the .meta method: MyClass.getmethods() # call MyClass's .getmethods method MyClass.meta.getmethods() # get the method list of MyClass Unless MyClass has defined or inherited a .getmethods method, the first call is an error. The second is guaranteed to work for Perl 6's standard MetaClass objects. You can also call .meta on any ordinary object: $obj.meta.getmethods(); That's equivalent to $obj.dispatcher.meta.getmethods(); [Update: There's no .dispatcher since all objects have a .meta now, and all objects of a class including class objects are of the same type.] As for which parts of a class are considered metadata--they all are, if you scratch hard enough. Everything that is not stored directly as a trait or property really ought to have some kind of trait-like method to access it. Even the method body closures have to be accessible as traits, since the .wrap method needs to have something to put its wrapper around. Minimally, we'll have user-specified class traits that look like this: identifier Dog-1.2.1- name Dog version 1.2.1 authority author Joe Random description This class implements camera obscura. subject optics, boxes language ja_JP licensed Artistic|GPL And there may be internal traits like these: isa list of parent classes roles list of roles disambig how to deal with ambiguous method names from roles layout P6opaque, P6hash, P5hash, P5array, PyDict, Cstruct, etc. The layout determines whether one class can actually derive from another or has to fake it. Any P6opaque class can compatibly inherit from any other P6opaque class, but if it inherits from any P5 class, it must use some form of delegation to another invocant. (Hopefully with a smart enough invocant reference that, if the delegated object unknowingly calls back into our layout system, we can recover the original object reference and maintain some kind of compositional integrity.) The metaclass's .getmethods method returns method-descriptor objects with at least the following properties: name the name of the method signature the parameters of the method returns the return type of the method multi whether duplicate names are allowed do the method body The .getmethods method has a selector parameter that lets you specify whether you want to see a flattened or hierarchical view, whether you're interested in private methods, and so forth. If you want a hierarchical view, you only get the methods actually defined in the class proper. To get at the others, you follow the "isa" trait to find your parent classes' methods, and you follow the "roles" trait to get to role methods, and from parents or roles you may also find links to further parents or roles. The .getattributes method returns a list of attribute descriptors that have traits like these: name type scope rw private accessor build Additionally they can have any other variable traits that can reasonably be applied to object attributes, such as constant. Strictly speaking, metamethods like .isa(), .does(), and .can() should be called through the meta object: $obj.meta.can("bark") $obj.meta.does(Dog) $obj.meta.isa(Mammal) And they can always be called that way. For convenience you can often omit the .meta call because the base Object type translates any unrecognized .foo() into .meta.foo() if the meta class has a method of that name. But if a derived class overrides such a metamethod, you have to go through the .meta call explicitly to get the original call. In previous Apocalypses we said that: $obj ~~ Dog calls: $obj.isa(Dog) That is not longer the case--you're actually calling: $obj.meta.does(Dog) which is true if $obj either "does" or "isa" Dog (or "isa" something that "does" Dog). That is, it asks if $obj is likely to satisfy the interface that comes from the Dog role or class. The .isa method, by contrast, is strictly asking if $obj inherits from the Dog class. It's erroneous to call it on a role. Well, okay, it's not strictly erroneous. It will just never return true. The optimizer will love you, and remove half your code. Note that either of .does or .isa can lie, insofar as you might include an interface that you later override parts of. When in doubt, rely on .can instead. Better yet, rely on your dispatcher to pick the right method without trying to second guess it. (And then be prepared to catch the exception if the dispatcher throws up its hands in disgust...) by default in this list of potential handlers, so there is no reason for subclasses to have to redefine .can to reflect the new names. This does potentially, that being said, many classes may wish to dynamically specify at the last moment which methods they can or cannot handle. That is, they want a hook to allow a class to declare names even while the .can candidate list is being built. By default .meta.can includes all wildcard delegations and autoloads at the end of the list. However, it will exclude from the list of candidates any class that defines its own AUTOMETH method, on the assumption that each such AUTOMETH method has already had its chance to add any callable names to the list. If the class's AUTOMETH wishes to supply a method, it should return a reference to that method. Do not confuse AUTOMETH with AUTOMETHDEF. The former is equivalent to declaring a stub declaration. The latter is equivalent to supplying a body for an existing stub. Whether AUTOMETH actually creates a stub, or AUTOMETHDEF actually creates a body, is entirely up to those routines. If they wish to cache their results, of course, then they should create the stub or body. There are corresponding AUTOSUB and AUTOSUBDEF hooks. And AUTOVAR and AUTOVARDEF hooks. These all pretty much make AUTOLOAD obsolete. But AUTOLOAD is still there for old times's sake. [Update: These are all subsumed into CANDO multies and AUTODEF submethods.] A lot of time went by while I was in the hospital last year, so we ended up polishing up the design of Perl 6 in a number of areas not directly related to OO. Since I've already got your attention (and we're already 90% of the way through this Apocalypse), I might as well list these decisions here. The trait we'll use for exportation (typically from modules but also from classes pretending to be modules) is export: # Tagset... sub foo is export(:DEFAULT) {...} # :DEFAULT, :ALL sub bar is export(:DEFAULT :others) {...} # :DEFAULT, :ALL, :others sub baz is export(:MANDATORY) {...} # (always exported) sub bop is export {...} # :ALL sub qux is export(:others) {...} # :ALL, :others Compared to Perl 5, we've basically made it easier to mark something as exportable, but more difficult to export something by default. You no longer have to declare your tagsets separately, since :foo parameters are self-declaring, and the module will automatically build the tagsets for you from the export trait arguments. We used one example of the conjectural gather/take construct. A gather executes a closure, returning a list of all the values returned by take within its lexical scope. In a lazy context it might run as a coroutine. There probably ought to be a dynamically scoped variant. Unless it should be dynamic by default, in which case there probably ought to be a lexically scoped variant... There's a new pair syntax that is more conducive to use as option arguments. This syntax is reminiscent of both the Unix command line syntax and the I/O layers syntax of Perl 5. But unlike Unix command-line options, we use colon to introduce the option rather than the overly negative minus sign. And unlike Perl 5's layers options, you can use these outside of a string. We haven't discarded the old pair syntax. It's still more readable for certain uses, and it allows the key to be a non-identifier. Plus we can define the new syntax in terms of it: Old New --- --- foo => $bar :foo($bar) foo => [1,2,3,@many] :foo[1,2,3,@many] foo => «alice bob charles» :foo«alice bob charles» foo => 'alice' :foo«alice» foo => { a => 1, b => 2 } :foo{ a => 1, b => 2 } foo => { dostuff() } :foo{ dostuff() } foo => 0 :foo(0) foo => 1 :foo It's that last one that's the real winner for passing boolean options. One other nice thing is that if you have several options in a row you don't have to put commas between: $handle = open $file, :chomp :encoding«guess» :ungzip or die "Oops"; It might be argued that this conflicts the :foo notation for private methods. I don't think it's a problem because method names never occur in isolation. [Update: We ended up changing private methods to use ! instead. Also, there's a :!foo form to mean :foo(0).] Oh, one other feature of option pairs is that certain operations can use them as adverbs. For instance, you often want to tell the range operator how much to skip on each iteration. That looks like this: 1..100 :by(3) Note that this only works where an operator is expected rather than a term. So there's no confusion between: randomlistop 1..100 :by(3) and randomlistop 1..100, :by(3) In the latter case, the option is being passed to randomlistop() rather than the infix:.. operator. [Update: That's infix:<..> now.] Novice Perl 5 programmers are continually getting trapped by subscripts that autoquote unexpectedly. So in Perl 6, we'll remove that special case. %hash{shift} now always calls the shift function, because the inside of curlies is always an expression. Instead, if you want to subscript a hash with a constant string, or a slice of constant strings, use the new French qw//-ish brackets like this: %hash«alice» # same as %hash{'alice'} %hash«alice bob charlie» # same as %hash{'alice','bob','charlie'} Note in particular that, since slices in Perl 6 are determined by the subscript only, not the sigil, this: %hash«alice» = @x; evaluates the right side in scalar context, while %hash«alice bob charlie» = @x; evaluates the right side in list context. [Update: That is now false. A subscripted lvalue expression is always assumed to be scalar unless it is in parentheses.) As with all other uses of the French quotes in Perl 6, you can always use: %hash<<alice>> = @x; if you can't figure out how to type ^K < < or ^K > > in vim. On the other hand, if you've got a fully Unicode aware editor, you could probably write some macros to use the big double angles from Asian languages: %hash《alice》 = @x; But by default we only provide the Latin-1 compatible versions. It would be easy to overuse Unicode in Perl 6, so we're trying to underuse Unicode for small values of 6. (Not to be confused with ⁶, or ⅵ.) [Update: We switched to bare angles for this. Double angles now do shell-like interpolation, so double angles relate to single angles much like double quotes relate to single quotes.] The mathematicians got confused when we started talking about "vector" operators, so these dimensionally dwimming versions of scalar operators are now called hyper operators (again). Some folks see operations like @a »*« @b as totally useless, and maybe they are--to a mathematician. But to someone simply trying to calculate a bunch of things in parallel (think cellular automata, or aerodynamic simulations, for instance), they make a lot of sense. And don't restrict your thinking to math operators. How about appending a newline to every string before printing it out: print @strings »~« "\n"; Of course, for @strings {say} is a shorter way to do the same thing. (" say" is just Perl 6's version of a printline function.) Unary operators read better if they only "hyper" on the side where there's an actual argument: @neg = -« @pos; @indexes = @x »++; And in particular, I consider a method spec like .bletch(1,2,3) to be a unary postfix operator, and it would be really ugly to say: @objects».bletch(1,2,3)« So that's just: @objects».bletch(1,2,3) In general, binary operators still take "hypers" on both sides, indicating that both sides participate in the dwimmery. @a »+« @a To indicate that one side or the other should be evaluated as a scalar before participating in the hyperoperator, you can always put in a context specifier: @a »+« +@a $thumb.twiddleNo Longer Requires Parens When Interpolated In Apocalypse 2 we said that any method interpolated into a double-quoted string has to have parentheses. We're throwing out that special rule in the interests of consistency. Now if you want to interpolate a variable followed by an "accidental" dot, use one of these: $($var).twiddle $var\.twiddle Yes, that will make it a little harder to translate Perl 5 to Perl 6. (Parentheses are still required if there are any arguments, however.) [Update: We're back to requiring parens on methods. In fact, we've gone the other way--we now require square brackets on arrays and curlies on hashes. And a bare closure also interpolates. The only interpolator that doesn't require some kind of bracketing terminator is a simple scalar. See S2.] There is a new =:= identity operator, which tests to see if two objects are the same object. The association with the := binding operator should be obvious. (Some classes such as integers may consider all objects of the same value to be a single object, in a Platonic sense.) Hmm? No, there is no associated assignment operator. And if there were, I wouldn't tell you about it. Sheesh, some people... But there is, of course, a hyper version: @a »=:=« @b The current set of grammatical categories for operator names is: Category Example of use -------- -------------- {...} infix_postfix_meta_operator:= $x += 2; postfix_prefix_meta_operator:» @array »++ prefix_postfix_meta_operator:« -« @magnitudes infix_circumfix_meta_operator:»« @a »+« @b Now, you may be thinking that some of these have long, unwieldy names. You'd be right. The longer the name, the longer you should think before adding a new operator of that category. (And the length of time you should think probably scales exponentially with the length of the name.) [Update: The actual operator name must be quoted like a hash subscript: {...} statement_modifier:<if> ... if $condition infix_postfix_meta_operator:<=> $x += 2; postfix_prefix_meta_operator:{'»'} @array »++ prefix_postfix_meta_operator:{'«'} -« @magnitudes infix_circumfix_meta_operator:{'»','«'} @a »+« @b Please note that the "hole" in circumfixes is now specified by slice notation. There is no longer any special split-down-the-middle rule.] statevariable declaration now does "first" semantics. As we talked about earlier, assignment to a " has" variable is really pseudo-assignment representing a call to the " build" trait. In the same way, assignment to state variables (Perl's version of lexically scoped "static" variables), is taken as pseudo-assignment representing a call to the " first" trait. The first time through a piece of code is when state variables typically like to be initialized. So saying: state $pc = $startpc; is equivalent to state $pc is first( $startpc ); which means that it will pay attention to the $startpc variable only the first time this block is ever executed. Note that any side effects within the expression will only happen the first time through. If you say state $x = $y++; then that statement will only ever increment $y once. If that's not what you want, then use a real assignment as a separate statement: state $x; $x = $y++; The := and .= operators also attempt to do what you mean, which in the case of: state $x := $y++; still probably doesn't do what you want. :-) In general, any "preset" trait is smart about when to apply its value to the container it's being applied to, such that the value is set statically if that's possible, and if that's not possible, it is set dynamically at the "correct" moment. For ordinary assignment to a " my" variable, that correct moment just happens to be every time it is executed, so = represents ordinary assignment. If you want to force an initial value at execution time that was calculated earlier, however, then just use ordinary assignment to assign the results of a precalculated block: my @canines = INIT { split slurp "%ENV«HOME»/.canines" }; It's only the has and state declarators that redefine assignment to set defaults with traits. (For has, that's because the actual attribute variable won't exist until the object is created. For state, that's because we want the default to be "first time through".) But you can use any of the traits on any variable for which it makes sense. For instance, just because we invented the " first" initializer for state variables: state $lexstate is first(0); doesn't mean you can't use it to initialize any variable only the first time through a block of code: my $foo is first(0); However, it probably doesn't make a lot of sense on a " my" variable, unless you really want it to be undefined the second time through. It does make a little more sense on an " our" variable that will hang onto its value like a state variable: our $counter is first(0); An assignment would often be wrong in this case. But generally, the naive user can simply use assignment, and it will usually do what they want (if occasionally more often than they want). But it does exactly what they want on has and state variables--presuming they are savvy enough to want what it actually does... :-) So as with has variables, state variables can be initialized with precomputed values: state $x = BEGIN { calc() } state $x = CHECK { calc() } state $x = INIT { calc() } state $x = FIRST { calc() } state $x = ENTER { calc() } which mean something like: state $x is first( BEGIN { calc() } ) state $x is first( CHECK { calc() } ) state $x is first( INIT { calc() } ) state $x is first( FIRST { calc() } ) state $x is first( ENTER { calc() } ) Note, however, that the last one doesn't in fact make much sense, since ENTER happens more frequently than FIRST. Come to think of it, doing FIRST inside a first doesn't buy you much either... In Perl 6 you're not going to see my $sizeofstring = length($string); That's because "length" has been deemed to be an insufficiently specified concept, because it doesn't specify the units. Instead, if you want the length of something in characters you use my $sizeinchars = chars($string); and if you want the size in elements, you use my $sizeinelems = elems(@array); This is more orthogonal in some ways, insofar as you can now ask for the size in chars of an array, and it will add up all the lengths of the strings in it for you: my $sizeinchars = chars(@array); And if you ask for the number of elems of a scalar, it knows to dereference it: my $ref = [1,2,3]; my $sizeinelems = elems($ref); These are, in fact, just generic object methods: @array.elems $string.chars @array.chars $ref.elems And the functional forms are just multimethod calls. (Unless they're indirect object calls...who knows?) You can also use %hash.elems, which returns the number of pairs in the hash. I don't think %hash.chars is terribly useful, but it will tell you how many characters total there are in the values. (The key lengths are ignored, just like the integer "keys" of an ordinary array.) Actually, the meaning of .chars varies depending on your current level of Unicode support. To be more specific, there's also: $string.bytes $string.codepoints $string.graphemes $string.letters [Update: Those are shortened to .codes, .graphs, and .langs now.] ...none of which should be confused with: $string.columns or its evil twin: $string.pixels Those last two require knowledge of the current font and rendering engine, in fact. Though .columns is likely to be pretty much the same for most Unicode fonts that restrict themselves to single and double-wide characters. A corollary to the preceding is that string positions are not numbers. If you say either $pos = index($string, "foo"); or $string ~~ /foo/; $pos = $string.pos; then $pos points to that location in that string. If you ask for the numeric value of $pos, you'll get a number, but which number you get can vary depending on whether you're currently treating characters as bytes, codepoints, graphemes, or letters. When you pass a $pos to substr($string, $pos, 3), you'll get back " foo", but not because it counted over some number of characters. If you use $pos on some other string, then it has to interpret the value numerically in the current view of what "character" means. In a boolean context, a position is true if the position is defined, even if that position would evaluate to 0 numerically. ( index and rindex return undef when they "run out".) And, in fact, when you say $len = .chars, you're really getting back the position of the end of the string, which just happens to numerify to the number of characters in the string in the current view. A consequence of the preceding rules is that "".chars is true, but +"".chars is false. So Perl 5 code that says length($string) needs to be translated to +chars($string) if used in a boolean context. Routines like substr and index take either positions or integers for arguments. Integers will automatically be turned into positions in the current view. This may involve traversing the string for variable-width representations, especially when working with combining characters as parts of graphemes. Once you're working with abstract positions, however, they are efficient. So while $pos = index($string, "fido", $pos + 1) {...} never has to rescan the string. The other point of all this is that you can pass $pos or $len to another module, and it doesn't matter if you're doing offsets in graphemes and they are doing offsets in codepoints. They get the correct position by their lights, even though the number of characters looks different. The main constraint on this is that if you pass a position from a lower Unicode support level to a higher Unicode support level, you can end up with a position that is inside what you think of as a unitary character, whether that's a byte within a codepoint, or a codepoint within a grapheme or letter. If you deref such a position, an exception is thrown. But generally high-level routines call into low-level routines, so the issue shouldn't arise all that often in practice. However, low-level routines that want to be called from high-level routines should strive not to return positions inside high-level characters--the fly in the ointment being that the low-level routine doesn't necessarily know the Unicode level expected by the calling routine. But we have a solution for that... High-level routines that suspect they may have a "partial position" can call $pos.snap (or $pos.=snap) to round up to the next integral position in the current view, or (much less commonly) $pos.snapback (or $pos.=snapback) to round down to the next integral position in the current view. This only biases the position rightward or leftward. It doesn't actually do any repositioning unless we're about to throw an exception. So this allows the low-level routine to return $pos.snap without knowing at the time how far forward to snap. The actual snapping is done later when the high-level routine tries to use the position, and at that point we know which semantics to snap forward under. By the way, if you bind to a position rather than assign, it tracks the string in question: my $string = "xyz"; my $endpos := $string.chars; # $endpos == 3 substr($string,0,0,"abc"); # $endpos == 6, $string = "abcxyz" Deletions of string around a position cause the position to be reduced to the beginning of the deletion. Insertions at a position are assumed to be after that position. That is, the position stays pointing to the beginning of the newly inserted string, like this: my $string = "xyz"; my $endpos := $string.chars; # $endpos == 3 substr($string,2,1,"abc"); # $endpos == 2, $string = "xyabc" Hence concatenation never updates any positions. Which means that sometimes you just have to call .chars again... (Perhaps we'll provide a way to optionally insert before any matching position.) Note that positions try very hard not to get demoted to integers. In particular, position objects overload addition and substraction such that $string.chars - 1 index($string, "foo") + 2 are still position objects with an implicit reference into the string. (Subtracting one position object from another results in an integer, however.) Analogous to the disjunctional | separator, we're also putting in a conjunctional & separator into our regex syntax: "DOG" ~~ /D [ <vowel>+ & <upper>+ ] G/ The semantics of it are pretty straightforward, as long as you realize that all of the ANDed assertions have to match with the same length. More precisely, they have to start and stop matching at the same location. So the following is always going to be false: / . & .. / It would be possible to have the other semantics where, as long as the trailing assertion matches either way, it doesn't have to match the trailing assertion the same way. But then tell me whether $1 should return " O" or " G" after this: "DOG" ~~ /^[. & ..] (.)/ Besides, it's easy enough to get the other semantics with lookahead assertions. Autoanchoring all the legs of a conjunction to the same spot adds much more value to it by differentiating it from lookahead. You have to work pretty hard to make separate lookaheads match the same length. Plus doing that turns what should be a symmetric operator into a non-symmetrical one, where the final lookahead can't be a lookahead because someone has to "eat" the characters that all the assertions have agreed on are the right number to eat. So for all these reasons it's better to have a conjunction operator with complicated enough start/stop semantics to be useful. Actually, this operator was originally suggested to me by a biologist. Which leads us to our... Biologist: What's worse than being chased by a Velociraptor? Physicist: Obviously, being chased by an Acceloraptor. Away from Acceloraptors, obviously. Nathanael Schärli, Stéphane Ducasse, Oscar Nierstrasz and Andrew Black. Traits: Composable Units of Behavior. European Conference on Object-Oriented Programming (ECOOP), July 2003. Springer LNCS 2743, Ed. Luca Cardelli.
http://search.cpan.org/dist/Perl6-Doc/share/Apocalypse/A12.pod
CC-MAIN-2017-30
en
refinedweb
On Fri, Mar 11, 2011 at 12:56:43PM +1100, Angus Salkeld wrote: > Hi > > I am writing a python test suite that uses oz () > which uses libquestfs. I am simulating a small cloud and have some apps that need > to talk to the guests. > > All works really well until I needed to start another process. > So I start a process then "oz" starts up a VM (it uses libquestfs) > then when "oz" cleans up it calls libquestfs.kill_subprocess(). > At this point my test locks up. As Chris says, any reason to be using kill_subprocess at all? You can just delete the handle which has the same effect (and is a much more well-tested path). Something like: del g > A bacetrace of the python code is: > #0 0x00000036fe80ef1e in waitpid () from /lib64/libpthread.so.0 > #1 0x0000003629c0df7f in guestfs_close () from /usr/lib64/libguestfs.so.0 > then a mess of python stuff > > If I attach to it with strace it shows: > wait4(0, > > It looks like libguestfs's children are already dead > pstree 13107 > python─┬─cped───3*[{cped}] > └─qpidd───9*[{qpidd}] > > so it's seems like it's waiting on my process to die. > > So I changed the oz code to call close (in python "del obj") and all is well, > however I was looking in libquestfs code and saw: > #if 0 > /* Set up a new process group, so we can signal this process > * and all subprocesses (eg. if qemu is really a shell script). > */ > setpgid (0, 0); > #endif > > Any reason this is "if def'ed" out? > this was done in commit 88f69eb03160a62d38 > I was thinking this might prevent my problem from occuring in the > first place? I don't know why exactly waitpid isn't working, but I doubt it's anything to do with the (lack of) a process group. Are you using a qemu wrapper script? Rich. -- Richard Jones, Virtualization Group, Red Hat libguestfs lets you edit virtual machines. Supports shell scripting, bindings from many languages.
https://www.redhat.com/archives/libguestfs/2011-March/msg00041.html
CC-MAIN-2017-30
en
refinedweb
After two years of development Angular 2.0 Final has been officially released on September 14, 2016. In this blog I’ll describe how to create your first Angular 2 project. During the last couple of months Angular 2 was substantially redesigned/improved in several areas. {} Only the bootable module can be BrowserModule. If your app uses several module (e.g. ShipmentModule, BillingModule, FormsModule, HttpModule), those modules are called feature modules are based on the CommonModule instead of the BrowserModule. Each of the feature modules can be loaded either eagerly when the app starts, or lazily, e.g. when the user clicks on the Shipping link. Angular compiler-cli (ngc), and not just transpiling from TypeScript to JavaScript here. A half of the size of a small app is the angular compiler itself, and just by using the AoT you’re app becomes slimmer because the compiler won’t be downloaded to the browser. One of the reasons the modules were introduced is that it helps the Angular compiler to know which artifacts has to be compiled for the module. In this blog we’ll use the JIT compilation, and I’ll show you how to start a new Angular 2 project (managed by npm) from scratch without using the scaffolding tool Angular-CLI. To start a new project, create a new directory (e.g. angular-seed) and open it in the command window. Then run the command npm init -y, which will create the initial version of the package.json configuration file. Normally npm init asks several questions while creating the file, but the -y flag makes it accept the default values for all options. The following example shows the log of this command running in the empty angular-seed directory. $ npm init -y Wrote to /Users/username/angular-seed/package.json: { "name": "angular-seed", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC" } Most of the generated configuration is needed either for publishing the project into the npm registry or while installing the package as a dependency for another project. Because we’re not going to publish our app into the npm registry, you should remove all of the properties except name, description, and scripts. The configuration of any npm-based project is located in the file package.json, which can look like this: { "name": "angular-seed", "description": "A simple npm-managed project", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" } } The scripts configuration allows you to specify commands that you can run in the command window. By default, npm init creates the test command, which can be run like this: npm test. Let’s replace it with the start command that we’ll be using for launching a web server that will feed our app to the browser. Several simple Web servers are available, and we’ll be using the one called live-server that’s we’ll add to the generated package.json a bit later. Here’s the configuration of the scripts property: { ... "scripts": { "start": "live-server" } } While the start command is one of the pre-defined commands in npm scripts, and you can run it from the command window by entering npm start. Actually, you can define and run any other command that would serve as a shortcut for any command you could run manually, but in this case you’d need to run such command as follows: npm run mycommand.. So let’s add the dependencies and devDependencies sections to the package.json file so it’ll include everything that a typical Angular 2 app needs: { "name": "angular-seed", "description": "My simple project", "private": true, "scripts": { "start": "live-server" }, "dependencies": { "@angular/common": "2.0.0", "@angular/compiler": "2.0.0", "@angular/core": "2.0.0", "@angular/forms": "2.0.0", "@angular/http": "2.0.0", "@angular/platform-browser": "2.0.0", "@angular/platform-browser-dynamic": "2.0.0", "@angular/router": "3.0.0", "core-js": "^2.4.0", "rxjs": "5.0.0-beta.12", "systemjs": "0.19.37", "zone.js": "0.6.21" }, "devDependencies": { "live-server": "0.8.2", "typescript": "^2.0.0" } } Now run the command npm install on the command line from the directory where your package.json is located, and npm will download the preceding packages and their dependencies into the node_modules folder. After this process is complete, you’ll see a couple of hundred (sigh) of directories and subdirectories subdirectories in the node_modules dir, including @angular, systemjs, live-server, and typescript. angular-seed ├── index.html ├── package.json └── app └── app.ts ├──node_modules ├── @angular ├── systemjs ├── typescript ├── live-server └── … In the angular-seed folder, let’s create a slightly modified version of index.html with the following content: <!DOCTYPE html> <html> <head> <title>Angular seed project</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <script src="node_modules/typescript/lib/typescript.js"></script> > <app>Loading...</app> </body> </html> The script tags load the required dependencies of Angular from the local directory node_modules. Angular modules will be loaded according to the SystemJS configuration file systemjs.config.js, which can look as follows:'} } }); The app code will consist of three files: – app.component.ts – the one and only component of our app – app.module.ts – The declaration of the module that will include our component – main.ts – the bootstrap of the module Let’s create the file app.component.ts with the following content: ---- import {Component} from '@angular/core'; @Component({ selector: 'app', template: `<h1>Hello {{ name }}!</h1>` }) export class AppComponent { name: string; constructor() { this.name = 'Angular 2'; } } Now you need to create a module that will contain our AppComponent. This code we’ll place inside the app.module.ts file: import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; @NgModule({ imports: [ BrowserModule ], declarations: [ AppComponent ], bootstrap: [ AppComponent ] }) export class AppModule { } This file just contains the definition of the Angular module. The class is annotated with @NgModule that includes the BrowserModule that every browser must import. Since our module contains only one class, we need to list it in the declarations property, and list it as the bootstrap class. In the section packages of the SystemJS config file we mapped the name app to main.ts that will look like this: import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './app.module'; platformBrowserDynamic().bootstrapModule(AppModule); The last line of the above script actually compiles and loads the module. Start the application by executing the npm start command from the angular-seed directory, and it’ll open your browser and show the message “Loading…” for a second, followed by “Hello Angular 2!”. You can find the source code of our angular-seed project at. 24 thoughts on “Starting an Angular 2.0 project” Thanks for the tutorial ! There is a lot of breaking changes in recent angular RC and it s really confusing. I started a project with rc1 , I have to make changes for RC5, and now some things are broken again with RC6. I m seriously wondering to move to aurelia.io for my next project. Angular2 seems an over-engineered project with too much complexity for nothing. Maybe I will change my mind, but the first week with angular2 does not convinced me 😉 If you’re looking for a simple solution for a small project, Angular 2 may be not for you. But if you need a complete solution, go Angular 2. The upgrade from RC5 to RC6 didn’t require any changes in my apps – just the package.json and systemjs config files were affected. OMG, angular 2 is in RC now, not GA. some breaking changes are predictable. this is completely normal. by the way, my Material2 app (started with RC.5) is broken now (after RC.6 upgrade) but that was my choice to use smth in alpha stage. Don’t panic 😉 Angular 2 with that new NgModel lazy architecture is really awesome, and i’m not sure that i’ll move to some other framework at all. regards > OMG, angular 2 is in RC now, not GA. some breaking changes are predictable No. And because the guys know that, they commited themselves to semantic versioning: MANY thanks Yakov – What a moving target this has been! Tell me about it 🙂 where is import { Control } from ‘@angular/common’ in rc5 and now gone in rc6 RC.6 removes deprecated API import { ReactiveFormsModule, FormControl, FormGroup } from ‘@angular/forms’; the script is like this in rc5 when i upgraded to rc6 “import Control” cannot be found! import { Control } from ‘@angular/common’; export class BasicValidators{ static email(control: Control){ var regEx = /^(([^()\[\]\\.,;:\s@”]+(\.[^()\[\]\\.,;:\s@”]+)*)|(“.+”))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; var valid = regEx.test(control.value); I really liked the post on stability of Angular2 and its drastic changes. Your posts are more informative looking forward to hear many such from you 🙂 . Keep going. Is there any reason to use JIT now that the AOT is out?? How install the angular-cli to generate project with Angular RC6 ?| npm install -g angular-cli@webpack Thank you for your helper, I installed npm install -g angular-cli@webpack , but still in my packge.json this Angular RC5. I’d want to create new projects with angular-cli using AngularRC6. Any idea? Looks like they still didn’t fix this issue: There is a hack with downgrading webpack to beta 19, but you better wait for the next release of CLI Thank’s a lot! Actually, after the Final release you can just run npm install -g angular-cli Then enter ng –version, and you should see beta.14 that supports webpack. how can i upload file using reactive form in this angular 2.0.0 version. i try to do but input type=file returns null instead of file name. my code is here, teaminfo.ts :- —————– import { Component, Inject } from ‘@angular/core’; import { Router, ActivatedRoute } from ‘@angular/router’; import { ReactiveFormsModule, FormGroup, FormArray, FormBuilder, Validators } from ‘@angular/forms’; @Component({ selector: ‘team-info’, templateUrl: ‘./servicer/registration/templates/team-info.html’ }) export class TeamInfoComponent { teamForm: FormGroup; servicer = new ServicerModel(); constructor( fb: FormBuilder, private _router: Router, private _route: ActivatedRoute ) { this.teamForm = fb.group({ teamfilename: [”], }); } onSubmit(value: any) { console.log(value); } } team-info.html:- —————- Upload Photo HI! Thanks for the article… my domain is done in Angular2! You can see some examples and projects did in Angular2 and news projects will. Come and take a look!!!
https://yakovfain.com/2016/09/01/starting-an-angular-2-rc-6-project/
CC-MAIN-2017-30
en
refinedweb
C# is a great language. It allows you to be extremely productive and efficient by eliminating the need for manual memory management, and providing fast compile times, an extensive standard library, and various other handy features. However, for applications requiring heavy number crunching, its performance can be less than adequate. In this article, I will show you how C# can call into C++ functions when necessary, and provide an analysis of its performance. Given a large number of random rectangles lying between (0, 0) and (2, 2), let us find the percentage of these rectangles that lie between (0, 0) and (1, 1). We will solve this problem using brute force in order to stress the CPU. The code for this algorithm is pretty straightforward. Basically, we generate four random numbers in the interval (0, 2) for each rectangle, and assign them to the corner points. Then we count how many of these rectangles lie in the desired interval. All tests are carried out with 10 million rectangles on a q6600 with 4gb ram. This is all C#, and is used as a reference to measure relative performance. For 10 million rectangles, this method takes around 146 ms. This is the easiest way to do interop. The C# side code for this is: [DllImport("DllFuncs.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint= "nativef")] public static extern float getPercentBBMarshal( [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] BBox[] boxes, int size); Basically, this tells the runtime to look for a function named nativef using the calling convention cdecl in the native library called "DllFuncs.dll". It also tells the runtime to transparently convert the C# array of BBoxes into a C++ array. We need to pass the size, as arrays in C++ are unaware of their length. The corresponding C++ function is this: nativef BBoxe struct BBox { float x1, y1, x2, y2; int isValid() { return (x1 < 1) && (x2 < 1) && (y1 < 1) && (y2 < 1) && (x1 > 0) && (x2 > 0) && (y1 > 0) && (y2 > 0); } }; __declspec(dllexport) float __cdecl nativef(BBox * boxes, int size) { int sum = 0; for (int i = 0; i < size; i++) { sum+= boxes[i].isValid(); } return (float)sum/(float)size * 100; } Measuring the performance of this function with a timer, we see an interesting result. The native function takes 341 ms for 10 million elements, which is around Twice the time taken by the C# equivalent! Moreover, for 1000 elements, marshaling takes 239.3 ms, which is way above the 0.054 ms taken by pure C#. Surely, marshaling is adding a huge overhead, the relative importance of which is diminishing with the amount of work. To know where this overhead comes from, we need to know how marshaling works: Now, we can easily see the reason for bad performance. We are essentially allocating 10 million rectangles and copying the values of each of these. That is allocating and moving around 160 MB of data! No wonder performance is horrible. You may be asking yourself why the whole exercise of copying is necessary in the first place. There are two reasons for this: So, is it possible to get around these problems? Let's find out! [StructLayout(LayoutKind.Sequential)] struct BBox { public float x1, y1, x2, y2; //Corner points of the rectangle } fixed [DllImport("DllFuncs.dll", CallingConvention = CallingConvention.Cdecl)] public static extern unsafe float nativef(IntPtr p, int size); public static unsafe float getPercentBBInterop(BBox[] boxes) { float result; fixed (BBox* p = boxes) { result = nativef((IntPtr)p, boxes.Length); } return result; } The function returns in 115 ms, which is around 26% faster that the C# equivalent. The performance gain is likely to increase with the complexity of the functions delegated to native code. Charts displaying the performance with respect to various numbers of elements processed are shown below: The source code for this is hosted on Github: Make sure to check it out. This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL) public static float getPercentBBInterop(BBox[] boxes, int size) { GCHandle handle = GCHandle.Alloc(boxes, GCHandleType.Pinned); float result = nativef(handle.AddrOfPinnedObject(), size); handle.Free(); return result; } General News Suggestion Question Bug Answer Joke Rant Admin Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
http://www.codeproject.com/Articles/445455/Csharp-Native-Interop-Methods-and-Performance
CC-MAIN-2015-06
en
refinedweb
Validation - Struts Validation How can i use validation framework i don't understand am having problem while implementing this, can anybody help me with example. Hi friend, Phone validation using javaScript function validation - Framework validation how to validate the action forms in struts? could you please explain how cross validation is done for date? You go the following url: Struts validation not work properly - Struts Struts validation not work properly hi... i have a problem with my struts validation framework. i using struts 1.0... i have 2 page which...) { this.address = address; } } my struts-config.xml Date Validation Date Validation Hi, I need Date Validation using java in spring framework. Please Anyone help me... Thanks in advance struts validation struts validation Sir i am getting stucked how to validate struts using action forms, the field vechicleNo should not be null and it should accept only integer values.can you help me please public ActionErrors validate validation struts validation I want to apply validation on my program.But i am failure to do that.I have followed all the rules for validation still I am unable to solve the problem. please kindly help me.. I describe my program below Struts - Framework /struts/". Its a very good site to learn struts. You dont need to be expert in any other framework or else before starting struts. you just need to have... struts application ? Before that what kind of things necessary Struts Validator Framework Struts Validator Framework  ... Framework. In this lesson you will learn how to use Struts Validator Framework... to Validator Framework Struts Framework provides the functionality to validate the form struts - Framework Struts flow of execution diagram What is the structure of struts flow ..can you show it with the help of diagram Framework MVC java - Framework Framework MVC java Hi everybody I'm here coze I need your help... framework MVC" like SpringMVC, Struts ou JSF and I don't know how to beging and which methode i must implements .... And thanks for tour help. PS: my Struts - Framework project and is open source. Struts Framework is suited for the application... struts application ? Before that what kind of things necessary..., Struts : Struts Frame work is the implementation of Model-View-Controller server side validation in struts server side validation in struts Hello sir, i want to do server side validation in struts based on 3 fields. those 3 field are BatchNo... for this....please help me java - Framework STRUTS and SPRING framework?which framework is better now a day's... to the appropriate Action class with the help of the action mapping specified in Struts... the validation in spring framework too. Morethan this, it provides all features like validation message - Struts validation message sir, i took help of that example but in that we change only color of the message i want to shift the place of the error message.means all messages are put together at top of the form Struts development application - Framework code for validation.xml,validation-rules.xml in DynaValidator framework regarding for struts framework,and what is difference b/w validation.xml and validation.... Thanks sing validator framework work in struts sing validator framework work in struts How does client side validation using validator framework work in struts Struts Articles into two categories: server-side and client-side. A struts validation framework... the existing struts validation framework with AJAX. A few components, such as a controller... examples of Struts extensions are the Struts Validation framework and the Tiles An introduction to spring framework Framework. Other popular framewoks like Struts, Tapestry, JSF etc., are very good web... SPRING Framework... AN INTRODUCTION... application framework, introduced and developed in 2004. The main ideas were Struts 2 Validation (Int Validator) Struts 2 Validation (Int Validator) Struts 2 Framework provides in-built validation functions to validate user... are stored. Struts 2 validation framework validates user input against the defined rules need the answer vry urgently..plz help me...[plzzzzzzzz need the answer vry urgently..plz help me...[plzzzzzzzz the question.... 2.javascript validation, 3.check against the database that all the information given...... useing struts or servlet... in eclipse platform...can any one tell me the source struts-netbeans - Framework struts-netbeans hai friends please provide some help "how to execute struts programs in netbeans IDE?" is requires any software or any supporting files to execute this. thanks friends in advance Struts 1 Tutorial and example programs framework then these struts 1 tutorials will help you in learning the Struts 1...; Introduction to Struts Validator Framework Struts.... Client Side Address Validation in Struts Why Struts 2 of design problem of struts1 framework that has been resolved in the struts 2 framework. Most of the Struts 2 classes are based on interfaces and most of its... Why Struts 2 The new version Struts Struts First Example - Framework Struts First Example HI i am new to Struts and developing a single...: "org.apache.struts.taglib.html.BEAN" in any scope if any body knows about it please help me... in details of problem for complete solution. For read more information on struts Validation - Struts Validation what is the best way to use validation in Struts?either "validation.xml" or JavaScript Struts 2 - Validation - Struts Struts 2 - Validation annotations digging for a simple struts 2 validation annotations example validation..... validation..... hi.......... thanks for ur reply for validation code. but i want a very simple code in java swings where user is allowed to enter... this be done???? plz help I want to put validation rules on my project.But... validation rules,put the plugins inside strutsconfig.xml, put the html:errors tag... that violate the rules for struts automatic validation.So how I get the solution Client Side Address Validation in Struts for the address form. Struts Validator Framework uses this rule for generating... Client Side Address Validation in Struts  .... In this lesson you learned how to use Struts Validator Framework to validate Validation accepts only integers? Please help... import java.awt.*; import...); JLabel label=new JLabel("JTable validation Example",JLabel.CENTER); JPanel panel=new JPanel(); panel.add(scroll); JFrame frame=new JFrame("JTable validation validation validation please help me to check validation for <form> <table class="form"> <tr> <td class="col1"> <label>Sno:</label> </td> <td Struts Reference Struts Validation framework with example Struts Tiles example Struts... Struts Reference Welcome to the Jakarta Online Reference page, you will find everything you need to know to quick start your Struts validation :checkbox< Validation it in the database? PLEASE HELP!!!!! import java.awt.*; import java.sql.*; import validation - Struts validation Hi Deepak can you please tell me about struts validations perticularly on server side such as how they work whats their role etc.? thank you validation - Struts information, Thanks struts validation problem - Struts struts validation problem i used client side validation in struts 2 .but message will display only on the top of the component.i want to display.../struts/struts2/ Need Project Need Project How to develop School management project by using Struts Framework? Please give me suggestion and sample examples for my project Regarding struts validation - Struts Regarding struts validation how to validate mobile number field should have 10 digits and should be start with 9 in struts validation? Hi... ------------------------------------------------------------- For more information : Validation - Struts the struts validator... Hi Friend, Please visit the following links: joptionpane validation help me!i need to validate the user input on the joptionpane,and if the user... for your help Struts API - Struts Framework API online Struts API - Struts Framework API online... are looking for the Struts API, you can either download the struts framework... of Struts framework and many versions will be released in - Framework Struts design pattern Please explain Struts design pattern struts - Framework Struts Spring Hibernate Integration struts spring hibernate integration tutorial struts - Framework struts Tag libs in struts what is custom validation in struts what is custom validation in struts what is custom validatons in struts Need help with this! Need help with this! Can anyone please help me... to a file at all at this time. Any help would be greatly appreciated, thank you... to effectivly end the loop with out the need to break it. for(i=(0); i < Struts 2 Validation Example Struts 2 Validation Example  ... framework. Struts 2 is very elegant framework that provides a lot... the form validation code in Struts 2 very easily. We will add the form validation struts - Framework struts can show some example framework of struts Hi Friend, Please visit the following links: Hope that the above links Struts Alternative and widely used framework, but there exists the alternative to the struts framework... to the struts framework. Struts Alternatives: Cocoon... of conflicts. Swing Jakarta Struts is a framework COLLECTION FRAMEWORK COLLECTION FRAMEWORK Hi, i need complete detailed explanation on COLLECTION FRAMEWORK with examples(which include set,list,queue,map and operations performed on them).need help... Regards, Anu struts client side validation struts client side validation how can i code for client side validation framework Struts framework How to populate the value in textbox of one JSP page from listbox of another JSP page using Struts-html tag and java script Struts Projects ASAP. These Struts Project will help you jump the hurdle of learning complex... learning easy Using Spring framework in your application Project in STRUTS Framework using MYSQL database as back end Struts Projects are supported be fully struts - Framework struts Hi,roseindia I want best example for struts Login... in struts... Hi Friend, You can get login applications from the following links: 1) 2)http need of Ioc - Framework need of Ioc what is IOC in spring framework? Hi Friend, Please visit the following link: Hope that it will be helpful for you. Thanks need need i need a jsp coding based project plz help me Struts - Struts Struts What is Struts Framework? Hi,Struts 1 tutorial with examples are available at Struts 2 Tutorials...:// these links will help you build - Struts Struts How to display single validation error message, in stude of ? Hi friend, I am sending you a link. This link will help you. Please visit for more information. need help to remove and optimise the code for creating a page need help to remove and optimise the code for creating a page i have the following code but it has some sorts of error whenever i run the page after validation through javascript it calls for the servlets and then i tried struts2 - Framework framework...i want to create a jsp page in struts2 i need two buttons in tha jsp... those come in two differnet rows(lines).....i need one jsp with two textfields...; Hi Satish, Struts 2 uses tiles internally and hence if you dont specify related Question Struts related Question Hi All, I have a one question on validation framework for client side validation please help me on that. suppose i don't want to put required=true in our JSP then what will happen. what error will come Setup validator framework in Struts Setup validator framework in Struts How to Setup validator framework in Struts Understanding Struts - Struts Understanding Struts Hello, Please I need your help on how I... is built with Strut framework and I need to customize this application but I do... books on how to understand this, but still not getting it. So , I just need core classes of the Struts Framework core classes of the Struts Framework What are the core classes of the Struts Framework Struts Validator Framework Struts Validator Framework What is Struts Validator Framework Struts - Framework ================== ........ ....... ......... ........ ================= struts-config.xml Struts Tutorial , struts integration with other framework, Struts Validator Framework. What is Struts ? Struts is an open source MVC based framework for developing web... to Apache Foundation. Struts allows for the web form components, validation Struts 2.2.1 - An introduction to Struts 2.2.1 Features all the libraries need to setup and run Struts 2.2.1 based applications... 2.2.1 framework. These files will also help you in learning the concepts of Struts 2.2.1 framework. Features of Struts 2.2.1 Here are features and changes make Using the Validator framework in struts Using the Validator framework in struts What is the Benefits of Using the Validator framework in struts Struts - Struts Java Bean tags in struts 2 i need the reference of bean tags in struts 2. Thanks! Hello,Here is example of bean tags in struts 2:http... code will help you learn Struts 2.Thanks What are Interceptors in Struts 2 and how do they work? of the work in Struts 2 framework. Interceptors can invoke logic before...What are Interceptors in Struts 2 and how do they work? Understanding Struts 2 Interceptors concept is very important in learning the Struts 2. You should struts - Framework be defined in the Commons Validator configuration when dynamicJavascript="true struts - Framework struts opensource framework struts opensource framework i know how to struts flow ,but i want struts framework open source code
http://www.roseindia.net/tutorialhelp/comment/100127
CC-MAIN-2015-06
en
refinedweb
22 January 2013 23:47 [Source: ICIS news] HOUSTON (ICIS)--BP’s group chief executive said on Tuesday that the company is “gravely concerned” about the welfare of four employees who remain unaccounted for following the conclusion of the In Amenas hostage crisis in ?xml:namespace> Bob Dudley said the “It is with great sadness that I now have to say that we fear the worst for them all,” Four employees of BP and five workers of Fourteen of BP’s 18 employees working at the gas field at the time of the attack have been confirmed safe and have left The company's offices around the world will be holding a minute of silence on Wednesday as a mark of respect for those who lost their lives at In Amenas. BP also said it has sent personnel back to In Amenas to support efforts to gather confirmed information. “The terrible events of last week have affected every one of us at BP deeply,” “We are mindful that many others – from partners, contractors and other companies – have died or remain unaccounted for. Our thoughts are also with their families, friends and loved ones at this time.” The In Amenas gas field is jointly operated by Algerian state-owned Sonatrach, BP and Statoil. According to BP, the field is a large operation with a workforce at times of 500-700 people, the majority of them being Algerian
http://www.icis.com/Articles/2013/01/22/9634038/bp-gravely-concerned-about-missing-workers-in-algeria.html
CC-MAIN-2015-06
en
refinedweb
From this point on: any major changes, or suggestions thereof, to the draft would probably mean that CD2 would be prevented from being adopted as the DIS. Possibly read: "Yes, we would like to see CD2 advanced to DIS status, and here are our comments for things we would like to see fixed." This presentation will be posted to the Comeau Computing WEB page tomorrow (as copyrighted HTML) located at:. For instance, an issue which came up was the status of the Standard C library within C++ programs. In specific, should C names from <stdio.h> or <cstdio> such as printf belong in the global namespace as ::printf or in the the std namespace as std::printf? It was confirmed that so-called .h style headers should use the global namespace and so-called cname headers should use the std namespace. The preference is the cname forms unless strict compatibility with C is needed. Personally, we feel that this will be a muddled issue for many years to come. It'll be interesting to see if we've seen the last on this. This was a strange meeting. This is to say, the technical experts voted out the Standard at the last meeting and so things were now stuck in a bureaucratic phase of approval. This meant that the committee formally could not work on things like DRs since the document was still not bureaucratically approved, so things were somewhat circular. In any event, this gave the committee an opportunity to take a deep breath. It also gave the committee a comfortably paced opportunity to consider what the future will hold and what waters should be charted or not. FYI, at this point the FDIS Status was that it was not out in ballot yet, but would be shortly. It was noted that the CD1 ballot period for C9x would be closing on April 7 (there were some 300 comments and paper "10176" needs interpretation from WG20). C9X expects a final CD this year, after June meeting, with hopefully FDIS bureaucracy approval in 99. It was decided that for now, the committee should move from meeting 3 times a year to two times a year, around April and October, effectively meaning there would no longer be a July meeting, at least for now. Probably too, it would be interesting to see the C and C++ committees co-locate their meetings. This might increase the quality and understanding of both standards. A common consideration was that "C++ needs stability, and that should reign over the committee doing new things." As mentioned above, things were still in an unclear state ISO-wise, nevertheless, it was considered useful to expect that DRs would be incorporated in the working paper in about 2-3 years. Some discussion about ISO copyrights and their revenue streams was brought forth. Standard organizations' budgets are not outrageous, and upon DIS, ISO asserts copyright and feels obliged to go after offenders. Some argued that the criteria used by some standards organizations was "unimaginative" about what the so-called price per page should be. It was also raised that the ISO Council voted to assert that ISO hold a copyright on every WG "N#" document number. JTC1 asked for a 1 year extension to study this. Result: all SC's reported it has worked well for each JTC to determine its own distribution issues, and so one year was not long enough, and so asked for a few more years. Suffice it to say that some of this is confusing (we also feel some of it is bogus but so be it for now). Although our document is now a DIS, it's not yet available on paper (see above). To see it quickly for now, then you must join the standards body. Next year national bodies (ANSI, etc) will sell you a copy. Some discussion took place about: Possibilities for TRs might include: hash tables, garbage collection, embedded systems. It was agreed that if this were to go forward that we would need to produce proposals, but that now was not time to ask the committee to vote on anything yet. Just talking is good. Things moved along to discuss DRs. It was considered that we should begin to process DRs soon, say for next year or so. However, that process must not be a back door to extensions. Furthermore, we should start to discuss what new work items/areas we might wish to bring up. It would certainly be too premature right now to raise it otherwise, hence let's just start to identify future work items. Of course, in order to be successful at not being hasty, the committee needs to be sure they understand the direction of the language before making extensions, etc. To wit, they need knowledge of the sum of things proposed along with a history et al. Before we start, we should do things like tech sessions for a year. Then, before we vote, maintain a view. Some of the problems of the users is that vendors adopted the issues in a different order. We might be able to clarify that better, and we can make suggestions for portability. For instance, perhaps issues should be forwarded to to comp.std.c++? At this point it was noted that a message arrived that ISO finally received the final proof of the draft and that balloting will go out by the end of this month. Discussion turned to wondering if C could document their "known" incompatibilities with C++ (with realization that no guarantee can be created by the process since C9x was still a work in progress). In short, the C committee was meeting again and there was not complete coordination, etc, between the two committees. Hence we therefore don't know what the incompatibilities are, and don't have the expertise yet to document them on our side yet. For instance, consider this possible proposal: In view of the number of new features in CD9899 ("C9X") which are orthogonal to the C++ Features in FDIS 14882, WG21 requests that SC22 affirm that WG21 (C++) will not necessarily be required to adopt C9X features in future revisions of C++. Requesting this passed J16, and WG21 This was clearly both a technical and political issue that perhaps could be looked into. And there were realities such as that C9x was never obliged to heed the C liaison from the C++ committee, and so on. It was noted that there are facilities in C that are solved in C++ in a different way. There is enough history to back this up. For instance, consider that the new ways of initialization proposed in C9x would not be necessary if C had constructors. But -- big but -- C was not obliged to heed the C++ liaison. But the C9x people support this latter point: they never thought they were undertaking the features for the 5 year revision period for C++. This is significant because there will soon no longer be a C89 standard. But the C++ standard does not incorporate C be reference, but by inclusion. We may therefore want to create a C document of some sort. There was a minor discussion about a new topic, that of pursing some sort of Embedded Systems proposal. The sense of the committee is that they did not yet know what should be looked at, but at least looking was a direction they wanted to pursue. The committee then resumed discussion about the future. It was raised: Some thought there should be no TR before a year. As people do stuff, they therefore make existing practice, and only then is it appropriate to bring it to the committee. In the meantime, the committee needs to demonstrate stability. It was then asked where would C9X numerics fit in? Also, it was mentioned that we have a unique opportunity wrt future extensions, that is, to try and implement library extensions before standardizing them. This opportunity is appetizing. We really want "user experience reports" to see what we can learn about what works and doesn't in things such as STL as it now stands. That is, first, this should not be an attempt to standardize, but to learn from it. We will have gained a lot. Furthermore, increased consistency cannot be done by subtraction. And adding arbitrary extensions w/o a clear view of where C++ should go is not a good idea. We need a vision. We need to allow ourselves a clear guideline on which extensions are acceptable. This of course begs the question of: What mechanism(s) can be available to expose libs to the world so that may later be considered for standardization? Well, some felt that the ISO C++ committee should not be the committee to provide that mechanism. Let's keep on the standardization hat and let other wear the invention hat. That said, it was raised that wrt TRs, it's important for WG21 (the C++ committee) to get the ideas debated. People who are interested can look at it, else don't. It should also be noted that TRs have no "legal" basis per se. Of course too, something should wait till it is concrete enough before coming to the committee if at all possible. The committee's job should not be in the experimental parts. As such, let a TR follow the experience. C++'s design is very pragmatic, and always was. So we need to listen to users, to solve their problems. An artist won't paint a picture from a vision, but from a sketch book. The committee then ensued on various mock situations w.r.t. DRs and how the process might actually occur, since DRs are a new thing for the committee. Here's an executive summary of the Nice meeting: The committee discussed the issue of the practicality of making the core and library issues lists public. It was felt that since there was finally a Standard that problems should be able to be tracked externally. Points were raised about how soon the list should be made public and how soon specific issues should be made public. (Do realize that at this point there is no list.) The general consensus seemed to be that we should get as much info out there as possible w/o being misleading. In short, there was still NO Defect Reports yet, but technical progress occurred as well as investigating a chain of command and processing when DRs finally do start coming in. As well, the Performance subgroup seems to be finding itself well. Some details follow. The committee looked at some major core language issues: Some Library Issues: The committee established a subgroup to consider the issue of a Performance TR. Their issues included: The flow for handling DRs was discussed and clarified. (What follows is our understanding of the flow, not some official narrative.) Formally, defects are sent to the ISO Convener. However, he (rightly) feels that it is not the best approach if he alone handles all the DRs directly per se. So instead, the convener will take input from different sources: NBs (national bodies), the editor of the Standard, and the UK C++ Panel group. The editor of the standard feels similarly though, so although it is within his power, he would rather take his input from X3J16. J16 of course internally delegated their work to subgroups (core, library, etc) as they have always done. The subgroups will maintain issues lists. Effectively, the subgroups (that is, members of the committee) can submit Issues and Potential DRs to the Issues List Maintainer (this is usually done by public posting to the committee's internal newsgroup). Additionally, the moderators of comp.lang.c++ have volunteered to act as a filter in sending Potential Defects submitted by the general public at large to the Issues List Maintainer. If the moderators Reject it, the UK C++ Panel group will acts as an ombudsman and if they deem it a Defect, they will sent it to the convener. If they deem it a Potential Defect, that it is sent to the respective Issues List Maintainer. If they also reject it, then an NB can still pick it up as a Defect and submit that to the convener. Once a respective Issue is on a list, the respective subgroup will review it. If they decide that it wasn't really a Defect, then as above, an NB can still pick it up as a Defect and submit that to the convener. If they decide it is a Potential Defect, then it is proposed to the whole committee. If the whole committee votes that they feel it is a potential defect then it is submitted to the editor. As mentioned above, the editor prefers go with the sentiment of the committee (this is probably not a promise, but there's many years of a good track record here). NBs can also submit directly to the convener, whether as discussed above or on their own. So to summarize, the convener gets Defect Reports from NBs, the UK Panel, and the Editor. The Convener then effectively provides the Defects to the ISO committee (it's passed J16 already at this point) who can vote it Tentatively Resolved. Finally there is a Record of Response generated to the person who originally submitted the Defect, and the Issue is Officially Resolved. It then finds its way into a TC (Technical Corrigenda). In short, the TC is a collection of the correct wording resolving the respective Defects. It is guessed that two TC's for Standard C++ might be issued. Do note that policy is to wait 5 years before re-opening up the Standard, so only Defects can be processed at this point. (Don't get us wrong, things like pure extensions will still find their way onto Issues Lists for when the right time comes, they just won't be officially handled at this point, since this activity is just for handling defects.) The bottom line is that the status (Potential Defect, Rejected, etc) of the Issue will be recorded in the Issues List and will be made publically available by the committee. Check out the latest public Issues Lists. The above is just intended as a quick overview. For a more precise description on how DRs will be handled in terms of the public, check out the details offered in the respective questions of the comp.std.c++ FAQ on how to do it. Some of the more interesting technical issues discussed by the subgroups included: Additionally, the committee considered and accepted a new "work item" to produce a type-2 technical report on C++ library issues. The report will consider current library practice, APIs, logical extensions, etc. and may include things for the next revision of the standard when that comes along. As well, work on the C++ performance report continued. Additionally, the committee agreed to submit a proposal to ISO in order to produce a Technical Report (TC) of Type 2 on C++ Library Extensions. The report will consider current library practice, APIs, logical extensions, etc. and may include things for the next revision of the C++ standard. Here's the scope, from the new work item proposal: Library extensions of broad interest to users of C++ (possible examples include hashtables, regular expressions, and extensions for C99 compatibility), and potential future directions for the standard C++ library.Informally, there was also some discussion about a possible new work item or a possible new subgroup within the committee that might take place in terms of the future and evolution of C++. This was an evening talk given by Bjarne Stroustrup by going through a number of points from his slides. We'll add more about this shortly.
http://www.comeaucomputing.com/iso/meetings.html
CC-MAIN-2015-06
en
refinedweb
28 January 2010 18:48 [Source: ICIS news] (adds paragraph 3) HOUSTON (ICIS news)--Earnings in LyondellBasell’s polymers segment - its biggest overachiever for much of 2009 - declined drastically in December as US polyethylene (PE) margins were squeezed by rising feedstock costs, the producer said on Thursday. Speaking on a monthly conference call with analysts, chief executive Jim Gallogly said the declining US PE margins, combined with an expected seasonal slowdown in polypropylene (PP) demand, led the decline. The company also said it took a $40m hit after it adjusted its internal polymers cost allocations. Overall, polymers earnings before interest, tax, depreciation and amortisation and restructuring costs (EBITDAR) resulted in a loss of $27m (€19m) after posting a $58m profit in November. “As seasonally expected, December was a difficult month,” Gallogly said. “There are [PE] price increases in the industry pending, but we have seen ethylene prices rise faster and we do expect a margin squeeze. No doubt there will be some continued pressure. “That said, the export markets continue to be fairly robust, and that should help us get the price increases,” he added. In particular, low-density PE (LDPE) faces the most difficult market conditions, he said. Elsewhere in polymers, global PP volumes declined by about 5% month over month on holiday weakness, but the underlying EBITDAR was unchanged, Gallogly said. For the full 2009 year, Lyondell’s polymers segment earned $769m – well ahead of its operating forecast of $453m. Within the chemicals segment, however, EBITDAR bounced back to $126m in December from $41m in November and $108m in October due to improved margins and higher volumes within propylene oxide (?xml:namespace> For all of 2009, chemicals earnings were $861m – ahead of the $731m projected. However, Lyondell’s overall 2009 earnings of $2.26bn were only slightly higher than the $2.11bn predicted, due in large part to the struggling fuels segment. Lyondell said weak refining industry conditions continued in December and were likely to continue in the first part of 2010, capping a year in which the fuels segment earned $255m – well under the forecast of $710m. Going forward, Lyondell said olefins profitability would be subject to oil price movements, while the polymers outlook would largely depend on whether the US PE export window to ($1 = €0.71) For more on LyondellBasell visit ICIS company intelligence For more on PE, PP and
http://www.icis.com/Articles/2010/01/28/9329838/rising-costs-squeeze-us-dec-pe-lyondellbasell.html
CC-MAIN-2015-06
en
refinedweb
meta data for this page Media Manager Namespaces Choose namespace Media Files - Media Files - Upload - Search Search in common File - Date: - 2016/05/20 08:59 - Filename: - windows_64bit.zip - Size: - 19MB - References for: - Nothing was found. Wiki for LUT School of Industrial Engineering and Management
https://www.it.lut.fi/wiki/doku.php/admin/helpdesk?image=admin%3Awindows_64bit.zip&tab_details=view&do=media&tab_files=search&ns=common
CC-MAIN-2022-05
en
refinedweb
JavaScript animations JavaScript animations can handle things that CSS can't. For instance, moving along a complex path, with a timing function different from Bezier curves, or an animation on a canvas. Using setInterval An animation can be implemented as a sequence of frames -- usually small changes to HTML/CSS properties. For instance, changing style.left from 0px to 100px moves the element. And if we increase it in setInterval, changing by 2px with a tiny delay, like 50 times per second, then it looks smooth. That's the same principle as in the cinema: 24 or more frames per second is enough to make it look smooth. The pseudo-code can look like this: let timer = setInterval(function() { if (animation complete) clearInterval(timer); else increase style.left by 2px }, 20); // change by 2px every 20ms, about 50 frames per second More complete example of the animation: let start = Date.now(); // remember start time let timer = setInterval(function() { // how much time passed from the start? let timePassed = Date.now() - start; if (timePassed >= 2000) { clearInterval(timer); // finish the animation after 2 seconds return; } // draw the animation at the moment timePassed draw(timePassed); }, 20); // as timePassed goes from 0 to 2000 // left gets values from 0px to 400px function draw(timePassed) { train.style.left = timePassed / 5 + 'px'; } Using requestAnimationFrame Let's imagine we have several animations running simultaneously. If we run them separately, then even though each one has setInterval(..., 20), then the browser would have to repaint much more often than every 20ms. That's because they have different starting time, so "every 20ms" differs between different animations. The intervals are not alignned. So we'll have several independent runs within 20ms. In other words, this: setInterval(function() { animate1(); animate2(); animate3(); }, 20) ...Is lighter than three independent calls: setInterval(animate1, 20); // independent animations setInterval(animate2, 20); // in different places of the script setInterval(animate3, 20); These several independent redraws should be grouped together, to make the redraw easier for the browser (and hence smoother for people). There's one more thing to keep in mind. Sometimes when CPU is overloaded, or there are other reasons to redraw less often (like when the browser tab is hidden), so we really shouldn't run it every 20ms. But how do we know about that in JavaScript? There's a specification Animation timing that provides the function requestAnimationFrame. It addresses all these issues and even more. The syntax: let requestId = requestAnimationFrame(callback) That schedules the callback function to run in the closest time when the browser wants to do animation. If we do changes in elements in callback then they will be grouped together with other requestAnimationFrame callbacks and with CSS animations. So there will be one geometry recalculation and repaint instead of many. The returned value requestId can be used to cancel the call: // cancel the scheduled execution of callback cancelAnimationFrame(requestId); The callback gets one argument -- the time passed from the beginning of the page load in microseconds. This time can also be obtained by calling performance.now(). Usually callback runs very soon, unless the CPU is overloaded or the laptop battery is almost discharged, or there's another reason. The code below shows the time between first 10 runs for requestAnimationFrame. Usually it's 10-20ms: <script> let prev = performance.now(); let times = 0; requestAnimationFrame(function measure(time) { document.body.insertAdjacentHTML("beforeEnd", Math.floor(time - prev) + " "); prev = time; if (times++ < 10) requestAnimationFrame(measure); }) </script> Structured animation Now we can make a more universal animation function based on requestAnimationFrame:); } }); } Function animate accepts 3 parameters that essentially describes the animation: duration : Total time of animation. Like, 1000. timing(timeFraction) : Timing function, like CSS-property transition-timing-function that gets the fraction of time that passed ( 0 at start, 1 at the end) and returns the animation completion (like y on the Bezier curve). For instance, a linear function means that the animation goes on uniformly with the same speed: function linear(timeFraction) { return timeFraction; } It's graph: That's just like `transition-timing-function: linear`. There are more interesting variants shown below. draw(progress) : The function that takes the animation completion state and draws it. The value progress=0 denotes the beginning animation state, and progress=1 -- the end state. This is that function that actually draws out the animation. It can move the element: function draw(progress) { train.style.left = progress + 'px'; } ...Or do anything else, we can animate anything, in any way. Let's animate the element width from 0 to 100% using our function. The code for it: animate({ duration: 1000, timing(timeFraction) { return timeFraction; }, draw(progress) { elem.style.width = progress * 100 + '%'; } }); Unlike CSS animation, we can make any timing function and any drawing function here. The timing function is not limited by Bezier curves. And draw can go beyond properties, create new elements for like fireworks animation or something. Timing functions We saw the simplest, linear timing function above. Let's see more of them. We'll try movement animations with different timing functions to see how they work. Power of n If we want to speed up the animation, we can use progress in the power n. For instance, a parabolic curve: function quad(timeFraction) { return Math.pow(timeFraction, 2) } The graph: ...Or the cubic curve or event greater n. Increasing the power makes it speed up faster. Here's the graph for progress in the power 5: The arc function circ(timeFraction) { return 1 - Math.sin(Math.acos(timeFraction)); } The graph: Back: bow shooting This function does the "bow shooting". First we "pull the bowstring", and then "shoot". Unlike previous functions, it depends on an additional parameter x, the "elasticity coefficient". The distance of "bowstring pulling" is defined by it. The code: function back(x, timeFraction) { return Math.pow(timeFraction, 2) * ((x + 1) * timeFraction - x) } The graph for x = 1.5: Bounce Imagine we are dropping a ball. It falls down, then bounces back a few times and stops. The bounce function does the same, but in the reverse order: "bouncing" starts immediately. It uses few special coefficients for that: function bounce(timeFraction) { for (let a = 0, b = 1, result; 1; a += b, b /= 2) { if (timeFraction >= (7 - 4 * a) / 11) { return -Math.pow((11 - 6 * a - 11 * timeFraction) / 4, 2) + Math.pow(b, 2) } } } Elastic animation One more "elastic" function that accepts an additional parameter x for the "initial range". function elastic(x, timeFraction) { return Math.pow(2, 10 * (timeFraction - 1)) * Math.cos(20 * Math.PI * x / 3 * timeFraction) } The graph for x=1.5: Reversal: ease* So we have a collection of timing functions. Their direct application is called "easeIn". Sometimes we need to show the animation in the reverse order. That's done with the "easeOut" transform. easeOut In the "easeOut" mode the timing function is put into a wrapper timingEaseOut: timingEaseOut(timeFraction) = 1 - timing(1 - timeFraction) In other words, we have a "transform" function makeEaseOut that takes a "regular" timing function and returns the wrapper around it: // accepts a timing function, returns the transformed variant function makeEaseOut(timing) { return function(timeFraction) { return 1 - timing(1 - timeFraction); } } For instance, we can take the bounce function described above and apply it: let bounceEaseOut = makeEaseOut(bounce); Then the bounce will be not in the beginning, but at the end of the animation. Looks even better: [codetabs src=""] Here we can see how the transform changes the behavior of the function: If there's an animation effect in the beginning, like bouncing -- it will be shown at the end. In the graph above the regular bounce has the red color, and the easeOut bounce is blue. - Regular bounce -- the object bounces at the bottom, then at the end sharply jumps to the top. - After easeOut-- it first jumps to the top, then bounces there. easeInOut We also can show the effect both in the beginning and the end of the animation. The transform is called "easeInOut". Given the timing function, we calculate the animation state like this: if (timeFraction <= 0.5) { // first half of the animation return timing(2 * timeFraction) / 2; } else { // second half of the animation return (2 - timing(2 * (1 - timeFraction))) / 2; } The wrapper code: function makeEaseInOut(timing) { return function(timeFraction) { if (timeFraction < .5) return timing(2 * timeFraction) / 2; else return (2 - timing(2 * (1 - timeFraction))) / 2; } } bounceEaseInOut = makeEaseInOut(bounce); The "easeInOut" transform joins two graphs into one: easeIn (regular) for the first half of the animation and easeOut (reversed) -- for the second part. The effect is clearly seen if we compare the graphs of easeIn, easeOut and easeInOut of the circ timing function: - Red is the regular variantof circ( easeIn). - Green -- easeOut. - Blue -- easeInOut. As we can see, the graph of the first half of the animation is the scaled down easeIn, and the second half is the scaled down easeOut. As a result, the animation starts and finishes with the same effect. More interesting "draw" Instead of moving the element we can do something else. All we need is to write the write the proper draw. Here's the animated "bouncing" text typing: [codetabs src=""] Summary For animations that CSS can't handle well, or those that need tight control, JavaScript can help. JavaScript animations should be implemented via requestAnimationFrame. That built-in method allows to setup a callback function to run when the browser will be preparing a repaint. Usually that's very soon, but the exact time depends on the browser. When a page is in the background, there are no repaints at all, so the callback won't run: the animation will be suspended and won't consume resources. That's great. Here's the helper animate function to setup most animations:); } }); } Options: duration-- the total animation time in ms. timing-- the function to calculate animation progress. Gets a time fraction from 0 to 1, returns the animation progress, usually from 0 to 1. draw-- the function to draw the animation. Surely we could improve it, add more bells and whistles, but JavaScript animations are not applied on a daily basis. They are used to do something interesting and non-standard. So you'd want to add the features that you need when you need them. JavaScript animations can use any timing function. We covered a lot of examples and transformations to make them even more versatile. Unlike CSS, we are not limited to Bezier curves here. The same is about draw: we can animate anything, not just CSS properties.
http://semantic-portal.net/javascript-animation-js-animation
CC-MAIN-2022-05
en
refinedweb
RedLine Infostealer RedLine in a Nutshell RedLine is a newly emerging infostealer. An infostealer malware is designed to gather information, and steal valuable assets from an infected system. The most common form of infostealer is to gather login information, like usernames and passwords. RedLine was first being noticed at 2020 via COVID-19 phishing emails, and has been active in 2021. RedLine is almost everywhere, and has appeared variously as trojanized services, games, and cracks. RedLine is used for extensive information stealing operations, like: credit card credentials, Crypto wallets, sensitive files, etc. Furthermore, RedLine also can be used as malware loader or dropper for extended malicious impact. For instance, it can be used to infect the victim with additional malwares like ransomwares. The RedLine malware family has been distributed and sold mostly via underground malware forums. Many samples of RedLine also appear with legit-looking digital certificates. RedLine is considered as one of the most serious threats that are currently in the wild, therefore it is a must to know how it works, how to detect it, and how to protect your organization. RedLine Infection Vector RedLine is extremely versatile, and has been noted being delivered by numerous mechanisms. It is used in multiple smaller campaigns by individuals who have purchased the malware from the underground malware forums. Due to this, there are a wide range of known infection vectors. Only few of them are stated below: - Trojanized as popular services: Telegram, Signal, Discord (i.e. legit-looking installers). - Abusing Google Ads while hosting Trojanized or fake websites. - Social engineering campaigns to attack digital artists using Non-Fungible Tokens. - Downloaded by malware loaders. Technical Summary - Configuration Extraction: RedLine comes with embedded configuration, in this variant, the configuration is Base64 encoded plus an additional layer of XOR encryption with hard-coded key. These configuration contains the C&C server and the malware Botnet ID , which it will communicate with to exfiltrate gathered information, and also for further remote commands. - C2 Communication: After extracting the C&C and before doing anything, RedLine will check if there is a possibility to reach its C&C server. If there is an available connection, RedLine will then try to obtain the malicious Scan Settings. These scan arguments contain flags that will be used to determine which information to be stolen. Moreover, the obtained scan arguments contain tuning parameters, to specify desired data assets. For instance, search patterns to specify certain files to be exfiltrated, etc. - Host Profiling: RedLine will gather information about the infected host, in order to decide further actions. Mostly relying on Windows Management Instrumentation (WMI), it harvests and generates the following information: Hardware ID, Usernames, OS version, Installed languages, Installed programs, Current running processes, Anti-malware products, Graphics card info, Victim’s Location, IP address, etc. In addition to all these, RedLine contains functions to exclude Blacklisted countries as well as Blocked IPs from infection. - Information Stealing: Here lies the bulk of its functionality. As being an information stealer, based on the obtained scan arguments, RedLine can exfiltrates the following information: - Files: Any specified files in the following directories: ProgramData, Program Files, Program Files (x86). - Browsers: Login credentials, Cookies, Auto-fill fields used by websites, and Credit card details. - Crypto Wallets: Credentials of: Armory, Exodus, Ethereum, Monero, Atomic, BinanceChain, and a lot more. - VPN Clients: Credentials of the following VPN clients: NordVPN, ProtonVPN, and OpenVPN. - Gaming Clients: It’s targeting the credentials of the famous Valve’s Steam gaming platform. - Instant Messengers: Currently it’s targeting Telegram session data and Discord tokens. - FTP Clients: Credentials of FileZilla FTP client. - Remote Execution: After successful data exfiltration, RedLine will try to obtain additional remote commands to execute within the infected machine. Going beyond information stealing, RedLine is able to perform the following remote actions: - Download additional files. - Download and execute PE files (i.e. additional malware like ransomware). - Open desired links (i.e. malicious websites). - Execute remote commands via CMD.exe. Technical Analysis First look & Unpacking This sample comes -in disguise- as packed C/C++ file, which will be responsible to unpack and expose the real RedLine malware. However, the initial packed file as you can see in the last figure is flagged malicious by 20 security vendors according to VirusTotal. For simplicity sake, I’ve decided to use UnpacMe to do the unpacking process. The final unpacked file is found to a .NET application, which is the real RedLine malware that I will analyze in details. I’ve decided to focus on RedLine data structures, to properly understand which & how data is being exfiltrated. Configuration Extraction RedLine begins with hiding its UI from the infected user. It dynamically resolves GetConsoleWindow() and ShowWindow() APIs do that. RedLine calls ShowWindow() with the parameter SW_HIDE=0 to effectively hide its window. Then, it uses the Decrypt() function to extract the embedded encrypted configuration. For this particular sample, the decrypted C&C is "188.124.36.242:25802" and the decrypted Botnet ID is "paladin". The Botent ID is being used to track the malware and to better identify the infected machines. C2 Communication After successfully extracting the C&C IP address, RedLine will check if it can reach the C&C server using the functions RequestConnection() and TryGetConnection(). If there is an available connection, RedLine will then try to obtain the malicious Scan Settings using the function TryGetArgs(). These settings simply represents the full arsenal of RedLine, and what capabilities it possess. The available scan settings are below: These scan arguments contain flags that will be used to determine which information to be stolen. Each flag is used in certain functions to decide whether to perform the scanning functionality or not -I will show examples in a moment. Moreover, the obtained scan arguments contain tuning parameters, to specify desired data assets. For instance, they contain search patterns to specify files to be exfiltrated, paths for locating certain browsers, or a list of Blacklisted countries to exclude from infection, etc. After getting the scanning arguments (settings), RedLine proceeds to preform its main purpose, which is information stealing. Information Stealing RedLine contains many functions to collect and harvest almost every valuable asset in the infected machine. Some of these functions are very simple, regarding the purpose and the implementation. For instance, Enumerate_username(), Get_Malware_Path(), Enumerate_OS_Version(),etc. Yet, before proceeding to the scanning functionality once again, RedLine instantiates very important data structures, which will be populated with the stolen assets and the gathered host profile. Below are the two important classes ScanResult and ScanDetails : For instance, Specified files by the scanning arguments will be populated into ScannedFile class in order to be exfiltrated and so on. The scannedFile class is included in the bigger ScanDetails class, which is also included in the bigger ScanResult class. It’s very important to understand the hierarchy of these nested classes, to draw a map of how the precious data assets are being organized and stolen from the infected machine. Host Profiling RedLine contains more than 20 functions to perform almost full sweeping of the infected machine. Some of them are fairly simple, they just perform windows registry querying or they use documented APIs. For instance, since Microsoft Edge is the default browser, the Enumerate_Browsers() function searches the registry keys HKEY_LOCAL_MACHINE\Software\Clients\StartMenuInternet and its WoW6432 twin to find the installed browsers, in order to harvest their credentials later on. The Enumerate_Installed_Software() function uses the registry key HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall to list every installed software in the system. Also, RedLine uses the Take_Screenshots() functions to take live screenshots of the infected system. Moreover, the Enumerate_Security_Defenders() function uses the WMI to enumerate any installed security solution. It allows it to get the installed Antivirus, AntiSpyware and Firewall (third party) software using the root\SecurityCenter or the root\SecurityCenter2 namespaces. Not to forget, the Enumerate_Running_Processess() function which also uses the Win32_Process WMI class that represents a process on an operating system. It gets the process name + PID + command line arguemtns in order to build a live full view of the infected machine. I think the attacker uses these information to decide further malicious actions i.e. certain exploits. Lastly, one more interesting function is the Send() function which contains the above method. It uses the following remote API to gather very detailed geographical information about the victim. The remote API returns XML data specifying many detailed information: {"organization":"XXXXXXXX","longitude":XXXXXXX,"city":"XXXXXX","timezone":"XXXXXX","isp":"XXXXXXX","offset":XXXXX,"region":"XXXXX","asn":XXXXX,"asn_organization":"XXXXX","country":"XXXXX","ip":"XXXXXXX","latitude":XXXXXXX,"continent_code":"XXXX","country_code":"XXXX","region_code":"XXXXX"} Exfiltrating Files It’s important to know the inner structures of the ScannedFile class which is used to populate the exfiltrated files. As you can see in the above screenshot, once a file is being instantiated, nearly all of its important contents is stolen. Based on the obtained scan arguments (settings) during the previous C2 communication, they contain search patterns to specify desired files to be stolen. RedLine currently use the search patterns to locate files in the following directories only: Program Files (X86)/, Program Files/, and Program Data/. The directory ProgramData/ is for user-agnostic data generated during execution such as shared cache, shared databases, shared settings, shared preferences, etc. RedLine only needs to locate the specified files based on the search patterns then create a ScannedFile instance of the filtered filename. Once instantiated with the filename, almost all of the file contents is stolen because of the ScannedFile constructor code. Harvesting Browsers Also, It’s very important to know the inner structures of the Browser class, which is used to populate the harvested browser credentials. Once a browser is targeted, RedLine steals its accounts credentials, credit card credentials, cookies, and auto-fill data. RedLine targets Chromium based browsers as well as Gecko based browsers, which makes RedLine nearly targets most used browsers. RedLine also uses more methods like DecryptChromium() in order to effectively harvest the targeted credentials. It’s also being noticed that for Gecko based browsers, this sample only steals the cookies unlike the targeted Chromium based browsers. Stealing Crypto Wallets A crypto wallet is an application used to both cold store and retrieve digital cryptocurrency assets. RedLine of course targets these valuable assets because of the rise of people’s interest in cryptocurrency during the past few years. RedLine comes with many classes targeting many crypto wallets like: Armory, Exodus, Ethereum, Monero, Atomic, BinanceChain, Jaxx, Electrum, Guarda, etc. RedLine uses pre-defined search patterns and scan arguments to populate the wallets into ScannedFile instances. Each class in the previous figure is just used to initialize defined search patterns to be passed to the regular Search() function which is used in files exfiltration. These search patterns specify the credentials files which is being used for the specific wallet type. For every wallet class, it is used to override the GetScanArgs() function which is used internally in the Search() function in order to filter for the appropriate wallet files. These filtered files will be exfiltrated. Harvesting Instant Messenger Clients Instant Messenger (IM) clients like Discord and Telegram have seen a recent rise in popularity, with Discord boasting over 100 million active users. For Telegram, RedLine looks used the GetProcessesByName() function to get the ExecutablePath for Telegram running process. Then, it looks for the folder tdata. This is where the Instant Messenger stores its session data, including images and conversations: It’s also used to override the GetScanArgs() function which is used internally in the Search() function in order to filter for the targeted files. For Discord, RedLine is stealing its tokens using the Discord.GetTokens() function. A Discord token is a phrase of letters and numbers that acts as an authorization code to access Discord’s servers. It effectively acts as an encryption of your username and password. Snatching VPN Clients Credentials With the rise in popularity in VPN services, RedLine doesn’t have any plans to miss this chance. RedLine targets the VPN clients of the following services: NordVPN, OpenVPN, and ProtonVPN. For NordVPN client, RedLine uses obfuscated strings to locate the targeted XML files which contain the VPN credentials: Then, it uses decrypting functions to decipher the wanted credentials: Yet, for OpenVPN and ProtonVPN, RedLine uses the same old method of overriding the GetScanArgs() function which is used internally in the Search() function in order to filter for the targeted files. Then, it exfiltrates the filtered files as ScannedFile instances which contains the VPN credentials. Harvesting Gaming Clients Steam is a video game digital distribution service by Valve. By 2019, the service had over 34,000 games with over 95 million monthly active users. Steam is regarded as one of the best gaming platforms in the industry. Steam has an in-built store with a lot of ‘Steam accounts’ having various other services and banking details related to it. RedLine attempts to go after the Steam Sentry File which is used to store credentials: A VDF file is a data file format used by Valve’s Source game engine. It contains various kinds of game metadata, including data for resources, installation scripts, configuration scripts, and visualization elements. Stealing FTP Credentials. RedLine targets the free, open-source FileZilla application. RedLine uses the ScanCredentials() function to extract the required credentials and to populate them in Account class which will contain the URL + username + password. Remote Execution RedLine extends its functionality beyond information stealing. Here, RedLine takes the role of a malware loader. A malware loader is the software which drops the actual malicious content on the system, then executes the first stage of the attack. Hence, RedLine is capable of delivering some additional serious threats to the infected machine, like ransomwares for example. After successfully performing the information stealing operations, RedLine uses the TryGetTasks() function to obtain a list of UpdateTask class, which contains the required arguments to successfully perform remote execution actions: Once a connection with its C&C server has been established, RedLine can remotely perform the operations described in the above figure. Below are the inner details of the DownloadAndExecuteUpdate class which is used -as the name suggests- to download a PE file and executes it in the infected machine: RedLine can be used effectively as malware loader or dropper for further wanted malicious activities. Moreover, it can be used to open desired links for various malicious or non-malicious purposes. Conclusion RedLine is regarded as a true security threat to any machine. The capabilities of being able to steal almost every valuable asset, and being able to load additional serious malwares or exploits are regarded most fatal. This threat has been sold as individual packages with several pricing options, or as Malware-as-a-Service (MaaS) on a subscription-based pricing package. With the rise of Maas underground forums, RedLine threats will not fade away in the very near future. Therefore, it is a must to know how it works, how to detect it, and how to protect your organization. IoCs YARA Rule rule redline : infostealer { meta: description = "This is a noob rule for detecting unpacked RedLine" author = "Nidal Fikri @cyber_anubis" strings: $mz = {4D 5A} //PE File $s1 = "IRemoteEndpoint" $s2 = "ITaskProcessor" $s3 = "ScannedFile" $s4 = "ScanningArgs" $s5 = "ScanResult" $s6 = "DownloadAndExecuteUpdate" $s7 = "OpenUpdate" $s8 = "CommandLineUpdate" $s9 = "TryCompleteTask" $s10 = "TryGetTasks" $s11 = "TryInitBrowsers" $s12 = "InstalledBrowsers" $s13 = "TryInitInstalledBrowsers" $s14 = "TryInitInstalledSoftwares" $s15 = "TryGetConnection" condition: ($mz at 0) and (10 of ($s*)) }
https://cyber-anubis.github.io/malware%20analysis/redline/
CC-MAIN-2022-05
en
refinedweb
public class RawNetworkReceiver extends Receiver<Object> implements Logging RawNetworkReceiver(String host, int port, StorageLevel storageLevel) public Thread blockPushingThread()<Object> public void onStop() onStart()must be cleaned up in this method. onStopin class Receiver<Object>
https://spark.apache.org/docs/1.2.1/api/java/org/apache/spark/streaming/dstream/RawNetworkReceiver.html
CC-MAIN-2022-05
en
refinedweb
OverviewOverview This module is a generic server daemon framework, which supports a component plug-in system. It can be used as a basis to create custom daemons such as web app backends. It provides basic services such as configuration file loading, command-line argument parsing, logging, and more. Component plug-ins can be created by you, or you can use some pre-made ones. UsageUsage Use npm to install the module: npm install pixl-server Then use require() to load it in your code: var PixlServer = require('pixl-server'); Then instantiate a server object and start it up: var server = new PixlServer({ __name: 'MyServer', __version: "1.0", config: { "log_dir": "/var/log", "debug_level": 9, "uid": "www" }, components: [] }); server.startup( function() { // startup complete } ); Of course, this example won't actually do anything useful, because the server has no components. Let's add a web server component to our server, just to show how it works: var PixlServer = require('pixl-server'); var server = new PixlServer({ __name: 'MyServer', __version: "1.0", config: { "log_dir": "/var/log", "debug_level": 9, "uid": "www", "WebServer": { "http_port": 80, "http_htdocs_dir": "/var/www/html" } }, components: [ require('pixl-server-web') ] }); server.startup( function() { // startup complete } ); This example uses the pixl-server-web component to turn our server into a web (HTTP) server. It will listen on port 80 and serve static files in the /var/www/html folder. As you can see we're loading the pixl-server-web module by calling require() into the components array when creating our server object: components: [ require('pixl-server-web') ] To include additional components, simply add them to this array. Please note that the order matters here. Components that rely on WebServer, for example, should be listed after it. Also, notice in the above example we added a new section to our existing config object, and named it WebServer (must match the component exactly). In there we're setting a couple of new keys, which are specifically for that component: "WebServer": { "http_port": 80, "http_htdocs_dir": "/var/www/html" } Each component has its own section in the configuration file (or hash). For more details on the WebServer configuration, see the module documentation. ComponentsComponents Components make up the actual server functionality, and can be things like a web (HTTP) server, a SocketIO server, a back-end storage system, or a multi-server cluster manager. A server may load multiple components (and some rely on each other). A component typically starts some sort of listener (network socket listener, etc.) or simply exposes an API for other components or your code to use directly. Stock ComponentsStock Components As of this writing, the following stock server components are available via npm: WebServer (pixl-server-web)WebServer (pixl-server-web) The WebServer (pixl-server-web) component implements a full web (HTTP) server. It supports HTTP and/or HTTPS, static file hosting, custom headers, as well as a hook system for routing specific URIs to your own handlers. For more details, check it out on npm: pixl-server-web PoolManager (pixl-server-pool)PoolManager (pixl-server-pool) The PoolManager (pixl-server-pool) component can delegate web requests to a pool of worker child processes. This can be useful for CPU-hard operations such as image transformations, which would otherwise block the main thread. For more details, check it out on npm: pixl-server-pool JSON API (pixl-server-api)JSON API (pixl-server-api) The API (pixl-server-api) component provides a JSON REST API for your application. It sits on top of (and relies on) the WebServer (pixl-server-web) component. For more details, check it out on npm: pixl-server-api UserManager (pixl-server-user)UserManager (pixl-server-user) The UserManager (pixl-server-user) component provides a full user login and user / session management system for your application. Users can create accounts, login, update information, and logout. It relies on the API (pixl-server-api) component, as well as the Storage (pixl-server-storage) component. For more details, check it out on npm: pixl-server-user Storage (pixl-server-storage)Storage (pixl-server-storage) The Storage (pixl-server-storage) component provides an internal API for other components to store data on disk (or to the cloud). It supports local disk storage, as well as Amazon S3. One of its unique features is a high performance, double-ended linked list, built on top of a key/value store. This is useful for web apps to store infinitely-sized lists of data. For more details, check it out on npm: pixl-server-storage MultiServer (pixl-server-multi)MultiServer (pixl-server-multi) The MultiServer (pixl-server-multi) component automatically manages a cluster of servers on the same network. They auto-detect each other using UDP broadcast packets. One server is flagged as the "master" node at all times, while the rest are "slaves". If the master server goes down, one of the slaves will automatically take over. An API is provided to get the list of server hostnames in the cluster, and it also emits events so your code can react to becoming master, etc. For more details, check it out on npm: pixl-server-multi EventsEvents The following events are emitted by the server. prestartprestart The prestart event is fired during server initialization. The server's configuration and logging systems are available, and components are initialized but not started. Your callback is not passed any arguments. readyready The ready event is fired when the server and all components have completed startup. Your callback is not passed any arguments. shutdownshutdown The shutdown event is fired when the server and all components have shutdown, and Node is about to exit. Your callback is not passed any arguments. Maintenance EventsMaintenance Events These events are emitted periodically, and can be used to schedule time-based events such as hourly log rotation, daily storage cleanup, etc. Unless otherwise noted, your callback will be passed an object representing the current local date and time, as returned from getDateArgs(). ticktick This event is fired approximately once every second, but is not guaranteed to be fired on the second. It is more for things like general heartbeat tasks (check for status of running jobs, etc.). Your callback is not passed any arguments. minuteminute This event is fired every minute, on the minute. Example: server.on('minute', function(args) { // Do something every minute }); :MM:MM Also fired every minute, this event name will contain the actual minute number (two-digit padded from 00 to 59), so you can schedule hourly jobs that run at a particular minute. Don't forget the colon (:) prefix. Example: server.on(':15', function(args) { // This will run on the :15 of the hour, every hour }); HH:MMHH:MM Also fired every minute, this event name will contain both the hour digits (from 00 to 23) and the minute (from 00 to 59), so you can schedule daily jobs that run at a particular time. Example: server.on('04:30', function(args) { // This will run once at 4:30 AM, every day }); hourhour This event is fired every hour, on the hour. Example: server.on('hour', function(args) { // Do something every hour }); dayday This event is fired every day at midnight. Example: server.on('day', function(args) { // Do something every day at midnight }); monthmonth This event is fired at midnight when the month changes. Example: server.on('month', function(args) { // Do something every month }); yearyear This event is fired at midnight when the year changes. Example: server.on('year', function(args) { // Do something every year }); ConfigurationConfiguration The server configuration consists of a set of global, top-level keys, and then each component has its own sub-section keyed by its name. The configuration can be specified as an inline JSON object to the constructor in the config property like this: { config: { "log_dir": "/var/log", "debug_level": 9, "uid": "www" } } Or it can be saved in JSON file, and specified using the configFile property like this: { configFile: "conf/config.json" } Here are the global configuration keys: Remember that each component should have its own configuration key. Here is an example server configuration, including the WebServer component: { config: { "log_dir": "/var/log", "debug_level": 9, "uid": "www", "WebServer": { "http_port": 80, "http_htdocs_dir": "/var/www/html" } } } Consult the documentation for each component you use to see which keys they require. Command-Line ArgumentsCommand-Line Arguments You can specify command-line arguments when launching your server. If these are in the form of --key value they will override any global configuration keys with matching names. For example, you can launch your server in debug mode and enable log echo like this: node my-script.js --debug 1 --echo 1 Actually, you can set a configuration key to boolean true simply by including it without a value, so this works too: node my-script.js --debug --echo Optional Echo CategoriesOptional Echo Categories If you want to limit the log echo to certain log categories or components, you can specify them on the command-line, like this: node my-script.js --debug 1 --echo "debug error" This would limit the log echo to entries that had their category or component column set to either debug or error. Other non-matched entries would still be logged -- they just wouldn't be echoed to the console. Multi-File ConfigurationMulti-File Configuration If your app has multiple configuration files, you can specify a multiConfig property (instead of configFile) in your pixl-server class. The multiConfig property should be an array of objects, with each object representing one configuration file. The properties in the objects should be as follows: So for example, let's say you had one main configuration file which you want loaded and parsed as usual, but you also have an environment-specific config file, and want it included as well, but separated into its own namespace. Here is how you could accomplish this with multiConfig: "multiConfig": [ { "file": "/opt/myapp/conf/config.json" }, { "file": "/etc/env.json", "key": "env" } ] So in the above example the config.json file would be loaded and parsed as if it were the main configuration file (since it has no key property), and its contents merged into the top-level server configuration. Then the /etc/env.json file would also be parsed, and its contents made available in the env configuration key. So you could access it via: var env = server.config.get('env'); Both files would be monitored for changes (polled every 10 seconds by default) and hot-reloaded as necessary. If any file is reloaded, a reload event is emitted on the main server.config object, so you can listen for this and perform any app-specific operations as needed. For another example, let's say your environment-specific file is actually in XML format. For this, you need to specify a custom parser function via the parser property. If you use our own pixl-xml module, the usage is as follows: "multiConfig": [ { "file": "/opt/myapp/conf/config.json" }, { "file": "/etc/env.xml", "key": "env", "parser": require('pixl-xml').parse } ] Your parser function is passed a single argument, which is the file contents preloaded as UTF-8 text, and it is expected to return an object containing the parsed data. If you need to parse your own custom file format, you can call your own inline function like this: "multiConfig": [ { "file": "/opt/myapp/conf/config.json" }, { "file": "/etc/env.ini", "key": "env", "parser": function(text) { // parse simple INI `key=value` format var config = {}; text.split(/\n/).forEach( function(line) { if (line.trim().match(/^(\w+)\=(.+)/)) { config[ RegExp.$1 ] = RegExp.$2; } } ); return config; } } ] If your custom parser function throws during the initial load at startup, the error will bubble up and cause an immediate shutdown. However, if it throws during a hot reload event, the error is caught, logged as a level 1 debug event, and the old configuration is used until the file is modified again. This way a malformed config file edit won't bring down a live server. It is perfectly fine to have multiple configuration files that "share" the top-level main configuration namespace. Just specify multiple files without key properties. Example: "multiConfig": [ { "file": "/opt/myapp/conf/config-part-1.json" }, { "file": "/opt/myapp/conf/config-part-2.json" } ] Beware of key collision here inside your files: no error is thrown, and the latter prevails. You can also combine an inline config object, and the multiConfig object, in your server properties. The files in the multiConfig array take precedence, and can override any keys present in the inline config. Example: { "config": { "log_dir": "/var/log", "log_filename": "myapp.log", "debug_level": 9 }, "multiConfig": [ { "file": "/opt/myapp/conf/config.json" }, { "file": "/etc/env.json", "key": "env" } ] } If you need to temporarily swap out your multiConfig file paths for testing, you can do so on the command-line. Simply specify one or more --multiConfig CLI arguments, each one pointing to a replacement file. The files must be specified in order of the items in your multiConfig array. Example: node myserver.js --multiConfig test/config.json --multiConfig test/env.json Note: The configFile and multiConfig server properties are mutually exclusive. If you specify configFile it takes precedence, and disables the multi-config system. LoggingLogging The server keeps an event log using the pixl-logger module. This is a combination of a debug log, error log and transaction log, with a category column denoting the type of log entry. By default, the log columns are defined as: ['hires_epoch', 'date', 'hostname', 'component', 'category', 'code', 'msg', 'data'] However, you can override these and provide your own array of log columns by specifying a log_columns configuration key. Here is an example debug log snippet: [1432581882.204][2015-05-25 12:24:42][joeretina-2.local][][debug][1][MyServer v1.0 Starting Up][] [1432581882.207][2015-05-25 12:24:42][joeretina-2.local][][debug][2][Configuration][{"log_dir":"/Users/jhuckaby/temp","debug_level":9,"WebServer":{"http_port":3012,"http_htdocs_dir":"/Users/jhuckaby/temp"},"debug":true,"echo":true}] [1432581882.208][2015-05-25 12:24:42][joeretina-2.local][][debug][2][Server IP: 10.1.10.17, Daemon PID: 26801][] [1432581882.208][2015-05-25 12:24:42][joeretina-2.local][][debug][3][Starting component: WebServer][] [1432581882.209][2015-05-25 12:24:42][joeretina-2.local][WebServer][debug][2][Starting HTTP server on port: 3012][] [1432581882.218][2015-05-25 12:24:42][joeretina-2.local][][debug][2][Startup complete, entering main loop][] For debug log entries, the category column is set to debug, and the code columns is used as the debug level. The server object (and your component object) has methods for logging debug messages, errors and transactions: server.logDebug( 9, "This would be logged at level 9 or higher." ); server.logError( 1005, "Error message for code 1005 here." ); server.logTransaction( 99.99, "Description of transaction here." ); These three methods all accept two required arguments, and an optional 3rd "data" object, which is serialized and logged into its own column if provided. For the debug log, the first argument is the debug level. Otherwise, it is considered a "code" (can be used however your app wants). When you call logDebug(), logError() or logTransaction() on your component object, the component column will be set to the component name. Otherwise, it will be blank (including when the server logs its own debug messages). If you need low-level, direct access to the pixl-logger object, you can call it by accessing the logger property of the server object or your component class. Example: server.logger.print({ category: 'custom', code: 'custom code', msg: "Custom message here", data: { text: "Will be serialized to JSON" } }); The server and component classes have a utility method named debugLevel(), which accepts a log level integer, and will return true if the current debug log level is high enough to emit something at the specified level, or false if it would be silenced. Component DevelopmentComponent Development To develop your own component, create a class that inherits from the pixl-server/component base class. It is recommended you use the pixl-class module for this. Set your __name property to a unique, alphanumeric name, which will be your Component ID. This is how other components can reference yours from the server object, and this is the key used for your component's configuration as well. Here is a simple component example: var Class = require("pixl-class"); var Component = require("pixl-server/component"); module.exports = Class.create({ __name: 'MyComponent', __parent: Component, startup: function(callback) { this.logDebug(1, "My component is starting up!"); callback(); }, shutdown: function(callback) { this.logDebug(1, "My component is shutting down!"); callback(); } }); Now, assuming you saved this class as my_component.js, you would load it in a server by adding it to the components array like this: components: [ require('pixl-server-web'), require('./my_component.js') ] This would load the pixl-server-web component first, followed by your my_component.js component after it. Remember that the load order is important, if you have a component that relies on another. Your component's configuration would be keyed off the value in your __name property, like this: { config: { "log_dir": "/var/log", "debug_level": 9, "uid": "www", "WebServer": { "http_port": 80, "http_htdocs_dir": "/var/www/html" }, "MyComponent": { "key1": "Value 1", "key2": "Value 2" } } } If you want to specify default configuration keys (in case they are missing from the server configuration for your component), you can define a defaultConfig property in your class, like this: module.exports = Class.create({ __name: 'MyComponent', __parent: Component, defaultConfig: { "key1": "Default Value 1", "key2": "Default Value 2" } }); Startup and ShutdownStartup and Shutdown Your component should at least provide startup() and shutdown() methods. These are both async methods, which should invoke the provided callback function when they are complete. Example: { startup: function(callback) { this.logDebug(1, "My component is starting up!"); callback(); }, shutdown: function(callback) { this.logDebug(1, "My component is shutting down!"); callback(); } } As with all Node.js callbacks, if something goes wrong and you want to abort the startup or shutdown routines, pass an Error object to the callback method. Accessing Your ConfigurationAccessing Your Configuration Your configuration object is always accessible via this.config. Note that this is an instance of pixl-config, so you need to call get() on it to fetch individual configuration keys, or you can fetch the entire object by calling it without an argument: { startup: function(callback) { this.logDebug(1, "My component is starting up!"); // access our component configuration var key1 = this.config.get('key1'); var entire_config = this.config.get(); callback(); } } If the server configuration is live-reloaded due to a changed file, your component's config object will emit a reload event, which you can listen for. Accessing The Root ServerAccessing The Root Server Your component can always access the root server object via this.server. Example: { startup: function(callback) { this.logDebug(1, "My component is starting up!"); // access the main server configuration var server_uid = this.server.config.get('uid'); callback(); } } Accessing Other ComponentsAccessing Other Components Other components are accessible via this.server.COMPONENT_NAME. Please be aware of the component load order, as components listed below yours in the server components array won't be fully loaded when your startup() method is called. Example: { startup: function(callback) { this.logDebug(1, "My component is starting up!"); // access the WebServer component this.server.WebServer.addURIHandler( '/my/custom/uri', 'Custom Name', function(args, callback) { // custom request handler for our URI callback( "200 OK", { 'Content-Type': "text/html" }, "Hello this is custom content!\n" ); } ); callback(); } } Accessing The Server LogAccessing The Server Log Your component's base class has convenience methods for logging debug messages, errors and transactions via the logDebug(), logError() and logTransaction() methods, respectively. These log messages will all be tagged with your component name, to differentiate them from other components and generic server messages. Example: this.logDebug( 9, "This would be logged at level 9 or higher." ); this.logError( 1005, "Error message for code 1005 here." ); this.logTransaction( 99.99, "Description of transaction here." ); If you need low-level, direct access to the pixl-logger object, you can call it by accessing the logger property of your component class. Example: this.logger.print({ category: 'custom', code: 'custom code', msg: "Custom message here", data: { text: "Will be serialized to JSON" } }); Uncaught ExceptionsUncaught Exceptions When the log_crashes feature is enabled, the uncatch module is used to manage uncaught exceptions. The server registers a listener to log crashes, but you can also add your own listener to perform emergency shutdown procedures in the event of a crash (uncaught exception). The idea with uncatch is that multiple modules can all register listeners, and that includes your application code. Example: require('uncatch').on('uncaughtException', function(err) { // run your own sync shutdown code here // do not call process.exit }); On an uncaught exception, this code would run in addition to the server logging the exception to the crash log. Uncatch then emits the error and stack trace to STDERR and calls process.exit(1) after all listeners have executed. LicenseLicense.
https://www.npmjs.com/package/pixl-server
CC-MAIN-2022-05
en
refinedweb
This system test program creates different test cases with a single eNB and several UEs, all having the same Radio Bearer specification. More... #include "lte-test-tdmt-ff-mac-scheduler.h" This system test program creates different test cases with a single eNB and several UEs, all having the same Radio Bearer specification. In each test case, the UEs see the same SINR from the eNB; different test cases are implemented obtained by using different SINR values and different numbers of UEs. The test consists on checking that the obtained throughput performance is consistent with the definition of maximum throughput scheduling Definition at line 45 of file lte-test-tdmt-ff-mac-scheduler.h. Constructor. Definition at line 166 of file lte-test-tdmt-ff-mac-scheduler.cc. Definition at line 176 of file lte-test-tdmt-ff-mac-scheduler.cc. Builds the test name string based on provided parameter values. Definition at line 159 of file lte-test-tdmt-ff-mac-scheduler.cc. Implementation to actually run this TestCase. Subclasses should override this method to conduct their tests. Initialize Simulation Scenario: 1 eNB and m_nUser UEs Check that the downlink assignation is done in a "time domain maximum throughput" manner Check that the assignation is done in a "time domain maximum throughput" manner among users with maximum SINRs: without fading, current FD MT always assign all resources to one UE Check that the uplink assignation is done in a "proportional fair" manner Check that the assignation is done in a "proportional fair" manner among users with equal SINRs: the bandwidth should be distributed according to the ratio of the estimated throughput per TTI of each user; therefore equally partitioning the whole bandwidth achievable from a single users in a TTI Implements ns3::TestCase. Definition at line 182 of file lte-test-tdmt-ff-mac-scheduler.cc. References ns3::LteHelper::ActivateDataRadioBearer(), ns3::LteHelper::Attach(), ns3::NodeContainer::Create(), ns3::LteHelper::EnableMacTraces(), ns3::LteHelper::EnableRlcTraces(), ns3::NetDeviceContainer::Get(), ns3::NodeContainer::Get(), ns3::RadioBearerStatsCalculator::GetDlRxData(), ns3::Object::GetObject(), ns3::LteEnbNetDevice::GetPhy(), ns3::LteUeNetDevice::GetPhy(), ns3::LteHelper::GetRlcStats(), ns3::RadioBearerStatsCalculator::GetUlRxData(), ns3::LteHelper::InstallEnbDevice(), ns3::LteHelper::InstallUeDevice(), m_dist, m_errorModelEnabled, m_nUser, m_thrRefDl, m_thrRefUl, third::mobility, NS_LOG_FUNCTION, NS_LOG_INFO, NS_TEST_ASSERT_MSG_EQ_TOL, ns3::Seconds(), ns3::ObjectBase::SetAttribute(), ns3::Config::SetDefault(), ns3::MobilityModel::SetPosition(), ns3::LteHelper::SetSchedulerAttribute(), and ns3::LteHelper::SetSchedulerType(). the distance between nodes Definition at line 70 of file lte-test-tdmt-ff-mac-scheduler.h. whether the error model is enabled Definition at line 73 of file lte-test-tdmt-ff-mac-scheduler.h. number of UE nodes Definition at line 69 of file lte-test-tdmt-ff-mac-scheduler.h. the DL throughput reference Definition at line 71 of file lte-test-tdmt-ff-mac-scheduler.h. the UL throughput reference Definition at line 72 of file lte-test-tdmt-ff-mac-scheduler.h.
https://www.nsnam.org/docs/release/3.30/doxygen/class_lena_td_mt_ff_mac_scheduler_test_case.html
CC-MAIN-2022-05
en
refinedweb