text stringlengths 454 608k | url stringlengths 17 896 | dump stringclasses 91 values | source stringclasses 1 value | word_count int64 101 114k | flesch_reading_ease float64 50 104 |
|---|---|---|---|---|---|
Best way to learn kNN Algorithm using R Programming
Introduction
In this article, I’ll show you the application of kNN (k – nearest neighbor) algorithm using R Programming. But, before we go ahead on that journey, you should read the following articles:
- Basics of machine learning from my previous article
- Common machine learning algorithms
- Introduction to kNN – simplified
We’ll also discuss a case study which describes the step by step process of implementing kNN in building models.
This algorithm is a supervised learning algorithm, where the destination is known, but the path to the destination is not. Understanding nearest neighbors forms the quintessence of machine learning. Just like Regression, this algorithm is also easy to learn and apply.
What is kNN Algorithm?
Let’s assume we have several groups of labeled samples. The items present in the groups are homogeneous in nature. Now, suppose we have an unlabeled example which needs to be classified into one of the several labeled groups. How do you do that? Unhesitatingly, using kNN Algorithm.
k nearest neighbors is a simple algorithm that stores all available cases and classifies new cases by a majority vote of its k neighbors. This algorithms segregates unlabeled data points into well defined groups.
How to select appropriate k value?
Choosing the number of nearest neighbors i.e. determining the value of k plays a significant role in determining the efficacy of the model. Thus, selection of k will determine how well the data can be utilized to generalize the results of the kNN algorithm. A large k value has benefits which include reducing the variance due to the noisy data; the side effect being developing a bias due to which the learner tends to ignore the smaller patterns which may have useful insights.
The following example will give you practical insight on selecting the appropriate k value.
Example of kNN Algorithm
Let’s consider 10 ’drinking items’ which are rated on two parameters on a scale of 1 to 10. The two parameters are “sweetness” and “fizziness”. This is more of a perception based rating and so may vary between individuals. I would be considering my ratings (which might differ) to take this illustration ahead. The ratings of few items look somewhat as:
“Sweetness” determines the perception of the sugar content in the items. “Fizziness” ascertains the presence of bubbles in the drink due to the carbon dioxide content in the drink. Again, all these ratings used are based on personal perception and are strictly relative.
From the above figure, it is clear we have bucketed the 10 items into 4 groups namely, ’COLD DRINKS’, ‘ENERGY DRINKS’, ‘HEALTH DRINKS’ and ‘HARD DRINKS’. The question here is, to which group would ‘Maaza’ fall into? This will be determined by calculating distance.
Calculating Distance
Now, calculating distance between ‘Maaza’ and its nearest neighbors (‘ACTIV’, ‘Vodka’, ‘Pepsi’ and ‘Monster’) requires the usage of a distance formula, the most popular being Euclidean distance formula i.e. the shortest distance between the 2 points which may be obtained using a ruler.
Source: Gamesetmap
Using the co-ordinates of Maaza (8,2) and Vodka (2,1), the distance between ‘Maaza’ and ‘Vodka’ can be calculated as:
dist(Maaza,Vodka) = 6.08
Using Euclidean distance, we can calculate the distance of Maaza from each of its nearest neighbors. Distance between Maaza and ACTIV being the least, it may be inferred that Maaza is same as ACTIV in nature which in turn belongs to the group of drinks (Health Drinks).
If k=1, the algorithm considers the nearest neighbor to Maaza i.e, ACTIV; if k=3, the algorithm considers ‘3’ nearest neighbors to Maaza to compare the distances (ACTIV, Vodka, Monster) – ACTIV stands the nearest to Maaza.
kNN Algorithm – Pros and Cons
Pros: The algorithm is highly unbiased in nature and makes no prior assumption of the underlying data. Being simple and effective in nature, it is easy to implement and has gained good popularity.
Cons: Indeed it is simple but kN.
Case Study: Detecting Prostate Cancer
Machine learning finds extensive usage in pharmaceutical industry especially in detection of oncogenic (cancer cells) growth. R finds application in machine learning to build models to predict the abnormal growth of cells thereby helping in detection of cancer and benefiting the health system.
Let’s see the process of building this model using kNN algorithm in R Programming. Below you’ll observe I’ve explained every line of code written to accomplish this task.
Step 1- Data collection
We will use a data set of 100 patients (created solely for the purpose of practice) to implement the knn algorithm and thereby interpreting results .The data set has been prepared keeping in mind the results which are generally obtained from DRE (Digital Rectal Exam). You can download the data set and practice these steps as I explain.
The data set consists of 100 observations and 10 variables (out of which 8 numeric variables and one categorical variable and is ID) which are as follows:
- Radius
- Texture
- Perimeter
- Area
- Smoothness
- Compactness
- Symmetry
- Fractal dimension
In real life, there are dozens of important parameters needed to measure the probability of cancerous growth but for simplicity purposes let’s deal with 8 of them!
Here’s how the data set looks like:
Step 2- Preparing and exploring the data
Let’s make sure that we understand every line of code before proceeding to the next stage:
setwd("C:/Users/Payal/Desktop/KNN") #Using this command, we've imported the ‘Prostate_Cancer.csv’ data file. This command is used to point to the folder containing the required file. Do keep in mind, that it’s a common mistake to use “\” instead of “/” after the setwd command.
prc <- read.csv("Prostate_Cancer.csv",stringsAsFactors = FALSE) #This command imports the required data set and saves it to the prc data frame.
stringsAsFactors = FALSE #This command helps to convert every character vector to a factor wherever it makes sense.
str(prc) #We use this command to see whether the data is structured or not.
We find that the data is structured with 10 variables and 100 observations. If we observe the data set, the first variable ‘id’ is unique in nature and can be removed as it does not provide useful information.
prc <- prc[-1] #removes the first variable(id) from the data set.
The data set contains patients who have been diagnosed with either Malignant (M) or Benign (B) cancer
table(prc$diagnosis_result) # it helps us to get the numbers of patients
(The variable diagnosis_result is our target variable i.e. this variable will determine the results of the diagnosis based on the 8 numeric variables)
In case we wish to rename B as”Benign” and M as “Malignant” and see the results in the percentage form, we may write as:
prc$diagnosis <- factor(prc$diagnosis_result, levels = c("B", "M"), labels = c("Benign", "Malignant"))
round(prop.table(table(prc$diagnosis)) * 100, digits = 1) # it gives the result in the percentage form rounded of to 1 decimal place( and so it’s digits = 1)
Normalizing numeric data
This feature is of paramount importance since the scale used for the values for each variable might be different. The best practice is to normalize the data and transform all the values to a common scale.
normalize <- function(x) { return ((x - min(x)) / (max(x) - min(x))) }
Once we run this code, we are required to normalize the numeric features in the data set. Instead of normalizing each of the 8 individual variables we use:
prc_n <- as.data.frame(lapply(prc[2:9], normalize))
The first variable in our data set (after removal of id) is ‘diagnosis_result’ which is not numeric in nature. So, we start from 2nd variable. The function lapply() applies normalize() to each feature in the data frame. The final result is stored to prc_n data frame using as.data.frame() function
Let’s check using the variable ‘radius’ whether the data has been normalized.
summary(prc_n$radius)
The results show that the data has been normalized. Do try with the other variables such as perimeter, area etc.
Creating training and test data set
The kNN algorithm is applied to the training data set and the results are verified on the test data set.
For this, we would divide the data set into 2 portions in the ratio of 65: 35 (assumed) for the training and test data set respectively. You may use a different ratio altogether depending on the business requirement!
We shall divide the prc_n data frame into prc_train and prc_test data frames
prc_train <- prc_n[1:65,] prc_test <- prc_n[66:100,]
A blank value in each of the above statements indicate that all rows and columns should be included.
Our target variable is ‘diagnosis_result’ which we have not included in our training and test data sets.
prc_train_labels <- prc[1:65, 1] prc_test_labels <- prc[66:100, 1] #This code takes the diagnosis factor in column 1 of the prc data frame and on turn creates prc_train_labels and prc_test_labels data frame.
Step 3 – Training a model on data
The knn () function needs to be used to train a model for which we need to install a package ‘class’. The knn() function identifies the k-nearest neighbors using Euclidean distance where k is a user-specified number.
You need to type in the following commands to use knn()
install.packages(“class”) library(class)
Now we are ready to use the knn() function to classify test data
prc_test_pred <- knn(train = prc_train, test = prc_test,cl = prc_train_labels, k=10)
The value for k is generally chosen as the square root of the number of observations.. To ensure this, we need to use the CrossTable() function available in the package ‘gmodels’.
We can install it using:
install.packages("gmodels")
The test data consisted of 35 observations. Out of which 5 cases have been accurately predicted (TN->True Negatives) as Benign (B) in nature which constitutes 14.3%. Also, 16 out of 35 observations were accurately predicted (TP-> True Positives) as Malignant (M) in nature which constitutes 45.7%. Thus a total of 16 out of 35 predictions where TP i.e, True Positive in nature.
There were no cases of False Negatives (FN) meaning no cases were recorded which actually are malignant in nature but got predicted as benign. The FN’s if any poses a potential threat for the same reason and the main focus to increase the accuracy of the model is to reduce FN’s.
There were 14 cases of False Positives (FP) meaning 14 cases were actually benign in nature but got predicted as malignant.
The total accuracy of the model is 60 %( (TN+TP)/35) which shows that there may be chances to improve the model performance
Step 5 – Improve the performance of the model
This can be taken into account by repeating the steps 3 and 4 and by changing the k-value. Generally, it is the square root of the observations and in this case we took k=10 which is a perfect square root of 100.The k-value may be fluctuated in and around the value of 10 to check the increased accuracy of the model. Do try it out with values of your choice to increase the accuracy! Also remember, to keep the value of FN’s as low as possible.
End Notes
For practice purpose, you can also solicit a dummy data set and execute the above mentioned codes to get a taste of the kNN algorithm. The results may not be that precise taking into account the nature of data but one thing for sure: the ability to understand the CrossTable() function and to interpret the results is what we should achieve.
In this article, I’ve explained kNN algorithm using an interesting example and a case study where I have demonstrated the process to apply kNN algorithm in building models.
Did you find this article helpful? Please share your opinions / thoughts in the comments section below.
This article was originally written by Payel Roy Choudhury, before Kunal did his experiment to set the tone. Payel has completed her MBA with specialization in Analytics from Narsee Monjee Institute of Management Studies (NMIMS) and is currently working with ZS Associates. She is looking forward to contribute regularly to Analytics Vidhya.
Leave a Reply Your email address will not be published. Required fields are marked * | https://www.analyticsvidhya.com/blog/2015/08/learning-concept-knn-algorithms-programming/ | CC-MAIN-2022-21 | refinedweb | 2,062 | 52.49 |
Unified abstraction for handling xls, xlsx and CSV files in Python
Project description
# TableReader
TableReader is an unified abstraction for handling xls, xlsx and CSV files in Python. It also reads csv tables as unicode on request.
If you are familiar with csv.DictReader from the standard library, think of TableReader as DictReader on steroids.
from tablereader import TableReader reader = TableReader("some_input.xlsx", sheet="The Data") for row in reader: print row['valuecolumn']
In case you have csv and need unicode support:
reader = TableReader("unicode_input.csv", force_type="unicodecsv") for row in reader: print row['valuecolumn']
If you want to strip out leading and trailing spaces while reading rows, you can:
reader = TableReader("input_with_whitespaces.csv", strip_whitespaces=True) for row in reader: print row['valuecolumn']
And if for some reason you have a file with wrong type by line-ending (commonly found when sharing xls), override auto-detection:
reader = TableReader("wrong_named.xls", force_type="xlsx") for row in reader: print row['valuecolumn']
Sometimes headers are not in the first line. So specify some header row search text and the entire row will be used as column name and all rows after are returned:
from tablereader import OffsetTableReader reader = OffsetTableReader("wrong_named.xls", "BEGIN_DATA") for row in reader: print row['valuecolumn']
The library has been tested on CPython 2.6, 2.7 and 3.4 as well as PyPy 2.4.1.
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/tablereader/1.1.0/ | CC-MAIN-2022-40 | refinedweb | 250 | 56.45 |
Lee Gentry6,364 Points
Bummer! We expected repeat("hi", 5) to print "hi" 5 times, but instead we got "hihihihihi"!
I've slammed my head against this challenge for the past two hours and can't figure out what is being asked of me.
I tried all different types of formatting... puts over print... I tried printing out from different parts of the method...
There wasn't even any reference to the string "hi" or the times integer needing to be at 5 in the challenge to begin with. What's that about?
I'm guessing it's something syntactically minor, but I couldn't even figure out how to google my way out of this one.
What am I doing wrong?
- Lee
def repeat(string, times) string = "hi" times = 5 counter = 0 loop do print(string) counter += 1 if counter == times break end end end
1 Answer
Jennifer NordellTreehouse Staff
Hi there! Would it be comforting to know that you're actually doing splendidly? Your syntax and logic are spot on! Seriously, they are. However, you are resetting the values that Treehouse is sending in. They're going to determine the value of string and the value of times.
So if I simply remove:
string = "hi" times = 5
... your code passes with flying colors! You can think of parameters in the definition of a function or method as local variable declarations. They are going to accept some piece of information from another piece of code. Something is going to send in the string they want to be printed and the number of times to be printed. By hard coding those values your code will always print out "hi" exactly 5 times. But if we keep it more generic then another piece of code can send in "Lee" and 10 and it will print out "Lee" ten times.
Hope this helps clarify things!
Lee Gentry6,364 Points
Lee Gentry6,364 Points
Thank you, Jennifer! Comforting and informative! ????? | https://teamtreehouse.com/community/-bummer-we-expected-repeathi-5-to-print-hi-5-times-but-instead-we-got-hihihihihi | CC-MAIN-2020-05 | refinedweb | 327 | 76.22 |
Creating REST Microservices with Javalin
Last modified: August 16, 2019
1. Introduction
Javalin is a lightweight web framework written for Java and Kotlin. It's written on top of the Jetty web server, which makes it highly performant. Javalin is modeled closely off of koa.js, which means it's written from the ground up to be simple to understand and build on.
In this tutorial, we'll walk through steps of building a basic REST microservice using this light framework.
2. Adding Dependencies
To create a basic application, we only need one dependency – Javalin itself:
<dependency> <groupId>io.javalin</groupId> <artifactId>javalin</artifactId> <version>1.6.1</version> </dependency>
The current version can be found here.
3. Setting up Javalin
Javalin makes setting up a basic application easy. We're going to start by defining our main class and setting up a simple “Hello World” application.
Let's create a new file in our base package called JavalinApp.java.
Inside this file, we create a main method and add the following to set up a basic application:
Javalin app = Javalin.create() .port(7000) .start(); app.get("/hello", ctx -> ctx.html("Hello, Javalin!"));
We're creating a new instance of Javalin, making it listen on port 7000, and then starting the application.
We're also setting up our first endpoint listening for a GET request at the /hello endpoint.
Let's run this application and visit to see the results.
4. Creating a UserController
A “Hello World” example is great for introducing a topic, but it isn't beneficial for a real application. Let's look into a more realistic use case for Javalin now.
First, we need to create a model of the object we're working with. We start by creating a package called user under the root project.
Then, we add a new User class:
public class User { public final int id; public final String name; // constructors }
Also, we need to set up our data access object (DAO). We'll use an in-memory object to store our users in this example.
We create a new class in the user packaged called UserDao.java:
class UserDao { private List<User> users = Arrays.asList( new User(0, "Steve Rogers"), new User(1, "Tony Stark"), new User(2, "Carol Danvers") ); private static UserDao userDao = null; private UserDao() { } static UserDao instance() { if (userDao == null) { userDao = new UserDao(); } return userDao; } Optional<User> getUserById(int id) { return users.stream() .filter(u -> u.id == id) .findAny(); } Iterable<String> getAllUsernames() { return users.stream() .map(user -> user.name) .collect(Collectors.toList()); } }
Implementing our DAO as a singleton makes it easier to use in the example. We could also declare it as a static member of our main class or use dependency injection from a library like Guice if we wanted to.
Finally, we want to create our controller class. Javalin allows us to be very flexible when we declare our route handlers, so this is only one way of defining them.
We create a new class called UserController.java in the user package:
public class UserController { public static Handler fetchAllUsernames = ctx -> { UserDao dao = UserDao.instance(); Iterable<String> allUsers = dao.getAllUsernames(); ctx.json(allUsers); }; public static Handler fetchById = ctx -> { int id = Integer.parseInt(Objects.requireNonNull(ctx.param("id"))); UserDao dao = UserDao.instance(); User user = dao.getUserById(id); if (user == null) { ctx.html("Not Found"); } else { ctx.json(user); } }; }
By declaring the handlers as static, we ensure that the controller itself holds no state. But, in more complex applications, we may want to store state between requests, in which case we'd need to remove the static modifier.
Also note that unit testing is harder with static methods, so if we want that level of testing we will need to use non-static methods.
5. Adding Routes
We now have multiple ways of fetching data from our model. The last step is to expose this data via REST endpoints. We need to register two new routes in our main application.
Let's add them to our main application class:
app.get("/users", UserController.fetchAllUsernames); app.get("/users/:id", UserController.fetchById);
After compiling and running the application, we can make a request to each of these new endpoints. Calling will list all users and calling will get the single User JSON object with the id 0. We now have a microservice that allows us to retrieve User data.
6. Extending Routes
Retrieving data is a vital task of most microservices.
However, we also need to be able to store data in our datastore. Javalin provides the full set of path handlers that are required to build services.
We saw an example of GET above, but PATCH, POST, DELETE, and PUT are possible as well.
Also, if we include Jackson as a dependency, we can parse JSON request bodies automatically into our model classes. For instance:
app.post("/") { ctx -> User user = ctx.bodyAsClass(User.class); }
would allow us to grab the JSON User object from the request body and translate it into the User model object.
7. Conclusion
We can combine all of these techniques to make our microservice.
In this article, we saw how to set up Javalin and build a simple application. We also talked about how to use the different HTTP method types to let clients interact with our service.
For more advanced examples of how to use Javalin, be sure to check out the documentation.
Also, as always, the code can be found over on GitHub. | https://www.baeldung.com/javalin-rest-microservices | CC-MAIN-2021-17 | refinedweb | 910 | 57.87 |
So, i thought that is a good idea to take a copy of all the interesting threads on varius forums, just in case they shut down. doing it manually is waste of time. so, i went coding and make a crawler. after spending a couple of hours, i have now made a crawler that reads lines from a txt file, and downloads pages into folders from that.
code is here: Forum crawler.py
or here:
import urllib2 import re import os def isodd(num): return num & 1 and True or False #open data about what to rip file0 = open("Forum threads/threads.txt",'r') #assign data to var data0 = file0.readlines() #hard var number = 0 #skip odd numbers for line in data0: #if it is even, then set first var, and continue if not isodd(number): outputfolder = line outputfolder = outputfolder[:-1] number = number+1 continue #get thread url and remove last chars (linebreak + if isodd(number): threadurl = line threadurl = threadurl[:-2] number = number+1 print "starting to crawl thread "+threadurl #create folder if not os.path.isdir("Forum threads/"+outputfolder): os.makedirs("Forum threads/"+outputfolder) #var introduction lastdata2 = "ijdsfijkds" lastdata = "kjdsfsa" #looping over all the pages for page in range(999): #range starts at 0, so +1 is needed response = urllib2.urlopen(threadurl+str(page+1)) #assign the data to a var page_source = response.read() #used for detection of identical output #replace data in var2 lastdata2 = lastdata #load new data into var1 lastdata = page_source #check if they are identical if page>0: if lastdata == lastdata2: print "data identical, stopping loop" break #alternative check, check len if page>0: if len(lastdata) == len(lastdata2): print "length identical, stopping loop" break #used for detection of identical output #create a file for each page, and save the data in it output = open("Forum threads/"+outputfolder+"/"+str(page+1)+".html",'w') output.write(page_source) #progress print "wrote page "+str(page+1)+" in "+outputfolder+"/" print "length of file is "+str(len(page_source))
1
1 | http://emilkirkegaard.dk/en/?p=3584 | CC-MAIN-2016-44 | refinedweb | 329 | 57.71 |
Hi guys,
I am trying to count the number of words in a sentence. My method of doing this is as follows;
1.Accept a sentence from the user using System.in
2.Scan the user input and store as a String.
3.Scan the String.
4.Enter while loop that is entered as long as the sentence has another String.
Within while loop;
5.Next word in sentence is stored as a String.
6.Get length of that word.
7.Create a substring minus the previous word.
8.Increment an int variable to count the words.
Hers's my code;
import java.util.Scanner;//Imports Scanner class
public class Test//Start of public class
{
public static void main(String[] args)//Start of main method
{
Scanner input = new Scanner(System.in);//Sets up new Scanner object. Reads from system
System.out.print("user: Tell me about yourself"); //Creates input from system
String Sentence = input.nextLine();//Store input as a String
Scanner sentence = new Scanner(Sentence);//Scan that String
int wordcount = 0;
int length;
int fullLength;
while(sentence.hasNext())
{
String word = sentence.next();//Store next word in sentence as a String
length = word.length();//Get length of that word
fullLength = Sentence.length();//Length of full sentence
Sentence = Sentence.substring(length+1, fullLength);//Create new sentence minus the previous word
wordcount++;//Increment int variable
}
System.out.println("This sentence has "+wordcount+" words");
System.exit(0);
}
}
My problem is I get an outOfBounds exception when creating the substring. I can't see how this is as the begin and end index are within the length of the String.
Any help would be much appreciated.
Kind Regards,
DD. | http://www.javaprogrammingforums.com/%20whats-wrong-my-code/14478-substring-stringindexoutofboundsexception-printingthethread.html | CC-MAIN-2013-48 | refinedweb | 274 | 62.85 |
MooseX::Role::Pluggable - add plugins to your Moose classes
version 0.04
package MyMoose; use Moose; with 'MooseX::Role::Pluggable'; my $moose = MyMoose->new({ plugins => [ 'Antlers' , 'Tail' , '+After::Market::GroundEffectsPackage' ] , # other args here }); foreach my $plugin ( @{ $moose->plugin_list } ) { if ( $plugin->can( 'some_method' )) { $plugin->some_method(); } } # call a method in a particular plugin directly # (plugin_hash() returns a hash ref of 'plugin_name => plugin') $moose->plugin_hash->{Antlers}->gore( $other_moose ); # plugins are indexed by the name that was used in the original 'plugins' list $moose->plugin_hash->{After::Market::GroundEffectsPackage}->light_up(); # see the documentation for MooseX::Role::Pluggable::Plugin for info on # how to write plugins...
This is a role that allows your class to consume an arbitrary set of plugin modules and then access those plugins and use them to do stuff.
Plugins are loaded based on the list of plugin names in the 'plugins' attribute. Names that start with a '+' are used as the full name to load; names that don't start with a leading '+' are assumed to be in a 'Plugins' namespace under your class name. (E.g., if your app is 'MyApp', plugins will be loaded from 'MyApp::Plugin').
NOTE: Plugins are lazily loaded -- that is, no plugins will be loaded until either the 'plugin_list' or 'plugin_hash' methods are called. If you want to force plugins to load at object instantiation time, your best bet is to call one of those method right after you call 'new()'.
Plugin classes should consume the 'MooseX::Role::Pluggable::Plugin' role; see the documentation for that module for more information.
MooseX::Role::Pluggable - add plugins to your Moose classes
Returns a hashref with a mapping of 'plugin_name' to the actual plugin object.
Returns an arrayref of loaded plugin objects. The arrayref will have the same order as the plugins array ref passed in during object creation.
Looks for a method named $method_name in each plugin in the plugin list. If a method of given name is found, it will be run. (N.b., this is essentially the
foreach loop from the "SYNOPSIS".)
John SJ Anderson,
genehack@genehack.org
MooseX::Role::Pluggable::Plugin, MooseX::Object::Pluggable, Object::Pluggable. | http://search.cpan.org/~genehack/MooseX-Role-Pluggable/lib/MooseX/Role/Pluggable.pm | CC-MAIN-2014-23 | refinedweb | 352 | 52.8 |
dgaudet 98/04/08 18:28:58
Modified: . STATUS
Log:
I, too, retract my votes, opinions, and plans regarding 1.3.
Revision Changes Path
1.282 +14 -52 apache-1.3/STATUS
Index: STATUS
===================================================================
RCS file: /export/home/cvs/apache-1.3/STATUS,v
retrieving revision 1.281
retrieving revision 1.282
diff -u -r1.281 -r1.282
--- STATUS 1998/04/09 00:42:54 1.281
+++ STATUS 1998/04/09 01:28:57 1.282
@@ -15,7 +15,7 @@
or not, and if not, what changes are needed to make it right.
Approve guidelines as written:
- +1: Dean, Paul, Jim, Martin, Ralf, Randy, Brian, Ken
+ +1: Paul, Jim, Martin, Ralf, Randy, Brian, Ken
+0:
-1:
@@ -195,15 +195,12 @@):
+ * uri issues
- RFC2068 requires a server to recognize its own IP addr(s) in dot
notation, we do this fine if the user follows the dns-caveats
documentation... we should handle it in the case the user doesn't ever
@@ -233,11 +230,11 @@
ap_xxx: +1: Ken, Brian, Ralf, Martin, Paul, Randy
- Public API functions (e.g., palloc)
- ap_xxx: +1: Ralf, Dean, Randy, Martin, Brian, Paul
+ ap_xxx: +1: Ralf, Randy, Martin, Brian, Paul
- Private functions which we can't make static (because of
cross-object usage) but should be (e.g., new_connection)
- ap_xxx: +1: Dean, Randy, Martin, Brian, Paul
+ ap_xxx: +1: Randy, Martin, Brian, Paul
-0: Ralf
apx_xxx: +1: Ralf
appri_xxx: +0: Ralf
@@ -246,7 +243,7 @@
status_module) which are used special in Configure,
mod_so, etc and have to be exported:
[CANNOT BE DONE AUTOMATICALLY BY RENAME.PL!]
- ..._module:+1: Dean
+ ..._module:+1:
+0: Ralf
ap_xxx: +1:
-0: Ralf
@@ -293,32 +290,6 @@
the user while still providing the private
symbolspace.
- - Dean: [Use ap_ only].
-
- Furthermore, nobody has explained just what happens when
- functions which are "part of the API", such as palloc
- suddenly get moved to libap and are no longer "part of
- the API". Calling it apapi_palloc is foolish. The name
- "ap_palloc" has two prefixes for those not paying attention,
- the first "ap_" protects apache's namespace. The next,
- "p" indicates it is a pool function. Similarly we would
- have "ap_table_get". There's no need to waste space with
- "apapi_table_get", the "api" part is just redundant.
-
- If folks can't figure out what is in the api and what
- isn't THEN IT'S IS A DOCUMENTATION PROBLEM. It's not
- a code problem. They have to look in header files or
- other docs anyhow to learn how to use a function, so why
- should they repeatedly type apapi ?
-
- ap_ is a name space protection mechanism, it is not a
- documentation mechanism.
-
- Randy: I agree with Dean 100%. The work created to
keep this straight far outweighs any gain this
could give.
@@ -342,14 +313,7 @@
background of our cognitive model of the source code).
*.
+ it a lot.
* The binary should have the same name on Win32 and UNIX.
+1: Ken
@@ -362,15 +326,15 @@
* Maybe a http_paths.h file? See
<Pine.BSF.3.95q.971209222046.25627D-100000@valis.worldgate.com>
- +1: Dean, Brian, Paul, Ralf, Martin
+ +1: Brian, Paul, Ralf, Mart
+ * root's environment is inherited by the Apache server. Jim & Ken
+ think we should recommend using 'env' to build the
appropriate environment. Marc and Alexei don't see any
big deal. Martin says that not every "env" has a -u flag.
@@ -381,13 +345,11 @@
Apache should be sending 200 *and* Accept-Ranges.
* Marc's socket options like source routing (kill them?)
- Marc, Dean, Martin say Yes
+ Marc, Martin say Yes
* Ken's PR#1053: an error when accessing a negotiated document
explicitly names the variant selected. Should it do so, or should
the base input name be referenced?
- Dean says: doesn't seem important enough to be in the STATUS...
- it's probably a pain to fix.
* Proposed API Changes:
@@ -396,7 +358,7 @@
field is r->content_languages. Heck it's not even mentioned in
apache-devsite/mmn.txt when we got content_languages (note the s!).
The proposal is to remove r->content_language:
- Status: Dean +1, Paul +1, Ralf +1, Ken +1
+ Status: Paul +1, Ralf +1, Ken +1
- child_exit() is redundant, it can be implemented via cleanups. It is
not "symmetric" in the sense that there is no exit API method to go
@@ -405,7 +367,7 @@
mod_mmap_static, and mod_php3 for example). The proposal is to
remove the child_exit() method and document cleanups as the method of
handling this need.
- Status: Dean +1, Rasmus +1, Paul +1, Jim +1,
+ Status: Rasmus +1, Paul +1, Jim +1,
Martin +1, Ralf +1, Ken +1
* Don't wait for WIN32: It's been quite some time and WIN32 doesn't seem
@@ -415,7 +377,7 @@
Proposal: the next release should be named 1.3.0 and should be labelled
"stable on unix, beta on NT".
- +1: Dean
+ +1:
-0: Ralf (because we've done a lot of good but new stuff
in 1.3b6-dev now and we should give us at least
one pre-release before the so-called "release" [1.3.0].
@@ -429,7 +391,7 @@
candidate on unix, beta on NT". The release after that will be
called 1.3.0 "stable on unix, beta on NT".
+1: Jim, Ralf, Randy, Brian, Martin
- +0: Dean
+ +0:
Notes:
Randy: APACI should go in a beta release if it is to go in at all. | http://mail-archives.apache.org/mod_mbox/httpd-cvs/199804.mbox/%3C19980409012859.7109.qmail@hyperreal.org%3E | CC-MAIN-2017-17 | refinedweb | 889 | 74.49 |
mknod, mknodat - make directory, special file, or regular file
[XSI]
#include <sys/stat.h>#include <sys/stat.h>
int mknod(const char *path, mode_t mode, dev_t dev);
[OH]
#include <fcntl.h>#include <fcntl.h> -1 and set errno to indicate the error. If -1 is returned, the new file shall not be created..
None.
chmod, creat, exec, fstatat, mkdir, mkfifo, open, umask
XBD <fcntl.h>, <sys/stat mknodat()388 [324], XSH/TC1-2008/0389 [461], XSH/TC1-2008/0390 [146,435], XSH/TC1-2008/0391 [278], and XSH/TC1-2008/0392 [278] are applied.
POSIX.1-2008, Technical Corrigendum 2, XSH/TC2-2008/0222 [591], XSH/TC2-2008/0223 [817], XSH/TC2-2008/0224 [822], XSH/TC2-2008/0225 [817], and XSH/TC2-2008/0226 [591] are applied.
return to top of pagereturn to top of page | https://pubs.opengroup.org/onlinepubs/9699919799/functions/mknod.html | CC-MAIN-2019-47 | refinedweb | 137 | 67.86 |
int fgetpos( FILE *fp, fpos_t *pos )
FILE *fp; /* input stream pointer */
fpos_t *pos; /* structure to hold file position information */
Synopsis
#include "stdio.h"
The fgetpos function retrieves the current position from fp and stores it into the structure pointed to by pos . This value may be subsequently used by fsetpos .
Parameters
fp is an open file stream. pos is the address of a file position structure (fpos_t is defined in stdio.h).
Return Value
fgetpos returns 0 if successful, and a non-zero value if not.
The fpos_t type is provided for recording file positions, where the possible length of the file is too large to be represented in a long integer.
See Also
fsetpos
Help URL: | http://silverscreen.com/idh_silverc_compiler_reference_fgetpos.htm | CC-MAIN-2021-21 | refinedweb | 117 | 65.42 |
Apollo is a huge step towards making GraphQL easy to use, but there's still a lot that needs to be done manually. Loading data, executing mutations, writing your GraphQL schema, etc. all require some boilerplate.
In this article, I explain how VulcanJS approaches this and tries to make your life easier by providing some sensible defaults:
This is excellent, and something that I and probably many others have been looking for.
Could this be the answer to Apollo integration and 1.5 release - will it happen anytime soon??
I'm also wondering whether it would be better if MDG comes up with Meteor integration with Apollo as mentioned by @hwillson in July 2016 in Great News: Meteor/Apollo Integration Coming in 1.5 in which @benjamn is quoted as saying:
the current plan for Meteor 1.5 is to focus on Apollo/GraphQL integration, in order to support databases other than Mongo (among other important goals)
I've read the article yesterday, it was a very nice read and definitely a good direction.
As long as it's not a front-end agnostic answer (like Vulcan being tied up to React), it will be only a partial answer, so I expect from official Apollo/Meteor integration something different.
I've had a quick look at the code to look for use of meteor/apollo as described in:
Would it be better to use it, considering that it is an official package by Apollo developers?Or were there reasons not to use it?
Since that time, we've changed the plans, as you can hear if you listen to some of the recent podcasts etc - Meteor as a project is not going to focus on Apollo integration in the near future, and instead is going to focus on the needs of current Meteor developers, most of which we have found are not that interested in Apollo yet.
Vulcan does use this integration, and in fact Vulcan contributors are some of the main maintainers of meteor/apollo!
meteor/apollo
I heard @sacha is already building some projects on Vulcan, so it could be something cool to try if you're looking for convenience!
What I noticed in particular is that the Vulcan code declares createMeteorNetworkInterface at
createMeteorNetworkInterface
instead of importing it like:
import { createMeteorNetworkInterface, meteorClientConfig } from 'meteor/apollo'
as shown in
I couldn't find any import from 'meteor/apollo'` in the code. So it appears that it does not use it.
from 'meteor/apollo'
The chronology of things is more or less that @loren worked on the first version of the meteor-apollo package, but then we realized that it didn't quite do what we wanted, so @xavcz worked on building our own integration instead. Since then he's become the main maintainer for the package, and he's been applying what he learned working on Vulcan towards improving the package.
meteor-apollo
So although right now Vulcan doesn't use the meteor-apollo package, both are basically being developed by the same person, and I expect they'll converge pretty soon.
Also just to be clear, the meteor-apollo package only sets up the Apollo infrastructure, it doesn't include the extra utilities that Vulcan provides.
So I believe Vulcan is the closest thing to a "Meteor/Apollo integration" in the sense of making Apollo as easy to use as pub/sub in Meteor apps.
That's great to hear and I'm looking forward to it.
It also appears that @xavcz has been working on:
So could the starter kit be a first stepping stone for beginners, and when they are ready to move onto developing a fully-featured app for the real world they can look at Vulcan?
Would you continue to rename everything from Telescope and nova to Vulcan? I still see the old names in GitHub and Vulcan documentation, which could cause confusion.
@sacha do you think it would be possible to use some of your Apollo-related packages with different view layer?
I don't think they're really comparable. The starter kit is a minimal example meant to get you to understand how Meteor, Apollo, GraphQL, and React all work together by looking at the code. On the other hand Vulcan is a set of APIs built on top of all this. In other words it's a bit like comparing Ruby and Rails, building an app with Rails is going to be a lot easier for a beginner even if the Rails codebase itself is a lot more complex than a Ruby starter app.
And yes we're eventually going to rename everything to Vulcan, we're just taking our time
Not really, sorry. They're pretty tied to React. On the other hand you can reuse the same concepts.
Well, it was worth trying. I'll investigate reusing the concepts then.
I already have to say I love you for the superb comments on the code. This is brilliant, all developers should follow this example. | https://forums.meteor.com/t/article-five-ways-vulcan-makes-apollo-even-better/35007 | CC-MAIN-2017-26 | refinedweb | 835 | 58.82 |
I just saw an amusing example of JSF 2.0 on Jim Driscoll's blog. He's creating a simple output-only component to display some text in yellow, using an inline CSS style. To make things 'simpler' (my quotes) he's using JSF.
Here's his JSF page:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ""> <html xmlns="" xmlns: <h:head> <title>Yellow Text Example</title> </h:head> <h:body> <h1>Editable Text Example</h1> <h:form <ez:out <p><h:commandButton</p> <h:messages/> </h:form> </h:body> </html>
Not too bad ... the relevant part is
<ez:out, that's the reference to his Out component inside his simpleout library. JSF puts a lot of interpretation into the namespace URLs.
On the other hand, the implementation of this simple component seems a bit out of hand:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ""> <html xmlns="" xmlns: <head> <title>This will not be present in rendered output</title> </head> <body> <composite:interface <composite:attribute </composite:interface> <composite:implementation> <h:outputText </composite:implementation> </body> </html>
You can kind of vaguely see, inside all that clutter, what the component is doing. I'm personally troubled by
name="yellowOut" ... is the component's name "out" or "yellowOut"? Also, compared to the Tapestry version coming up, you can see that a few nods to visual builder tools are included.
So, what does the Tapestry equivalent look like?
Well, our page template would look something like*:
<html xmlns: <head> <title>Yellow Text Example (Tapestry)</title> </head> <body> <h1>Yellow Text Example</h1> <t:form t: <t:out <p><input type="submit" value="reload"/></p> </t:form> </body> </html>
The Tapestry namespace identifies elements and attributes that are not truly HTML, but controlled by Tapestry. This includes built-in Tapestry components such as Form as well as user-defined components such as Out.
The Out component itself is in two parts: a Java class to define the parameters (and, in a real world example, provide other logic and properties) and a matching template to perform output**. First the class:
package org.example.myapp.components; import org.apache.tapestry5.BindingConstants; import org.apache.tapestry5.annotations.*; public class Out { @Property @Parameter(defaultPrefix = BindingConstants.LITERAL) private String value; }
The @Parameter annotation on the value field marks the field as a parameter. The defaultPrefix attribute is configured to indicate that, by default, the binding expression (the value attribute inside the page template) should be interpreted as a literal string (as opposed to the normal default, a property expression).
The @Property annotation directs Tapestry to provide a getter and setter method for the field, so that it can be accessed from the template.
<span style="background-color: yellow">${value}</span>
Again, this is a trivial example. We didn't even have to define the Tapestry namespace for this template. The
${value} is an expansion which outputs the value property of the Out component instance, which itself is the literal string ("Test Value") bound to the Out component's value parameter.
Let's add a little improvement: If the value is null or empty, don't even render the <span> tag. This is accomplished in one of two ways.
First, we can change the template slightly, to turn the <span> tag into an If component that renders a span tag:
<span t:${value}</span>
The If component evaluates its test parameter and if true, renders its tag (the <span> in this case), its non-Tapestry attributes (style) and its body (
${value}).
Alternately, we can leave the template alone and abort the component's render in the Java class:
boolean beforeRenderTemplate() { return ! (value == null || value.equals("")); }
This is a Tapestry render phase method, a kind of optional callback method that can control how the component is rendered. We return true to render normally, and false to skip the template rendering. Tapestry invokes this method at the right time based on a naming convention, though an annotation can be used if that is more to your taste.
This is a good example of how Tapestry really cuts to the chase relative to other frameworks. Both the usage of the component and its definition are simple, concise and readable. Further, Tapestry components can scale up nicely, adding sub-components in the template, and more properties and logic in the Java class. Finally, we can also see a hint of how Tapestry relieves you of a lot of low-level drudgery, such as using the @Property annotation rather than writing those methods by hand (Tapestry has a wide ranging set of such meta-programming tools built in).
* I'm not sure why the original version used a form, but I've dutifully recreated that here.
** For a component this simple I'd normally not bother with a template and do it all in code.
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}{{ parent.urlSource.name }} | https://dzone.com/articles/simple-jsf-20-component-vs-tap | CC-MAIN-2019-35 | refinedweb | 816 | 54.32 |
Having.
Problem: there is no simple equivalent to ‘re.findall’ in JS. re.findall goes like this:
from re import findall textvar = getsometext() list_of_matches = findall('^foo\.([\S])+?', textvar)
The convenient part is that this is a very common operation to want to make, and there is a nice function that directly handles this requirement and returns the results. PHP is slightly less direct:
$matches = array(); preg_match_all('/^foo\.([\S])+?/', $textvar, $matches, PREG_SET_ORDER);
Slightly more obtuse; I tend to wrap this in a function called ‘findAll()’ in a base class somewhere.
JavaScript is a bit more work again ( as suggested by the Rhino book ):
var rx = new RegExp("^foo\.([\S])+?", "g"); var matches = new Array(); while((match = rx.exec(textvar)) !== null){ matches.push(match); }
You could do this in a slightly different way off of the String object:
var matches = textVar.match(/^foo\.([\S])+?/g);
…but you only get the outer match, no the sub-matches from the parentheses. =/ | https://www.activestate.com/blog/javascript-refindall-workalike/ | CC-MAIN-2020-16 | refinedweb | 157 | 65.83 |
On Wed, Feb 18, 2004 at 02:21:36PM +1100, Benjamin Herrenschmidt wrote: > > Hi need people who own those machiens, especially the recent iBook2 models > with a G3 CPU and titanium powerbooks with a G4, to test this patch and > tell me if sleep mode still works reliably or becomes unstable. [snip] > ===== arch/ppc/kernel/l2cr.S 1.15 vs edited ===== > --- 1.15/arch/ppc/kernel/l2cr.S Tue Oct 14 17:28:01 2003 > +++ edited/arch/ppc/kernel/l2cr.S Wed Feb 18 14:14:33 2004 > @@ -130,11 +130,13 @@ > mtspr HID0,r4 /* Disable DPM */ > sync > > +#if 0 > /* Flush & disable L1 */ > mr r5,r3 > bl __flush_disable_L1 > mr r3,r5 > - > +#endif > + > /* Get the current enable bit of the L2CR into r4 */ > mfspr r4,L2CR > > @@ -236,8 +238,10 @@ > sync > > 4: > - bl __inval_enable_L1 > > +#if 0 > + bl __inval_enable_L1 > +#endif > /* Restore HID0[DPM] to whatever it was before */ > sync > mtspr 1008,r8 Are you sure that you can get away with this, passed on how the manuals (745x) describe the sequence of flush/invalidating the L2 (and, L3) ? -- Tom Rini | https://lists.debian.org/debian-powerpc/2004/02/msg00565.html | CC-MAIN-2014-10 | refinedweb | 178 | 51.55 |
This add-on is operated by Keen Labs Inc
Analytics for Developers
Keen IO
Last updated 24 August 2016
Table of Contents.
Keen IO is accessible via an API and has supported client libraries for Java, Ruby, Python, and Node.js.
Provisioning the add-on
Keen IO can be attached to a Heroku application via the CLI:
$ heroku addons:create keen -----> Adding keen to sharp-mountain-4005... done, v18 (free)
A list of all plans available can be found here.
Once Keen IO has been added, a number of environment variables/settings will be available for your app configuration. They are:
KEEN_PROJECT_ID- The Project ID generated for your add-on.
KEEN_WRITE_KEY- The Write Key generated for your add-on.
KEEN_READ_KEY- The Read Key generated for your add-on.
KEEN_API_URL- The URL to make API requests to.
This can be confirmed using the
heroku config:get command.
$ heroku config:get KEEN_API_URL
After installing Keen KEEN_API Keen IO config values retrieved from heroku config to your
.env file.
$ heroku config -s | grep KEEN >> .env $ more .env
Credentials and other sensitive configuration values should not be committed to source-control. In Git exclude the .env file with:
echo .env >> .gitignore.
For more information, see the Heroku Local article.
Using with Ruby/Rails 3.x
Ruby on Rails applications will need to add the following entry into their
Gemfile specifying the Keen IO client library.
gem 'keen'
Update application dependencies with bundler.
$ bundle install
Then send Keen IO an event from anywhere in your code:
Keen.publish("sign_ups", { :username => "lloyd", :referred_by => "harry" })
This will publish an event to the
username and
referred_by properties set.
Using with Python/Django
Install with pip:
$ pip install keen
Then send Keen IO an event from anywhere in your code:
import keen keen.add_event("sign_ups", { "username": "lloyd", "referred_by": "harry" })
This will publish an event to the ‘sign_ups’ collection with the
username and
referred_by properties set.
Using with Node
Install with npm:
npm install keen-js
Then send Keen IO an event from anywhere in your code:
var Keen = require('keen-js'); // Configure instance. Only projectId and writeKey are required to send data. var client = new Keen({ projectId: process.env['KEEN_PROJECT_ID'], writeKey: process.env['KEEN_WRITE_KEY'] }); client.addEvent("sign_ups", {"username": "lloyd", "referred_by": "harry"}, function(err, res) { if (err) { console.log("Oh no, an error!"); } else { console.log("Hooray, it worked!"); } });
This will publish an event to the 'sign_ups’ collection with the
username and
referred_by properties set.
Using with Java
Download the jar from.
Add it to your other external libraries.
Then send Keen IO an event from anywhere in your code:
protected void track() { // create an event to upload to Keen Map<String, Object> event = new HashMap<String, Object>(); event.put("username", "lloyd"); event.put("referred_by", "harry"); // add it to the "sign_ups" collection in your Keen Project try { KeenClient.client().addEvent("sign_ups", event); } catch (KeenException e) { // handle the exception in a way that makes sense to you e.printStackTrace(); } }
This will publish an event to the 'sign_ups’ collection with the
username and
referred_by properties set.
Admin Panel
The Keen IO Admin Panel allows you to look at the events you’ve collected and their properties. It also has an API Workbench to make constructing queries super easy.
The dashboard can be accessed via the CLI:
$ heroku addons:open keen Opening keen for sharp-mountain-4005…
or by visiting the Heroku apps web interface and selecting the application in question. Select Keen IO from the Add-ons menu.
Troubleshooting
Jump on the Keen IO Users Chat or e-mail team@keen.io!
Migrating between plans
Application owners should carefully manage the migration timing to ensure proper application function during the migration process.
Use the
heroku addons:upgrade command to migrate to a new plan.
$ heroku addons:upgrade keen:startup -----> Upgrading keen:startup to sharp-mountain-4005... done, v18 ($32/mo) Your plan has been updated to: keen:startup
Removing the add-on
Keen IO can be removed via the CLI.
This will make all associated data inaccessible. Contact support if you do this accidentally.
$ heroku addons:destroy keen -----> Removing keen from sharp-mountain-4005... done, v20 (free)
Before removing Keen IO a data export can be performed by doing an Extraction.
Support
All Keen IO support and runtime issues should be submitted via one of the Heroku Support channels. Any non-support related issues or product feedback is welcome at team@keen.io. | https://devcenter.heroku.com/articles/keen | CC-MAIN-2018-05 | refinedweb | 731 | 58.79 |
How to Use the javap Command
The javap command is called the Java disassembler because it takes apart class files and tells you what’s inside them. You won’t use this command often, but using it to find out how a particular Java statement works is fun, sometimes. You can also use it to find out what methods are available for a class if you don’t have the source code that was used to create the class.
Here is the general format:
javap filename [options]
The following is typical of the information you get when you run the javap command:
C:\java\samples>javap HelloApp Compiled from "HelloApp.java" public class HelloApp extends java.lang.Object{ public HelloApp(); public static void main(java.lang.String[]); }
As you can see, the javap command indicates that the HelloApp class was compiled from the HelloApp.java file and that it consists of a HelloApp public class and a main public method.
You may want to use two options with the javap command. If you use the -c option, the javap command displays the actual Java bytecodes created by the compiler for the class. (Java bytecode is the executable program compiled from your Java source file.)
And if you use the -verbose option, the bytecodes — plus a ton of other fascinating information about the innards of the class — are displayed. Here’s the -c output for a class named HelloApp:
C:\java\samples>javap HelloApp -c Compiled from "HelloApp.java" public class HelloApp extends java.lang.Object{ public HelloApp(); } | http://www.dummies.com/how-to/content/how-to-use-the-javap-command.navId-323185.html | CC-MAIN-2014-15 | refinedweb | 257 | 63.9 |
What are modules in Python?
Modules refer to a file containing Python statements and definitions.
A file containing Python code, for example:.
How to import modules in Python?
We can import the definitions inside a module to another module or the interactive interpreter in Python.
We use the
import keyword to do this. To import our previously defined module
example, we type the following in the Python prompt.
>>> import example
This does not import the names of the functions defined in
example directly in the current symbol table. It only imports the module name
example there.
Using the module name we can access the function using the dot
. operator. For example:
>>> example.add(4,5.5) 9.5
Python has tons of standard modules. You can check out the full list of Python standard modules and their use cases. These files are in the Lib directory inside the location where you installed Python.
Standard modules can be imported the same way as we import our user-defined modules.
There are various ways to import modules. They are listed below..
Python import statement
We can import a module using the
import statement print("The value of pi is", m.pi)
We have renamed the
math module as
m. This can save us typing time in some cases.
Note that the name
math is not recognized in our scope. Hence,
math.pi is invalid, and
m.pi is the correct implementation.
Python from...import statement
We can import specific names from a module without importing the module as a whole. Here is an example.
# import only pi from math module from math import pi print("The value of pi is", pi)
Here, we imported only the
pi attribute from the
math module.
In such cases,)
Here, we have imported all the definitions from the math module. This includes all names visible in our scope except those beginning with an underscore(private definitions). built-in module not found), Python looks into a list of directories defined in
sys.path. The search is in this order.
- The current directory.
PYTHONPATH(an environment variable with a list of directories).
- The installation-dependent default directory.
>>> import sys >>> sys.path ['', 'C:\\Python33\\Lib\\idlelib', 'C:\\Windows\\system32\\python33.zip', 'C:\\Python33\\DLLs', 'C:\\Python33\\lib', 'C:\\Python33', 'C:\\Python33\\lib\\site-packages']
We can add and more efficient way of doing this. We can use the
reload() function inside the
imp module to reload a module. We can do it in the following ways:
>>>.
We can use
dir in
example module in the following way:
>>> dir(example) ['__builtins__', '__cached__', '__doc__', '__file__', '__initializing__', '__loader__', '__name__', '__package__', 'add']
Here, we can see a sorted list of names (along with
add). All other names that begin with an underscore are default Python attributes associated with the module (not user-defined).'] | https://cdn.programiz.com/python-programming/modules | CC-MAIN-2020-24 | refinedweb | 470 | 60.41 |
The role of controllers in Angular is to expose data to our view via
$scope,
and to add functions to
$scope that contain business logic to enhance view
behavior. Presentation logic should remain within views and directives.
Let's start by creating an angular application with the following code:
<!DOCTYPE html> <html> <head> <title>AngularJS Controllers</title> <script type="text/javascript" src=""></script> <script type="text/javascript" src="app.js"></script> </head> <body> <div ng- <h1>Controllers</h1> </div> </body> </html>
The value given to the
ng-app directive tells angular what module to look for
when angular boots up, in this case our module name is
app.
Let's create our
app module in
app.js
angular.module('app', []);
The first parameter of
angular.module defines the name of the module. The
second parameter is an array that declares the module dependencies that our
module uses. Our app currently doesn't depend on any other modules.
Now, create our controller with the following code in app.js:
angular.module('app', []); angular.module('app').controller('MainCtrl', function (){ });
We register a controller with our angular module using the controller function
provided by modules. Then, the first parameter is a string that specifies the
controller name, and the second parameter is the function that represents our
controller. In order to pass data to our view, we'll need to inject
$scope
and add some data to it.
Inject
$scope to our controller by specifying it as a parameter
angular.module('app').controller('MainCtrl', function ($scope){ });
Set
$scope.message with an object:
angular.module('app').controller('MainCtrl', function ($scope){ $scope.message = 'hello'; });
Now that we have a controller ready to use, let's create a div with a paragraph that contains our message
<div ng- <h1>Controllers</h1> <div ng- <p>{{ message }}</p> </div> </div>
We can see that we can simply access variables initialized on
$scope in our
controller by using bindings. Now, let's build out some functionality to let us
manipulate the data.
Create a
updateMessage function on
$scope that updates
$scope.message,
given a message
angular.module('app').controller('MainCtrl', function ($scope){ $scope.message = 'hello'; $scope.updateMessage = function(message){ $scope.message = message; }; });
Create a form that contains an input and uses the
updateMessage function we
created.
<div ng- <p>{{ message }}</p> <form ng- <input type="text" ng- <button type="submit">Update Message</button> </form> </div>
The ng-submit directive that we used in our form tag contains an Angular expression that gets executed when the form gets submitted. When we type a message into our form and hit enter or the Update Mesage button, we can see the original message above the form get updated with the text from the input.
Controller As Syntax
While everything we've created in this example so far works fine, a
possible issue we can come accross as our application grows is when we start
nesting controllers. Since each controller gets assigned their own scope,
controllers that are nested can have trouble accessing variables from the
parent scope. Specifically when data is being read from a child controller,
where the value is directly assigned to the parent
$scope and not namespaced
within an object (accessing
$scope.data.message will work from a child
controller but accessing
$scope.message can break). The rule of thumb is to
always have a dot when referencing variables from controllers in your angular
expressions. We can enforce this by using the "controller as" syntax. This
makes it so that your controllers can be directly referenced within the view.
The "controller as" syntax is generally the preferred syntax for controllers.
Read this post on the "controller as" syntax
Now let's update our code to use the "controller as". Since our scope becomes
the
this keyword in our controller, we'll need to create a reference to
this so that we don't lose context of our controller when we create/call
functions within our controller.
Read the MDN reference
for the
this keyword in javascript
Create a reference to
this in our controller.
angular.module('app').controller('MainCtrl', function ($scope){ var self = this;
Remove
$scope from our controller dependency, and use
self instead of
$scope.
angular.module('app').controller('MainCtrl', function (){ var self = this; self.message = 'hello'; self.changeMessage = function(message){ self.message = message; }; });
Now, let's update our view to use the "controller as" syntax.
<div ng- <p>{{ main.message }}</p> <form ng- <input type="text" ng- <button type="submit">Change Message</button> </form> </div>
Now all of our variables in our Angular expressions contain a dot, and we're
able to directly reference our controllers so that when we have nested or
multiple nested controllers, we can access variables directly instead of using
$parent. | https://thinkster.io/controllers | CC-MAIN-2018-51 | refinedweb | 788 | 56.25 |
SCIM Integration
👤 This documentation is intended for Site Administrators.
The SCIM (System for Cross-Identity Management) integration allows for the synchronization of roles and permissions between Sisense for Cloud Data Teams (CDT) and Okta. The SCIM specification is an open standard designed to manage user identity information. SCIM provides a defined schema for representing users and groups, and a RESTful API to run CRUD operations on those user and group resources.
NOTE: Given that SSO/SCIM requires heavy configuration, we recommend contacting Support before you begin testing, and turning on Support Access ahead of time. With this, Support will be available to log into your system and revert SSO/SCIM changes in a more timely manner.
NOTE: SCIM is only available for Cloud Data Teams customers who have Okta SSO as their Identity Provider (IdP) and have RBAC enabled.
<LI><a href="#Before Starting Setup">Before Starting Setup</a></LI>
<LI><a href="#Assign a User to Sisense for Cloud Data Teams in Okta">Assign a User to Sisense for Cloud Data Teams in Okta</a></LI>
<LI><a href="#Add Custom Attributes to the Okta User Profile">Add Custom Attributes to the Okta User Profile</a></LI>
<LI><a href="#Enable & Configure SCIM Integration">Enable & Configure SCIM Integration</a></LI>
<LI><a href="#Configure Sign-on Method">Configure Sign-on Method/a></LI>
<LI><a href="#Provisioning Users in Okta">Provisioning Users in Okta</a></LI>
<LI><a href="#Logging In via SSO using SCIM">Logging In via SSO using SCIM</a></LI>
<LI><a href="#Deprovisioning Users">Deprovisioning Users</a></LI>
<LI><a href="#Troubleshooting">Troubleshooting</a></LI>
<LI><a href="#Example Python Script">Example Python Script</a></LI>
Before Starting Setup
- Complete the Okta SSO Integration before attempting to enable SCIM. SCIM requires that this integration is already in place and functional.
- Compile a list of existing user roles and role assignments using the User and Role Management API or the <LI><a href="#Example Python Script">Example Python Script</a></LI> to write users’ names, emails and roles to a .csv file. This information is necessary to ensure that users are set up correctly with their current role assignments.
- We do not recommend testing SCIM setup on a production environment that is business-critical. If you require a test space, please contact supportdt@sisense.com
- Setting up SCIM will require you to jump back and forth between CDT and Okta. It is suggested that you have both browser windows open throughout the process.
- The order in which you perform these actions can impact the success of your SCIM setup, so read the documentation carefully.
<a href="#top">Back to top</a>
<a name="Assign a User to Sisense for Cloud Data Teams in Okta"></a>
Assign a User to Sisense for Cloud Data Teams in Okta
In this step, you will assign the Admin user to the application, and configure the user profile in Okta, so that the user will be able to enable and configure the SCIM integration.
In the Sisense for Cloud Data Teams application, click Assignments > Assign to People.
Search for the user, and assign to the app by clicking Assign > Done.
<a href="#top">Back to top</a>
<a name="Add Custom Attributes to the Okta User Profile"></a>
Add Custom Attributes to the Okta User Profile
In Okta, go to Directory > Profile Editor in the left navigation, and select User Profile. This is the profile that will be configured for all your users.
Click Add Attribute in the Profile Editor.
In the Display name and Variable name fields, type roles, and click Save. After doing this, every user who uses this profile will have the attribute of ```roles``` available.
<a href="#top">Back to top</a>
<a name="Enable & Configure SCIM Integration"></a>
Enable & Configure SCIM Integration
Log in to CDT using the Login with SSO link.
Go to the Billing & Authentication page from the gear icon in the left navigation.
Choose your Default Space from the drop-down list of spaces and check the Enable SCIM Provisioning checkbox, and click Save.
On the Enable SCIM confirmation modal, click Enable.
A Site Host and API key string will be displayed. The API key format is “site_host:SECRET”. This API key will be used in Okta to configure the SCIM integration. Copy and store this key, as it is generated only once. If lost, a new API key will need to be generated and updated in Okta.
NOTE: Due to syncing issues, close the Copy API Key modal before testing close this modal BEFORE testing the API credentials in Okta.
Return to Okta. Click Applications > Sisense for Cloud Data Teams > To App > Provisioning. Click Edit to populate the API key, and test the integration.
Click Configure API Integration.
Click the Enable API Integration check box, which will display a field to populate the API key. Use the API key provided in the previous section, and click Test API Credentials. When you receive the success message, click Save.
Click Edit again to allow Okta to provision users to CDT.
Select the workflows you want the integration to control by checking or unchecking the boxes next to the workflows. Then click Save. You can allow Okta to:
- Create Users
- Update User Attributes
- Deactivate Users
<a href="#top">Back to top</a>
<a name="Configure Sign-on Method"></a>
Configure Sign-on Method
Within the Sisense for Cloud Data Teams app, click Sign On > Edit > Attributes.
Within the Attribute Statements, enter roles in the Name field and user.roles in the Value field . Then click Save.
<a href="#top">Back to top</a>
<a name="Provisioning Users in Okta"></a>
Provisioning Users in Okta
There are two ways users can be provisioned (synced):
- Via a user’s profile
- JIT (Just In Time)
Be aware that provisioning behavior differs from sites that use Okta SSO with SCIM enabled, and without SCIM enabled:
In Okta, go to Applications > Assignments. If the user is displayed in the list, you can click Assign. If the user is not displayed, click Assign to People and search for the user.
Identify the user you want to provision, and click Assign next to the user.
Open the user’s profile by clicking on the blue user name link under Assignments. Click Profile > Edit to display the attributes associated with that user.
The custom attribute role should be displayed at the bottom of the attribute list. Use this field to add the appropriate roles, and click Save.
Roles exist in a site's Roles and Policies page including both the Cloud Data Teams default user roles (Everyone, Admin, Analyst, and Business User) as well as custom roles. Multiple roles should be comma separated and are case sensitive. Characters entered in these fields should match the characters in application. In this way, different `roles` and `platform` can be added for different Spaces if a site has more than one Space available and can be added following the format below:
The `site-host` can be found by referencing a dashboard URL:
After saving, assigned `roles` and `platform` will be visible in the user’s profile in Okta. The user will then have access according to the `roles` and `platform` to which they have been assigned.
<a href="#top">Back to top</a>
<a name="Logging In via SSO using SCIM"></a>
Logging In via SSO using SCIM
As soon as users are provisioned in Okta, they can log in to Cloud Data Teams using the Login with SSO link.
If the user has already logged in, they may need to refresh their browser to see this change in their permissions. Provisioning through the user’s profile should allow existing Cloud Data Teams users to log in without any issue.
When a user logs in for the first time, by default, Okta will only provide the users ‘first name’, ‘last name’ and ‘email’. It will not include any roles. In this case, a user may receive a message stating that they have “No Privileges”.
The message indicates that the user is successfully able to access Cloud Data Teams via Okta with SCIM. However they have not been provisioned to any roles and therefore have no privileges. The Okta Admin will need to assign roles in Okta before the user will be able to access Cloud Data Teams successfully.
Admins may see an error associated with a user in Okta until the user logs into Cloud Data Teams. A user does not exist in Cloud Data Teams until the first the user logs into the application using SSO. This error will most likely occur after making changes to a user via their profile in Okta.
<a href="#top">Back to top</a>
<a name="Deprovisioning Users"></a>
Deprovisioning Users
If a user is removed from the Okta app or deleted in Okta, the user will also be deleted in Cloud Data Teams. Users that are deactivated in Okta won't be automatically logged out of Cloud Data Teams if they have no permissions.
However, those users will not be able to perform any actions once they are deprovisioned and will be logged out after they refresh the page or their current session is otherwise ended. Users with permissions that are deactivated in Okta will be automatically logged out.
<a href="#top">Back to top</a>
<a name="Troubleshooting"></a>
Troubleshooting
Provisioning Alerts
Admins must provide a minimum of one email address for provisioning alerts. Any errors generated during provisioning will send an email to the address(es) provided.
Error messages associated with SCIM will display a list of errors associated with the user.
Generate a New API Key
If you need to generate a new API key, open the Billing & Authentication page. Next to the SCIM API Key field, click Regenerate.
<a href="#top">Back to top</a>
<a name="Example Python Script"></a>
Example Python Script
import requests
import json
import csv
#insert site host and api_key
finished = False
next_page_start = ''
header = ['login', 'firstName', 'lastName', 'email', 'roles']
site_host = 'site host here'
#open a csv file with write access
with open('userlist25.csv', 'w') as outfile:
writer = csv.writer(outfile, delimiter=',')
writer.writerow(header)
while finished is False:
headers = {
'HTTP-X-PARTNER-AUTH':'site host here:api key here',
'Content-Type' : 'application/json'
}
url = ''+next_page_start
response = requests.get(url, headers=headers)
response = response.json()
#loop through each user in json response and grab first name, last name, and email
for line in response['users']:
user =(line['email']+','+line['first_name']+','+line['last_name']+ ','+ line['email'])
#loop through roles for each user and join roles with semi colon for easy csv output
roles = ';'.join(site_host+':'+role['name'] for role in line['roles'])
#write the user and role data together to a CSV
outfile.write('{}, {}\n'.format(user, roles))
if response['next_page_start']==None:
finished = True
else:
next_page_start = response['next_page_start'] | https://dtdocs.sisense.com/article/scim | CC-MAIN-2022-40 | refinedweb | 1,807 | 52.8 |
Shortest Common SuperSequence 【O(M*N) time complexity】
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: 35 minutes
Given two strings X and Y, the supersequence of string X and Y is such a string Z that both X and Y is subsequence of Z. in other words shortest supersequence of X and Y is smallest possible string Z such that all the alphabets of both the strings occurs in Z and in same order as of the original string.
Let's understand it with an example:
X = "opengenus" Y = "operagenes" shortest common supersequence of X and Y: z = "openragenues" and length of z is 12 we can see that both "opengenus" and "operagenes" is subsequence of "openragenues".
There can be more than one shortest common supersequence, in that case we may consider any of them as the lenght of the supersequence will be the same.
Here we will se two approachs to find the minimum lenght of common supersequence and also how to print a shortest common suersequence.
Algorithms
1. Recursive (Brute Force) approach
The method to find the shortest common supersequence is similar to that of finding the longest common subsequence. We start scanning from the left of both the string, if the current charecter matches then we add it to the supersequence and recur for the remaining strings (i.e. after skipping first charecter of both string). If the charecter doesn't matches then we take to cases, one when we add the cuurent charecter of first string to supersequence and recur for the remaining first string and complete second string, and the second is vice versa. Then we take the minimum length supersequence from the two.
As a base case when any of the string becomes empty we append the remaining string (if any) to the supersequence and return the same.
def shortestCommonSuper(str1, str2, scstr): if len(str1) == 0 or len(str2) == 0: scstr = scstr + str1[::-1] + str2[::-1] return scstr if str1[0] == str2[0]: return shortestCommonSuper( str1[1:], str2[1:], scstr + str1[0]) else: scstr1 = shortestCommonSuper( str1[1:], str2, scstr + str1[0]) scstr2 = shortestCommonSuper( str1, str2[1:], scstr + str2[0]) return scstr1 if len(scstr1) < len(scstr2) else scstr2
The recursive approach takes O(2min(m,n)) where m, n is length of the respective strings.
At each instance of the recursive function, we recur for at most 2 times and at each function call the string length is decreasing, so we have at most min(m, n) recursive calls. So overall time of the algorithm is O(2min(m, n)) in the worst case.
2. Dynamic Programming approach
Before going to the dynamic programming approach, let's understand the recursive method a bit more by partial recursion tree of a problem:
In the above partial tree we represented the repeated subproblems with same underlined colour bars. We can see that it already contains two repeated subproblems.
So the problem contains both repeated subproblems and optimal sub-structure property so we can solve it optimally with dynamic programming and memoization in O(m*n) time.]) return sc_len = dp[len(str1)][len(str2)] # for printing purpose #######
Implementations
Code in python3
import sys]) sc_len = dp[len(str1)][len(str2)] # for printing purpose scstr = [ None for _ in range(sc_len)] i, j = len(str1), len(str2) while i > 0 and j > 0 : if str1[i - 1] == str2[j - 1]: scstr[sc_len - 1] = str1[i - 1] i -= 1 j -= 1 sc_len -= 1 elif dp[i][j - 1] < dp[i - 1][j]: scstr[sc_len - 1] = str2[j - 1] j -= 1 sc_len -= 1 else: scstr[sc_len - 1] = str1[i - 1] i -= 1 sc_len -= 1 while i > 0: scstr[sc_len - 1] = str1[i - 1] i -= 1 sc_len -= 1 while j > 0: scstr[sc_len - 1] = str2[j - 1] j -= 1 sc_len -= 1 scstr = "".join(map(str, scstr)) return scstr str1 = "AGGTAB" str2 = "GXTXAYB" scstr = shortestCommonSuperDP(str1, str2) print("Length of the shortest common supersequence is:", len(scstr)) print("Shortest common supersequence is:", scstr)
Output
Length of the shortest common supersequence is: 9 Shortest common supersequence is: AGXGTXAYB
Complexity
Time Complexity
- The recursive brute force approach takes O(2min(m, n)) time.
- The Dynamice programming approach takes O(m*n) time. Where m, n are the length of the first and second string respectively.
Space complexity
- The Recursive approach takes O(m+n) auxiliary space, and stack space.
- The Dynamic Programming approach takes O(m*n) auxiliary space. | https://iq.opengenus.org/shortest-common-supersequence/ | CC-MAIN-2021-17 | refinedweb | 757 | 51.01 |
Change NumberAnimation while running
I wonder how to change the property of a NumberAnimation (say "loops" or "to") while it's running.
Of course I tried to use a variable but it has no effect. Example:
SequentialAnimation { id: anim // change rotation centers PropertyAction { target: rotSpin; property: "origin.x"; value: xCenterNeedle } PropertyAction { target: rotSpin; property: "origin.y"; value: yCenterNeedle } NumberAnimation { id: numAnim; target: rotSpin; property: "angle"; easing.type: Easing.Linear; to: _degree; duration: _time; } onStopped: {_isSpinning = false; } }
I start it:
function startSpin() { _degree += 360; _time = _timeForSector * 12; anim.loops = Animation.Infinite _isSpinning = true; anim.start() }
and now I want to change something:
function stopSpin() { if (_isSpinning) { var angle = rotSpin.angle; // current angle var currSector = Math.floor(angle / 30); // current sector numAnim.to = (currSector + 1) * 30; // angle of the next sector anim.loops = 1; // stop when reach the requested angle } }
but nothing happens.
Where's my error?
By the way, the specific goal is to stop a spinning needle on a precise angle (x * 30) when requested.
I don't know the answer to your more than one rotation... but I do know Rotations are easier with RotationAnimation QML Type - this way you can cross that 0-360 degree boundary without a full opposite wind.
I have things like:
onValueChanged: RotationAnimation { target: root; property: "rotation" easing.type: Easing.InOutSine; to:root.value; direction: RotationAnimator.Shortest; duration: 300;
Thanks, but I don't need the shortest path.
I only need to rotate an Image until a signal fires. At that moment, let's say the angle is 53 degrees, I need to stop the animation when it reaches 60 degrees.
@Mark81 said in Change NumberAnimation while running:
NumberAnimation
Well, I'm not trying to sell you! I just know that that NumberAnimation will not spin but start counting down from the number that is in your angle just before it crosses the threshold.
Your "rotate an image until a signal fires" - won't work very well when for example it's winding up / clockwise up close to a full rotation - at which point the value crosses and if the intent is keep spinning - instead for that single animation it will unwind counterclockwise, then the next update continuing to the next target clockwise.
It just looks very wrong - you do what you recon - maybe you know the value is never reaching a full rotation - but "spin" to me indicated you wish to perform one or more rotations.
I'll leave you to figure out your target angle - that math is basic - or ... maybe you could just use states
Dunno, just trying to give you leads to get moving again...
states: State { name: "SectorOne"; when: (value >= 0 && value <= 30 ) // change rotation centers PropertyAction { target: rotSpin; property: "origin.x"; value: xCenterNeedle } PropertyAction { target: rotSpin; property: "origin.y"; value: yCenterNeedle } PropertyAction { target: rotSpin; property: "angle"; value: 30 } NumberAnimation { id: numAnim; target: rotSpin; property: "angle"; easing.type: Easing.Linear; to: _degree; duration: _time; } State { name: "SectorTwo"; when: (value > 30 && value <= 60 ) // change rotation centers PropertyAction { target: rotSpin; property: "origin.x"; value: xCenterNeedle } PropertyAction { target: rotSpin; property: "origin.y"; value: yCenterNeedle } PropertyAction { target: rotSpin; property: "angle"; value: 60 } NumberAnimation { id: numAnim; target: rotSpin; property: "angle"; easing.type: Easing.Linear; to: _degree; duration: _time; }
Thanks a lot for your answer.
I will try your approach, but I'm not sure I explained the scenario very well. I'm going to try with a simpler example.
Let's image to have a stopwatch, with a single needle. When the stopwatch start, the needle begins to "spin" forever.
But when the user decides to stop it (i.e. the stopSpin() event is fired) the needle cannot just stop where it is but it has to reach the very next "hour". I.e. if the event fired when the needle was pointing to 85 degrees, it should stop ONLY when it has reached 90 degrees.
Right now I ended up with a workaround.
In the stopSpin() function I stop the animation and in the onStopped event I read the current angle of my needle. Then I start again the same animation setting the new target and duration fields to reach the desired angle.
It works (as you said, it's a matter of basic maths) but sometimes the needle stops a while before moving again. Instead the animation should be flawless.
I think you'd need to interrupt your animation. I'd be looking for a solution where you just update your target and indeed get flawless animation.
I haven't had to deal with interrupted animations - I have known baud rates and controls that are reactive (not responsive to user input) so it's easy to setup animation speeds to always complete slightly faster than my configured baud rate.
Maybe you'll find is better for you?
@6thC said in Change NumberAnimation while running:
Maybe you'll find is better for you?
I will give it a try, but unfortunately I cannot use any Easing type but the Linear one. Anyway perhaps I might find a way to use it. It's not clear to me what does the maximumEasingTime property mean. I'm going to play a little with it.
I have wanted to do similar things before but eventually decided I was expecting too much from the QML Animation types suddenly trying to get them to something else part way through an animation. I decided to just take more control instead... here's an example minute-hand clock (runs in Qt 5.9.1's qmlscene); click the window to start and stop the clock movement:
import QtQuick 2.7 Rectangle { id: main width: 512 height: 512 Rectangle { x: 0.5*parent.width y: 0.5*parent.height width: 10 height: 200 radius: 5 color: 'red' transformOrigin: Item.Top rotation: (((control.spinning ? clock.time : control.stopTime)-control.lostTime)/60.0)%360.0 } Timer { id: clock interval: 1000.0/60.0 repeat: true running: true triggeredOnStart: true onTriggered: time=(new Date()).getTime() property real time } MouseArea { id: control anchors.fill: parent onClicked: { if (spinning) { stopTime=clock.time spinning=false } else { startTime=clock.time lostTime+=(startTime-stopTime) spinning=true } } property bool spinning: true property real stopTime: 0.0 property real startTime: 0.0 property real lostTime: 0.0 } }
I was actually a little paranoid about the resolution of the QML/javascript-world timers so in an actual app I replace that QML Timer with a QTimer with
setTimerType(Qt::PreciseTimer)in the hosting C++ QQuickView. Not sure it makes any difference though.
Thanks for the hint. Here the changes I've made to allow stopping on defined position:
rotation: { if (control.spinning || clock.time < control.stopTime) { return ((clock.time - control.lostTime) / 60.0) % 360.0; } else { return (( control.stopTime - control.lostTime) / 60.0) % 360.0; } }
and in the stop event:
if (spinning) { stopTime=clock.time + 500 // set the stop position spinning=false } ... | https://forum.qt.io/topic/85693/change-numberanimation-while-running | CC-MAIN-2018-43 | refinedweb | 1,140 | 58.18 |
Hi,:
import sqlite3
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "X/sqlite3/__init__.py", line 23, in <module>
File "X/sqlite3/dbapi2.py", line 26, in <module>
ImportError: No module named '_sqlite3'
It's not compiled in. I'd like to add it, but it's not currently a high priority, and compiling custom versions of Python is a challenging and time consuming task.
If you want to use that plugin for your very own you probably could extend sys.path to the modules path from your local Python distribution and import modules from there, too.
sys.path
That might be a good solution. I am still having problems with it though.
1) Not really essential but: Why don't I simply get an "No module named 'sqlite3'" if sqlite3 is not included? Instead I get the error posted above.
2) When I first add the modules path from your local Python distribution to ST3 and then try to import 'sqlite3', I still get an error (see below). In my case the path is '/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3' (PATH variable below).
import sys
sys.path.insert(0, PATH)
import sqlite3
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/sqlite3/__init__.py", line 23, in <module>
from sqlite3.dbapi2 import *
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/sqlite3/dbapi2.py", line 26, in <module>
from _sqlite3 import *
ImportError: No module named '_sqlite3'
okay, problem solved. On Mac OX, the code below allows you to import sqlite3 by adding the modules path from your local Python distribution to sys.path. The example uses the location on my system. You can find out which one is the correct location on your system by importing import sqlite3 and import _sqlite3 in your system python and then running print(sqlite3.__file__) and print(_sqlite3.__file__). import sqlite3 works afterwards but maybe the additions to the search path are problematic down the road. I haven't tested this solution enough.
import sqlite3
import _sqlite3
print(sqlite3.__file__)
print(_sqlite3.__file__)
sys.path.insert(0, '/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/lib-dynload')
sys.path.insert(0, '/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3')
import sqlite3
and if you want to package it, simply copy the sqlite3 folder from /Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3 to your ST3 package folder and add _sqlite3.so from /Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/lib-dynload to that folder. Now you should be able to import sqlite3 from your package without messing with the sys.path.
sqlite3
/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3
_sqlite3.so
/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/lib-dynload
My last solution actually does not work for sqlite3 because '_sqlite3' doesn't get imported (when I tried earlier, the additional path were still part of sys.path). So you can do this:1) copy the sqlite3 folder from /Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3 to your ST3 package folder2) begin your plugin with import syssys.path.append('/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/lib-dynload')import sqlite3
This works on my machine but doesn't seem to be a good solution for packaging!
Any solution to include '_sqlite3.so' as part of the plugin files to that import _sqlite3?(import sqlite3 fails because of the problem with import _sqlite3)
I had the same issue with a plugin that we use. It really is a shame that the python included with Sublime is so handicapped - and that it seems nearly impossible to permanently extend the python with e.g. pip or other standard python package tools.
For those interested, we did manage to solve the issue for a range of packages, including sqlite3, crypto and wincrypt encryption, keyring and pyfiglet. All packages with C code simply include the platform-specific binaries. See e.g. github.com/scholer/Mediawiker/tree/master/lib ..
You might want to check out Package Control's dependency feature: packagecontrol.io/docs/dependencies
It still needs some polishing that has been happening in the past few weeks and should be released as 3.0.1 soon, but it will surely be usable after that. There are a few example repositories like _ssl that include binaries for all systems. | https://forum.sublimetext.com/t/sqlite3-module-in-st3/8697/7 | CC-MAIN-2017-09 | refinedweb | 754 | 58.38 |
A class that compiles a shader and saves it into an existing shader HDA. More...
#include <VOP_HDACodeCompiler.h>
A class that compiles a shader and saves it into an existing shader HDA.
Definition at line 359 of file VOP_HDACodeCompiler.h.
Constructor.
Compiles a given node to the sections of a given HDA (already existing). This is used for HDAs that have contents network, but also want to store cached vfl/vex code.
Reimplemented from VOP_HDACodeCompiler.
Compiles the given context type of the source node to the HDA in OTL.
Implements VOP_ShaderHDACompiler.
Obtains the context types for which to compile the code.
Implements VOP_ShaderHDACompiler. | http://www.sidefx.com/docs/hdk/class_v_o_p___shader_h_d_a_compiler_h_d_a.html | CC-MAIN-2018-43 | refinedweb | 103 | 58.79 |
Show: Delphi C++
Display Preferences
Talk:Main Page
From RAD Studio API Documentation
Consider documenting which units are included in which runtime package
I've always wondered why this isn't already documented considering how long packages have been around. I started to document this over on delphi.wikia.com but it would probably be more useful if each package had its own page listing links to the units it contains and each unit's page included a link to the package it is included in.
The msdn documentation for the .NET framework is kind of close to what I'm describing. For each type, method or property it describes which namespace and which assembly that construct is a member of.
Example:
RTL
RTL<nnn>.bpl
RTL.dcp
Contains the core functionality of the runtime type library upon which all other packages depend.
Anyway, just a suggestion. | http://docwiki.embarcadero.com/Libraries/Rio/en/Talk:Main_Page | CC-MAIN-2019-18 | refinedweb | 147 | 56.05 |
Hi.
It appears that the default hilight for JavaDoc errors in 3378 is as
error state.
Is that intentional? Do others think it should be warning by default?
Amnon
Hi.
It's always been that way. It's just @return highlighting broken so you noticed
that.
-
Maxim Shafirov
"Develop with pleasure!"
indeed very interesting and forced me to fix some java doc errors :D
If I do this:
@return <code>true</code> if busy, otherwise <code>false</code>.
...then an error is flagged in 3378 at the end of @return (under the space character immediately following "n"). Adding any other character before ]]> fixes that. | https://intellij-support.jetbrains.com/hc/en-us/community/posts/206250029-JavaDoc-Errors-default-highlight-3378 | CC-MAIN-2020-34 | refinedweb | 104 | 68.87 |
These are some of the common questions regarding CircuitPython and CircuitPython microcontrollers.
We are no longer building or supporting the CircuitPython 5.x or earlier library bundles. We highly encourage you to update CircuitPython to the latest version and use the current version of the libraries. However, if for some reason you cannot update, here are the last available library bundles for older versions:
We dropped ESP8266 support as of 4.x - For more information please read about it here!
We do not support ESP32 because it does not have native USB.
We do support ESP32-S2, which has native USB.
If you'd like to include WiFi in your project, check out this guide on using AirLift with CircuitPython. For further project examples, and guides about using AirLift with specific hardware, check out the Adafruit Learn System.
asynciosupport in CircuitPython?
We do not have asyncio support in CircuitPython at this time. However,
async and
await are turned on in many builds, and we are looking at how to use event loops and other constructs effectively and easily.
The status LED can tell you what's going on with your CircuitPython board. Read more here for what the colors mean!statements affect memory?
It can because the memory gets fragmented differently depending on allocation order and the size of objects. Loading .mpy files uses less memory so its recommended to do that for files you aren't editing.
You can make your own .mpy versions of files with
mpy-cross.
You can download
mpy-cross for your operating system from here. Builds are available for Windows, macOS, x64 Linux, and Raspberry Pi Linux. Choose the latest
mpy-cross whose version matches the version of CircuitPython you are using.
To make a .mpy file, run
./mpy-cross path/to/yourfile.py to create a yourfile.mpy in the same directory as the original file.
Run the following to see the number of bytes available for use:
import gc
gc.mem_free()
No. CircuitPython does not currently support interrupts. We do not have an estimated time for when they will be included
CP or CPy = CircuitPython
CPC = Circuit Playground Classic
CPX = Circuit Playground Express
CPB = Circuit Playground Bluefruit | https://learn.adafruit.com/adafruit-funhouse/frequently-asked-questions | CC-MAIN-2021-49 | refinedweb | 365 | 68.16 |
ipal Choksi(12)
Mahesh Chand(8)
Mike Gold(6)
Moses Soliman(6)
Shivani (5)
Sushila Patel(4)
Santhi Maadhaven(4)
Ashish Singhal(4)
Scott Lysle(4)
Jigar Desai(3)
Sanjay (3)
Levent Camlibel(2)
sushilsaini (2)
Ezhilan Muniswaran(2)
sayginteh (1)
Rajesh VS(1)
Amit Kukreja(1)
waheedkhan (1)
David Sandor)
Erika Ehrli)
Rammanohar (1)
Christopher Krause(1)
Dipen Lama(1)
Satish Arveti(1)
Joshy George(1)
Pankaj Gupta(1)
Prabakar Samiyappan(1)
Rehaman SK(1)
Rishi Alagesann(1)
Pradeep Tiwari(1)
Yogesh Verma(1)
Sanjay David(1)
John Charles Olamend.
Developing Web Applications in VS.NET
Mar 29, 2001.
This tutorial describes about Step-by-step tutorial guides you towards developing your first web application.
Graphics Animator in C#
May 26, 2001.
This program will generate a html page with animated gif. You just need at least 2 gifs and use the program to set the time to display each image....
Working with Namespaces in C#
Nov 07, 2001.
In C#, namespaces are used to logically arrange classes, structs, interfaces, enums and delegates. The namespaces in C# can be nested. That means one namespace can contain other namespaces also..
Creating Word Find Pzzules in C# and GDI+
Sep 30, 2003...
Learning Visual Studio 2005 IDE - Integrated FxCop and Accessibility Options
Jul 23, 2005.
Visual Studio 2005 IDE brings you many new and updated features and Project Properties dialog is one of the areas where you will see some new additions. In this article, I will discuss Accessibility and FxCop features of Project Properties dialog.
Building WebParts in ASP .Net 2.0
Aug 08, 2005...
Embedded Datagrids with Add, Edit and Delete funtionality
Jun 02, 2006.
This article features an embedded Datagrids with Add, Edit and Delete funtionality.
Nested Repeater : Display Hierarchal Data in Web Form by Using ASP.Net Repeater
Jun 02, 2006.
This article features how to display hierarchal data from multiple tables using an ASP.Net repeater control in a web form...
Tip: How to use Multiple Page Headers in Crystal Reports?
Jul 21, 2006.
Recently, I came across a problem in Crystal Reports. I wanted to display a separate page header on the first page of the report than the rest of the guide to ObjectDataSource control
Nov 17, 2006...
Paging in DataGrid
Jan 05, 2007.
This article demonstrates the paging in DataGrid in easy steps.
ASP.NET 2.0 Visio Custom Control
Jan 15, 2007.
This article describes a quick and simple approach to creating a custom web control used to display Microsoft Visio files within an ASP.NET page using Internet Explorer.
Refreshing a parent page from a child in ASP.NET 2.0
Jan 19, 2007.
I'm going to explain how to refresh a parent page from a child page using the new API of ASP.NET 2.0 and JavaScript language.
Embed PDFs into a Web Page with a Custom Control
Jan 23, 2007.
This article describes an approach to embedding and displaying PDF documents in a web page through the use of a simple ASP.NET 2.0 custom server control.
About Nested-Master-Page. | http://www.c-sharpcorner.com/tags/Nested-Master-Page | CC-MAIN-2016-30 | refinedweb | 515 | 59.19 |
Getting the JavaFX Screen Size
By Jim Connors-Oracle on Jul 24, 2009
In a previous post, I showed one way in which you could size the nodes in your scenegraph relative to the screen size without having to use binding, thus eliminating the potential for a bindstorm. At the time, the suggestion was to get the screen coordiantes via a call to AWT (Advanced Windowing Toolkit) as follows:
var AWTtoolkit = java.awt.Toolkit.getDefaultToolkit ();
var screenSizeFromAWT = AWTtoolkit.getScreenSize ();
This currently works for JavaFX Desktop deployments but is far from an optimal solution primarily because it is non-portable. There is no guarantee that AWT will exist-- in fact I'm pretty sure it will not exist -- in the JavaFX Mobile and JavaFX TV space. So attempting to utilize the code snippet above in a JavaFX Mobile or TV context will result in an error. Unfortunately at the time of the original post (Java FX 1.1), I didn't know of a better alternative.
With the advent of JavaFX 1.2, this problem is solved. A new class called javafx.Stage.Screen is provided which describes the characteristics of the display. The API definition of the class can be found here. So now you can query the JavaFX runtime in a portable fashion to get the screen coordinates as follows:
import javafx.stage.\*; //set Stage boundaries to consume entire screen Stage {
fullscreen: true width: Screen.primary.bounds.minX as Integer height: Screen.primary.bounds.minY as Integer ...
}
Cheers.
it works as fullScreen for me (note the capital S)
Posted by Hatim on September 16, 2009 at 11:16 AM EDT # | https://blogs.oracle.com/jtc/entry/getting_the_javafx_screen_size | CC-MAIN-2015-18 | refinedweb | 271 | 65.83 |
Trouble Compiling 1st programGood point! Open the command prompt window and run it from DOS if the .exe exists.
Trouble Compiling 1st programThere's nothing wrong with this source code:
// my first program in C++
#include <iostream.h>
...
Trouble Compiling 1st programI just tried it with Borland C++ Builder v6 with the .h and it worked fine.
Check your compiler ins...
Trouble Compiling 1st programTry .h after headers.
As in #include <iostream.h>
Colored Text WindowsI've been trying to write a Windows GUI based app for years, and
nobody has offered any useful hel...
This user does not accept Private Messages | http://www.cplusplus.com/user/sunrise38501/ | CC-MAIN-2017-26 | refinedweb | 102 | 79.36 |
The basics
This page introduces some concepts that you will need to be familiar with before we can get started with the cool stuff. Other pages will regularly refer back to the concepts introduced on this page. This page is important!
Type system
XPath and XQuery share the same type system. The most abstract data type available in this system is called
item. All other data types are (indirectly) derived from
item. The type system can be divided into three groups of data types. One group consists of all node types, another group consists of function types, and the last group consists of all atomic types.
All node types are derived from the abstract data type
node, which itself is derived from
item. There are seven different types of nodes derived from the abstract
node type:
attribute,
comment,
document,
element,
namespace,
processing instruction, and
text.
Then there are functions. There is one abstract
function data type, derived from
item. All functions are derived from this data type. But not only functions are derived from this abstract data type. Maps and arrays are too. The
map and
array data types are abstract data types too.
The last group consists of all atomic types. There is one generic atomic type called
xs:any. This data type is derived from
item. The following table is an overview of all available simple types.
Document order
Document order is the order in which nodes appear in an XML document. There's also a reverse document order, which is simply the reverse of the document order.
The document order is stable. This means that the relative order of any two nodes will not change while processing a query.
Document order satisfies the following constraints within a tree.
1. The root node is the first node The root node, in this case
<xml>, will always be the first node in document order.
XML
<xml> <paragraph>Paragraph content.</paragraph> </xml>
Open example in playground
2. A node always occurs before its children and descendants The root node, in this case
<xml>, will be followed by its child
<paragraph>. The
<paragraph> element will be followed by its text node child containing "Paragraph content.".
XML
<xml> <paragraph>Paragraph content.</paragraph> </xml>
Open example in playground
3. Namespace nodes immediately follow their element node The relative order of namespace nodes is stable but implementation-dependent. The root node
<xml> will be followed by its namespace node.
XML
<xml xmlns:</xml>
No playground example available.
4. Attribute nodes immediately follow their element node's namespace nodes The relative order of attribute nodes is stable but implementation-dependent. The root node
<xml> will be directly followed by its attribute
id and the
<paragraph> element will be directly followed by its
id attribute.
Other
<xml id="doc-1"> <paragraph id="p-1">Paragraph content.</paragraph> </xml>
No playground example available (yet).
5. The relative order of siblings is the order in which they occur in the children property of their parent node The
<paragraph> elements will be sorted in the order they occur in the document.
XML
<xml> <paragraph id="p-1" /> <paragraph id="p-2" /> <paragraph id="p-3" /> </xml>
Open example in playground
6. Children and descendants occur before the node's following siblings The text nodes in the
<paragraph> elements will occur directly after their parent, before their parent's following sibling.
Other
<xml> <paragraph>Paragraph content 1.</paragraph> <paragraph>Paragraph content 2.</paragraph> <paragraph>Paragraph content 3.</paragraph> </xml>
Open example in playground
Expressions
The expression is the basic building block in both XPath and XQuery. Everything is an expression in both languages, apart from a few constructs used in XQuery to define modules.
Consider the following example:
Expression example
XQuery
1 + 2
Open example in playground
This example consists of a total of three expressions. The
1 and
2 are literal expressions. The
+ is an arithmetic expression. The arithmetic expression expects two operands. In this example, its operands are the two literal expressions.
The example illustrates how expressions are nested. The literal expressions are nested in the arithmetic expression. The arithmetic expression is the top-level expression in this example. It could, in turn, be nested in another expression. There usually is only one top-level expression.
Expression context
Every expression has its own context. The expression context consists of all the information that can affect the result of an expression. Information in the context can be organized into two categories called the static context and the dynamic context.
Context item
The context item is part of the dynamic context. It is the most important piece of information in the expression context. When the context item is a node, it may also be called the context node instead of the context item. Examples of how to use the context item will be given in later chapters.
Context position
The context position is part of the dynamic context. It indicates the position of the context item in the sequence currently being processed. The position changes whenever the context item changes. The context position is returned by the
fn:position function.
Context size
The context size is part of the dynamic context. The context size is the number of items in the sequence currently being processed. Its value is always an integer greater than zero. The context size is returned by the
fn:last function.
Sequences
All data types in XPath and XQuery are derived from item, except for the sequence. A sequence is a collection of zero or more items. A value returned by an expression is always a sequence.
Creating a sequence
Creating a sequence is simple. You'll only need one pair of parentheses:
Creating an empty sequence
XQuery
()
Open example in playground
This pair of parentheses is a valid expression. This expression will resolve to an empty sequence, and that's it. An empty sequence is often used to return nothing. This is similar to returning
null in many other languages.
Sequences can also be created containing items. A sequence containing only one item is often called a singleton. An item is always equal to the singleton sequence containing that item. It's like the sequence is not there in that case.
Creating a singleton sequence
XQuery
(1)
Open example in playground
Creating a sequence
XQuery
(1, 2, 3)
Open example in playground
Creating a sequence with mixed data types
XQuery
("string", 123, true())
Open example in playground
The last example shows that the items in a sequence don't have to be of the same data type. Note that a lot of the operators and functions in XPath and XQuery do require all items in a sequence to be of the same type.
Accessing members
Accessing a member of a sequence can be done like this:
Accessing a sequence member
XQuery
("a", "b", "c", "d", "e")[1]
Open example in playground
Note that, in contrast to many other languages, indices in XPath and XQuery are one-based instead of zero-based. For this example, it means that the first item (
"a") is returned instead of the second item as you might expect.
The syntax used here looks similar to accessing a member of an array in many other languages. But it actually is a filter expression.
Nested sequences
Sequences cannot exist as a nested structure. Consider the following example:
Nested sequences
XQuery
((1, 2), 3, ((("a"), "b"), "c"))
Open example in playground
The result of this expression will be a single sequence containing three integers followed by three strings. The sequences will all be flattened to one sequence.
Range expression
If you want to create a sequence containing a range of numbers, you can use the range expression to create such sequence.
Range expression
XQuery
(1 to 5)
Open example in playground
Atomization
Some operators depend on a process called atomization. Atomization is applied to a value when a sequence of atomic values is required. The result of atomizing is either a sequence containing atomic values or a type error (FOTY0012). Atomizing a value is defined as the result of invoking the
fn:data function.
Atomization works according to these rules:
If the item is an atomic value, it is returned.
If the item is a node, its typed value is returned. If the node does not have a typed value, a type error (FOTY0012) is raised.
It the item is a function, including maps, excluding arrays, a type error (FOTY0013) is raised.
It the item is an array, atomization will be applied to each item in the array. This will happen recursively for nested arrays.
Effective boolean value
Some expressions use the effective boolean value of a value. The effective boolean value of a value is defined as the result of applying the
fn:boolean function to the value. This works according to the following rules.
Empty sequence
The effective boolean value of an empty sequence is false.
Effective boolean value of an empty sequence
XQuery
boolean(())
Open example in playground
Nodes
The effective boolean value of a sequence whose first item is a node is true.
Effective boolean value of a singleton sequence containing one node
XQuery
boolean(/xml)
Open example in playground
Effective boolean value of a sequence containing nodes
XQuery
boolean(/xml/child::*)
Open example in playground
Effective boolean value of a sequence whose first item is a node
XQuery
boolean((/xml, false()))
Open example in playground
Boolean values
The effective boolean value of a singleton sequence containing a value of type xs:boolean or a value derived from xs:boolean will return that value unchanged.
Effective boolean value of true
XQuery
boolean(true())
Open example in playground
Effective boolean value of false
XQuery
boolean(false())
Open example in playground
String values
The effective boolean value of a singleton sequence containing a value of type xs:string, xs:anyURI, xs:untypedAtomic, or a type that derivces from one of these will return false if the value has a length of zero and true otherwise.
Effective boolean value of an empty string
XQuery
boolean("")
Open example in playground
Effective boolean value of a string
XQuery
boolean("string")
Open example in playground
Numeric values
The effective boolean value of a singleton sequence containing a numeric type will return false for NaN or zero and true otherwise.
Effective boolean value of zero
XQuery
boolean(0)
Open example in playground
Effective boolean value of NaN
XQuery
boolean(xs:double("NaN"))
Open example in playground
Effective boolean value of a positive integer
XQuery
boolean(10)
Open example in playground
Effective boolean value of a negative integer
XQuery
boolean(-10)
Open example in playground
Effective boolean value of a decimal value
XQuery
boolean(1.2345)
Open example in playground
Other values
Other values than the ones listed above will raise a type error (FORG0006) when getting their effective boolean value. This includes sequences with more than one item, except for sequences containing multiple nodes, and for functions, including maps and arrays.
Effective boolean value of a non-singleton sequence raises a type error
XQuery
boolean((1, 2))
Open example in playground
Effective boolean value of an array raises a type error
XQuery
boolean(array {})
Open example in playground
Effective boolean value of a map raises a type error
XQuery
boolean(map {})
Open example in playground
Effective boolean value of a function raises a type error
XQuery
boolean(function () {})
Open example in playground | https://documentation.fontoxml.com/latest/the-basics-8f86ac089f84 | CC-MAIN-2021-25 | refinedweb | 1,894 | 55.54 |
On Fri, Jan 16, 2004 at 07:09:46PM +0100, Goswin von Brederlow wrote: > That means you can just as well install a chroot. > > The big goal is to have an amd64 system behave exactly like i386 if > the 32 bit environment is set. > > linux32 $SHELL ---> Your on i386 for all compiling and packaging > intents and purposes. > > That would be perfect. Folks should consider that with the 2.6 kernel, there are a few additional tools we can bring to bear on the problem; specifically, we can use "mount --bind" to allow part of the filesystem to be overmount another part of the filesystem, and namespaces, so that different programs get to see a different set of mounts. This may allow for some additional creative solutions that people may not have considered up until now.... - Ted | https://lists.debian.org/debian-amd64/2004/01/msg00116.html | CC-MAIN-2018-05 | refinedweb | 136 | 69.11 |
: Store Information in Structure and Display it
#include <iostream> using namespace std; struct student { char name[50]; int roll; float marks; } s[10]; int main() { cout << "Enter information of students: " << endl; // storing information for(int i = 0; i < 10; ++i) { s[i].roll = i+1; cout << "For roll number" << s[i].roll << "," << endl; cout << "Enter name: "; cin >> s[i].name; cout << "Enter marks: "; cin >> s[i].marks; cout << endl; } cout << "Displaying Information: " << endl; // Displaying information for(int i = 0; i < 10; ++i) { cout << "\nRoll number: " << i+1 << endl; cout << "Name: " << s[i].name << endl; cout << "Marks: " << s[i].marks << endl; } return 0; }
Output
Enter information of students: For roll number1, Enter name: Tom Enter marks: 98 For roll number2, Enter name: Jerry Enter marks: 89 . . . Displaying Information: Roll number: 1 Name: Tom Marks: 98 . . . | https://www.programiz.com/cpp-programming/examples/information-structure-array | CC-MAIN-2021-04 | refinedweb | 134 | 73.68 |
30585/hyperledger-fabric-creation-ordering-service-endpoint-created
I'm running this command to create a genesis block:
peer channel create -c myc
But I get error telling no ordering service endpoint created.
You have to pass an orderer in the command.
peer channel create -o orderer0:7050 -c mychannel
This error occurs when the system can ...READ MORE
First of all please note, that during ...READ MORE
Seems like you have not set the ...READ MORE
Try defining or referencing the application in ...READ MORE
Summary: Both should provide similar reliability of ...READ MORE
This will solve your problem
import org.apache.commons.codec.binary.Hex;
Transaction txn ...READ MORE
To read and add data you can ...READ MORE
The error is because the go path ...READ MORE
To plug in MSP:
Implement your own MSP ...READ MORE
OR
At least 1 upper-case and 1 lower-case letter
Minimum 8 characters and Maximum 50 characters
Already have an account? Sign in. | https://www.edureka.co/community/30585/hyperledger-fabric-creation-ordering-service-endpoint-created | CC-MAIN-2021-43 | refinedweb | 163 | 60.01 |
27 January 2012 07:39 [Source: ICIS news]
By ?xml:namespace>
SINGAPORE (ICIS)--Asian naphtha prices will draw support from tighter supply because of limited arbitrage shipments from
Prices will also be buoyed by lower Indian exports for the second successive month, they added.
“It is supply-driven,” said a trader, explaining why prices have surged and they are likely to rise further.
Open-spec naphtha prices for the first half of March rose to $974-977/tonne (€740-743/tonne) CFR (cost and freight)
On Thursday, the naphtha crack spread surged to an eight-month high of $143.38/tonne against Brent crude futures, the data showed.
“Prices are tracking the strength in
Refinery shutdowns in Europe have sapped supply availabilities of the petrochemical feedstock naphtha, resulting in tighter arbitrage shipments to
“The East (
European crackers are using more naphtha as alternative feedstock propane is getting more expensive, traders said.
In addition, the robust gasoline prices in
Overall, the naphtha market was buoyed by the strength in global crude values, which strengthened in the latter part of week, tracking a rally in the stock market.
A weak dollar also supported crude oil, after the US Federal Reserve statement said it will keep interest rates unchanged until 2014 in an attempt to stimulate the economy. The market is facing low quantities from Indian refiners, traders said.
The company has cut February export availabilities to two cargoes from the usual three to four lots, they added.
A lighter cracker turnaround season will see firm spot buying of naphtha, traders said.
“The market is also expecting strong buying after China comes back from the Lunar New Year holiday,” said one trader.
Expectations that China, the biggest petrochemical importer in Asia, will adopt a more loose monetary policy going forward will boost trade in the commodities market.
The Chinese authorities are widely expected to adjust down the reserve requirement ratio for banks after China posted its slowest growth in two-and-a-half years, of 8.9% in the fourth quarter of 2011.
In China, a loosening of its tight monetary policy would free up liquidity for cash-strapped small and medium-sized enterprises.
($1 = €0.76)
Please visit the complete ICIS plants and projects database
For more information | http://www.icis.com/Articles/2012/01/27/9527290/asia-naphtha-to-surge-on-lower-supply-from-europe-india.html | CC-MAIN-2014-52 | refinedweb | 376 | 50.16 |
I want to be able to set an option in a Field after it
has been constructed, i. e. Field should get a method
setOption(name, value)
e. g.
setOption('hide', 1)
This effect could be accomplished by
def setOption(self, name, value):
self._options[name] = value
in the Field class.
Motivation: Mostly, fields are made once, upon
construction of a FieldDefinition and don't change
after then. However, I have an (or several) situations
where I go through a form and then a preview page to
look at a formatted version of the entered form data
and to confirm that it should be put into the database.
Apart from a submit button, the preview page contains
all the form data from the previous form but as hidden
fields. So I want to use - almost - the same fields
(escpecially including their ValidatorConverter s) for
the form but with the 'hide' option set to 1. I build
my form definitions as mutable ones on the fly, so
there's no problem in modifying a list of Field s. (I
make a copy of the field list.)
Let me know if you need more info.
Stefan | http://sourceforge.net/p/funformkit/feature-requests/1/ | CC-MAIN-2015-22 | refinedweb | 194 | 71.14 |
The QImageWriter class provides a format independent interface for writing images to files or other devices. More...
#include <QImageWriter>
Note: All functions in this class are reentrant..().().
Returns the format QImageWriter uses for writing images.
See also setFormat().
Returns the gamma level of the image.
See also setGamma().()..
See also format().().
This is an image format specific function that sets the quality level of the image to quality. For image formats that do not support setting the quality, this value is ignored.
The value range of quality depends on the image format. For example, the "jpeg" format supports a quality range from 0 (low quality, high compression) to 100 (high quality, low compression).
See also.(). | https://doc.qt.io/archives/4.6/qimagewriter.html | CC-MAIN-2021-25 | refinedweb | 115 | 52.36 |
Jul
25
2010
Posted by ebal at 03:41:25 in planet_ellak, code
This is a better and improved version of one of my previous perl script:
#!/usr/bin/env python # Created by Evaggelos Balaskas on Sun Jul 25 06:36:29 EEST 2010 # Remove mails from mbox by subject import sys import mailbox import re SUBJECTS = ( 'automatically rejected mail', 'delivery failure', 'delivery notification', 'delivery status notification', 'failure notice', 'mail delivery failed', 'mail delivery failure', 'nondeliverable', 'returned mail', 'undeliverable', 'undelivered', 'warning: could not send message for past' ) if len(sys.argv) == 2: for message in mailbox.mbox( sys.argv[1] ) : s = message['subject'] flag = 0 for i in SUBJECTS: m = re.search ( i, str(s), re.I ) if m != None : flag = 1 break print message else: print "Usage should be: " + sys.argv[0] + " mbox > new.mbox"
Sunday, July 25, 2010 - 10:36:43
Nice script. Thanks for sharing…
Reading it I could help but notice that there is a lot of looping that could probably be written in a cleaner, more ‘Pythonic’ manner. There is a nice pattern in Common Lisp that you can copy to reduce the number of ‘boilerplate’ lines in Python code like this. With two functions that accept a function-argument and check a list of items one by one for a match like this:
<pre>def every(check, args):
for a in args:
if not check(a):
return False
return True
def some(check, args):
for a in args:
if check(a):
return True
return False</pre>
You can write code like this:
<pre>def null(arg):
return arg is None
# Check if *every* item of a list matches a predicate/check function.
if every(null, [None, None, None]):
print “Only null items found.”
# Check if at least *one* item of a list matches a predicate/check function.
if some(null, [1, 2, 3, None, 5]):
print “At least one null item found.”</pre>
Having a ‘higher order’ function like every() and some() means that you can construct matching functions for each regexp pattern on the fly, e.g.:
<pre> patterns = (
r’automatically rejected mail’,
r’delivery failure’,
r’delivery notification’,
r’delivery status notification’,
r’failure notice’,
r’mail delivery failed’,
r’mail delivery failure’,
r’nondeliverable’,
r’returned mail’,
r’undeliverable’,
r’undelivered’,
r’warning: could not send message for past’
)
for mboxfile in sys.argv[1:]:
for msg in mailbox.mbox(mboxfile):
subject = msg[’subject’]
if some(lambda (pat): re.search(pat, subject, re.I), patterns):
continue
print msg</pre>
The resulting code generates anonymous many lambda functions and may not be the fastest option. It uses a more ‘functional’ style though. Looking at this version of the code it seems then more ‘natural’ to work with list comprehensions and check the regexp patterns with something like this:
<pre>[re.search(pat, subject, re.I) for pat in patterns]</pre>
The third iteration of the script code is then:
<pre> def null(arg):
return arg is None
def every(check, args):
for a in args:
if not check(a):
return False
return True
patterns = ( r’foo’, r’bar’ … )
for mboxfile in sys.argv[1:]:
for msg in mailbox.mbox(mboxfile):
s = msg[’subject’]
if every(null, [re.search(pat, s, re.I) for pat in patterns]):
print msg</pre>
I think this version of the script looks moderately cleaner. More supporting functions, but a much smaller ‘main loop’. Smaller main loops are usually good, because they are easier to read, with less boilerplate code to ‘hide’ the actual logic of the program.
Sunday, July 25, 2010 - 10:41:24
Argh! The comment was mangled by the web UI. I’ve posted a plain text version of the same code at | https://balaskas.gr/blog/2010/07/25/how-to-remove-specific-mails-from-mbox-with-python/comments/ | CC-MAIN-2019-35 | refinedweb | 618 | 63.9 |
If
Welcome to the 21st century, C#, now that case blocks support a variety of pattern-matching formats.
02/02/2017
Find the patterns in your data sets using these Clustering.R script tricks.
02/01/2017
A roundup of a few more features: deprecated any type, literal datatypes, read-only properties, more!
01/30/2017
The third release candidate of the venerable, all-encompassing and integrated Microsoft developer platform has been re-released after being pulled for a short time due to reports of developer machines crashing due to an odd installation issue.
01/27/2017
You want to keep an object around only as long as you have memory available, do ya? Then you need the WeakReference class.
01/27/2017
Marten is PostgreSQL-based, so take advantage of relational features where it makes sense. Here's an example.
01/24/2017
Peter starts off with a perfectly good solution to a problem but then complicates the problem . . . and ends up moving to a different design pattern. While on that journey he has some best practices around designing Data Transfer Objects.
01/23/2017
A not-ready-for-production preview, which contains updates and additions to the Windows namespace, is available for testing to Windows Insiders members.
01/19/2017
String functions, integer functions ... booorrring! Tuples in C# 7.0 -- let's explore what makes them infinitely more exciting.
01/18/2017
Chatbots are the new mobile application. In this article, Nick demonstrates how you can integrate a bot right into your Universal Windows Platform app via the Microsoft Bot Framework Direct Line API.
01/17/2017
As a company's problems continue to become more complicated, your code will become more complicated. Peter shows how refactoring code can lead you to better designs.
01/16/2017
P
Last VS Code update of 2016 has hot exit and a number of other code-focused enhancements and improvements.
01/10
Whether you're building an application database or generating data access code, we've got a round-up of tools to make the job easier.
01/04
> More Webcasts | https://visualstudiomagazine.com/pages/topic-pages/c-sharp-vb-tutorials.aspx?Page=8 | CC-MAIN-2020-45 | refinedweb | 350 | 57.87 |
> Tony quickly discovered that a Python module with name > starting with "sb-" can't be used in an import statement from > any other module. Not quickly enough to avoid checking them all in with the wrong name, though... (you'd have thought with all these Python experts on the list, one of them would have pointed out the flaw during the discussions <wink>). > I'm unclear on why it was thought > desirable to uglify all the names, Blame Greg Ward, it was his idea ;) The reason is (quoted from Alex): "the issue is namespace pollution. The gist of the argument is that if we use such generic names, then future people will be barred from using equally generic names... but we have no more right to those names than those other people, so we should not pre-emptively take the names." =Tony Meyer | https://mail.python.org/pipermail/spambayes-dev/2003-September/000997.html | CC-MAIN-2017-30 | refinedweb | 143 | 73.31 |
Its summer, you’re sweating heavily and all you really want to know is why the weatherman predicted this morning that today’s relative temperature would max out to 20°C while it feels more like 25°C. Enter the DHT11, DHT22/AM2302 Digital Temperature & Humidity Sensor from AOSONG – the best way to prove the weatherman wrong!
These sensors are fairly simple to use, low cost and are great for hobbyists who want to sense the world around them! These sensors are pre-calibrated and don’t require extra components so you can start measuring relative humidity and temperature right away.
One of the greatest features they provide is that both temperature & humidity are measured to the nearest tenth; that is, to one decimal place. The only downside of this sensor is you can get new data from it once every second or two. But, considering its performance and price, you can’t complain.
DHT11 Vs DHT22/AM2302
We have two versions of the DHTxx sensor series. They look a bit similar and have the same pinout, but have different characteristics. Here are the details:
The DHT22 is the more expensive version which obviously has better specifications. Its temperature measuring range is from -40°C to +125°C with +-0.5 degrees accuracy, while the DHT11 temperature range is from 0°C to 50°C with +-2 degrees accuracy. Also the DHT22 sensor has better humidity measuring range, from 0 to 100% with 2-5% accuracy, while the DHT11 humidity range is from 20 to 80% with 5% accuracy.
Though DHT22/AM2302 is more precise, more accurate and works in a bigger range of temperature & humidity; there are three things where the DHT11 beats the hell out of DHT22. It’s less expensive, smaller in size and has higher sampling rate. The sampling rate of the DHT11 is 1Hz i.e. one reading every second, while the sampling rate of DHT22 is 0.5Hz i.e. one reading every two seconds.
However, the operating voltage of both sensors is from 3 to 5 volts, while the max current used during conversion (while requesting data) is 2.5mA. And the best thing is that DHT11 and DHT22/AM2302 sensors are ‘swappable’ – meaning, if you build your project with one you can just unplug it and use another. Your code may have to adjust a little but at least the wiring is the same!
For a little more insight, please refer below datasheets for DHT11 and DHT22/AM2302 sensor.
Hardware Overview
Now let’s move on to the interesting stuff. Let’s teardown both the DHT11 and DHT22/AM2302 sensors and see what’s inside.
The casing is in two parts so to get inside it is just a matter of getting a sharp knife and splitting the case apart. Inside the case, on the sensing side, there is a humidity sensing component along with a NTC temperature sensor (or thermistor)
Humidity sensing component is used, of course to measure humidity, which has two electrodes with moisture holding substrate (usually a salt or conductive plastic polymer) sandwiched between them. The ions are released by the substrate as water vapor is absorbed by it, which in turn increases the conductivity between the electrodes. The change in resistance between the two electrodes is proportional to the relative humidity. Higher relative humidity decreases the resistance between the electrodes, while lower relative humidity increases the resistance between the electrodes.
Besides, they consist of a NTC temperature sensor/Thermistor to measure temperature.! The term “NTC” means “Negative Temperature Coefficient”, which means that the resistance decreases with increase of the temperature.
On the other side, there is a small PCB with an 8-bit SOIC-14 packaged IC. This IC measures and processes the analog signal with stored calibration coefficients, does analog to digital conversion and spits out a digital signal with the temperature and humidity.
How DHT11 and DHT22/AM2302 Works?
Let’s briefly discuss how DHT11, DHT22/AM2302 sensors work before we connect it to an Arduino.
The DHT11, DHT22/AM2302 sensors use their own (non-standard but similar to Dallas) 1-wire protocol for communication. As this protocol is based on the MASTER (MCU, say Arduino) – SLAVE (Sensor) structure, the sensor will answer only when master requests for the data. Otherwise, sensor keeps quiet (remains in sleep mode). To access the sensor, master must follow the sequence of single bus, if there is a sequence of confusion, the sensor will not respond to the master.
NOTE
These sensors (Usually all 1-wire sensors) have open drain outputs so the external pull-up resistor, about 5.1kΩ – 10kΩ, is usually required. So, when the bus is idle, its status will switch to HIGH. This maintains logic “1” when the bus is not driven, just like with I2C.
Once the sensor is powered up, it takes up to 2s to become stable. In this period, the sensor tests the environment temperature and humidity, and records relative data. When finished, it enters sleep mode automatically.
The communication starts, when the master (MCU) sends out a start signal. With this, the sensor wakes up from the sleep mode, switches to the High-speed mode and sends a response signal. Following that it outputs a string of 40 bits data consisting of relative temperature and humidity values. Once finished, the sensor switches back to the sleep mode automatically, waiting for next communication. The corresponding timing diagram is shown as below.
Start Signal:
To request a reading, microcontroller pulls the data line LOW for more than 800µs (The typical hold time is 1ms). After this fairly lengthy time, the line is pulled HIGH again but for a much shorter 20µs. This sequence acts as a start signal and awakens the sensor from its idle state.
Response Signal:
Once the start signal ends, the sensor sends out a response signal. The sensor pulls the data line LOW for 80µs an pulls HIGH again for 80µs. In this period, the sensor re-tests the environmental temperature and humidity, records the relative data and gets ready for the data transmission.
40 bit Data:
When response signal ends, the sensor starts outputting 40 bits serial data continuously. Before sending every bit, sensor pulls the data line LOW for around 50µs. Following that the length of the HIGH pulse decides the bit status i.e. either 0 or 1. If the line is HIGH for 26-28µs, it indicates bit ‘0’, whereas 70µs long pulse indicates bit ‘1’.
Once all the 40 bits are transmitted, the sensor pulls the data line LOW for 50ms to indicate the end and enters the sleep mode automatically.
How To Read Temperature and Humidity From 40 bit Data
Now, comes one of the most mysterious aspects of the sensor: figuring out what the 40 bit data mean. While the relative humidity is always a non-negative number, the temperature might be negative. And don’t forget about the decimal fraction portion of the number. Let’s see if we can solve this mystery.
The 40 bit data contains 16 bits of humidity, 16 bits of temperature and last 8 bits represent parity bits (a simplest form of error detecting code) with Most Significant Bit (MSB) first. The corresponding timing diagram is shown as below.
NOTE
The 16 bits of humidity & temperature is actually a 16-bit representation of 10 times the actual humidity & temperature values. The scaling factor of 10 will make more sense in a moment.
Consider we received following 40 bits of data from the sensor.
0000 0010 1001 0010 0000 0001 0000 1101 1010 0010
As we discussed above, first 16 bits represent relative humidity. Next 16 bits represent relative temperature and last 8 bits represent checksum. With this, the data can be separated as:
It’s always a good idea to confirm if the data received does not contain any errors before proceeding further. Let’s see how a checksum can help pinpoint erroneous results.
Here the simple rule is SUM of first four bytes (8 bits) should match last byte i.e. checksum. If this doesn’t match, you should discard the scrambled pattern.
0000 0010 + 1001 0010 + 0000 0001 + 0000 1101 = 1010 0010
This clearly indicates that the received data is valid. So, now you can proceed with calculation of relative humidity and temperature.
To get the relative humidity and temperature, you just need to convert the 16-bit binary value to decimal. That’s it.
Relative Humidity => 0000 0010 1001 0010 (BIN) => 658 (DEC)
Relative Temperature => 0000 0001 0000 1101 (BIN) => 269 (DEC)
But remember, these values are 10 times greater than the actual values. So, the final result will be.
Relative Humidity = 65.8 % RH
Relative Temperature = 26.9 °C
Voila! There’s the relative humidity and temperature, accurate to one decimal place, shining away at you.
DHT11 and DHT22/AM2302 Pinout
The DHT11, DHT22/AM2302 sensors are fairly easy to connect. They have four pins:
VCC pin supplies power for the sensor. Although supply voltage ranges from 3.3V to 5.5V, 5V supply is recommended. In case of 5V power supply, you can keep the sensor as long as 20 meters. However, with 3.3V supply voltage, cable length shall not be greater than 1 meter. Otherwise, the line voltage drop will lead to errors in measurement.
Data pin is used to communication between the sensor and the microcontroller.
NC Not connected
GND should be connected to the ground of Arduino.
Wiring – Connecting DHT11 and DHT22/AM2302 to Arduino UNO
Now that we have a complete understanding of how DHT sensors work, we can begin hooking it up to our Arduino!
Luckily, it is trivial to connect DHT11, DHT22/AM2302 sensors to Arduino. They have fairly long 0.1″-pitch pins so you can easily plug them into any breadboard. Power the sensor with 5V and connect ground to ground. Finally, connect the Data pin to a digital pin #2.
Remember, as discussed earlier in this tutorial, we need to place a pull-up resistor of 10KΩ between VCC and data line to keep it HIGH for proper communication between sensor and MCU. If you happen to have a breakout board of the sensor, you need not add any external pull-up. It comes with a built-in pull-up resistor.
With that, you’re now ready to upload some code and get it working.
Arduino Code – Printing values on Serial Monitor
As discussed earlier in this tutorial, the DHT11, DHT22/AM2302 sensors have their own single wire protocol used for transferring the data. This protocol requires precise timing. Fortunately, we don’t have to worry much about this because we are going to use the DHT library which takes care of almost everything.
Download the library first, by visiting the GitHub repo or, just click this button to download the zip:
To install it, open the Arduino IDE, go to Sketch > Include Library > Add .ZIP Library, and then select the DHTlib ZIP file that you just downloaded. If you need more details on installing a library, visit this Installing an Arduino Library tutorial.
Once you have the library installed, you can copy this sketch into the Arduino IDE. The following test sketch will print the temperature and relative humidity values on the serial monitor. Try the sketch out; and then we will explain it in some detail.
#include <dht.h> #define dataPin 8 // Defines pin number to which the sensor is connected dht DHT; // Creats a DHT object void setup() { Serial.begin(9600); } void loop() { //Uncomment whatever type you're using! int readData = DHT.read22(dataPin); // DHT22/AM2302 //int readData = DHT.read11(dataPin); // DHT11 float t = DHT.temperature; // Gets the values of the temperature float h = DHT.humidity; // Gets the values of the humidity // Printing the results on the serial monitor Serial.print("Temperature = "); Serial.print(t); Serial.print(" "); Serial.print((char)176);//shows degrees character Serial.print("C | "); Serial.print((t * 9.0) / 5.0 + 32.0);//print the temperature in Fahrenheit Serial.print(" "); Serial.print((char)176);//shows degrees character Serial.println("F "); Serial.print("Humidity = "); Serial.print(h); Serial.println(" % "); Serial.println(""); delay(2000); // Delays 2 secods }
The sketch starts by including DHT library. Next, we need to define the Arduino pin number to which our sensor’s Data pin is connected and create a DHT object. So, that we can access special functions related to the library.
#include <dht.h> #define dataPin 8 // Defines pin number to which the sensor is connected dht DHT; // Creats a DHT object
In the ‘setup’ function; we need to initiate the serial communication as we will use the serial monitor to print the results.
void setup() { Serial.begin(9600); }
In the ‘loop’ function; we will use the read22() function which reads the data from the DHT22/AM2302. It takes sensor’s Data pin number as a parameter. If you are tinkering with DHT11, you need to use
read11() function. You can do that by uncommenting second line.
//Uncomment whatever type you're using! int readData = DHT.read22(dataPin); // DHT22/AM2302 //int readData = DHT.read11(dataPin); // DHT11
Once the humidity and temperature values are calculated, we can access them by:
float t = DHT.temperature; // Gets the values of the temperature float h = DHT.humidity; // Gets the values of the humidity
The DHT object returns temperature value in Celsius (°C). It can be converted in to Fahrenheit (°F) using a simple formula:
T(°F) = T(°C) × 9/5 + 32
//print the temperature in Fahrenheit Serial.print((t * 9.0) / 5.0 + 32.0);
At the end we will print the temperature and the humidity values on the serial monitor.
Arduino Project
Arduino Code – DHT11 and DHT22/AM2302 with LCD
Sometimes you come up with an idea where you want to monitor temperature and humidity levels in your DIY incubator. Then you’ll probably need 16×2 character LCD to display prevailing conditions in your incubator, instead of a serial monitor. So, in this example, we’ll hook the LCD up to the Arduino along with the DHT11, DHT22/AM2302 sensor.
In case you are not familiar with 16×2 character LCDs, consider reading (at least skimming) below tutorial.
SUGGESTED READING
Next, we need to make connections to the LCD as shown below.
The following sketch will print the temperature and relative humidity values on the 16×2 character LCD. It uses the same code except we print values on LCD.
#include <LiquidCrystal.h> // includes the LiquidCrystal Library #include <dht.h> #define dataPin 8 LiquidCrystal lcd(12, 11, 5, 4, 3, 2); // Creates an LCD object. Parameters: (rs, enable, d4, d5, d6, d7) dht DHT; bool showcelciusorfarenheit = false; void setup() { lcd.begin(16,2); // Initializes the interface to the LCD screen, and specifies the dimensions (width and height) of the display } void loop() { int readData = DHT.read22(dataPin); float t = DHT.temperature; float h = DHT.humidity; lcd.setCursor(0,0); // Sets the location at which subsequent text written to the LCD will be displayed lcd.print("Temp.: "); // Prints string "Temp." on the LCD //Print temperature value in Celcius and Fahrenheit every alternate cycle if(showcelciusorfarenheit) { lcd.print(t); // Prints the temperature value from the sensor lcd.print(" "); lcd.print((char)223);//shows degrees character lcd.print("C"); showcelciusorfarenheit = false; } else { lcd.print((t * 9.0) / 5.0 + 32.0); // print the temperature in Fahrenheit lcd.print(" "); lcd.print((char)223);//shows degrees character lcd.print("F"); showcelciusorfarenheit = true; } lcd.setCursor(0,1); lcd.print("Humi.: "); lcd.print(h); lcd.print(" %"); delay(5000); }
| https://lastminuteengineers.com/dht11-dht22-arduino-tutorial/ | CC-MAIN-2019-35 | refinedweb | 2,590 | 56.76 |
IPC::Cache - a perl module that implements an object storage space where data is persisted across process boundaries
use IPC::Cache;
# create a cache in the specified namespace, where objects # will expire in one day
my $cache = new Cache( { namespace => 'MyCache', expires_in => 86400 } );
# store a value in the cache (will expire in one day)
$cache->set("key1", "value1");
# retrieve a value from the cache
$cache->get("key1");
# store a value that expires in one hour
$cache->set("key2", "value2", 3600);
# clear this cache's contents
$cache->clear();
# delete all namespaces from shared memory
IPC::Cache::CLEAR();
IPC::Cache is used to persist data across processes via shared memory.
A typical scenario for this would be a mod_perl or perl CGI application. In a multi-tier architecture, it is likely that a trip from the front-end to the database is the most expensive operation, and that data may not change frequently. Using this module will help keep that data on the front-end.
Consider the following usage in a mod_perl application, where a mod_perl application serves out images that are retrieved from a database. Those images change infrequently, but we want to check them once an hour, just in case.
my $cache = new Cache( { namespace => 'Images', expires_in => 3600 } );
my $image = $imageCache->get("the_requested_image");
if (!$image) {
# $image = [expensive database call to get the image] $cache->set("the_requested_image", $image);
}
That bit of code, executed in any instance of the mod_perl/httpd process will first try the shared memory cache, and only perform the expensive database call if the image has not been fetched before, has timed out, or the cache has been cleared.
Creates a new instance of the cache object. The constructor takes a reference to an options hash which can contain any or all of the following:
Namespaces provide isolation between objects. Each cache refers to one and only one namespace. Multiple caches can refer to the same namespace, however. While specifying a namespace is not required, it is recommended so as not to have data collide.
If the "expires_in" option is set, all objects in this cache will be cleared in that number of seconds. It can be overridden on a per-object basis. If expires_in is not set, the objects will never expire unless explicitly set.
The "cache_key" is used to determine the underlying shared memory segment to use. In typical usage, leaving this unset and relying on namespaces alone will be more than adequate.
Adds an object to the cache. set takes the following parameters:
The key the refers to this object.
The object to be stored.
The object will be cleared from the cache in this number of seconds. Overrides the default expire_in for the cache.
Retrieves an object from the cache. get takes the following parameter:
The key referring to the object to be retrieved.
Removes all objects from this cache.
Removes all objects that have expired
Removes this cache and all the associated namespaces from shared memory. CLEAR takes the following parameter:
Specifies the shared memory segment to be cleared. Needed only if a cache was created in a non-standard shared memory segment.
Removes all objects in all namespaces that have expired. PURGE takes the following parameter:
Specifies the shared memory segment to be purged. Needed only if a cache was created in a non-standard shared memory segment.
Roughly estimates the amount of memory in use. SIZE takes the following parameter:
Specifies the shared memory segment to be examined. Needed only if a cache was created in a non-standard shared memory segment.
DeWitt Clinton <dclinton@eziba.com> | http://search.cpan.org/dist/IPC-Cache/Cache.pm | CC-MAIN-2017-26 | refinedweb | 596 | 63.9 |
Summary: Learn how to use jobs to run parallel queries, remove objects from active memory, work with text files and use the Get-Member Cmdlet to go behind the scenes of PowerShell commands in this edition of Quick Hits Friday.
In this Post:
- Use Jobs to Run Parallel Queries with Windows PowerShell
- Remove Application Objects from Active Memory
- Add Information to Text Files with VBScript
- Go Behind the Scenes of a PowerShell Command with Get-Member
Use Jobs to Run Parallel Queries with Windows PowerShell
Hey, Scripting Guy! I have a (hopefully) simple question. I’m developing a script to measure the size of user home directories on multiple servers for billing purposes. In my example below, there are only two, but later there will be more than 50 servers to challenge. Is there a way I can run the queries in parallel in order to save time? The script below only does them one after the other.
$dir = “server1.mydomain.com”, “server2.mydomain.com”
foreach ($server in $dir){
Invoke-Command -ComputerName $server -ScriptBlock{
$parent = Get-ChildItem ‘e:users’
foreach ($child in $parent){
$check = “e:users” + $child.name
$colItems = (Get-ChildItem $check -recurse | Measure-Object -property length -sum)
$mem = “{0:N2}” -f ($colItems.sum / 1MB) + ” MB ”
$check + “…..” + $mem
}}}
— MH
Hello MH, Microsoft Scripting Guy Ed Wilson here. You may want to use the –asjob switch for your Invoke–Command command. It will allow your job to run in the background. Here are some Hey, Scripting Guy! posts where I talking about how to run and receive jobs. You may also consider specifying the –throttleLimit parameter. By default, the Invoke-Command cmdlet will maintain 32 concurrent connections. You may want to bump that number up , depending on the resources that are available to your machine.
Remove Application Objects from Active Memory
Hey, Scripting Guy! You make it very clear how to create an object (such as an Excel application) within VBScript code but after that object is created and opened, it remains in memory even after the script is closed. I cannot seem to find any method of removing that created Excel application from active memory. Please help.
— BC
Hello BC, you have to call the quit method from the application object. Here is an example of a VBScript that I wrote that creates an instance of the Excel.Application object, opens a particular Microsoft Excel spreadsheet, and reads particular information from that spreadsheet. After it is finished reading the spreadsheet, it calls the quit method.
Option Explicit
on error resume next
Dim objExcel, objWorkbook
Dim intRow
Dim strSheet
strSheet = “D:VBSworkshopLabsExtrasNewUsers.xls”
Set objExcel = CreateObject(“Excel.Application”)
Set objWorkbook = objExcel.Workbooks.Open (strSheet)
intRow = 2 ‘this is the row in the sheet we start reading.
WScript.Echo “”
intRow = intRow + 1
Loop
objExcel.Quit ‘closes out the excel object – YOU MUST include this or Excel.exe will keep running.
Add Information to Text Files with VBScript
Hey, Scripting Guy! I am a VBScript lover from China. I am having problems with a script right now. I want to add some information to a specified file. I have learned some information from MSDN to realize the CIM_LogicalFile Class is not implemented by WMI so what else can I do to use it with VBScript?
— SL
Hello SL, the best way to add information to a text file from within VBScript is to use the FileSystemObject.
I have a large number of Hey, Scripting Guy! Blog posts that talk about how to work with text files from within VBScript. In addition, there are 50 VBScripts that illustrate working with text files on the Scripting Guys Script Repository. In addition to those two resources, if you find yourself in need of assistance while you work on your script, you may want to post a question to the Official Scripting Guys Forum.
Go Behind the Scenes of a PowerShell Command with Get-Member
Hey, Scripting Guy! I’ve used following code so that I could ‘copy’ permissions from one folder, and assign them to another folder.
$ACL = Get-Acl “\TESTSTO01s$Democorp”
Set-Acl “\TESTSTO01$Driveletter$$Company” $ACL
It did work correctly, but I cannot see what is happening. Can I see the script behind this? That would be very helpful to understand this process!
— NT
Hello NT, that is the cool thing about Windows PowerShell, there is no script behind the scenes. The Windows PowerShell cmdlets interact directly with the .NET security classes to perform the commands.
If you want to see what is going on “behind the scenes” you have to use the Get-Member cmdlet. Here is an example.
Here I use the Get-Acl Windows PowerShell cmdlet to retrieve security information from a particular file on my computer. I store the security information in the $acl variable. If I examine what is contained in the $acl variable, I have an overview of the information that is contained in the variable. This is seen here.
PS C:> $acl = Get-Acl -Path C:fsoa.txt
PS C:> $acl
Directory: C:fso
Path Owner Access
—- —– ——
a.txt NORTHAMERICAedwils BUILTINAdministrators Allow …
If I want to know what is going on behind the scenes, the Get-Acl Windows PowerShell cmdlet has obtained a FileSecurity .NET Framework class. This class is located in the System.Security.AccessControl .NET Framework namespace. This particular class has a number of things it can do (methods) and several things it can describe (properties). The Get-Member Windows PowerShell cmdlet will display the members of the FileSecurity class. This is seen here.
PS C:> $acl | get-member
TypeName: System.Security.AccessControl.FileSecurity
Name MemberType Definition
—- ———- ———-
Access CodeProperty System.Security.AccessControl.AuthorizationRuleCo…Ru…
AddAccessRule Method System.Void AddAccessRule(System.Security.AccessC…
AddAuditRule Method System.Void AddAuditRule(System.Security.AccessCo…
AuditRuleFactory Method System.Security.AccessControl.AuditRule AuditRule…
Equals Method bool Equals(System.Object obj)
GetAccessRules Method System.Security.AccessControl.AuthorizationRuleCo…
GetAuditRules Method System.Security.AccessControl.AuthorizationRuleCo…
GetGroup Method System.Security.Principal.IdentityReference GetGr…
GetHashCode Method int GetHashCode()
GetOwner Method System.Security.Principal.IdentityReference GetOw…
GetSecurityDescriptorBinaryForm Method byte[] GetSecurityDescriptorBinaryForm()
GetSecurityDescriptorSddlForm Method string GetSecurityDescriptorSddlForm(System.Secur…
GetType Method type GetType()
ModifyAccessRule Method bool ModifyAccessRule(System.Security.AccessContr…
ModifyAuditRule &nbs | https://blogs.technet.microsoft.com/heyscriptingguy/2011/01/14/use-jobs-to-run-parallel-queries-or-remove-objects-from-active-memory/ | CC-MAIN-2017-17 | refinedweb | 1,022 | 50.84 |
You can subscribe to this list here.
Showing
1
results of 1
Hello everyone,
Im trying to import some external vocabulary into my wiki (for examples,
thesauri terms, dublin core properties, etc).
I need it because I want my pages to be exported into the semantic web,
thorugh the "Export RDF" feature.
Importing known vocabularies will allow me to acomplish this in a more
massive way I think, cause I will be able to connect some of my pages to
external resources through the imported vocabularies.
Moreover, I dont want the imported terms will be considered as pages into
my wiki. They represent just external terms. So I defined a new
"External_term" namespace for them.
So for each term imported I defined an "External_term" page for it. And for
every property imported, I just tag my property page with the "equivalent"
tag.
I want to know if Im taking the right approach to expose my pages into the
semantic web.
Thanks in advance,
Marcelo. | http://sourceforge.net/p/semediawiki/mailman/semediawiki-devel/?viewmonth=201304&viewday=25 | CC-MAIN-2014-52 | refinedweb | 164 | 64.81 |
Is C Still A Suitable Language Today?
Damien Katz, Couchbase, believes that C is still a great language for back-end programming, while other developers argue that C has too many flaws, supporting C++ or Java, while others like neither.
In a recent blog post entitled The Unreasonable Effectiveness of C, Damien Katz, the Creator of CouchDB, affirms that C is a great language for the back-end, supporting it in spite of more modern languages such as C++ , Java, or even Erlang or Ruby. Katz does not think C is simply better than any other language out there, but when “raw performance and reliability are critical, C is very, very hard to beat,” - quote taken from a subsequent post meant to clarify his position.
While initially doing much of CouchDB in Erlang, Katz became unhappy with it after spending .
For that and for performance reasons, Katz decided to progressively rewrite “more of the Couchbase code in C, and choosing it as the first option for more new features.” Interestingly, C has proven to be “much more predictable when we'll hit issues and how to debug and fix them. In the long run, it's more productive.”
Katz outlines several reasons making C better than higher level languages such as C++ or Java for the back-end:
- Expressiveness – “The syntax and semantics of C is amazingly powerful and expressive. It makes it easy to reason about high level algorithms and low level hardware at the same time. Its semantics are so simple and the syntax so powerful it lowers the cognitive load substantially, letting the programmer focus on what's important.”
- Simplicity – “C is a weak, statically typed language and its type system is quite simple. … What sounds like a weakness ends up being a virtue: the "surface area" of C APIs tend to be simple and small. Instead of massive frameworks, there is a strong tendency and culture to create small libraries that are lightweight abstractions over simple types.”
- Speed and Memory Footprint – .”
- Faster Development Cycle – “Critically important to developer efficiency and productivity is the "build, run, debug" cycle. The faster the cycle is, the more interactive development is, and the more you stay in the state of flow and on task. C has the fastest development interactivity of any mainstream statically typed language.”
- Debugging – .”
- Cross-platform – .”
Katz also agrees C has “many flaws”:
…!
Katz’s love affair with C seems to originate from the need to push Couchbase’s performance limits and debugging problems arising from combining C plugins with the Erlang VM. He does not consider C++, Go or D as a better replacement for C, but he thinks Rust could be “the language of my dreams” if it achieves “C-like performance but safe with Erlang concurrency and robustness built in.”
Katz’ post has sparked a wide debate on Reddit and Hacker News, many developers arguing the virtues of C and suggesting other languages instead. robinei blames string manipulation and error checking hassles:
I always want to get back to C (from C++ among others), and when I do it's usually refreshingly simple in some ways. It feels good!
But then I need to do string manipulation, or some such awkward activity..
Where lots of allocations happen, it is a pain to have to match every single one with an explicit free. I try to fix this by creating fancy trees of arena allocators, and Go-like slice-strings, but in the end C's lack of useful syntactic tools (above namespace-prefixed functions) make everything seem much more awkward than it could be. (and allocating everything into arenas is also quite painful)
I see source files become twice as long as they need to because of explicit error checking (doesn't normally happen, but in some libraries like sqlite, anything can fail).
There are just so many things that drain my energy, and make me dissatisfied.
After a little bit of all that, I crawl back to where I came from. Usually C++.
madhadron proposes a “more realistic view of C”:
- C is straightforward to compile into fast machine code...on a PDP-11. …
- C's standard library is a joke. Its shortcomings, particularly around string handling, have been responsible for an appalling fraction of the security holes of the past forty years.
- C's tooling is hardly something to brag about, especially compared to its contemporaries like Smalltalk and Lisp. Most of the debuggers people use with C are command line monstrosities. Compare them to the standard debuggers of, say, Squeak or Allegro Common Lisp.
- Claiming a fast build/debug/run cycle for C is sad. It seems fast because of the failure in this area of C++. Go look at Turbo Pascal if you want to know how to make the build/debug/run cycle fast.
- Claiming that C is callable from anywhere via its standard ABI equates all the world with Unix. Sadly, that's almost true today, though, but maybe it's because of the ubiquity of C rather than the other way around.
geophile is dissatisfied with all of them:
C/C++/Java. A programmer's version of Rock/Paper/Scissors.
I started out in C, many years ago. I found myself using macros and libraries to provide useful combinations of state and functions. I was reinventing objects and found C++.
I was a very happy user of C++ for many years, starting very early on (cfront days). But I was burned by the complexity of the language, and the extremely subtle interaction of features. And I was tired of memory management. I was longing for Java, and then it appeared.
And I was happy. As I was learning the language, I was sure I missed something. Every object is in the heap? Really? There is really no way to have one object physically embedded within another? But everything else was so nice, I didn't care.
And now I'm writing a couple of system that would like to use many gigabytes of memory, containing millions of objects, some small, some large. The per-object overhead is killing me. GC tuning is a nightmare. I'm implementing suballocation schemes. I'm writing micro-benchmarks to compare working with ordinary objects with objects serialized to byte arrays. And since C++ has become a hideous mess, far more complicated than the early version that burned me, I long for C again.
So I don't like any language right now.
For some, C looks too flawed and unproductive to be useful today, but others still manage to make good use of it in spite of its peculiarities. The developer community would be probable better off avoiding a war over the best language out there, and rather trying to understand the tradeoffs of each language, choosing the best suited considering the project at hand and the skills available. After all, no language is perfect.
Depends on your goals and environment...
by
Mark Peskin
Overall, if you're doing a large, complex, and sustained project with a significant developer staff, I think you're much better off with Java (or Scala, etc.). Save the C for the odd (and increasingly less frequent) occasions where you really need native code, and use a message-based system to integrate the two (JNI sucks). Forget about C++.
Re: Depends on your goals and environment...
by
Josh Long
I'm with Mark and - to some extent - Damien on this one..
In all cases, definitely forget about C++ :)
Re: Depends on your goals and environment...
by
Bernd Kolb
mbeddr was designed to better support embedded software development (although not limited to that) for small as well as large systems based on an extensible version of C language and IDE. Existing extensions include interfaces with pre- and postconditions, components, state machines and physical units, as well as support for requirements tracing and product line variability. Based on these abstractions, mbeddr also supports formal verification based on model checking and SMT solving.
With that approach C can be made "scalable" for larger projects and teams. In addition it allows the introduction modern programming principles. By extending mbeddr you even add primitives for e.g. messaging.
Of course you cannot blame C for race conditions...
by
Patrick Viry
So instead of blaming the Erlang runtime for race conditions, you'll end up blaming the C threading library you selected. This is hardly an argument against using Erlang.
On the contrary, the threading model provided by the various C libraries is so complex - compared to the Erlang concurrency model - that you'd probably spend months debugging race conditions in your own | http://www.infoq.com/news/2013/01/C-Language | CC-MAIN-2015-18 | refinedweb | 1,441 | 62.88 |
VARSYM(1) DragonFly General Commands Manual VARSYM(1)
NAMEvarsym -- get and set user and system-wide variables for variant symlinks
SYNOPSISvarsym [-adpqsux] [var[=data] ...] varsym -x [var[=data] ...] command args
DESCRIPTIONThe varsym program manages user and system-wide variables. These vari- ables are typically used by the system to resolve variant symlinks but may also be used generally. For each operand set, modify, retrieve, or delete the specified variable. By default variables specified without data are retrieved and variables specified with data are set. Variables may be set to empty. -a List all variables at the specified level. Note that per- process variables override per-user variables and per-user variables override system-wide variables. By default, per- user variables are listed. -d Delete mode. The specified variables are deleted. Any specified data is ignored. -p This option causes variables to be set on a per-process basis and restricts retrievals to process-specific vari- ables. Note that since varsym is run as its own process, using this option to set a variable will not affect your shell's namespace. Instead you might want to use the -x option to set local varsyms and exec a command. -q Quiet mode. When retrieving a variable only its data is printed. -s This option causes variables to be set system-wide and restricts retrievals to system-specific variables. -u This option causes variables to be set on a per-user-id basis and restricts retrievals to user-specific variables. This is the default unless -x is used. -x This option causes variables to be set only within the varsym process and its children, and also allows you to specify a command and arguments to exec after the var=data specifications.
EXIT STATUSThe varsym utility exits with one of the following values: 0 No errors occurred. 1 A requested variable could not be found 2 A requested variable could not be set
SEE ALSOln(1), varsym(2), varsym.conf(5) DragonFly 4.7 September 27, 2009 DragonFly 4.7 | https://www.dragonflybsd.org/cgi/web-man?command=varsym§ion1 | CC-MAIN-2017-04 | refinedweb | 336 | 59.3 |
Saumya Purkayastha wrote:
Why is it that in a public class we have to name the .java file exactly as the class name.
This restriction implies that there must be at most one such type per compilation unit. This restriction makes it easy for a compiler for the Java programming language or an implementation of.
Is this restriction only for Public class?
Ulf Dittmer wrote:
Is this restriction only for Public class?
That's quite easy to test, no?
Kenny Kuchera wrote:True, but I do think its the same for non-public classes.
Saumya Purkayastha wrote:If you know the answer please let me know rather than asking me to test.
This is a request because it will be helpful for the community other than me. I have tested as per your recommendations
Gimme a satisfactory answer. | http://www.coderanch.com/t/489137/java/java/give-file-class-public-class | CC-MAIN-2014-10 | refinedweb | 138 | 76.01 |
On Mon, 22 Nov 2004, Mitchell Blank Jr wrote:> > When gcc accepts an arbitrary algebraic expression as an lvalue I'll be> impressed :-)Btw, the "+0" thing is something that actually might be dropped pretty early, and as such a compiler _might_ get it wrong just because it ended up optimizing the expression away. So you don't need to be all that impressed, certain trivial expressions might just disappear under some circumstances.Side note: the _biggest_ reason why "+0" is hard to optimize away early isactually type handling, not the expression itself. The C type rules meansthat "+0" isn't actually a no-op: it implies type expansion for smallinteger types etc.So I agree that it's unlikely to be a problem in practice, but I literally think that the reason gcc ends up considering a comma-operator to be an lvalue, but not a +-operator really _is_ the type-casting issues. A comma doesn't do implicit type expansion.What I find really strange is the ternary operator lvalue thing, though. A ternary operator _does_ do type expansion, so that extended lvalue thing is really quite complex for ternary ops. Try something like this: int test(int arg) { char c; int i; return (arg ? c : i) = 1023; }and think about what a total disaster that is. Yes, gcc gets it right, butdammit, what a total crock. The people who thought of this feature shouldjust be shot.(Yes, it looks cool. Oh, well. The compiler can always simplify the expression "(a ? b : c) = d" into "tmp = d ; a ? b = tmp : c = tmp", but hey, so can the user, so what's the point? Looking at the output from gcc, it really looks like gcc actually handles it as a special case, rather than as the generic simplification. Scary. Scary. Scary.) Linus-To unsubscribe from this list: send the line "unsubscribe linux-kernel" inthe body of a message to majordomo@vger.kernel.orgMore majordomo info at read the FAQ at | https://lkml.org/lkml/2004/11/22/242 | CC-MAIN-2016-44 | refinedweb | 331 | 63.29 |
Description
Getting or viewing *.svgz file(which is essentially a gzipped *.svg file) is broken. Browser shows following:
XML Parsing Error: not well-formed Location: Line Number 1, Column 1:
Steps to reproduce
- Attach *.svgz file to some wiki page
- Try to view or get it
Example
*.svg file which should be fine
*.svgz file which causes error
*.svg.gz file which causes same error
*.tar.gz file for comparison
*.tgz file for comparison
Component selection
- general
Details
After some disscussion on irc here is what seems to be correct:
python should have .svgz -> .svg.gz map in mimetypes.suffix_map, that is python issue which can be worked around by modifying mimtypes in wiki configs.
- moinmoin should add 'Content-Encoding: gzip' http header for *.svgz files
- if this is done, firefox will decompress the file, but nevertheless save it as example.svg.gz (or .svgz), which is wrong, because it is not gzipped any more.
This Wiki.
Workaround
In order to workaround .svgz -> .svg.gz map issue I have added following to moin.cgi file:
import mimetypes mimetypes.suffix_map['.svgz'] = '.svg.gz'
Discussion
Plan
- Priority:
- Assigned to:
- Status: | http://www.moinmo.in/MoinMoinBugs/SvgzAttachmentsDownloadBroken | crawl-003 | refinedweb | 188 | 62.14 |
You must programmatically create an office building. You will have to create 5 classes, Elevator, Programmer, Artist, Executive, and Worker. All the classes will work with each other. Please use any python data structures (List, Sets, and Dictionaries) and what we have learned about object-oriented programming to develop this program. You will find documentation for the functions that you must implement for each class below. Feel free to use the accompanying unit test to test your code. Feel free to use Grader Than to submit your work to receive your Grade instantly and help. You may submit your work via Moodle or Grader Than.
This is a base class for Programmer, Artist, and Executive. The worker has a first name (str) and last name (str) a destination floor (int) and a total amount of energy (float 0-1).
def __init__(first_name:str, last_name:str, destination:int):The constructor for the class. first_name is a string representing the first name of the worker. last_name is a string representing the last name of the worker. the destination is an integer representing the floor the workers are going to get off on.
def get_destination() ->int:
Should return destination specified when the worker was constructed.
def get_name() -> str:
should return the first and last name separated by a space.
def __hash__()->int:
This should hash the string returned by get_name().def __eq__(other)->bool:
This should test if one object of type Worker is equal to another type. Hint, testing if their names are equal will suffice.
def work(hours:float):
A worker only has enough energy to work 8 hours a day. This should decrease the worker's energy by a quantity that will make their energy level 0 when they have worked 8 hours. Or make their energy equal to .5 when they have worked 4 hours.
def get_energy() ->float :
Returns the current amount of energy the worker has within a 0-1 range. This should change after work() is called with a given amount of hours. This should never return less than 0.
This class extends workers but overrides worker class's functions because executives only work 5 hours a day. Executives' destination floor is a random floor between 40 and 60.
def __init__(first_name:str, last_name:str):Their floor should be randomly selected between 40 and 60.
def work(hours):
An executive only has enough energy to work 5 hours a day. This should decrease the worker's energy by a quantity that will make their energy level 0 when they have worked 5 hours.
This class extends workers but overrides worker class's functions because artists only work 6 hours a day. Artist's destination floor is a random floor between 20 and 39.
def __init__(first_name:str, last_name:str):Their floor should be randomly selected between 20 and 39
An artist only has enough energy to work 6hours a day. This should decrease the worker's energy by a quantity that will make their energy level 0 when they have worked 6 hours.
This class extends workers but overrides work class's functions because programmers work 10 hours a day. The programmer's destination floor is a random floor between 1 and 19.
def __init__(first_name:str, last_name:str):Their floor should be randomly selected between 1 and 19
A programmer only has enough energy to work 10 hours a day. This should decrease the worker's energy by a quantity that will make their energy level 0 when they have worked 10 hours.
An elevator is an object that is able to hold workers and transport them to a destination. The elevator's destination is a specific floor (int). This destination of the elevator my change depending on its occupants and the minimum and maximum floor that is services.
def __init__(capacity:int, min_floor:int, max_floor:int):This is the constructor of the elevator the capacity is the maximum amount of occupants that this elevator my hold. min_floor is the lowest floor that the elevator may go to and the max_floor - 1 is the highest floor that the elevator may travel to, both values will be greater than 0. min_floor
def add_occupant(person:Worker)->bool:
This method adds a worker to the elevator. If the elevator is already full (meaning the total number of workers on the elevator currently is >= the capacity specified at initialization) then the worker should not be added to the elevator. Returns True if the person was added to the elevator and false if they were not added.
def services_floor(floor:int)-> bool:This should return True if the floor specified as a parameter is >= min_floor specified at initialization of this object and
def riders() -> set:This should return a set containing all of the workers on the elevator.
def max_riders() -> int:This will return the capacity specified at initialization.
def full() -> bool:This will return True if the total number of workers on this elevator is >= the capacity specified when this object was created.
def current_floor() -> int:A number indicating which floor this elevator is currently on, this should never be less than 0. See move() to understand how this elevator may move from one floor to the next.
def direction() -> int:
This function will return a number greater than or less than zero. The value return will tell you which direction the elevator is going to move the next time move() is called. This will decide the direction by choosing the closest worker's destination to the elevator's current floor.
def move() -> set:This function will move the elevator up or down one floor. The direction that the elevator will move is based on the value returned by direction(). Please see the direction() documentation for a better understanding. This function will return a set of workers on the elevator whose destination is equal to the floor that the elevator has moved to. Once this method is called and it has returned a set of workers that have gotten off the elevator those workers that have left the elevator should not be in the set of workers returned by riders().
Attachments:
0
answers so far
For this assignment, you will use the create my guitar shop SQL database. This work has assignments for Chapters 12 and 13. Submit your scripts in a Notepad document and be sure to identify each...
Using string, int, and float data types, create an array of 3people implementing classes Name, Address, and Height. Using a sortfunction, sort the array in last_name,first_name order and printthe...
Using MySQL -- For part one of this assignment you are to make a database
with the following specifications and run the following
queries -- Table creation queries should immedatley follow the drop...
At this point, you will add data to your database and validate that they loaded properly. In tabular format, include 3 rows for each table, making sure that the primary-key and foreign! | https://www.transtutors.com/questions/you-must-programmatically-create-an-office-building-you-will-have-to-create-5-classe-5399069.htm | CC-MAIN-2020-24 | refinedweb | 1,154 | 63.59 |
| Join
Last post 03-26-2008 7:38 PM by philos. 1 replies.
Sort Posts:
Oldest to newest
Newest to oldest
hello,
i am trying to use the 3.5 extensions with ajax and silverlight for a web application, but have been uable to find the right "mix" of templates. i tried using the 3.5 extension template and adding a silverlight link using "Add Silverlight Link..." but when i drag the ScriptManager and Silverlight controls over to the work space, i get various errors including "The server tag 'asp:ScriptManager' is ambiguous."
can anyone suggest a template that gives me a fully functional .net 3.5 extensions, silverlight and ajax capability without having to figure out what namespaces and references go where?
thanks!
ok, good for anyone else has this issue...the install of the extensions failed at the what seemed to be the end. consequently the contols were not installed. once i recovered them from the dll, i was able to see the controls and use ajax and silverlight with the 3.5 extensions. whew.
Advertise on ASP.NET
About this Site
© 2008 Microsoft Corporation. All Rights Reserved. | Terms of Use | Trademarks | Privacy Statement | http://forums.asp.net/p/1238476/2257808.aspx | crawl-001 | refinedweb | 196 | 68.16 |
Pytorch RNN API
Events describe a difference of luminance in the scene, so running neural networks for pattern recognition is not as performant if you do not use some form of memory. This is why we tend to use Recurrent Neural Network to deal with video sequences.
In this tutorial, we will explain one of the fundamental model architectures that we have used in our Metavision API: ConvRNN.
import os import glob import numpy as np import torch from metavision_ml.core import temporal_modules as tm, modules as m
A typical Sequence
In our API, an EB video sequence is represented by 5-d tensors of shape T,B,C,H,W:
T: number of time bins
B: batch size
C: number of channels
H: height of the input
W: width of the input
In Pytorch, 2D operations usually only take the last 4 dimensions. To
ease the transformation between the 5d and 4d tensors, we use function
time_to_batch to “flatten” the 5d tensor to 4d, and function
batch_to_time to unflatten the 4d tensor to 5d. These functions can
be imported from <metavision_ml.core.temporal_modules>.
t,b,c,h,w = 3,4,5,64,64 #random 5-d input x = torch.randn(t,b,c,h,w) print("Input shape: ", x.shape) flatten_x, _ = tm.time_to_batch(x) print("Flattened shape: ", flatten_x.shape) unflatten_back_x = tm.batch_to_time(flatten_x, b) print("Back to original shape: ", unflatten_back_x.shape)
Input shape: torch.Size([3, 4, 5, 64, 64]) Flatten shape: torch.Size([12, 5, 64, 64]) Back to original shape: torch.Size([3, 4, 5, 64, 64])
We also created a wrapper around torch nn module, so that all the
before-mentioned transformations can be performed within the wrapper
called
seq_wise:
cout = 16 layer = m.ConvLayer(c, cout) y = tm.seq_wise(layer)(x) print("Output shape: ", y.shape)
Output shape: torch.Size([3, 4, 16, 64, 64])
In practice, what this wrapper does is just to flatten the 5d input tensor to 4d before passing to the 2d operator, then convert it back to 5d as result.
ConvRNN
All this is great if we just care about processing time steps in parallel in isolation, but what if we want to propagate information sequentially? This is where the ConvRNN comes to the rescue.
You can call the ConvRNN class from the <metavision_ml.core.temporal_modules> as well.
rnn_layer = tm.ConvRNN(c, cout) # let's test it on the input x y = rnn_layer(x) print('output: ', y.shape)
output: torch.Size([3, 4, 16, 64, 64])
ConvRNN layers
ConvRNN class is composed of 2 parts:
a 2d input-to-hidden layer performed in parallel (using the “flattening” operations described above)
a for-loop of 2d operations for hidden-to-hidden transformations.
Here the input-to-hidden layer outputs 4 times the number of output channels, because for the RNN part we use LSTM unit which contains 4 components:
input
cell
forget
output
See for complete information.
Let’s take a look in the ConvRNN layers:
with torch.no_grad(): x1 = rnn_layer.conv_x2h(x) print('first part: ', x1.shape) x2 = rnn_layer.timepool(x1) print('second part: ', x2.shape)
first part: torch.Size([3, 4, 64, 64, 64]) second part: torch.Size([3, 4, 16, 64, 64])
The RNN Cell
The for-loop is a bit hidden in the previous example, let’s take a closer look at the RNN component
import torch.nn as nn x2h = nn.Conv2d(c, cout, kernel_size=3, stride=1, padding=1) h2h = nn.Conv2d(cout, cout, kernel_size=3, stride=1, padding=1) x1 = tm.seq_wise(x2h)(x) ht = torch.zeros((b,cout,h,w), dtype=torch.float32) # we initialize a hidden state ourselves all_timesteps = [] for t, xt in enumerate(x1.unbind(0)): ht = torch.sigmoid(xt + h2h(ht)) # basic rnn cell all_timesteps.append(ht[None]) print('final output: ', ht.shape) # Our dummy loss final_output = torch.cat(all_timesteps) loss = final_output.sum() # We can backward everything using Pytorch's AD loss.backward() print('Beginning of gradient of hidden-to-hidden connexion: ', h2h.weight.grad.view(-1)[:10], ' ...')
final output: torch.Size([4, 16, 64, 64]) Beginning of gradient of hidden-to-hidden connexion: tensor([3066.7192, 3116.1343, 3067.7227, 3124.3948, 3176.4548, 3119.4619, 3070.6348, 3118.1299, 3064.5928, 3604.1628]) ... | http://docs.prophesee.ai/stable/metavision_sdk/modules/ml/training/pytorch_rnn_api.html | CC-MAIN-2022-05 | refinedweb | 706 | 60.21 |
NRF24l01 Sensor_id aleatory
Hello, i need help
I have a gateway with nrf24l01 with the mysensor lib and a client with the arduino mini pro.
However when I get in the gatway the topic of the sensor_id is random.
I tested with an arduino nano and it worked well.
Something that is escaping me?
63551 GWT:TPS:TOPIC=mygateway1-out/255/174/3/0/3,MSG SENT
64551 TSF:MSG:READ,255-255-0,s=139,c=3,t=3,pt=0,l=0,sg=0:
64557 GWT:TPS:TOPIC=mygateway1-out/255/139/3/0/3,MSG SENT
65557 TSF:MSG:READ,255-255-0,s=104,c=3,t=3,pt=0,l=0,sg=0:
65562 GWT:TPS:TOPIC=mygateway1-out/255/104/3/0/3,MSG SENT
66562 TSF:MSG:READ,255-255-0,s=69,c=3,t=3,pt=0,l=0,sg=0:
66567 GWT:TPS:TOPIC=mygateway1-out/255/69/3/0/3,MSG SENT
174,139,104,69
in the client I only have two registered:
);
Strange problem.
Could you post the full sketch and the log from the node? (preferably with gateway log for the same time)
This??
Basic gateway :
// Enable debug prints to serial monitor
#define MY_DEBUG
// Use a bit lower baudrate for serial prints on ESP8266 than default in MyConfig.h
#define MY_BAUD_RATE 115200
// Enables and select radio type (if attached)
#define MY_RADIO_RF24
//#define MY_RADIO_RFM69
//#define MY_RADIO_RFM95
"username"
//#define MY_MQTT_PASSWORD "password"
// Set WIFI SSID and password
#define MY_WIFI_SSID "xxx"
#define MY_WIFI_PASSWORD "xxx"
//, 1, 211
//MQTT broker if using URL instead of ip address.
//#define MY_CONTROLLER_URL_ADDRESS "192.168.1.211"
//
}
Client, simple sketch to send only simple values like temperature a humidity :
// Enable debug prints
#define MY_DEBUG
// Enable and select radio type attached
#define MY_RADIO_NRF24
//#define MY_RADIO_RFM69
//#define MY_RS485
#include <SPI.h>
#include <MySensors.h>
//()
{
}
void loop()
{
send(msgTemp.set(12, 1));
send(msgHum.set(66, 1));
// Sleep for a while to save energy
//sleep(UPDATE_INTERVAL);
delay(UPDATE_INTERVAL);
}
Forget, i use node-red, the message arrives, but of course empty, because i subscribe : mygateway1-out/#...
I think that is a insufficient current. A mini is a 3.3v. Now a use a pro mini 5v, and work....
NRF24 can work with wemos d1 mini as client? I try but the result is the sensor_id in topic, in gateway is aleatory .
@maos the node is trying to request a node id.
Add #define MY_NODE_ID 3 (or whatever number between 1 and 254 you want your node to have) in the node sketch, above #include MySensors.h
@mfalkvidd said in NRF24l01 Sensor_id aleatory:
_NODE_ID 3 (or whatever nu
Yes, it does. This is the first time I work with this livrary. Thank you for taking the time to help me.
I have this scenario. Have a gateway with mqtt and others to send to this gateway. However I also need to send some information to the gateways. I have control receive (const MyMessage & message) {
However can I, send this information to all the clients that are sending to this gateway?
@maos great that you got it working.
Sending to all clients can be done, but there are a few things to consider:
- nodes on battery will be sleeping and will therefore not be able to receive messages. To handle this case, look at smartsleep.
- when should the information be sent? Is it triggered by some message from something? Or by time? Something else?
- will you be sending the exact same information, or will the information be customized per node?
Some controllers support sending to multiple nodes. How to do this differs depending on which controller you are using. Sometimes it is better to let the nodes request information from the controller.
Sorry, I guess I was not very clear. At this point would be to just send to another nearby node 3 or 4.
I do not want to send it to everyone at the same time.
From gateway to another node.
Stupid.....
mygateway1-in / 3/0/1/0/1, to publish .....
I'm going to study the library gradually, so far I think top | https://forum.mysensors.org/topic/10439/nrf24l01-sensor_id-aleatory/9?lang=en-US | CC-MAIN-2020-16 | refinedweb | 684 | 67.15 |
TL;TR
Clippit is .NETStandard 2.0 library that allows you to easily and efficiently extract all slides from PPTX presentation into one-slide presentations or compose slides back together into one presentation.
Why?
PowerPoint is still the most popular way to present information. Sales and marketing people regularly produce new presentations. But when they work on new presentation they often reuse slides from previous ones. Here is the gap: when you compose presentation you need slides that can be reused, but result of your work is the presentation and you are not generally interested in “slide management”.
One of my projects is enterprise search solution, that help people find Office documents across different enterprise storage systems. One of cool features is that we let our users find particular relevant slide from presentation rather than huge pptx with something relevant on slide 57.
How it was done before
Back in the day, Microsoft PowerPoint allowed us to “Publish slides” (save each individual slide into separate file). I am absolutely sure that this button was in PowerPoint 2013 and as far as I know was removed from PowerPoint 365 and 2019 versions.
When this feature was in the box, you could use Microsoft.Office.Interop.PowerPoint.dll to start instance of PowerPoint and communicate with it using COM Interop.
But server-side Automation of Office has never been recommended by Microsoft. You were never able to reliably scale your automation, like start multiple instances to work with different document (because you need to think about active window and any on them may stop responding to your command). There is no guarantee that File->Open command will return control to you program, because for example if file is password-protected Office will show popup and ask for password and so on.
That was hard, but doable. PowerPoint guarantees that published slides will be valid PowerPoint documents that user will be able to open and preview. So it is worth playing the ceremony of single-thread automation with retries, timeouts and process kills (when you do not receive control back).
Over the time it became clear that it is the dead end. We need to keep the old version of PowerPoint on some VM and never touch it or find a better way to do it.
The History
Windows only solution that requires MS Office installed on the machine and COM interop is not something that you expect from modern .NET solution.
Ideally it should be .NETStandard library on NuGet that platform-agnostic and able to solve you task anywhere and as fast as possible. But there was nothing on Nuget few months ago.
If you ever work with Office documents from C# you know that there is an OpenXml library that opens office document, deserialize it internals to an object model, let you modify it and then save it back. But OpenXml API is low-level and you need to know a lot about OpenXml internals to be able to extract slides with images, embedding, layouts, masters and cross-references into new presentation correctly.
If you google more you will find that there is a project “Open-Xml-PowerTools” developed by Microsoft since 2015 that have never been officially released on NuGet. Currently this project is archived by OfficeDev team and most actively maintained fork belongs to EricWhiteDev (No NuGet.org feed at this time).
Open-Xml-PowerTools has a feature called PresentationBuilder that was created for similar purpose – compose slide ranges from multiple presentations into one presentation. After playing with this library, I realized that it does a great job but does not fully satisfy my requirements:
- Resource usage are not efficient, same streams are opened multiple times and not always properly disposed.
- Library is much slower than it could be with proper resource management and less GC pressure.
- It generates slides with total size much larger than original presentation, because it copies all layouts when only one is needed.
- It does not properly name image parts inside slide, corrupt file extensions and does not support SVG.
It was a great starting point, but I realized that I can improve it. Not only fix all mentioned issues and improve performance 6x times but also add support for new image types, properly extract slide titles and convert then into presentation titles, propagate modification date and erase metadata that does not belong to slide.
How it is done today
So today, I am ready to present the new library Clippit that is technically a fork of most recent version of EricWhiteDev/Open-Xml-PowerTools that is extended and improved for one particular use case: extracting slides from presentation and composing them back efficiently.
All classes were moved to Clippit namespace, so you can load it side-by-side with any version of Open-Xml-PowerTools if you already use it.
The library is already available on NuGet, it is written using C# 8.0 (nullable reference types), compiled for .NET Standard 2.0, tested with .NET Core 3.1. It works perfectly on macOS/Linux and battle-tested on hundreds of real world PowerPoint presentations.
New API is quite simple and easy to use
P.S. Stay tuned, there will be more OpenXml goodness. | https://sergeytihon.com/tag/c/ | CC-MAIN-2021-31 | refinedweb | 871 | 53 |
AWS News Blog the initial preview, we’ve continued to iterate on customer feedback by adding features like automatic source language inference via Amazon Comprehend, Amazon CloudWatch metrics, and larger pieces of text in each TranslateText. In April, we made the service generally available and have continued to collect feature requests and feedback from customers.
Working with Amazon Translate
You can use the API explorer in the Amazon Translate Console to try out the new languages immediately.
You could also use any of the SDKs as well. I wrote a quick Python sample below.
import boto3 translate = boto3.client("translate") lang_flag_pairs = [("ja", "??"), ("ru", "??"), ("it", "??"), ("zh-TW", "??"), ("tr", "??"), ("cs", "??")] for lang, flag in lang_flag_pairs: print(flag) print(translate.translate_text( Text="Hello, World!", SourceLanguageCode="en", TargetLanguageCode=lang )['TranslatedText'])
Which gave me a cool result:
?? ハローワールド! ?? Привет, Мир! ?? Ciao, Mondo! ?? 你好,世界! ?? Merhaba, Dünya! ?? Ahoj, světe!
You can check out the examples page in the documentation for more interesting ways to use Amazon Translate.
I had the chance to chat with a few of our customers about how they’re using Amazon Translate. I found out that they’re using it to enable a lot of innovative use cases and customers are building real-time chat translation in games, capturing and translating tweets for analytics, and as you can see on this blog – translating blog posts and creating spoken versions of them with Polly.
Additional Info
Amazon Translate is available in US East (N. Virginia), US East (Ohio), US West (Oregon), and Europe (Ireland) and AWS GovCloud (US). It has a useful monthly free tier of 2 million characters for the first 12 months, and $15 per million characters after that.
The team wanted me to let you know that they’re hard at work on some additional functionality and that they’re hoping, later this year, to add support for Danish, Dutch, Finnish, Hebrew, Polish, and Swedish.
As always, let us know if you have any feedback on this service in the comments or on Twitter! | https://aws.amazon.com/blogs/aws/amazon-translate-adds-support-for-new-languages/ | CC-MAIN-2022-21 | refinedweb | 334 | 61.97 |
14770/python-using-basicconfig-method-to-log-to-console-and-file
I don't know why this code prints to the screen, but not to the file? File "example1.log" is created, but nothing is written there.
#!/usr/bin/env python3
import logging
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(message)s',
handlers=[logging.FileHandler("example1.log"),
logging.StreamHandler()])
logging.debug('This message should go to the log file and to the console')
logging.info('So should this')
logging.warning('And this, too')
I have "bypassed" this problem by creating a logging object (example code), but it keeps bugging me why basicConfig() approach failed?
PS. If I change basicConfig call to:
logging.basicConfig(level=logging.DEBUG,
filename="example2.log",
format='%(asctime)s %(message)s',
handlers=[logging.StreamHandler()])
Then all logs are in the file and nothing is displayed in the console
I can't reproduce it on Python 3.3. The messages are written both to the screen and the 'example2.log'. On Python <3.3 it creates the file but it is empty.
The code:
from logging_tree import printout # pip install logging_tree
printout()
shows that FileHandler() is not attached to the root logger on Python <3.3.
The docs for logging.basicConfig() say that handlers argument is added in Python 3.3. The handlers argument isn't mentioned in Python 3.2 documentation.
Try this working fine(tested in python 2.7) ...READ MORE
I am writing a script that needs ...READ MORE
key is just a variable name.
for key in ...READ MORE
That link has instructions for connecting to ...READ MORE
You can refer to this link for ...READ MORE
In Python 2, use urllib2 which comes ...READ MORE
class NegativeWeightFinder:
def __init__(self, graph: nx.Graph):
...READ MORE
subprocess.Popen(["hadoop", "fs", "-cat", "/path/to/myfile"], stdout ...READ MORE
The code that I've written below. The ...READ MORE
Part of the problem here is that ...READ MORE
OR
Already have an account? Sign in. | https://www.edureka.co/community/14770/python-using-basicconfig-method-to-log-to-console-and-file?show=14772 | CC-MAIN-2019-43 | refinedweb | 330 | 62.34 |
I am working in a method to verify the installed packages for the rpms module.
I checked python api and there isn’t any buildin method I could use, but I checked yum api and I found something interesting,
The output with the external command was:
S.?….. /usr/sbin/groupmod
prelink: /usr/sbin/useradd: at least one of file’s dependencies has changed since prelinking
S.?….. /usr/sbin/useradd
prelink: /usr/sbin/userdel: at least one of file’s dependencies has changed since prelinking
S.?….. /usr/sbin/userdel
prelink: /usr/sbin/usermod: at least one of file’s dependencies has changed since prelinking
S.?….. /usr/sbin/usermod
While the output with the yum api is:
/usr/sbin/userdel – checksum does not match
/usr/sbin/userdel – size does not match
/usr/sbin/groupdel – checksum does not match
/usr/sbin/groupdel – size does not match
/etc/login.defs – mtime does not match
/etc/login.defs – checksum does not match
/etc/login.defs – size does not match
/usr/bin/newgrp – checksum does not match
I intend to work now to allow the verification for only one package each time adding support for rpms.glob(). When its done the plan is to merge the yum module with the rpm module and create a new module called “packages”.
The current code is:
def verify(self, flatten=True):
“””
Returns information of the verification of all installed packages.
“””
import yum
ts = rpm.TransactionSet()
mi = ts.dbMatch()
results = []
for hdr in mi:
name = hdr[‘name’]
if flatten:
yb = yum.YumBase()
pkgs = yb.rpmdb.searchNevra(name)
for pkg in pkgs:
errors = pkg.verify()
for fn in errors.keys():
for prob in errors[fn]:
results.append(‘%s %s %s’ % (name, fn, prob.message))
else:
results.append(“%s-%s-%s.%s” % (name, version, release, arch))
return results
Feel free to give me some ideas or comments, thanks.
| https://miltonpaiva.wordpress.com/2009/03/ | CC-MAIN-2017-39 | refinedweb | 306 | 67.76 |
§HTTP Request Handlers
Play abstraction for handling requests is less sophisticated in the Play Java API, when compared to its Scala counterpart. However, it may still be enough if you only need to execute some code before the controller’s action method associated to the passed request is executed. If that’s not enough, then you should fall back to the Scala API for creating a HTTP request handler.
§Implementing a custom request handler
The
HttpRequestHandler interface has two methods that needs to be implemented:
createAction: Takes the request and the controller’s action method associated with the passed request.
wrapAction: Takes the action to be run and allows for a final global interceptor to be added to the action.
There is also a
DefaultHttpRequestHandler class that can be used if you don’t want to implement both methods.
Note: If you are providing an implementation of
wrapActionbecause you need to apply a cross cutting concern to an action before is executed, creating a filter is a more idiomatic way of achieving the same.
§Configuring the http request handler
A custom http handler can be supplied by creating a class in the root package called
RequestHandler that implements
HttpRequestHandler, for example:
import play.http.HttpRequestHandler; import play.libs.F; import play.mvc.Action; import play.mvc.Http; import play.mvc.Result; import java.lang.reflect.Method; public class RequestHandler implements HttpRequestHandler { @Override public Action createAction(Http.Request request, Method actionMethod) { return new Action.Simple() { @Override public F.Promise<Result> call(Http.Context ctx) throws Throwable { return delegate.call(ctx); } }; } @Override public Action wrapAction(Action action) { return action; } }.http.DefaultHttpRequestHandler"
Next: Advanced routing. | https://www.playframework.com/documentation/tr/2.4.x/JavaHttpRequestHandlers | CC-MAIN-2021-43 | refinedweb | 272 | 50.02 |
Machine learning is broadly split into two camps, statistical learning and non-statistical learning. The latter we’ve started to get a good picture of on this blog; we approached Perceptrons, decision trees, and neural networks from a non-statistical perspective. And generally “statistical” learning is just that, a perspective. Data is phrased in terms of independent and dependent variables, and statistical techniques are leveraged against the data. In this post we’ll focus on the simplest example of this, linear regression, and in the sequel see it applied to various learning problems.
As usual, all of the code presented in this post is available on this blog’s Github page.
The Linear Model, in Two Variables
And so given a data set we start by splitting it into independent variables and dependent variables. For this section, we’ll focus on the case of two variables,
. Here, if we want to be completely formal,
are real-valued random variables on the same probability space (see our primer on probability theory to keep up with this sort of terminology, but we won’t rely on it heavily in this post), and we choose one of them, say
, to be the independent variable and the other, say
, to be the dependent variable. All that means in is that we are assuming there is a relationship between
and
, and that we intend to use the value of
to predict the value of
. Perhaps a more computer-sciencey terminology would be to call the variables features and have input features and output features, but we will try to stick to the statistical terminology.
As a quick example, our sample space might be the set of all people,
could be age, and
could be height. Then by calling age “independent,” we’re asserting that we’re trying to use age to predict height.
One of the strongest mainstays of statistics is the linear model. That is, when there aren’t any known relationships among the observed data, the simplest possible relationship one could discover is a linear one. A change in
corresponds to a proportional change in
, and so one could hope there exist constants
so that (as random variables)
. If this were the case then we could just draw many pairs of sample values of
and
, and try to estimate the value of
and
.
If the data actually lies on a line, then two sample points will be enough to get a perfect prediction. Of course, nothing is exact outside of mathematics. And so if we were to use data coming from the real world, and even if we were to somehow produce some constants
, our “predictor” would almost always be off by a bit. In the diagram below, where it’s clear that the relationship between the variables is linear, only a small fraction of the data points appear to lie on the line itself.
An example of a linear model for a set of points (credit Wikipedia).
In such scenarios it would be hopelessly foolish to wish for a perfect predictor, and so instead we wish to summarize the trends in the data using a simple description mechanism. In this case, that mechanism is a line. Now the computation required to find the “best” coefficients of the line is quite straightforward once we pick a suitable notion of what “best” means.
Now suppose that we call our (presently unknown) prediction function
. We often call the function we’re producing as a result of our learning algorithm the hypothesis, but in this case we’ll stick to calling it a prediction function. If we’re given a data point
where
is a value of
and
of
, then the error of our predictor on this example is
. Geometrically this is the vertical distance from the actual
value to our prediction for the same
, and so we’d like to minimize this error. Indeed, we’d like to minimize the sum of all the errors of our linear predictor over all data points we see. We’ll describe this in more detail momentarily.
The word “minimize” might evoke long suppressed memories of torturous Calculus lessons, and indeed we will use elementary Calculus to find the optimal linear predictor. But one small catch is that our error function, being an absolute value, is not differentiable! To mend this we observe that minimizing the absolute value of a number is the same as minimizing the square of a number. In fact,
, and the square root function and its inverse are both increasing functions; they preserve minima of sets of nonnegative numbers. So we can describe our error as
, and use calculus to our heart’s content.
To explicitly formalize the problem, given a set of data points
and a potential prediction line
, we define the error of
on the examples to be
Which can also be written as
Note that since we’re fixing our data sample, the function
is purely a function of the variables
. Now we want to minimize this quantity with respect to
, so we can take a gradient,
and set them simultaneously equal to zero. In the first we solve for
:
If we denote by
this is just
. Substituting
into the other equation we get
Which, by factoring out
, further simplifies to
And so
And it’s not hard to see (by taking second partials, if you wish) that this corresponds to a minimum of the error function. This closed form gives us an immediate algorithm to compute the optimal linear estimator. In Python,
avg = lambda L: 1.0* sum(L)/len(L) def bestLinearEstimator(points): xAvg, yAvg = map(avg, zip(*points)) aNum = 0 aDenom = 0 for (x,y) in points: aNum += (y - yAvg) * x aDenom += (x - xAvg) * x a = float(aNum) / aDenom b = yAvg - a * xAvg return (a, b), lambda x: a*x + b
and a quick example of its use on synthetic data points:
>>> import random >>> a = 0.5 >>> b = 7.0 >>> points = [(x, a*x + b + (random.random() * 0.4 - 0.2)) for x in [random.random() * 10 for _ in range(100)]] >>> bestLinearEstimator(points)[0] (0.49649543577814137, 6.993035962110321)
Many Variables and Matrix Form
If we take those two variables
and tinker with them a bit, we can represent the solution to our regression problem in a different (a priori strange) way in terms of matrix multiplication.
First, we’ll transform the prediction function into matrixy style. We add in an extra variable
which we force to be 1, and then we can write our prediction line in a vector form as
. What is the benefit of such an awkward maneuver? It allows us to write the evaluation of our prediction function as a dot product
Now the notation is starting to get quite ugly, so let’s rename the coefficients of our line
, and the coefficients of the input data
. The output is still
. Here we understand implicitly that the indices line up: if
is the constant term, then that makes
our extra variable (often called a bias variable by statistically minded folks), and
is the linear term with coefficient
. Now we can just write the prediction function as
We still haven’t really seen the benefit of this vector notation (and we won’t see it’s true power until we extend this to kernel ridge regression in the next post), but we do have at least one additional notational convenience: we can add arbitrarily many input variables without changing our notation.
If we expand our horizons to think of the random variable
depending on the
random variables
, then our data will come in tuples of the form
, where again the
is fixed to 1. Then expanding our line
, our evaluation function is still
. Excellent.
Now we can write our error function using the same style of compact notation. In this case, we will store all of our input data points
as rows of a matrix
and the output values
as entries of a vector
. Forgetting the boldface notation and just understanding everything as a vector or matrix, we can write the deviation of the predictor (on all the data points) from the true values as
Indeed, each entry of the vector
is a dot product of a row of
(an input data point) with the coefficients of the line
. It’s just
applied to all the input data and stored as the entries of a vector. We still have the sign issue we did before, and so we can just take the square norm of the result and get the same effect as before:
This is just taking a dot product of
with itself. This form is awkward to differentiate because the variable
is nested in the norm. Luckily, we can get the same result by viewing
as a 1-by-
matrix, transposing it, and multiplying by
.
This notation is widely used, in particular because we have nice formulas for calculus on such forms. And so we can compute a gradient of
with respect to each of the
variables in
at the same time, and express the result as a vector. This is what taking a “partial derivative” with respect to a vector means: we just represent the system of partial derivates with respect to each entry as a vector. In this case, and using formula 61 from page 9 and formula 120 on page 13 of The Matrix Cookbook, we get
Indeed, it’s quite trivial to prove the latter formula, that for any vector
, the partial
. If the reader feels uncomfortable with this, we suggest taking the time to unpack the notation (which we admittedly just spent so long packing) and take a classical derivative entry-by-entry.
Solving the above quantity for
gives
, assuming the inverse of
exists. Again, we’ll spare the details proving that this is a minimum of the error function, but inspecting second derivatives provides this.
Now we can have a slightly more complicated program to compute the linear estimator for one input variable and many output variables. It’s “more complicated” in that much more mathematics is happening behind the code, but just admire the brevity!
from numpy import array, dot, transpose from numpy.linalg import inv def bestLinearEstimatorMV(points): # input points are n+1 tuples of n inputs and 1 output X = array([[1] + list(p[:-1]) for p in points]) # add bias as x_0 y = array([p[-1] for p in points]) Xt = transpose(X) theInverse = inv(dot(Xt, X)) w = dot(dot(theInverse, Xt), y) return w, lambda x: dot(w, x)
Here are some examples of its use. First we check consistency by verifying that it agrees with the test used in the two-variable case (note the reordering of the variables):
>>> print(bestLinearEstimatorMV(points)[0]) [ 6.97687136 0.50284939]
And a more complicated example:
>>> trueW = array([-3,1,2,3,4,5]) >>> bias, linearTerms = trueW[0], trueW[1:] >>> points = [tuple(v) + (dot(linearTerms, v) + bias + noise(),) for v in [numpy.random.random(5) for _ in range(100)]] >>> print(bestLinearEstimatorMV(points)[0]) [-3.02698484 1.03984389 2.01999929 3.0046756 4.01240348 4.99515123]
As a quick reminder, all of the code used in this post is available on this blog’s Github page.
Bias and Variance
There is a deeper explanation of the linear model we’ve been studying. In particular, there is a general technique in statistics called maximum likelihood estimation. And, to be as concise as possible, the linear regression formulas we’ve derived above provide the maximum likelihood estimator for a line with symmetric “Gaussian noise.” Rather than go into maximum likelihood estimation in general, we’ll just describe what it means to be a “line with Gaussian noise,” and measure the linear model’s bias and variance with respect to such a model. We saw this very briefly in the test cases for the code in the past two sections. Just a quick warning: the proofs we present in this section will use the notation and propositions of basic probability theory we’ve discussed on this blog before.
So what we’ve done so far in this post is describe a computational process that accepts as input some points and produces as output a line. We have said nothing about the quality of the line, and indeed we cannot say anything about its quality without some assumptions on how the data was generated. In usual statistical fashion, we will assume that the true data is being generated by an actual line, but with some added noise.
Specifically, let’s return to the case of two random variables
. If we assume that
is perfectly determined by
via some linear equation
, then as we already mentioned we can produce a perfect estimator using a mere two examples. On the other hand, what if every time we take a new
example, its corresponding
value is perturbed by some random coin flip (flipped at the time the example is produced)? Then the value of
would be
, and we say all the
are drawn independently and uniformly at random from the set
. In other words, with probability 1/2 we get -1, and otherwise 1, and none of the
depend on each other. In fact, we just want to make the blanket assumption that the noise doesn’t depend on anything (not the data drawn, the method we’re using to solve the problem, what our favorite color is…). In the notation of random variables, we’d call
the random variable producing the noise (in Greek
is the capital letter for
), and write
.
More realistically, the noise isn’t chosen uniformly from
, but is rather chosen to be Gaussian with mean
and some variance
. We’d denote this by
, and say the
are drawn independently from this normal distribution. If the reader is uncomfortable with Gaussian noise (it’s certainly a nontrivial problem to generate it computationally), just stick to the noise we defined in the previous paragraph. For the purpose of this post, any symmetric noise will result in the same analysis (and the code samples above use uniform noise over an interval anyway).
Moving back to the case of many variables, we assume our data points
are given by
where
is the observed data and
is Gaussian noise with mean zero and some (unknown) standard deviation
. Then if we call
our predicted linear coefficients (randomly depending on which samples are drawn), then its expected value conditioned on the data is
Replacing
by
,
Notice that the first term is a fat matrix (
) multiplied by its own inverse, so that cancels to 1. By linearity of expectation, we can split the resulting expression up as
but
is constant (so its expected value is just itself) and
by assumption that the noise is symmetric. So then the expected value of
is just
. Because this is true for all choices of data
, the bias of our estimator is zero.
The question of variance is a bit trickier, because the variance of the entries of
actually do depend on which samples are drawn. Briefly, to compute the covariance matrix of the
as variables depending on
, we apply the definition:
And after some tedious expanding and rewriting and recalling that the covariance matrix of
is just the diagonal matrix
, we get that
This means that if we get unlucky and draw some sample which makes some entries of
big, then our estimator will vary a lot from the truth. This can happen for a variety of reasons, one of which is including irrelevant input variables in the computation. Unfortunately a deeper discussion of the statistical issues that arise when trying to make hypotheses in such situations. However, the concept of a bias-variance tradeoff is quite relevant. As we’ll see next time, a technique called ridge-regression sacrifices some bias in this standard linear regression model in order to dampen the variance. Moreover, a “kernel trick” allows us to make non-linear predictions, turning this simple model for linear estimation into a very powerful learning tool.
Until then! | http://jeremykun.com/tag/variance/ | CC-MAIN-2014-10 | refinedweb | 2,672 | 56.59 |
And a little bit of fiddling later I come to this result: psp2html;
direct. I don't see the need of capturing the in-between Python code
anyway. As such it runs and appears pretty robust, without scary handler
hacks that I don't really understand.
Thanks Graham for the further input and advice.
from mod_python import _psp
import os
import sys
import StringIO
def psp2html (filename, vars={}):
dir, fname = os.path.split(filename)
dir += "/"
# produce usable python code using the psp parser.
pycode = _psp.parse(fname, dir).splitlines()
pycode = [s.rstrip() for s in pycode]
code = ""
# as req.write() for a real request object works a little different
# than the req.write we use here, we have to change the code a
# little bit.
for s in pycode:
code += s.replace(",0)", ")")+"\n"
vars["req"] = StringIO.StringIO()
try:
exec code in vars
except:
et, ev, etb = sys.exc_info()
raise et, ev, etb
return vars["req"].getvalue()
Wouter.
>
> | https://modpython.org/pipermail/mod_python/2005-May/018134.html | CC-MAIN-2022-33 | refinedweb | 158 | 69.89 |
Lex.db: A New Database Storage Solution for Windows 8
Recently, on my blog, I’ve talked a lot about the database solutions that are available in Windows Phone 8. There are many different ways to manage database, each one with its pros and cons. SQL CE with LINQ to SQL is the most powerful one, but isn’t supported by Windows 8 and it’s hard to share the code and the database with other platforms. SQLite support is very promising and the engine is very fast, but at the moment it lacks a powerful library to manage data, so it’s a bit limited.
Please welcome a new participant in this “contest”: Lex.db, an interesting solution developed by Lex Lavnikov (pay often a visit to his blog because it regularly posts update about the project).Do you remember Sterling? It’s an object oriented database that uses the file system to store data in a structured way, so that it can be used with LINQ to do queries and operation like a regular database. The biggest pro is that is available for many .NET technologies and it’s very fast, especially if you simply need to persist data: since it uses just the file system, it doesn’t add the overhead of a database engine.
Lex.db is based on the same principles, but it supports also Windows Runtime: for this reason it can be used not only with Windows Phone 8, but also with Windows Store apps and with the full .NET framework. How does it work? Lex.db is able to automatically serialize the data that we need to store in the file system and to keep in memory just the keys and the indexes that are needed to perform operations on the file. For this reason it’s really fast and often performances are superior than using SQL Lite.
Which are the downsides? For the moment, it still doesn’t support Windows Phone 7, so it’s not the perfect choice if you need to share the data layer of your application between two projects for Windows Phone 7 and Windows Phone 8. Plus, it’s not a real database solution: for example, for the moment relationships are not supported, so you’ll have to manually manage them if you need.
But, for example, if you’re going to develop a To Do List app (or any other app that needs to hold in storage a collection of data) and you want to share the data layer with a Windows Store version of the app it’s a really good solution.
Let’s see how to use it in a Windows Phone application (but the code would be exactly the same for a Windows Store app).
The first setup
The simplest way to use Lex.Db in your project is to install it using NuGet: right click on your project, choose Manage NuGet packages and, using the built in search engine, look for and install the package called Lex.db.
After that we can create the entity that will hold the information that will be stored in the file system. Unlike with sqlite-net or LINQ to SQL, we don’t have to decorate classes with special attributes: we just need to define the class. Let’s use the ToDo List app example: in this case we need a class to store all the information about an activity.
public class Activity { public int Id { get; set; } public string Title { get; set; } public string Description { get; set; } public DateTime ExpireDate { get; set; } }
Now, exactly like we do with SQL CE or SQL Lite, we need to tell to the library which is the structure of our database. In our example we’ll have one “table” to store all the activities. First we declare a new DbIstance object in the page, so that can be used by every method of the class:
private DbInstance db; private async void LoadDatabase() { db = new DbInstance("catalog"); db.Map<Activity>() .Automap(x => x.Id); await db.InitializeAsync(); }
Then we create a new instance of the DbInstance class, passing as parameter the name of the folder that will be created in the local storage to store all the data. We’ll need to refer always to this key in order to do operations on our data.
Then, using a fluent approach, we set which is the entity that we need to store with the Map<T> method, where T is the class we’re going to serialize (in our example, Activity). In the end we define which is the primary key of the table, that will be used to perform all the queries, using the Automap method: by using the lambda syntax we specify which property of our entity is the primary key, in our example the Id property. Before moving with doing operations we call the InitializeAsync() method on the DbInstance object, so that the library is able to create all the needed infrastructure to store the data. It’s an asynchronous operation, so we mark the method with the async keyword and we use the await keyword in order to wait that everything is correctly setup before doing something else. The library provides also synchronous methods, but I always suggest you to use the asynchronous ones, in order to provide a better user experience.
Now we are ready to save some data:
private async void OnInsertDataClicked(object sender, RoutedEventArgs e) { Activity activity = new Activity { Id = 1, Title = "Activity", Description = "This is an activity", ExpireDate = DateTime.Now.AddDays(3) }; await db.Table<Activity>().SaveAsync(activity); }
The syntax is pretty straightforward: we create a new Activity object and we pass it to the SaveAsync method on the Table<Activity> object, which is the mapping with the “table” that stores our data. Simple, isn’t it? And if we want to get our data back? Here is an example:
private async void OnReadDataClicked(object sender, RoutedEventArgs e) { Activity[] activities = await db.Table<Activity>().LoadAllAsync(); foreach (var activity in activities) { MessageBox.Show(activity.Title); } }
In this sample we retrieve, using an asynchronous method, all the Activity entities with the LoadAllAsync method, that is available using the Table<T> property of the database. Since the primary key of the table acts also as index, we can also query the table to get only the item with a specific id, by using the LoadByKeyAsync method:
private async void OnReadDataClicked(object sender, RoutedEventArgs e) { Activity activity = await db.Table<Activity>().LoadByKeyAsync(1); MessageBox.Show(activity.Title); }
Please note! The DbInstance object exposes directly some methods to do these basics operations, like Save() and LoadAll(). The library is able to understand which class we are using and to do the operation on the correct table. Anyway, I suggest you to always access to the data using the Table<T> property because, this way, you have access also to the asynchronous method that, otherwise, wouldn’t be available.
Using indexes
One common scenario in such an application is to query the data, to get only the items that meet specific criteria. This is what index are for: during the database setup you can choose to use one or more properties as index and use them to perform query operations. Let’s see an example: let’s say that we want to perform queries on the Title properties, to search for activities with a specific word in the title.
First we need to change the first database configuration:
private async void LoadDatabase() { db = new DbInstance("catalog"); db.Map<Activity>() .Automap(x => x.Id) .WithIndex("Title", x => x.Title); await db.InitializeAsync(); }
We’ve called a new method, which name is WithIndex: as parameter we pass the name of our index (Title, in our case) and, using a lambda expression, which is the property of our entity that will be mapped with the key.
Now we can execute queries on the Title property by using the same LoadAllAsync method we’ve seen before:
private async void OnReadDataClicked(object sender, RoutedEventArgs e) { List<Activity> activities = await db.Table<Activity>().LoadAllAsync("Title", "Activity"); foreach (var activity in activities) { MessageBox.Show(activity.Description); } }
The difference with the previous sample is that now are passing two parameters to the LoadAllAsync() method: the first one is the name of the index to use, while the second one is the value we’re looking for. The result of this code is that the activities collection will contain all the items which Title property is equal to “Activity”.
What’s going on under the hood?
If we want to see what’s happening under the hood we can use a tool like Windows Phone Power Tools to explore the storage of our application. We’ll see that the library has created a folder called Lex.db. Inside it you’ll find a subfolder with the name of the database you have specified when you created the first DbIstance object: inside it you’ll find a .data file, which holds the real data, and a .key file, which is used for indexing. If you try open it with a text editor like Notepad you’ll see the content of the data you’ve stored in the application, plus some other special chars due to the encoding made by the serialization engine of the library. image
If you want to experiment a bit with Lex.Db, use the following link to download a sample project I’ve created.
Download the sample project
(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.) | http://mobile.dzone.com/articles/lexdb-new-database-storage | CC-MAIN-2014-15 | refinedweb | 1,605 | 57.71 |
> I was noticing that every struct dentry has d_mounts and d_covers entries.> Which are unused 99% of the time, and just waste space.> > I was thinking of ways to shrink that, to at most one pointer.> What makes the most sense to me is to note that the covered dentry> has the name, and the dentry mounted on that doesn't contain anything> except an inode pointer.> > So why not have two inode pointers in the dentry? One for the covered> inode and one for the mounted inode? They'd be the same in most cases.Colin,your observation is right in principle, and I have also plans to changethe way a mount is done. In particular, the new mount should be independentof any hardware file system space boundaries, and should at least providewhat you can read in Uresh Vahalia's "Unix Internals" in chapter 11.11under the headline "stackable file systems", but implemented in ratherdifferent way which should be much simpler than even the old mount.For example, the inodes should not be used for mounts any more, becauseinodes are for doing actual IO in future, while dentries are for lookup()and other things concerning namespace.So everything concerning namespace should deal with dentries solely, andmounting is just adding a new dentry name space layer. For example,directory inodes would be superfluous at all if the attributes currentlybelonging to them are moved to a separate structure.I'm just busy with family affairs and have no time to explain itin detail, so please wait until a) Linus will converge the new vfs toa more stable state, and b) until I have more time again for discussionson the topic.-- Thomas | http://lkml.org/lkml/1997/8/6/42 | CC-MAIN-2013-20 | refinedweb | 280 | 60.55 |
Ter.
If you have not worked through the article Creating a Table JUDF with the Teradata Plug-in for Eclipse, do so now before you continue.
In this example, an aggregate JUDF takes a list of prices from a Product database table and returns the average price from that list.
Re-use the Teradata Project you created in the last article or create a new Teradata Project as described in the article Create a Teradata Project using the Teradata Plug-in for Eclipse. The Teradata Project gives you access to the Teradata Libraries. The Teradata Libraries contains the Java User Defined function utilities JAR (javFnc). You will need the javaFnc.jar to implement your aggregate JUDF.
In Eclipse, open the Data Base Perspective. Now open the connection for the database where you wish to create your aggregate JUDF in the Data Source Explorer (DSE). Expand the DSE tree to the schema where you want your JUDF. Select the User-Defined Function from the DSE Tree Node and right click. An option menu will come up. Select the menu optionTeradata->Create Java User Defined Function.
At this point, the JUDF Wizard will come up. The first page of the Wizard defines the properties file for the Table JUDF. You will need to enter the container name "/
SalesProject" and the name of the JUDF properties file "
AveragePrice". Once you have done this, select the “Next” button.
The next page is where the JUDF class is defined. Enter the source folder “
SalesProject/src/java”, package name “
sales” and the class name “
AveragePrice”. Once this is done hit the “Next” button.
This page allows you to define the function method for the JUDF. SQL data types are used to define the parameter types in this panel. The SQL data types are mapped to specific Java types.
Now, enter the method name “
getAveragePrice”. Next go to the "New" button for the parameter list and then add the parameter name “
price”. Pick the data type
FLOAT and choose the
Apply button. Now select the "Next" button.
The next page allows you to define the return type for your JUDF. The default for the return type is scalar. Select the Aggregate option from the Return Type Combo box, the aggregate column specification panel will appear. Now select FLOAT as the return type for the aggregate JUDF. You will also have the options to define an aggregate storage class and an aggregate phase code template to be generated with the JUDF. The aggregate storage option specifies that a storage class should be generated with the Java User Defined Function. The storage class is used to store context information needed to create an aggregate sum for the Java User Defined Function. The aggregate phase code template option specifies that a case statement is to be generated in the Java User Defined Function. The aggregate phase code switch statement manages the life cycle of the call to the Java User Defined Function. These options are selected by default.
Once you have set the return type for your JUDF, hit the next button until you get to the UDF Option Wizard Page. The Options Wizard Page allows the user to specify the DDL options for a JUDF. The Storage Size numeric option allows the user to specify the intermediate storage area for an aggregate function. For this example you can leave the storage size value to the default.
Now hit the next button until you get to the Preview SQL Wizard Page. Validate the SQL and then select the Finish button.
Once the Finish button is selected, the JUDF Multi-Page editor will come up.The JUDF Multi-Page Editor brings up the contents of the JUDF properties defined in the JUDF Wizard. The Multi-Page editor allows you to edit and deploy a JUDF.
The first page in the editor will show the Class Definition of the aggregate JUDF.
Select the source tab of the Multi-page Editor. This will bring up the source page. This editor page will have the generated code for the table JUDF. The storage class will be created if the option was selected in the JUDF Wizard. The storage class will use the JUDF input parameters as class members.
The aggregate phase code case statement will be generated with the Aggregate JUDF if this option was selected in the Wizard. This code is only a template. You will need to add in the logic to create the aggregate sum to return. First you will want to change your storage class to keep a count and add a method to calculate the average price. Replace the AveStor class with the following code:
/**
* Storage class for AveragePrice Java User Defined Function
*
*
*/
class AveStor implements Serializable {
private double price;
int count = 0;
/**
* Constructor
*
*
*/
public AveStor() {
// TODO Initialize to context object to maximum size
}
/**
* Get storage Class member price
*
* @return price
*/
public double getPrice() {
return this.price;
}
/**
* Set storage class member price
*
* @param price
*/
public void setPrice(double price) {
this.price = price;
}
/**
* @return the count
*/
public int getCount() {
return count;
}
/**
* @param count
* the count to set
*/
public void setCount(int count) {
this.count = count;
}
/**
*
* @return average
*/
public double getAverage() {
return (price / ((double) count));
}
}
Now you will need to update the phase code switch statement to use the new storage class. Replace the phase code switch statement with the following code:
try {
AveStor s1 = null;
/*
* AGR_DETAIL, AGR_COMBINE, and AGR_FINAL phases use the value from
* the aggregate storage area.
*/
if (phase.getPhase() > Phase.AGR_INIT
&& phase.getPhase() < Phase.AGR_NODATA) {
s1 = (AveStor) context[0].getObject(1);
}
switch (phase.getPhase()) {
/* The AGR_INIT phase is executed once. */
case Phase.AGR_INIT:
s1 = new AveStor();
/* Fall through to detail phase also. */
case Phase.AGR_DETAIL:
// Perform SUM
double total = s1.getPrice() + price;
s1.setPrice(total);
int countTotal = s1.getCount() + 1;
s1.setCount(countTotal);
break;
case Phase.AGR_COMBINE:
AveStor s2 = (AveStor) context[0].getObject(2);
// TODO SUM between AMPs.
double totalCombine = s1.getPrice() + s2.getPrice();
s1.setPrice(totalCombine);
int countTotalCombine = s1.getCount() + s2.getCount();
s1.setCount(countTotalCombine);
break;
case Phase.AGR_FINAL:
// Final, return SUM.
return s1.getAverage();
case Phase.AGR_NODATA:
/* Not expecting no data. */
return -1;
default:
throw new SQLException("Invalid Phase", "38U05");
}
/* Save the intermediate SUM in the aggregate storage. */
context[0].setObject(1, s1);
} catch (Exception ex) {
throw new SQLException(ex.getMessage(), "38101");
}
return returnValue;
}
The phase code case statement uses the class
com.teradata.fnc.Phase from the javFnc JAR in the Teradata Project. You allocate and set the context in this Phase class. You manage the life cycle of your JUDF by accessing the phases that are stored in the Phase class. For instance, the
Phase.AGR_INIT phase is where you allocate the memory for your storage class. The
Phase.AGR_DETAIL phase is where you sum values for the aggregate JUDF.
Once you are done editing your aggregate JUDF, select the JAR files tab. A prompt will come up asking if you want to save the changes to your JUDF. Now select the deploy button. This will create a JAR for your JUDF and deploy it on the target database.
The next step is to run the SQL to create the DDL for your table JUDF. Select the SQL tab. Now, select the RUN SQL button on the SQL editor page. This will install the aggregate JUDF DDL on your target database.
To run your aggregate JUDF, you will first need a database table of data. Enter the following SQL in a new DTP SQL editor window.
CREATE TABLE products (
id INTEGER NOT NULL PRIMARY KEY,
description varchar(255),
price decimal(15,2)
);
INSERT INTO products (id, description, price) values(1, 'Lamp', 25.0);
INSERT INTO products (id, description, price) values(2, 'Table', 50.0);
INSERT INTO products (id, description, price) values(3, 'Chair', 15.0);
Now right click in the SQL editor and select the menu option Execute all as Individual Statements.
Once you created and populated your table with data, enter the following SQL in the SQL editor.
select getAveragePrice(price) from products;
Now select the new SQL in the editor and right click and choose the menu option Execute Selected Text.
The results will show up in the Results tab in the Eclipse IDE.
The Teradata Plug-in has facilitated the implementation of your aggregate JUDF by creating and managing the associated source, JAR and DDL for your JUDF. This example has shown that Teradata JUDF Wizard and Editor takes the busy work out of creating an Aggregate JUDF. This will give you more time implementing the business logic for your JUDF. For more information on how to create aggregate JUDFs please refer to the online publication "SQL External Routine Programming" Release 13.0 (B035-1147-098. | http://community.teradata.com/t5/Tools/Creating-an-Aggregate-Java-User-Defined-Function-with-the/td-p/37962 | CC-MAIN-2017-22 | refinedweb | 1,445 | 67.04 |
Opened 7 years ago
Last modified 5 days ago
#10672 new enhancement
Automatically minify Javascript and CSS
Description (last modified by )
As discussed previously it might be a good idea to introduce a minification step that pre-processes the JavaScript and CSS files stored in source control.
This would allow developing with clean, well-commented source files while improving performance. We could then switch our JavaScript coding style to 4 spaces indentation and add copyright and documentation comments to file headers. (See #10802)
The step / a related step could do JSLint checking.
How should this be implemented?
- One suggestion was a
make minifystep.
- Another idea would be to add it to
setup.py. minify or distwebres provide setuptools commands (both use YUI compressor, which requires Java)
- Alternatively, we could hook it into
trac-admin deploysomehow.
- Or the web frontend could dynamically minify and cache and combine just the files required for a request into one file. (Including scripts by plugins.)
An important requirement might be to keep this step optional.
Attachments (4)
Change History (39)
follow-up: 2 comment:1 by , 7 years ago
by , 7 years ago
implementing the suggestion of minifying during deployment
comment:2 by , 7 years ago
As for the tool,
minifyseems to be the most convenient, as when you
easy_installit, it also downloads the YUI compressor.
distwebrescan't (yet?) be
easy_installed.
Well, as I quickly found out when implementing the above idea, pipy:minify is just a setuptools wrapper for pipy:yuicompressor. If we don't do the minification via setup.py but rather at deploy time, only the latter is necessary (and only to the extent it simplifies the setup, as then it's only a matter of doing an
easy_install yuicompressor; we could consider the alternative of asking people to specify the path to their
yuicompressor-...jar but people are lazy, downloading, unpacking the YUI compressor and specifying the path is probably goinf to be overkill ;-) ).
follow-up: 4 comment:3 by , 7 years ago
Very nice!
Two small suggestions:
- Print some informative message if minification fails, like "Minification of %(filename)s failed.
easy_install yuicompressorand
javain path are required."
yuicompress_all_but_jquery: Is this because jQuery is already minified? Would it make sense to detect a
-minsuffix instead of a
jqueryprefix?
comment:4 by , 7 years ago
Very nice!
Thanks!
Two small suggestions:
- Print some informative message if minification fails, like "Minification of %(filename)s failed.
easy_install yuicompressorand
javain path are required."
Ok, I agree some error reporting can be useful. Added this and also improved the command help, see [f187f18d/cboos.git] and previous.
yuicompress_all_but_jquery: Is this because jQuery is already minified? Would it make sense to detect a
-minsuffix instead of a
jqueryprefix?
Yes, this is also a good idea: some
jquery... files could benefit from minification, and it's nice to be able to tell plugin authors "if you don't want a specific resources to be minified, make sure it ends up with
.min.{css,js}". Only problem was for
jquery-ui.css, which is not minified (so I didn't want to add
.min to the name) but nevertheless should be excluded (as it triggers an error). I now explicitly blacklist that one.
comment:5 by , 7 years ago
Tiny correction:
-log("Package yuicompress is not installed") +log("Package yuicompressor is not installed")
follow-up: 21 comment:6 by , 7 years ago
On second thought, I'll rework this to make it an optional component, it's not appropriate to make the core refer to one particular external package. The only drawback is that I think we'll lose the possibility to have a
--minify parameter to deploy and instead we'll have to rely on the component being enabled or not.
comment:7 by , 7 years ago
comment:8 by , 7 years ago
comment:9 by , 7 years ago
comment:10 by , 7 years ago
redirected from #11024 IMO, nothing can be compared to node.js' uglify-js and clean-css.
And they are already cross platform. so the only new requirement would be for one to install node.js for the OS.
We can have a package.json with the needed dependencies so then the user would need to do
npm install and the dependencies would be retrieved for them.
comment:11 by , 7 years ago
Yes, that's why I didn't commit my initial approach, I wanted to make it possible to use different tools for that task.
comment:12 by , 7 years ago
I wouldn't be all too happy to add node.js as a required dependency for Trac. According to user feedback, Trac is already complicated enough to install. Having to install yet another "package manager" just for node.js doesn't strike me as a good idea.
comment:13 by , 7 years ago
node.js is the standard nowadays for web development. I hate dependencies myself but this is the optimal way IMO.
I would be happy if any way was used to minify and merge the CSS and JS files. Because at this point the problem is the size and the number of files.
comment:14 by , 7 years ago
Well, in a way installing node.js (which comes with its package manager npm) is somewhat less resource demanding than the alternative yuicompressor, which requires … Java. Not all Linux server platforms have it installed by default (for example, t.e.o does not).
Choice is good and neither minification tool should be required anyway.
comment:15 by , 7 years ago
I guess a simple solution for reducing the requests would be to just merge the files when deploying. Like doing
cat 1.js 2.js>javascript.js
comment:16 by , 7 years ago
BTW, there's definitely something wrong in v1.0 css or js. After I minified the CSS and JS files, the /log layout stopped working like before. Unfortunately I cannot provide more details, but I can attach the minified files.
comment:17 by , 7 years ago
LOL @ node.js
and what's wrong with minify and it's deployment of chained files ?
comment:18 by , 6 years ago
comment:19 by , 6 years ago
comment:20 by , 6 years ago
by , 5 years ago
Adapt cboos yuicompressor code to optional component and add uglify-js and clean-css alternatives.
comment:21 by , 5 years ago
make it an optional component, it's not appropriate to make the core refer to one particular external package.
In this patch I define a new extension point
IDeployTransformer and adapt your code to create a new optional component
tracopt.env.yuicompressor.
nothing can be compared to node.js' uglify-js and clean-css.
Alternatively, the patch also contains
tracopt.env.uglifyjs and
tracopt.env.clean-css for people that prefer NodeJS to Java.
(The YUI compressor seems to compress slightly better though.)
comment:22 by , 5 years ago
Some points I'm unsure about:
- Should
trac.env.IDeployTransformer:
- Be called something else? (E.g.
IStaticResourcePreprocessor,
IDeploymentParticipant, …)
- Be located in another module? (E.g.
trac.admin.api,
trac.web.chrome, …)
- Is that interface at the right abstraction level? Is it general enough to be useful for other use cases?
- PNG optimization (#11024) was mentioned, and seems like it would be no problem.
- Other vaguely similar preprocessing steps:
- Javascript compilation from Coffeescript, Typescript, Clojurescript, Dart, … (#10735)
- CSS compilation from LESS, SASS, … (#633)
- But these are usually not optional. So I am not sure the (optional) deploy step is the right place for these. (Unless the default is to interpret the unpreprocessed files in the browser. But even then it's unclear how references to the unpreprocessed files would be overridden if the optional preprocessed files are created.)
- These would probably want to change the extension of the destination filename. (I can't see anything that would prevent that at the moment, although it is currently not obvious from the interface documentation if that is allowed.)
- A similar problem comes up if we want to merge / concatenate files.
- Should the
tracopt.env.*modules:
- Be called something else? (
YUIvs.
Yui; is the
...DeployTransformersuffix a good idea? etc.)
- Be located in another package? (E.g.
tracopt.admin.deploy.*, …)
- Have different module names?
- Especially as
tracopt.env.yuicompressorcurrently requires the
from __future__ import absolute_importdirective to import its external dependency
yuicompressor.
- Should the Java, NodeJS and NPM package dependencies be declared in
setup.pysomehow?
- Are these three minifiers (YUI Compressor, UglifyJS and Clean-CSS) the ones we want to include?
- More?
- Less?
Any ideas or other concerns?
by , 5 years ago
comment:23 by , 5 years ago
For minifying Javascript we previously used Google Closure Compiler. Attached is a
IDeployTransformer for the online REST API, but there's a rate limit:
Too many compiles performed recently. Try again later.
Oops.
Also it refuses to compile diff.js:
Parse error. IE8 (and below) will parse trailing commas in array and object literals incorrectly. If you are targeting newer versions of JS, set the appropriate language_in option.
comment:24 by , 5 years ago
comment:25 by , 5 years ago
comment:26 by , 5 years ago
For comparison here are the results of the various Javascript transformers:
The Closure Compiler has three optimization levels (Whitespace only, Simple and Advanced). YUI outperforms UglifyJS. Only Closure Compiler with Advanced optimizations achieves better rates.
For the CSS CleanCSS and YUI perform very similarly:
(For CleanCSS I had to add another flag:
--skip-rebase.)
The online services (CleanCSS) and (UglifyJS) might also be interesting. (Although I guess there are too alternatives to try all of them).
by , 5 years ago
comment:27 by , 5 years ago
The results of these two online services are actually fairly competitive (very similar for CSS, slightly better than YUI for JS).
I'm actually tempted to only include that last simple implementation using these two online services in
tracopt, and leave the others for external plugins.
comment:28 by , 5 years ago
follow-up: 31 comment:29 by , 5 years ago
Still not sure what the right approach is. Maybe no complexity should be added to Trac as you can always run your favorite tool on the deployed files yourself.
comment:30 by , 5 years ago
For WordPress / PHP, these guys know what they're doing with. Perhaps poking around a bit to see how and what will help clarify things?
comment:31 by , 5 years ago
Maybe no complexity should be added to Trac as you can always run your favorite tool on the deployed files yourself.
The implicit optimization would be valuable to end users, many of whom already find Trac to be difficult to install and configure without needing to carry out an additional step of minifying the JS and CSS, even if it's not required and only an optimization. Once we expect the JS and CSS to be minified in a deployed application we can do all those things you mentioned in comment:description. That is enough to convince me.
I tested the code a few months back and it seemed good. I'll do some more testing once 1.1.2 is released and try to give feedback on comment:22.
comment:32 by , 5 years ago
Added keyword 'performance'.
comment:33 by , 5 years ago
comment:34 by , 3 years ago
comment:35 by , 5 days ago
Milestone renamed
Good idea! I had a run of the YUI compressor and indeed, this cuts the size of our .js by a half. The .css could also be shrinked down, though the savings are less important.
.js:
For the messages/*.js, the savings are marginal, between 93% and 97% of the original.
.css:
As for the tool,
minifyseems to be the most convenient, as when you
easy_installit, it also downloads the YUI compressor.
distwebrescan't (yet?) be
easy_installed.
Also, I think the best solution would be to do this minification step at
deploytime, as this will enable us to minify the resources from plugins as well. The
.cssand
.jsfiles would be minified before being copied in to the deploy location (in
_do_deploy).
For the last step you suggested, minify and combine on the fly, I'm not sure it's worth the effort, as going through Python for serving .js and .css, no matter what optimization we do at that level, is probably less efficient than letting directly the front-end serve them. And the front-end itself might be able to do such things and more (e.g. mod_pagespeed). | https://trac.edgewall.org/ticket/10672?cversion=0&cnum_hist=26 | CC-MAIN-2019-35 | refinedweb | 2,075 | 57.47 |
.
The Secure Sockets Layer (SSL) protocol uses certificates on the client and server to store encryption keys. The server provides its SSL certificate when a connection is made so that the client can verify the server identity..
For step-by-step instructions, see How to: Configure a Port with an SSL Certificate.
Namespace reservation assigns the rights for a portion of the HTTP URL namespace to a particular group of users. A reservation gives those users the right to create services that listen on that portion of the namespace. Reservations are URL prefixes, meaning that the reservation covers all sub-paths of the reservation path. Namespace reservations permit two ways to use wildcards. The HTTP Server API documentation describes the order of resolution between namespace claims that involve wildcards.
A running application can create a similar request to add namespace registrations. Registrations and reservations compete for portions of the namespace. A reservation may have precedence over a registration according to the order of resolution given in the order of resolution between namespace claims that involve wildcards. In this case, the reservation blocks the running application from receiving requests.
Use the httpcfg.exe set urlacl command to change namespace reservations. The Windows Support Tools documentation explains the syntax for the Httpcfg.exe tool. Modifying the reservation rights for a portion of the namespace requires either administrative privileges or ownership of that portion of the namespace. Initially, the entire HTTP namespace belongs to the local administrator.
The following shows the syntax of the Httpcfg command with the set urlacl option
httpcfg set urlacl /u { |} /aACL
The /u parameter is required when using set urlacl. It takes a string that contains a fully-qualified URL that serves as the record key for the reservation being made.
The /a parameter is also required when using set urlacl. It takes a string that contains an Access Control List (ACL) in the form of a Security Descriptor Definition Language (SDDL) string.
The following shows an example of using this command.
httpcfg.exe set urlacl /u /a "O:AOG:DAD:(A;;RPWPCCDCLCSWRCWDWOGA;;;S-1-0-0)"
If you are running on Windows Vista, you can use the Netsh.exe tool instead. The following shows an example of using this command.
netsh http add urlacl url= user=DOMAIN\user
The HTTP Server API only binds to an IP address and port once a user registers a URL. By default, the HTTP Server API binds to the port in the URL for all of the IP addresses of the machine. A conflict arises if an application that does only binds to those IP addresses that the list specifies. Modifying the IP Listen List requires administrative privileges. firewall. If you choose to customize the client base address of a dual connection, then you also must configure these HTTP settings on the client to match the new address.
The HTTP Server API has some advanced configuration settings that are not available through HttpCfg. These settings are maintained in the registry and apply to all applications running on the systems that use the HTTP Server APIs. For information about these settings, see Http.sys registry settings for IIS. Most users should not need to change these settings.
IIS does not support port sharing on Windows XP. If IIS is running and a WCF service attempts to use a namespace with the same port, the WCF service fails to start. IIS and WCF both default to using port 80. Either change the port assignment for one of the services or use the IP Listen List to assign the WCF service to a network adapter not used by IIS. IIS 6.0 and later have been redesigned to use the HTTP Server APIs. | http://msdn.microsoft.com/en-gb/library/ms733768.aspx | crawl-002 | refinedweb | 619 | 64.71 |
-
I have no idea what I meant, sorry. I've been using Jenkins for a while, and have cobbled together something that works, sort of. Short version is I had to use a sub job so I could run on a different host than the parent job. (Very long story, I'll leave it for now).
And, as you say, my example failed, so I switched to yours, and it works great, thank you.
Given that the jobs we run tend to run for HOURS, if not days, I'm not very concerned about performance unless its something really bad. This command will get run no more than 2 times per stage, and a day-long run has maybe 10 to 20 stages, maximum.
I am, however a little concerned about the 'other issues'. If someone can point me to where to find issues (indeed, documentation! - I'm still struggling to find things) - I would be grateful and will go off and read.
Thanks!
I suppose you meant
def checklog = checkjob.rawBuild.log
This will not work in the Groovy sandbox, and is likely to have poor performance, among other issues.
Lacking this, I did some searching and found a way to 'mostly' work around it (see ) for details. I'm adding it here so people trying to work around the issue have a pointer to a possible solution.
Basically (quoting directly from the above post):
def checkjob = build job: 'job name', parameters: [ any params here]
checklog = Jenkins.getInstance().getItemByFullName('job name').getBuildByNumber(checkjob.getNumber()).log
println checklog
Yes, there are negative issues with that solution, but for my needs I think its probably 'good enough'.
Are there any plans for implementing this? You have this already implemented for parallel stages which are running on multiple nodes - in our case we have parallel jobs running and the only output you get is:
Scheduling project: project Starting building: project
You can navigate to the project and check the logs from there, but when you have 15 jobs and each one has multiple stages which you want to check it makes navigation hard as you need to click "back" button in the browser and that goes through all the pages you've visited. Maybe as a "workaround" we could create a new issue which adds a "triggered by" button which allows you to go back to the job#number which triggered the job you are currently looking (similar to "Triggered Builds" which shows when the current job triggers another job, but backwards) ?
Not sure what that means. The build step only supports triggering a job on the same Jenkins service. Of course if you are talking about different agents, that can be done trivially inside a single Pipeline build.
Besides being insecure and slow, I guess there are no particular issues! | https://issues.jenkins-ci.org/browse/JENKINS-26124?actionOrder=desc | CC-MAIN-2020-24 | refinedweb | 469 | 68.4 |
I am able to understand preorder traversal without using recursion, but I'm having a hard time with inorder traversal. I just don't seem to get it, perhaps, because I haven't understood the inner working of recursion.
This is what I've tried so far:
def traverseInorder(node):
lifo = Lifo()
lifo.push(node)
while True:
if node is None:
break
if node.left is not None:
lifo.push(node.left)
node = node.left
continue
prev = node
while True:
if node is None:
break
print node.value
prev = node
node = lifo.pop()
node = prev
if node.right is not None:
lifo.push(node.right)
node = node.right
else:
break
Lifo
Node
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
class Lifo:
def __init__(self):
self.lifo = ()
def push(self, data):
self.lifo = (data, self.lifo)
def pop(self):
if len(self.lifo) == 0:
return None
ret, self.lifo = self.lifo
return ret
Start with the recursive algorithm (pseudocode) :
traverse(node): if node != None do: traverse(node.left) print node.value traverse(node.right) endif
This is a clear case of tail recursion, so you can easily turn it into a while-loop.
traverse(node): while node != None do: traverse(node.left) print node.value node = node.right endwhile
You're left with a recursive call. What the recursive call does is push a new context on the stack, run the code from the beginning, then retrieve the context and keep doing what it was doing. So, you create a stack for storage, and a loop that determines, on every iteration, whether we're in a "first run" situation (non-null node) or a "returning" situation (null node, non-empty stack) and runs the appropriate code:
traverse(node): stack = [] while !empty(stack) || node != None do: if node != None do: // this is a normal call, recurse push(stack,node) node = node.left else // we are now returning: pop and print the current node node = pop(stack) print node.value node = node.right endif endwhile
The hard thing to grasp is the "return" part: you have to determine, in your loop, whether the code you're running is in the "entering the function" situation or in the "returning from a call" situation, and you will have an
if/else chain with as many cases as you have non-terminal recursions in your code.
In this specific situation, we're using the node to keep information about the situation. Another way would be to store that in the stack itself (just like a computer does for recursion). With that technique, the code is less optimal, but easier to follow
traverse(node): // entry: if node == NULL do return traverse(node.left) // after-left-traversal: print node.value traverse(node.right) traverse(node): stack = [node,'entry'] while !empty(stack) do: [node,state] = pop(stack) switch state: case 'entry': if node == None do: break; // return push(stack,[node,'after-left-traversal']) // store return address push(stack,[node.left,'entry']) // recursive call break; case 'after-left-traversal': print node.value; // tail call : no return address push(stack,[node.right,'entry']) // recursive call end endwhile | https://codedump.io/share/vDiYnC9D4Eaa/1/help-me-understand-inorder-traversal-without-using-recursion | CC-MAIN-2017-39 | refinedweb | 528 | 61.43 |
ATL COM and ADO
I assume the reader knows or at least has a fair idea about COM programming using ATL as well as ADO programming with VB.
What is ADO?ADO standa for ActiveX Data Object.
ADO Features
- Allows acess to all types of data
- Supports free threading
- Supports asynchronous queries
- Supports client-side and server-side cursors
- Supports disconnected recordsets
ADO Architecture.
Using ADOF :
#import "C:\Program Files\Common Files\System\ADO\MSADO15.DLL" rename_namespace("ADOCust") rename("EOF","EndOfFile")
using namespace ADOC") like : rcustid, [out,retval] _Recordset **ptr); };
Building the ATL ComponentNow we are ready to code the SearchCust method to retrieve the corresponding information.What we need to do is :
- Initialize the COM library
- connect to the data source
- execute the SQL commands
- return the Recordset object
- Uninitialize the COM library
Initialize the COM library :
CoInitialize(NULL);
To connect to a data source, parameter....
Uninitialize the COM library :
::CoUninitialize();
Now build the component. This will register the DLL in the registry.
There are no comments yet. Be the first to comment! | http://www.codeguru.com/cpp/com-tech/atl/atl/article.php/c3625/ATL-COM-and-ADO.htm | CC-MAIN-2013-48 | refinedweb | 174 | 56.76 |
*
A friendly place for programming greenhorns!
Big Moose Saloon
Search
|
Java FAQ
|
Recent Topics
|
Flagged Topics
|
Hot Topics
|
Zero Replies
Register / Login
JavaRanch
»
Java Forums
»
Java
»
Swing / AWT / SWT
Author
retrieving textField value. Different approach
ibrahim yener
Ranch Hand
Joined: Jul 22, 2013
Posts: 134
I like...
posted
Sep 29, 2013 20:13:44
0
Hello all
First of all i am sorry for title because i could not find anything suits my question.
Okay, let's start...
I have an experimental project and i am trying to add all GUI components into one different Class
and access them through another Class but problem is i cannot get value from components.
Please let me explain on a code.
Let's say we have a Swing class called A.class and content of it as follows
import java.awt.Component; import java.awt.EventQueue; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import GraphicComponents.B; import javax.swing.JButton; public class A extends JFrame { private JPanel contentPane; public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { A frame = new A(); frame.setVisible(true); } }); } public A() { getContentPane().setLayout(null); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 450, 300); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); B bb = new B(); Object lblNewLabel = bb.displayLabel(); contentPane.add((Component) lblNewLabel); Object cc = bb.displayTextarea(); getContentPane().add((Component) cc); JButton btnNewButton = new JButton("New button"); btnNewButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { System.out.println(cc); } }); btnNewButton.setBounds(226, 221, 91, 21); contentPane.add((Component) btnNewButton); } }
and i have class which holds Graphic Components called B.class and contents is follows
package GraphicComponents; import java.awt.event.*; import javax.swing.*; public class B { public JPanel contentPane = new JPanel(); public JTextField textField; public Object displayLabel() { JLabel lblNewLabel = new JLabel("New label"); lblNewLabel.setBounds(10, 10, 50, 13); return lblNewLabel; } public Object displayTextarea() { textField = new JTextField(); textField.setBounds(130, 156, 96, 19); textField.setColumns(10); return textField; } }
What am i trying to do is, just want to make things are simple. Instead of creating textField, textField_1, textField_2, textField_3 ... etc just create one method holds textField and call it whereever i want
So, things are working here but i cannot get value of textField when Button clicked.
Is there someway to get it?
Regards
WinSystems
my Google play account.
Ping Kong
Tarun Bolla
Ranch Hand
Joined: Jun 20, 2011
Posts: 89
posted
Sep 29, 2013 22:28:00
0
Hi there.. you dont have a reference to the text field control.. I think you can not get its value like that. Instead, when you get the Text Field control from your reusable method, add it to a java.util.List and then display it on UI simultaneously. You can access the text field from the List at any time to get its value.
ibrahim yener
Ranch Hand
Joined: Jul 22, 2013
Posts: 134
I like...
posted
Sep 29, 2013 22:35:20
0
Dear Tarun
Thanks for reply. Here i have couple of questions based on your answer.
Forgive my ignorance because i am learning Java and school just started 2 months ago.
So,
1 - You don't have a reference to the textField control - How can i do that?
2 - Add it to java.util.List - How can i add it into java.util.List
3 - Display it on UI simultaneously - How can i display it?
I really appreciate if you give me explanation.
Regards
Tarun Bolla
Ranch Hand
Joined: Jun 20, 2011
Posts: 89
posted
Sep 29, 2013 23:03:21
0
Creating a reusable method to get a Text Field control (Component) created is good. But you cannot uniquely identify the Text Field until you have a reference variable for it.
JTextField field = new JTextField();
In the above code, field is a reference variable and you hardcode that reference variable in your code to get the value of that field.
String fieldValue = field.getText();
If you are creating a reusable method for returning Text Fields on the fly, you should also consider making the references of the newly created text fields available when needed. Consider the below code (Ignore my comment about List, lets take a Map. Maps are the data structures which will hold key value pairs).
public class A{ private Map<String, JComponent> componentMap = new HashMap<String, JComponent>); /* Consider this the starting method */ public void init(){ JTextField name = createATextField("name"); addToUI(name); JTextField age = createATextField("age"); addToUI(age); } /* Create a field and add it to map for future reference */ private void createATextField(String fieldName){ JTextField field = new JTextField(); componentMap.put(fieldName, field); } /* Read and return value of a labelled field */ public String getFieldValue(String fieldName){ JTextField field = componentMap.get(fieldName); return field.getText(); } }
Now, you have a place to refer to if you need value of the Text Field (The map). This is one way to do it.
Otherwise you can always hardcode the references in your code and create JTextField_1, JTextField_2, JTextField_3 at global level (Class level) which is absolutely fine and has no drawbacks.
ibrahim yener
Ranch Hand
Joined: Jul 22, 2013
Posts: 134
I like...
posted
Sep 30, 2013 00:54:54
0
Dear Tarun
Thanks you so much for your reply. You just gave me new point of view and vision.
regards
I agree. Here's the link:
subject: retrieving textField value. Different approach
Similar Threads
refresh textField and clear textArea when button clicked
Caanot get username from a class
why this is not equal
Refreshing a J-Frame
Can this old dog learn new tricks? Trying input window, manipulate string, output window
All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter
JForum
|
Paul Wheaton | http://www.coderanch.com/t/620921/GUI/java/retrieving-textField-approach | CC-MAIN-2014-42 | refinedweb | 969 | 59.3 |
aws-cfn-bootstrap versions prior to 1.4-22.14 suffer from a local code execution vulnerability.
959ceb0942bc38ddb3afd790bfa315c3
aws-cfn-bootstrap local code execution as root
==============================================
The latest version of this advisory is available at:
Overview
--------
AWS EC2 instances deployed with the AWS CloudFormation bootstrap contain a vulnerable
daemon that enables an attacker to execute arbitrary code as root.
Description
-----------
The aws-cfn-bootstrap `cfn-hup` daemon contains a local code execution vulnerability.
A non-privileged attacker with the capability to write files (either locally or
remotely) can write a specially crafted file which will result in arbitrary code
execution as root.
Impact
------
The non-privileged attacker is able to execute arbitrary commands as the administrative
user (root). This leads to complete loss of confidentiality, integrity and availability.
Details
-------
The discovered vulnerability, described in more detail below, enables multiple
independent attacks described here in brief:
Local Arbitrary Code Execution As Root
--------------------------------------
A local user can overwrite or replace a file with a specially crafted contents
that results in a code execution as root.
The code execution is limited to local users, unless a remotely accessible
service contains an arbitrary file write vulnerability in which case the combined
result is a remote code execution as root.
Information Leak
----------------
A local user can read the metadata_db file. This file typically contains cleartext
passwords and other similar confidential information.
The confidential data is exposed to local users, but if a remotely accessible service
contains an arbitrary file read vulnerability in which case the information is obviously
exposed to external attackers as well.
[CVE-2017-9450] Incorrect Permission Assignment for Critical Resource (CWE-732)
-------------------------------------------------------------------------------
The `cfn-hup` daemon of the `aws-cfn-bootstrap` package is running with umask 0. This
happens because /opt/aws/bin/cfn-hup does not set a secure umask for the `DaemonContext`
class of the `python-daemon` package:
with daemon.DaemonContext(pidfile=pidlockfile.TimeoutPIDLockFile('/var/run/cfn-hup.pid', 300),
signal_map={signal.SIGTERM : kill}):
The `python-daemon` package defaults to a umask of 0 as seen in :
`umask`
:Default: ``0``
File access creation mask ("umask") to set for the process on
daemon start.
A daemon should not rely on the parent process's umask value,
which is beyond its control and may prevent creating a file with
the required access mode. So when the daemon context opens, the
umask is set to an explicit known value.
If the conventional value of 0 is too open, consider setting a
value such as 0o022, 0o027, 0o077, or another specific value.
Otherwise, ensure the daemon creates every file with an
explicit access mode for the purpose.
Any file or directory created by the daemon will thus use the mask as specified
by the `mkdir` or `open` functions.
The code in /usr/lib/python2.7/dist-packages/cfnbootstrap/update_hooks.py does the
following:
def _create_storage_dir(self):
if os.name == 'nt':
self.storage_dir = os.path.expandvars(r'${SystemDrive}\cfn\cfn-hup\data')
else:
self.storage_dir = '/var/lib/cfn-hup/data'
if not os.path.isdir(self.storage_dir):
log.debug("Creating %s", self.storage_dir)
try:
os.makedirs(self.storage_dir)
Since `os.makedirs` defaults to mode 777 the resulting directories /var/lib/cfn-hup and
/var/lib/cfn-hup/data will have permissions 777 (`rwxrwxrwx`), that is, the directories
are world-writable.
The CFN hook processing code reads the file `metadata_db` with the Python `shelve`
module:
def process(self):
with contextlib.closing(shelve.open('%s/metadata_db' % self.dir)) as shelf:
self._resource_cache = {}
for hook in self.hooks:
try:
self._process_hook(hook, shelf)
And:
def _process_hook(self, hook, shelf):
try:
new_data = self._retrieve_path_data(hook.path)
except InFlightStatusError:
return
old_data = shelf.get(hook.name + "|" + hook.path, None)
The `shelve` module comes with a fat warning about possible arbitrary code execution:
> Warning: Because the shelve module is backed by pickle, it is insecure to load a
shelf from an untrusted source. Like with pickle, loading a shelf can execute
arbitrary code.
Since any user can write to the /var/lib/cfn-hup/data/metadata_db file and the
`cfn-hup` daemon is running as root, any user can execute arbitrary commands as
root.
A proof of concept exploit:
#!/usr/bin/env python
import os
import shelve
class E(object):
def __reduce__(self):
return (os.system, ('id >/pwned',))
s = shelve.open('/var/lib/cfn-hup/data/metadata_db')
for k in s.keys():
s[k] = E()
s.close()
The vulnerable code is executed every 15 minutes. So by average it takes 450
seconds for the exploit to get triggered. The exploit is also executed when
the daemon is started (for example at system boot).
Reproducing
-----------
1. Sign in to AWS.
2. From AWS Console "Management Tools" select "CloudFormation".
3. Select "Create Stack".
4. Select eg. the template "LAMP Stack".
5. Fill the relevant fields. Note to select the EC2 keypair to use for access.
6. Leave other options as-is.
7. Click "Create".
8. Once running, ssh to the box with the EC2 keypair as `ec2-user`.
9. Upload the PoC to the host and execute it.
10. Wait at most 15 minutes for the /pwned file to appear.
Vulnerable instances
--------------------
Any AWS EC2 instances that has been deployed with a CloudFormation template that
has the aws-cfn-bootstrap package 1.4-15.9.amzn1 and at least one hook included
(for example `cfn-auto-reloader-hook`). This includes, but is not limited to, the AWS
CloudFormation default LAMP, Rails and WordPress templates.
Hooks with the `on.command` trigger don't result in code execution. Some earlier
versions of aws-cfn-bootstrap might have also had such vulnerability for
`on.command` triggers, as well.
The history of this vulnerability and affected package versions are unclear, but the
vulnerability is believed to have existed at least since 2011. As such the number of
vulnerable systems could be high.
Recommendations to vendor
-------------------------
1. In aws-cfn-bootstrap `cfn-hup` command set the `DaemonContext` umask to 077.
2. For existing installations, run `chmod -R go-rwx /var/lib/cfn-hup` as root.
End user mitigation
-------------------
1. Upgrade aws-cfn-bootstrap to 1.4-22.14.amzn1 or or later
2. chmod -R go-rwx /var/lib/cfn-hup
Credits
-------
This vulnerability was discovered by Harry Sintonen / F-Secure Corporation.
Timeline
--------
05.04.2017 spotted the 'rwxrwxrwx' directories, suspected a vulnerability
08.04.2017 found a way to exploit the vulnerability, wrote the PoC exploit
08.04.2017 wrote a preliminary advisory
19.04.2017 minor adjustments
03.05.2017 some fixes and clarifications
03.05.2017 reported to [email protected]
04.05.2017 received response from the aws security team
12.05.2017 requested status of the issue
18.05.2017 requested status of the issue
25.05.2017 requested status of the issue
25.05.2017 received response: "appropriate actions are being taken"
01.06.2017 requested status of the issue
06.06.2017 received a response: "a fix has been is built, and will be
deployed in the coming couple of weeks."
06.06.2017 requested CVE from MITRE
06.06.2017 MITRE assigned CVE-2017-9450
13.06.2017 forwarded the CVE number to [email protected]
26.07.2017 AWS released a fix as ALAS-2017-861 -
26.07.2017 notified AWS security about the incomplete fix: umask is
still 0, leading to RCE as root via other vectors. sent a
new proof of concept exploit utilizing such new vector
04.08.2017 AWS released an updated ALAS-2017-861 fix, fixing the
vulnerability. the daemon umask is still 0 resulting in
potential information disclosure or code execution vulns
14.09.2017 AWS released a fix to the umask issue as ALAS-2017-895 -
29.11.2017 public release of the advisory | https://exploit.kitploit.com/2017/12/aws-cfn-bootstrap-local-code-execution.html | CC-MAIN-2018-51 | refinedweb | 1,279 | 51.65 |
With a processing cluster set-up and Migrate for Anthos and GKE installed, you are ready to perform the migration. First, you need to add a relevant migration source for your processing cluster as well as generate a migration plan for your VM. After reviewing and customizing the plan to your needs, you are able to generate and deploy Kubernetes artifacts onto the GKE cluster where the rest of your application is already running.
Objectives
At the end of this tutorial, you will have learned how to:
- Add a migration source.
- Create a migration plan from your VM workload.
- Review and customize the migration plan.
- Generate and deploy migration artifacts to your GKE cluster.
Before you begin
This tutorial is a follow-up of the Discovery and assessment tutorial. Before starting this tutorial, follow the instructions on that page to run the discovery tools on the monolith VM and create your processing cluster.
Stop the monolith VM
Before you perform the migration, you must stop the monolith VM to avoid unintentional disruption or data corruption which could occur if data is in movement during migration processes.
In the Google Cloud Console, go to the VM instances page.
Go to the VM instances page
Select the checkbox at the left end of the row for the
ledgermonolith-serviceVM.
At the top of the page, click the Stop button to stop the VM.
Wait for the VM to be fully stopped. This may take 1-2 minutes.
Migrate the VM
Now that your migration candidate VM is fully stopped, you can start preparing for the migration and execute it. You first need to create a source to designate your processing cluster as the designated cluster for your Compute Engine migration. Then, you can initiate a full migration of your VM.
Add a source
Open the Migrate for Anthos and GKE page in the Cloud Console.
Go to the Migrate for Anthos and GKE page
In the Sources tab, click Add Source.
Select the
migration-processingcluster from the drop-down list and click Next.
Specify the Name of the migration as
ledgermonolith-source.
Set the Source type to Compute Engine and click Next.
Ensure the right project is selected as the source project.
Create a service account that enables you to use Compute Engine as a migration source by selecting Create a new service account.
Click Next and then Add Source.
Create a migration
Open the Migrate for Anthos and GKE page in the Cloud Console.
Go to the Migrate for Anthos and GKE page
In the Migrations tab, click Create Migration.
Set the Migration name as
ledgermonolith-migration.
Select the migration source you created in the previous step:
ledgermonolith-source.
Set the VM OS type to
Linux.
Set the source Instance name to
ledgermonolith-service.
Set the Migration intent as
Image & Data.
Click Create Migration. This may take 1-2 minutes.
When the migration completes, the Status column displays Migration plan generated.
In the table, click on the Name of your migration,
ledgermonolith-migrationto open the details page.
Select the YAML tab.
In the migration plan, under
dataVolumes, replace the placeholder
<folder>with the location of the VM's PostgreSQL database,
/var/lib/postgresql. The object should look like this:
... dataVolumes: # Folders to include in the data volume, e.g. "/var/lib/mysql" # Included folders contain data and state, and therefore are automatically excluded from a generated container image # Replace the placeholder with the relevant path and add more items if needed - folders: - /var/lib/postgresql ...
This will make sure that you persist the database throughout the migration.
Still in the migration plan, under
deployment, make sure that your service has the name
ledgermonolith-service, port
8080, and protocol
TCP. The object should look like this:
... endpoints: - name: ledgermonolith-service port: 8080 protocol: TCP ...
Click Save and generate artifacts to begin the migration process. This process will take approximately 7-8 minutes.
The artifacts generated by Migrate for Anthos and GKE for this VM are:
- A Docker image of the VM process.
- A StatefulSet and a Service to run the newly migrated process.
- A Namespace and a DaemonSet to hold the container runtime.
- A PersistentVolumeClaim and a PersistentVolume to hold the PostgreSQL database.
Deploy the migrated workload
In the previous section, you have successfully migrated your monolith VM to a set of Kubernetes resources that can be deployed in a cluster. You can now deploy these resources onto your Bank of Anthos cluster, reconfigure the application for it to talk to the right endpoint for your newly migrated ledger service, and verifying that it all works.
Now that the migration artifacts has been generated, you can connect to the processing cluster and download the artifacts to your Cloud Shell environment.
gcloud container clusters get-credentials migration-processing --zone COMPUTE_ZONE --project PROJECT_ID
migctl migration get-artifacts ledgermonolith-migration
Connect to the Bank of Anthos cluster and deploy the generated Kubernetes resources. Additionally, install a container runtime using
migctlfor your cluster to be able to run your newly migrated Pod.
gcloud container clusters get-credentials boa-cluster --zone COMPUTE_ZONE
migctl setup install --runtime
kubectl apply -f deployment_spec.yaml
Fetching cluster endpoint and auth data. kubeconfig entry generated for boa-cluster. applying resources to the cluster namespace/v2k-system created daemonset.apps/runtime-deploy-node created statefulset.apps/ledgermonolith-service created service/ledgermonolith-service-java created persistentvolumeclaim/data-pvc-0-4e1b2e0e-021f-422a-8319-6da201a960e5 created persistentvolume/pvc-4d41e0f2-569e-415d-87d9-019490f18b1c created
Edit the ConfigMap containing the ledger hosts to point to your new Kubernetes Pod, rather than the ledger monolith VM that is no longer in service.
sed -i 's/'.c.PROJECT_ID.internal'//g' ${HOME}/bank-of-anthos/src/ledgermonolith/config.yaml
kubectl apply -f ${HOME}/bank-of-anthos/src/ledgermonolith/config.yaml
Delete all Pods to recreate them with your new configuration.
kubectl delete pods --all
You can view the state of the Pods using the following command:
kubectl get pods
It may take a few minutes for all the Pods to be up and running.
NAME READY STATUS RESTARTS AGE accounts-db-0 1/1 Running 0 5m43s contacts-d5dcdc87c-jbrhf 1/1 Running 0 5m44s frontend-5768bd978-xdvpl 1/1 Running 0 5m44s ledgermonolith-service-0 1/1 Running 0 5m44s loadgenerator-8485dfd-582xv 1/1 Running 0 5m44s userservice-8477dfcb46-rzw7z 1/1 Running 0 5m43s
Once all the Pods are set to
Running, you can find the
frontendLoadBalancer's external IP address.
kubectl get service frontend
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE frontend LoadBalancer 10.79.248.161 ##.##.##.##. 80:31304/TCP 46m
Open a browser and visit the web page at the external IP address found above (be sure to use HTTP, rather than HTTPS).
You should be able to login with the default credentials and see transactions. The transactions you see are coming from the ledger monolith which has now been migrated to a Kubernetes container.
Summary
You have started this tutorial with a live application composed of multiple services, some living in a GKE cluster and some living on a VM in Compute Engine. With only a few easy steps and without any code change or difficult refactorization, you have successfully migrated a monolithic service along with a database from a VM to the GKE cluster, thus reducing compute costs and increasing the ease of development for developers.. | https://cloud.google.com/migrate/anthos/docs/migrating-monolith-vm-migration-deployment | CC-MAIN-2021-39 | refinedweb | 1,226 | 56.05 |
"Mice" is the plural of mouse, the animal. So far there's no official parlance for the plural of mouse, the input device; the fact that "mice" is specifically a conjugation which refers to the plural of an animal with an -ouse sound (such as louse/lice) makes some grammaticians a bit worrisome about the further corruption of English, even though English is a connotative language. As such, some of them encourage the use of the kludgy and cumbersome term "mouses" instead. I personally prefer to take the cop-out approach and say "mouse input devices" so as to avoid any potential grammar vs. namespace conflict.
"Mouses" is what a mouser does - think Tom and Jerry: Tom is a mouser. He mouses. He mouses Jerry and any other meece (meeces?) that might populate the dwelling.
Coffee, please! Not lucid yet!
Log in or register to write something here or to contact authors.
Need help? accounthelp@everything2.com | https://everything2.com/title/mouses | CC-MAIN-2017-30 | refinedweb | 157 | 62.78 |
Logical•ai
Morsels
Written by
Dylan Holmes
Dylan Holmes
These are "morsels" — little ideas or results that can be expressed in a short space. They may be exported or extended to full articles at a later time. (You can go to page 2)
Convex shadows. Any convex 3D object will have a silhouette of a certain area. Averaged over all viewing angles, the size of the silhouette is exactly a quarter of the object's surface area.
Why? By dimensional analysis, the size of the silhouette must be proportional to surface area. By subdividing the surface into shadow-casting pieces, you can prove that the constant doesn't depend on shape as long as the shape is convex. So use the example of a unit sphere to compute its value.
The same principle applies in higher dimensions \(n\). The formulas for sphere surface area and volume involve the gamma function, which simplifies if you consider odd and even dimensions separately. Let \(\lambda_n\) designate the constant for \(n\) dimensions. Then:
\[\lambda_{n+1} = \begin{cases}\frac{1}{2^{n+1}} {n \choose n/2} & n\text{ even}\\\frac{1}{\pi}\frac{2^n}{n+1} {n \choose {\lfloor n/2\rfloor} }^{-1} & n\text{ odd}\end{cases}\]
\[\lambda_n = \frac{1}{2},\; \frac{1}{\pi},\; \frac{1}{4},\; \frac{2}{3\pi},\; \frac{3}{16},\; \frac{8}{15\pi},\; \ldots .\]
M'aide!. One afternoon, you call all your friends to come visit you. If they all depart their houses at once, travel in straight lines towards you, and are uniformly distributed throughout the surrounding area, how many people should you expect to arrive as time goes by?
The expected number of arrivals at each moment is proportional to the time since you called. Imagine a circle, centered on you, whose radius expands at the same rate everyone travels. Whenever the circle engulfs someone's house, that's the exact moment the person arrives at your door. Uniform distribution implies number of new arrivals proportional to circumference; number of cumulative arrivals proportional to area.
Same principle generalizes to higher dimensions \(n\).
Connect infinity. Extend the board game connect four so that it has infinitely many columns. You win after infinitely many moves if you've constructed an unbroken rightwardly-infinite horizontal sequence of pieces in any row and your opponent hasn't. (You don't need to fill the whole row, and diagonal/vertical chains don't count in this game.) Prove that you can force a draw.
Nailing down the proof is subtle, because blocking strategies for lower rows don't always generalize to higher rows. The general principle is to block your opponent infinitely many times in each row, preventing an unbroken chain. The specific principle is: to stop your opponent from reaching height \(k\) in a certain column, don't put any pieces there; wait until they build a tower of height \(k-1\) then put your piece on top.
For each row, choose infinite disjoint subsets of \(\mathbb{N}\): \(T_1, T_2, T_3, T_4\). Each \(T_k\) is a predetermined list of columns where you will interrupt your opponent's towers of height \(k\). Whenever your opponent moves, if their piece builds a tower of height \(k-1\) in a column in \(T_k\), put your next piece on top. Otherwise, put your piece in an empty column of \(T_1\) to the right of all pieces played so far.
You never put pieces on your opponent's except to block them, and this blocking process cannot be stopped. A key insight is you can't stymie your opponent by building your own interrupting towers, only by stopping theirs. There is no way to build a tower of height 3 or 4 if the other player wants to prevent it.
Blackout Turing machines. A "blackout machine" is a Turing machine where every transition prints a
1on the tape. The halting problem for blackout machines is decideable.
The tape of a blackout machine always consists of a contiguous region of 1s surrounded by infinite blank space on the left and right. Any machine that reads sufficiently many ones in a row must enter a control loop. By measuring the net movement during the loop, you can decide whether the machine will overall go left, right, or stay in place each iteration. Regardless of how many ones are in a row, using modular arithmetic, you can efficiently predict what state the machine will be in when it exits.
By this reasoning, a state-space graph will help us fast-forward the looping behavior of the machine. A q-state machine can enter a loop with period 1, 2, 3, …, or at most q. To anticipate its behavior on any-sized string of ones, it's therefore enough to know what the string size is mod 2, mod 3, …, mod q. Thus, for each option of left-side/right-side, each possible state of the machine's control, and each possible value of string length mod 2, mod 3, mod 4,… mod q, the graph has a node. By simulating the machine, you can efficiently compute the transitions between nodes of this graph, recording how the machine-and-tape will look whenever the machine exits the string of ones. (Add a special node for "loops forever within the string of ones" and "halts").
There are (on the order of) q! nodes in this graph—overkill, but still finite. You can simulate the machine in fast-forward using these graph transitions. After simulating a number of transitions equal to the number of nodes in this graph, the machine must either halt, loop forever within the region of ones, or revisit a node (in which case it loops forever, growing the region of ones).
Lopped polygons. Lop off the edges of a regular polygon, forming a regular polygon with twice as many edges. Repeat this process until, in the limit, you obtain a circle. As you might expect, that circle turns out to be the incircle of the polygon (i.e. the largest circle contained in it).
Interestingly, the cutting process multiplies the original perimeter of the object by \((\pi/n) \cot(\pi/n)\), where \(n\) is the original number of sides. It multiples the area by the same amount (!).
NP-complete morphemes. If you have a language (set) of even length strings, you can form a language comprising just the first half of each string, or just the second half.
- Is there a language which is in P, but where each half-language is NP-complete?
- Is there a language which is NP-complete, but where each half-language is in P?
The answer to both questions is yes. For the first question, make a language of strings where each half contains a hard problem and a solution to the problem in the other half. Then each half-language is hard because it's a hard problem paired with a solution to an unrelated problem. But the combined language is easy because then both problems come with solutions.
For the second question, make a language by pairing up easy problems according to a complicated criterion. So the half-langauges are easy, because they're just sets of easy problems. But the overall language is hard because deciding whether the pairing is valid is hard.
Concrete examples: In the first question, take strings of the form GxHy, where G and H are isomorphic Hamiltonian graphs; x is a Hamiltonian path through H; and y is an isomorphism from G to H. (Pad as necessary so Gx and Hy have the same length.) When Gx and Hy are separated, the strings x and y provide no useful information, so each half-language is as hard as HAMPATH. When united, GxHy is easy because x and y easily allow you to confirm that G and H are Hamiltonian.
In the second question, take strings of the form GH where G and H are graphs and G is isomorphic to a subgraph of H. This is an NP-complete problem. But each half-language is just the set of well-formed graphs, which is easy to check.
Juking jukebox. I couldn't tell whether my music player was shuffling songs or playing them in a fixed sequential order starting from the same first song each session. Part of the problem was that I didn't know how many songs were in the playlist, and all I could retain about songs is whether I had heard them before (not, e.g., which songs usually follow which).
You can model this situation as a model-selection problem over bitstrings representing whether played songs have been heard (0) or not-heard (1). Every bitstring is consistent with random play order, but only a handful are consistent with sequential play order (
...0001111...). Therefore, the longer you listen and remain unsure, the vastly more probable the sequential model is. (Specifically if you play n songs, there are n+1 outcomes consistent with sequential play out of 2n total outcomes.) (And yes; turns out my music player was sequential, which was strongly indicated by the fact that I felt unsure it was random in the first place.)
Loop counting. If there's a unique two-step path between every pair of nodes in a directed graph, then every node has \(k\) neighbors and the graph has \(k\) loops, where \(k^2\) is the number of nodes in the graph.
Astonishingly, you can prove this result using the machinery of linear algebra. You represent the graph as a matrix \(M\) whose \((i,j)\) entry is one if nodes \(i\) and \(j\) are neighbors, or 0 otherwise. The sum of the diagonal entries (the trace of the matrix) tells you the number of loops. The trace is also equal to the sum of the generalized eigenvalues, counting repetitions, so you can count loops in a graph by finding all the eigenvalues of the corresponding matrix.
The property about paths translates into the matrix equation \(M^2 = J\), where \(J\) is a matrix of all ones. (The r-th power of a matrix counts r-step paths between nodes.) This matrix \(J\) has a number of special properties—multiplying a matrix by \(J\) computes its row/column totals (i.e. the number of neighbors for a graph!), multiplying \(J\) by \(J\) produces a scalar multiple of \(J\), and \(J\) zeroes-out any vector whose entries sum to zero; this is an \(n-1\) dimensional subspace. The property that \(M^2=J\), along with special properties of \(J\), allows you to conclude that higher powers of \(M\) are all just multiples of \(J\); in particular, examining \(M^3=MJ=JM\) reveals that every node in the graph has the same number of neighbors \(k\). So \(M^3 = kJ\). (And \(k^2 = n\) because \(k^2\) is the number of two-step paths, which lead uniquely to each node in the graph.) Notice that because of this neighbor property, \(M\) sends a column vector of all ones to a column vector of all k's, so \(M\) has an eigenvalue \(k\). Based on the powers of \(M\), \(M\) furthermore has \((n-1)\) generalized eigenvectors with eigenvalue zero. There are always exactly \(n\) independent generalized eigenvalues, and we've just found all of them. Their sum is \(0+0+0+\ldots+0+k = k\), which establishes the result.
The same procedure establishes a more general result: If there's a unique r-step path between every pair of nodes in a graph, then every node has \(k\) neighbors and the graph has \(k\) loops, where \(k^r\) is the number of nodes in the graph.
Cheap numbers. The buttons on your postfix-notation calculator each come with a cost. You can push any operator (plus, minus, times, floored division, modulo, and copy) onto the stack for a cost of one. You can also push any integer (say, in a fixed range 1…9) onto the stack; the cost is the value of the integer itself. Find the smallest-cost program for producing any integer.
For example, optimal programs for the first few integers are
1, 2, 3, 2@+, 5, 3@+, 13@++, 2@@**, 3@*. (Here
@denotes the operator which puts a copy of the top element of the stack onto the stack.)
You can find short programs using branch-and-bound search to search the space of stack states. There are some optimizations: Using dynamic programming (Dijkstra's algorithm), you can cache the lowest-cost path to each state so that you never have to expand a state more than once. Second, you can use the size of the stack state as an admissible heuristic: if a stack has \(n\) items in it, it will take at least \(n-1\) binary operators to collapse it into single number.
There's a nice theorem, too: For any integer, the lowest-cost program only ever needs the constants 1 through 5 (additional constants never offer additional savings). The program never costs more than the integer itself, and in fact for sufficiently large integers (over 34), it costs less than half of the integer.
To prove the theorem, first show that every integer \(n\) has a (possibly nonoptimal) program which costs at most \(n\) and which uses the constants 1…5 2. Next, suppose you have an optimal-cost program which uses any set of constants. By the previous result, you can replace each constant with a short script that uses only 1…5, and this substitution won't increase the program's cost. Hence the program-with-substitutions is still optimal, but only uses the digits 1…5, QED.
Rolls with Advantage. In D&D5e, certain die rolls have advantage, meaning that instead of rolling the die once, you roll it twice and use the larger result. Similarly, a modifier is a constant you add to the result of a die roll. There's a simple probabilities nomogram for deciding whether you should prefer to roll (d20 + x) with advantage, or (d20 + y).
To use: draw a line from the DC on the first axis to the modifier on the second axis and continue until you hit the third axis. Read the right-hand value for the probability of success when rolling d20, or the left hand value when rolling d20 with advantage. For example, the orange line shows a situation where DC=16, modifier=+1. With advantage, success rate is around 50%. Without, it's around 30%.
The equation governing the odds \(P\) of beating a DC of \(D\) with a modifier of \(X\) when rolling a g-sided die is: \[g (1-P) = (1-D+X) \]
With advantage, the equation is surprisingly similar: \[g \sqrt{(1-P)} = (1-D+X) \]
And so both can be plotted on the same sum nomogram.
Categorical orientations. The pan and ace orientations are optimal in a certain mathematically rigorous sense. They factor out gender (in the definition, you don't need to know the person's gender or the person's model of gender), and they form what is called a categorical adjunction or Galois connection:
Consider the space of possible orientations. If we assume that each person has exactly one gender and that an orientation comprises a subset of attractive genders, then the space of possible orientations becomes a set \(G \times 2^G\). We can equip \(2^G\) with subset ordering; because genders aren't ordered, we'll equip \(G\) with the identity order (each gender is comparable only to itself). \(G\times 2^G\) has the induced product order.
There is a disorientation functor \(\mathscr{U}:G\times 2^G\rightarrow G\) which forgets a person's orientation but not their gender. Observe that the left adjoint of \(\mathscr{U}\) assigns an ace orientation to each person: \(g\mapsto \langle g, \emptyset\rangle\). And the right adjoint of \(\mathscr{U}\) assigns the pan orientation to each person: \(g\mapsto \langle g, G\rangle\). Each one represents a certain optimally unassuming solution to recovering an unknown orientation3.
\[\mathbf{Ace} \vdash \mathbf{Disorient} \vdash \mathbf{Pan}\]
P.S. The evaluation map \(\epsilon\) ("apply") detects same-gender attraction: In programming, evaluation sends arguments \(\langle f, x\rangle\) to \(f(x)\). Every subset of \(G\) is [equivalent to] a characteristic function \(G\rightarrow \{\text{true}, \text{false}\}\). So if we apply eval to an orientation in \(G\times 2^G\), we determine whether it includes same-gender attraction.
- Geometric orientations. There is a vast potential for amusing orientation-based results in differential geometry, which is a subject I don't yet have the expertise to formalize. For example, if you conceive of a manifold of possible genders with a designated base point for one's own gender, then you can define attraction to a gender by the existence of a geodesic joining them (orientation assigns an overall shape to the gender manifold); closed geodesics, indicative of same-gender attraction, exist only in the presence of curvature and therefore imply that the manifold is not flat.
Pyramid puzzles The objective of the number-tower puzzle is to fill in numbers in a triangular structure so that every number is equal to the sum of the two numbers below it. Some numbers are specified in advance, providing constraint. Example:
The question is, when designing such a puzzle, how many and which spaces should you specify in advance to guarantee that there is a single unique solution? For example, specifying all values at the base nodes is sufficient. How do you characterize all such arrangements?
Solution: Let \(h\) be the height of the tower. If you place \(h\) values in the tower such that you can't solve for any one value in terms of the others, then those \(h\) values uniquely determine a solution. You never require more or less than \(h\) values.
You can prove this using methods of linear algebra. The addition constraints for the tower define a system of linear equations (\(x_1 + x_2 = x_3\), and so on), which you can represent as a matrix. Because filling out the \(h\) base nodes of the tower uniquely determines the solution, and because the problem is linear, it always takes \(h\) independent values to determine a solution.
You can formalize the "solve for one value in terms of the other" in terms of a matrix determinant. Construct the ancestral path matrix \(N\) with one column for every node, and one row for every node specifically in the tower base. In each entry, put the number of distinct upward paths to that node from that base node. Next, if you choose \(h\) tower positions to fill in, pick out the corresponding columns of \(N\) and combine them into an \(h\times h\) matrix, \(D\). Those \(h\) positions uniquely determine the entire pyramid if and only if \(D\) is invertible, i.e. has a nonzero determinant.
This is because the rows of the ancestral path matrix \(N\) span the solution space—each row is a primitive solution. \(N\) sends the \(h\) parameters of the solution space to a complete filled-out solution. Selecting \(h\) columns of \(N\) amounts to forgetting (quotienting out) all but the \(h\) filled-in values in the complete solution. If you can undo the forgetting effect of $D$—if you can recover the \(h\) parameters of the solution space (e.g. the base tower values) from the filled-in values—then you can uniquely determine the complete solution from the filled in values.
Charting the mirror world. A parabolic mirror distorts shapes in the real world. By creating strange anti-distorted shapes, you can create shapes whose reflections "in the mirror world" look normal. With the right coordinate system, the anti-distortion transformation has surprisingly simple form. It's:
\[\widehat{x} = \frac{1 + \sin{\alpha}}{\cos{\alpha}}\] \[\widehat{\alpha} = \frac{1/4x^2 - f}{x}\]
Here (see figure), the parabola's focus is at the origin, the $x$-axis is perpendicular to the optical axis, and the angles \(\alpha\) are measured relative to the origin and x-axis. Every point, real or virtual, is uniquely defined by an \(\langle x, \alpha\rangle\) pair. Parabolas characteristically reflect vertical rays into rays through the focus and vice-versa; this is how you prove the above transformation, and why the transformed \(\widehat x\) coordinate is defined purely in terms of the original angle \(\alpha\) and vice-versa.
Miraculously, even in 3D these anti-distorted figures will have reflections that look correct from any viewing angle (!).
I imagine you could do this same trick for mirrors shaped like other conic sections (ellipse, hyperbola) but I haven't tried yet.
Adjunctions as rounding. (A fun math fact.)
There is a map \(i:\mathbb{N}\hookrightarrow \mathbb{R}\) which includes the natural numbers into the reals (by "typecasting"). Considering \(\mathbb{N}\) and \(\mathbb{R}\) as poset categories, the inclusion has both a left adjoint and a right adjoint.
As you can guess, they're the floor and ceiling functions: if the floor of a number is at least \(n\), then the number itself is at least \(n\), and conversely. This makes floor, perhaps surprisingly, the right adjoint.
\[\lceil \rceil\;\; \vdash \;\; i \vdash \;\; \lfloor \rfloor\]
At least spiritually, an adjunction is exactly like this: the left adjoints round up, adding additional structure, while the right adjoints round down, forgetting it.
Sundial curves. The shadow cast by the tip of a sundial always traces out a conic section. There is a cone formed by the daily circular path of the sun and the tip of the sundial. The shape changes with latitude and season; depending on whether the sun rises and sets (hyperbola), always stays above the horizon (ellipse), or just grazes the horizon (parabola).
Click the image below to see the animation.
The base of the golden cone shows the daily circular path of the sun. The tip of the gnomon casts a shadow where the black cone intersects the ground. In the animation, the cones tilt as you change latitudes, and the shadow changes from hyperbolic to elliptical.
Rainbow materials. A rainbow is formed at the boundary between two materials that bend light differently, such as water and air. Rainbows form perfect circles whose center is in the shadow of your head (the antisolar point) and whose size is determined by the two light-bending materials, irrespective of where you are.
For example, when it rains on the ocean, a rainbow formed from the salty sea spray will have a smaller extent than a rainbow formed from falling rainwater. This is because salt water bends light differently than pure water.
You can use the laws of optics to compute the rainbow's angular extent based on the materials involved 4. I have plotted the relationship in the chart below. As far as I have found, this is the first chart ever to depict rainbow size for materials other than water (which forms rainbows approximately of size 42.5° in air.)
“Rainbow arc nomogram” by Dylan Holmes can be reused under the CC BY-SA license.
Visual clocks. A clock's two hands move as shown in the picture below:
Using this kind of picture, you can visually find the twelve times (once per hour) that the positions of the hour and minute hand coincide (see where the red diagonal intersects the black trajectory):
And you can answer more complicated questions, such as when you swap the positions of the hour and minute hands, how often is the result a valid configuration? 5 Indeed, swapping the hands means flipping the axes:
And the swapped result is valid wherever it intersects the original graph, which it does in 12 x 12 - 1 = 143 distinct places:
Algebraic blood typing. The Jewish dietary law prohibiting mixtures of meat and milk has the same algebraic structure as the rules for which blood types are compatible donors—if you know one set of rules, you can transfer to the other.
In Jewish law, food is categorized by whether it contains meat, dairy, both, or neither, with some strict observers using color-coded dishware for each category6. Note that if you start with food of one type and mix in some other food, you might change its category (e.g. from containing only meat to containing both meat and dairy), contaminating the dishware.
In the simple ABO blood typing model, blood is categorized by whether it has A antigens, B antigens, both or neither. (Blood with both is called type AB; blood with neither is called type O.) To avoid an adverse clotting reaction, the donation rule is that blood with a particular antigen cannot be donated to blood without it.
The dietary laws and blood-typing laws are algebraically the same: food containing meat or milk is analogous to blood expressing A or B antigens. If you mix a little food into your main food, you may contaminate the dishware. If you donate a little blood to a person, the result may cause blood clotting. Contaminated dishware and blood clotting happen under equivalent circumstances.
Now you can determine that Type O blood is the universal donor, analogous to parev food (without meat or dairy). AB is the universal recipient, analogous to basar bechalav food (with both meat and dairy).
Meat-only and dairy-only foods are like type A and type B blood. Accordingly, A can donate to A or AB, and can receive from A or O. Similarly, basari food can be mixed into a dish of basari or basar bechalav food without affecting the dish's category; and the basari category of a dish is unaffected if you mix in basari or parev food.
Conic conversions. The conic sections are a family of 2D shapes comprising hyperbolas, ellipses/circles, and parabolas. You can transform any conic section into any other using a projective transformation ("homography"). If you represent the shape using homogeneous coordinates, a homography is just an invertible 3x3 matrix.
To transform the hyperbola \(y=1/x\) into the parabola \(y=x^2\), use: \(\mathbf{J}\equiv \begin{bmatrix}0&0&1\\0&1&0\\1&0&0\end{bmatrix}.\)
To transform the hyperbola \(y=1/x\) into the ellipse \(x^2+y^2=1\), use: \(\mathbf{K}\equiv \begin{bmatrix}1&-1&0\\0&0&2\\1&1&0\end{bmatrix}.\)
These matrices are invertible. By inverting, composing, scaling, translating, and rotating these transformations, you can therefore turn any conic into any other. (For example, to transform the standard parabola into the standard ellipse, use \(\mathbf{K}\mathbf{J^{-1}}\).)
Tunnel through the Earth. Suppose you magically construct a tunnel through the center of the Earth (ignoring heat, pressure, air friction, and a lot of other practical factors.) If you were to drop an object down the tunnel, it would fall until it reached the other side (accelerating as it approached the center of the Earth, then decelerating to a standstill as it reached the other side), then reverse direction and return to you, and so on.
This is periodic motion, like an elastic spring or a pendulum or an orbit. You can use Newton's law of gravitation to find the force on the object as it falls. (The force turns out to be proportional to its distance from the center, just like with an ideal elastic spring.) The period of a round trip is around 5068 sec (84.5 min, \(T = 2\pi \sqrt{R_{\mathsf{Earth}} / g}\)), which means the object would pass through the Earth in around 42 minutes.
Interestingly, the time period (84.5 minutes) is independent of a large number of factors. The tunnel can follow a diameter through the center of the Earth or any other chord. The tunnel can begin at the surface of the Earth or somewhere beneath it. (These variations are analogous to the way an elastic spring's period does not depend on how far it was stretched initially, or in which direction.)
For similar reasons, a satellite in circular orbit very close to the surface of the Earth also travels periodically with the same period of 84.5 min. If the satellite were directly over the tunnel as you dropped an object down it, they would both reach the other side of the planet at the same time.
- Netwonian insight A parabola is an ellipse with one focus at infinity. Closed orbits—such as a satellite orbiting the earth—are ellipse-shaped with one focus at the center of the earth7. For near-earth projectiles, the center of the earth is effectively infinitely distant. This is a geometric way to understand why near-earth projectiles seem to follow parabolic paths.
Calculus is small arithmetic. What if we invented a new positive number \(\delta > 0\) that was so small its square was zero (\(\delta^2 = 0\))?
We'd get two complementary sets of numbers: ordinary-sized numbers like 1, 2, 3, and small numbers like \(\delta, 2\delta, 3\delta\). We can do arithmetic combining them together, like \(3+2\delta\) or \(\delta(4+7\delta)\). This numerical system is called dual numbers. Every number in this system has a ordinary-sized component and a small-sized component, just like complex numbers have real and imaginary components. They can all be written \(a + b\delta\).
The surprise is that you can do calculus just using arithmetic with these dual numbers. For example, take any polynomial \(P(x)\) and apply it to a dual number \(a+b\delta\). Using the smallness property \(\delta^2=0\), you can prove that \(P(a+b\delta)\) is a dual number whose ordinary-sized part is \(P(a)\) and whose small part is the derivative \(b\cdot P^\prime(a)\) (!)8. Thus dual numbers give you a way to compute the derivatives of polynomials just by evaluating them.
You can retrofit all smooth functions to work with dual numbers; just take this polynomial property as a definition for how ordinary functions should behave:
\[f(a + b\delta) \equiv f(a) + (b\delta) \cdot f^\prime(a)\]
With this definition, you can prove all of the differentiation rules from calculus using only arithmetic. For example, here's the product rule: If \(h(x) = f(x)g(x)\) then:\begin{align*} h(x+\delta) &= f(x+\delta)g(x+\delta)\\ & = [f(x) + \delta f^\prime(x)][g(x) + \delta g^\prime(x)]\\ & = f(x)g(x) + \delta \left[f^\prime(x)g(x) + f(x)g^\prime(x)\right] + \delta^2 [f^\prime(x)g^\prime(x)]\\ & = f(x)g(x) + \delta \left[f^\prime(x)g(x) + f(x)g^\prime(x)\right]\\ \end{align*}
The small part of \(h(x+\delta)\) is \(h^\prime(x)\) by definition, and we have shown that this part is equal to \(f^\prime(x)g(x) + f(x)g^\prime(x)\), proving the product rule. As an exercise, you can prove the other differentiation rules (sum rule, chain rule, quotient rule9, etc.)
These dual numbers are not just a mathematical curiosity; you can define them as a new datatype in a programming language. By defining a few primitive functions that use dual numbers, e.g. \(\sin(a+b\delta)\equiv \sin(a)+b\delta\,\cos(a)\), the definition above gives you a method for computing exact (not approximate) values for the derivative of any combination of those primitive functions. This is called automatic differentiation; it has practical applications in areas such as machine learning.
Conic number systems. The complex numbers introduce a special new number \(i\) with \(i^2=-1\). What would happen if you introduce \(j\) where \(j^2\) is some other real number?
Such numbers still have "real" and "imaginary" components that combine separately. \((a+bj)+(c+dj)=(a+c) + j(b+d)\). You can make complex conjugates \(a+bj \leftrightarrow a-bj\). You can represent these numbers \((a+bj)\) using matrices of the form \(\begin{bmatrix}a & bj^2 \\ b & a\end{bmatrix}\), in which case matrix arithmetic (addition, multiplication, etc.) does the right thing.
You can do arithmetic with these numbers, so you can form polynomials with them, so you can define the exponential as an infinite polynomial: \(\exp(jx) \equiv \sum_{k=0}^\infty \frac{(jx)^k}{k!}\). The "real" part of \(\exp{jx}\) comes from the even-numbered terms in the sum and behaves like cosine. The "imaginary" part comes from the odd-numbered terms and behaves like sine.
Multiplying a point by \(\exp{j\theta}\) moves that point along a circle ("rotation"), along two parallel lines ("translation"), or along a hyperbola ("hyperbolic rotation").
If the real axis is space and the \(j\) axis is time, then these movements have a physical interpretation.
Time is relativistic when \(j^2=+1\); the movement is a "Lorenz boost", changing from one person's spacetime coordinates to another. Time is classical when \(j^2 = 0\); the movement is a Galilean boost (\(\widehat{x} = x - vt\)). Time is just another dimension of space when \(j^2=-1\); the movement is a rotation in space-time. In all three cases, you can think of \(j^2\) as \(1/c\), the speed of light.
Birthdays and bitstrings. Suppose you assign a random k-bit identification number to \(n\) objects. What's the probability of a collision—that at least two objects are assigned the same id?
If you plot the collision probability as a function of the number of bits \(k\), the curve is surprisingly S-shaped—nearly 100% when \(k\) is small, until it suddenly plunges, with a surprisingly graceful tail end, toward a 0% asymptote. Here, I've plotted the probability of collision if you randomly assign a k-bit id to each of the 100 bil neurons (\(n=10^{11}\)) in the human brain:
I approximate the probability of birthday collision very closely as \(p(n,k) \approx 1-\exp(n(n-1)/2^{k+1})\), using the fact that \((1-x) \approx \exp(-x)\) whenever \(x\ll 1\).
We can mark that steep transition between nearly 100% and nearly 0% by finding the place where the function changes most rapidly. This occurs when the numerator \(n(n-1)\) and denominator \(2^{k+1}\) are equal. Intuitively, this is when there is exactly one bitstring for every distinct pair of objects \(n(n-1)/2\) –in this specific case (n=100 bil neurons), when each bitstring has \(k\approx \mathbf{72}\) bits, corresponding to the \(n(n-1)/2 \approx 10^{22}\) possible pairs of neurons.
Note that this is twice as many bits as you'd need if you were sequentially numbering the neurons by hand— \(\log_2(n)\) bits —rather than choosing numerical ids at random — \(\log_2( n(n-1)/2)\) bits. Concretely, if you were using hexadecimal strings as ids for neurons, you could use strings like
60 f4 51 ce adfor sequential numbering, but would need strings at least twice as long (
20 49 3e 99 18 ab ac db 4d | b0 fd fa ce 56 f0 61 6f 5a) to comfortably avoid collisions when choosing at random.
Reading the pinhole camera. Suppose an ideal pinhole camera sits axis-aligned at the origin, pointing in the Z direction. Every homography (3x3 invertible matrix) describes how a particular plane in 3D space is transformed from world space into (homogeneous) 2D camera-screen space.
In particular, the first two columns of the homography describe two 3D vectors (S,T) embeded in that plane, and the third column describes the plane's origin point U. Every point on that plane can be described as Sx + Ty + U. The point at Sx + Ty + U is projected onto the homogeneous point \(\begin{bmatrix}\vec{\mathbf{S}} & \vec{\mathbf{T}} & \vec{\mathbf{U}}\end{bmatrix}\cdot \begin{bmatrix}x&y&1\end{bmatrix}^\top\) on the camera's projection screen.
Reading homographies this way provides a deeper understanding of Morsel #20 (Conic conversions): through foreshortening, you can make ellipses, hyperbolas, or parabolas, look like one another (or, really, segments of one another) when viewed through a pinhole camera. The homography tells you how to arrange a planar drawing of one conic so it looks like another.
Bonus: because homographies are invertible and composable, it follows that you can transform between any two pinhole camera views of a common scene using a homography: send one view to a common plane, then send that plane to the other view.
An easier quadratic formula. (Loh's method). The goal is to factor the equation \[x^2 + bx + c = 0\] into \((x-r_1)(x-r_2)\) to expose the roots \(r_1, r_2\). By expanding, note that the roots have the key property that their sum is \(-b\) and their product is \(c\). In the usual guess-and-check method, you consider various ways of factoring \(c\) and check whether the sum is equal to \(-b\).
In the new method, you use these properties to solve for the roots directly. You don't have to memorize the quadratic formula or make any guesses. Note that the midpoint (average) between the two roots is \(-b/2\), and the two roots lie equidistant from that midpoint. Given that the roots must have the form \(-b/2 \pm u\) for some unknown \(u\), their product is \((-b/2+u)(-b/2-u) = b^2/4 - u^2\). As noted, the product of the roots is also equal to \(c\). Hence we have an equation \(b^2/4 - u^2 = c\) that can be solved immediately for the unknown \(u\) just by addition and taking a square root. The roots are then \(r_i = -b/2 \pm u\).
For example, in the equation \(x^2 + 8x - 9\), the roots are equidistant from -8/2 = -4. The product of the roots is \((-4-u)(-4+u) = 9\), which simplifies to \(16-u^2 = -9\). We solve for \(u\): \(u^2 = 25\), so \(u=5\). The two roots are \(-4 \pm 5\), i.e. 1 and -9. The overall factorization is \((x-1)(x+9) = x^2 +8x - 9\).
Random song access. The first song in your 100-song playlist is your favorite. Your music player has only two buttons: PREV (which goes to the previous song in the list) and RANDOM (which goes to a random song in the list, possibly the same one you're currently on). What's the ideal button-pressing strategy to get to your favorite song in as few presses as possible?
Solution: Let's generalize to \(n\) songs.
- Because RANDOM wipes out PREV's progress, an ideal strategy will perform all the RANDOM presses before all the PREV presses. Whether PREV or RANDOM is better depends on where you are in the list.
- If you're sufficiently close to the start of the list, the optimal strategy is to press PREV repeatedly until you get to the start and win. Hence if you're not sufficiently close, the optimal strategy is to press RANDOM repeatedly until you become sufficiently close, then press PREV repeatedly until you win.
We can solve for the precise value of "sufficiently close": Number the songs starting from 0, and let \(Z\) denote the last position where the PREV strategy is better than the RANDOM strategy.
The PREV strategy takes exactly \(q\) steps, where \(q\) is your position in the list. The RANDOM strategy takes expected \(n/(Z+1) + Z/2\) steps. (Expected number of RANDOMs to get sufficiently close, plus expected number of PREVs to complete.)
If \(Z\) is the last position where PREV is better than RANDOM, then \(Z\) must be the largest integer such that \(Z < n/(Z+1) + Z/2,\) i.e. such that
\[\frac{Z(Z+1)}{2} < n\]
\(Z\) is the index of the largest triangular number smaller than the total number of songs.
- For example, when there are \(n=100\) songs in the list, \(Z=13\) (the triangular number is \(Z(Z+1)/2=91\)), and the optimal strategy is to press RANDOM until you're before position 14 in the list, then press PREV until you get to position 0. This takes an average of around 12.64 steps.
Immortal lineage. Suppose there's a bacterium that, with probability \(p\), splits into two identical copies of itself, and the rest of the time simply dies out. What is the probability that this bacterium has an infinitely long chain of descendants?
Solution: We don't know the probability of an immortal lineage, but call it \(Q\). This event occurs if (a) the bacterium divides, and (b) one or both of its descendants has an immortal lineage itself.
Because the child-copies are independent, the probability of (b) is \(Q+Q-Q^2\) (sum of individual probability, minus probability of both). The probability of (a) is \(p\), as we know. Hence we have an equation in \(Q\):
\[Q = p(2Q-Q^2)\]
If \(Q\) is nonzero, we can solve for it through division: \[Q = 2-1/p\]
Thus when p is 50% (or lower), \(Q=0\) and the lineage will die out. At any higher probability, \(Q\) is nonzero and becomes progressively higher until it reaches \(Q=1\) when p = 100%.
The simple functional equation arose from the self-similar infinities involved—there are no edge cases when there are no edges. This puzzle is an instance of percolation.
Magic duel. To find out whether Magic: The Gathering is geared toward attack or defense, imagine the following scenario. You, playing defense, would like to successfully summon a creature. Your opponent would like to thwart you. If you both can invent any card abilities you like (subject to some fine print), who will succeed?
Small print: You have priority. Invented cards must use existing mechanisms and language, not invent new concepts out of whole cloth.
My solution, an irrefutable defender.
Pokémon linear optimization. The Pokémon type effectiveness chart can be represented as a matrix \(\mathbf{S}\), with one row and column for each type. Type effectiveness is either 2x, 1x, 0.5x, or 0x, but if you use the log of the effectiveness values instead (respectively +1, 0, -1, -∞), you can use matrix multiplication to compute the vulnerabilities of any type combination.
For example, if \(\vec{t}\) is a column vector with a 1 in the Grass and Poison positions and 0 elsewhere, then \(\mathbf{S}\vec{t}\) will be a vector listing the susceptibility of a Grass-Poison type to each attack type.
You can use the matrix approach to ask and answer questions about type effectiveness. For example, if you can combine more than two types, can you make a type combo that is resistant to every type? (Find \(\vec{u}\) so that \(\mathbf{S}\vec{u} \leq \vec{0}\).) Yes. In Gen II onward10, that type combo \(\vec{u}\) is
{:ground 1, :poison 2, :flying 1, :dark 1, :steel 1, :water 2}.
This combination uses eight types, which is minimal. There is exactly one other minimal solution (Challenge to the reader: can you find the other minimal solution?)
Side challenge: Assemble a team of four pokemon such that each of these eight types is represented. (For example, a Nidoking would take care of Ground and one Poison; a Zubat would take care of Flying and the second Poison.) Answer in footnote11.
Magic Squares. I once saw a 4x4 magic square, where the magic sum appeared not only in the rows, columns, and diagonals, but also the four corners, the 2x2 corner squares, the central 2x2, and opposite pairs of "incisors" in between the corner squares.
\(\begin{bmatrix} 17 & 10 & 7 & 17 \\ 20 & 4 & 21 & 6 \\ 5 & 11 & 15 & 20 \\ 9 & 26 & 8 & 8 \end{bmatrix}\)
I wondered how many free parameters such a magic square had. There are 16 variables (4x4 entries) and 18 different groups that sum to the same magic number. The linear sum constraints12 form an 18x16 matrix, whose null space has exactly 6 rows, meaning it takes exactly six independent numbers to specify all the entries completely.
The acutal required number is seven: the null space method assumes all the groups sum to zero. The seventh parameter is your chosen value of the magic sum.
import numpy as np import scipy.linalg # A B C D # E F G H # I J K L # M N O P A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P = np.identity(16) # WHICH THINGS SUM TO THE MAGIC NUMBER? constraints = np.array([ A+B+C+D, # rows E+F+G+H, I+J+K+L, M+N+O+P, A+E+I+M, # cols B+F+J+N, C+G+K+O, D+H+L+P, A+F+K+P, # diagonals D+G+J+M, A+B+E+F, # corner 2x2 C+D+G+H, I+J+M+N, K+L+O+P, F+G+J+K, # middle 2x2 B+C+N+O, # "incisors" E+H+I+L, A+D+M+P # corners ]) Z = scipy.linalg.null_space(constraints) print(Z.shape) # returns: (16, 6)
- Mana polynomials. You can represent costs in Magic: The Gathering as polynomials in the mana symbols WUBRGC, with boolean coefficients.
- Multiplication combines costs together. For example, R*R*R must be paid with three R.
- Exponentiation is shorthand for repeated multiplication; exponents tell you how much of each color is required. For example, R1U2 represents the cost RUU.
- Addition creates alternative costs. For example, (R+G) can be paid with R or G. As another example, (U+U+U) is redundant, equivalent to just U.
- (!) Just like with numbers, you can distribute multiplication across addition. For example, (R+G)(R+U) = RR+RU+GR+GU. The two costs are equivalent to each other.
- The "mana of any color" symbol is just (W+U+B+R+G+C).
- The coefficients aren't numbers; they're boolean values ⊥ and ⊤. ⊥ is unpayable (multiplies like zero), and ⊤ is free-of-charge (multiplies like 1). Based on the meaning of addition and multiplication, we must also have ⊤+⊤=⊤, ⊥+⊥=⊥.
- For example, R(⊤ + G) = R⊤ + RG = R+RG.
- For example, R(⊥ + G) = R⊥ + RG = ⊥ + RG = RG.
- For example, U+U+U = ⊤U+⊤U+⊤U = (⊤+⊤+⊤)U = ⊤U = U. (Redundant alternative costs become absorbed; coefficients are never higher than one and never negative.)
- Mana polynomials have no nontrivial roots, basically because no combination of costs is unpayable ⊥ except the unpayable cost ⊥ itself.
- A mana pool can be thought of as a monomial in this system (i.e. a polynomial with a single term like W3UUG); a pool exactly pays for a cost if the monomial appears in the polynomial. A simple formula is that the pool \(p\) exactly pays the cost \(c\) when \(p+c = c\). For example, as expected, an unpayable cost \(c=\bot\) is zero-like and never has this property; and an empty mana pool \(p=W^0U^0B^0R^0G^0C^0\) pays only for the gratis cost \(c=\top\).
- There are no fractions or negative numbers in this system, but if there were, the wildcard cost
Xwould have the formal value \[\frac{⊤}{⊤-(W+U+B+R+G)}\] because it is defined by the equation
X= ⊤+(W+U+B+R+G)
X.
Commuting polynomial chains. Two polynomials \(P(x)\) and \(Q(x)\) commute whenever \(P(Q(x)) = Q(P(x))\). Some polynmoials commute, and others don't. The set of powers \(\{x^1, x^2, x^3, \ldots, \}\) is an example of a chain—a list of polynomials, one of each degree, which all commute with each other. Are there any other chains?
Any linear polynomial \(\lambda(x)=ax+b\), (where a is nonzero), has an inverse \(\lambda^{-1}(y)=(y-b)/a\). And if \(\{P_i(x)\}\) is a chain, then \(\{\lambda^{-1}\circ P_i \circ \lambda\}\) is also a chain. So every chain is part of a family of similar polynomials. Up to similarity, there is only one other polynomial chain: the Chebyshev polynomials \(T_n(x) \equiv \cos(n\cdot \cos^{-1}(x))\).
Why? You can prove that any quadratic polynomials commutes with at most one polynomial of each degree (so the quadratic determines the whole chain), and each quadratic is similar to a quadratic of the form \(x^2+c\). In chains, the commuting constraint forces \(c(c+2)=0\). When \(c=0\), you get the power polynomials. When \(c=-2\), you get the Chebyshev polynomials. ref 1 ref 2.
Wrońskian derivative rules. The Wrońskian determinant satisfies several neat rules similar to the rules for derivatives:
\[\begin{align*}W[f_1 \cdot g, \ldots, f_n \cdot g](x) &= g^n \cdot W[f_1,\ldots,f_n](x)\\ W[f_1 / g, \ldots, f_n / g](x) &= g^{-n} \cdot W[f_1,\ldots,f_n](x)\\ W[f_1 \circ g, \ldots, f_n \circ g](x) &= (g^\prime)^{n(n-1)/2} \cdot W[f_1,\ldots,f_n]\circ g(x)\end{align*}\]
You can prove this by examining the pattern of derivatives, coefficients, and exponents you get when taking repeated derivatives of \(D_k(f\cdot g)\) or \(D_k(f / g)\) or \(D_k(f \circ g)\). In each case, they're linear combinations of the derivatives of \(f\) alone; the coefficients are polynomials in \(g,g^\prime, g^{\prime\prime}, \ldots, g^{(k)}\).
For the product rule, the pattern comes from Pascal's triangle. For the chain rule, the pattern comes from the combinatorics of partitions, specifically the partition (Bell) polynomials. Arrange the \(g,g^\prime,g^{\prime\prime},\ldots\) terms into a matrix \(\mathbf{G}\) so you can concisely write, say, \(W[f_1\cdot g, \ldots, f_n\cdot g] = \text{det}\mathbf{G} \cdot W[f_1,\ldots,f_n]\). But \(\mathbf{G}\) is a triangular matrix in each case, so its determinant is the product of its diagonal entries. You can find those entries by following the pattern; this establishes the result.
Jacobian derivative rules. The Jacobian determinant \(\partial(f,g)\) of two functions \(f(x,y)\) and \(g(x,y)\) is the determinant of the matrix containing the single-variable partial derivatives of \(f\) and \(g\). Like the Wrońskian mentioned earlier, it is a derivative-based quantity. You can show that the Jacobian determinant follows product, quotient, and chain rules that resemble the rules for ordinary derivatives:
\[\partial(f/g, h) = \frac{g \; \partial(f,h) - f\;\partial(g,h)}{g^2}\] \[\partial(fg, h) = f \; \partial(g,h) + g\;\partial(f,h)\] \[\partial(f\circ g, h) = (Df \circ g)\; \partial(g,h)\]
Pathfinding matrices. Given a directed graph with \(n\) nodes, you can build an \(n\times n\) adjacency matrix \(A\), where each entry \(A_{i,j}\) is one or zero, depending on if there's an edge \(i\rightarrow j\) or not. Surprisingly, you can use this matrix to count paths in the graph: you can prove that the matrix product \(A^p\) is a matrix whose \((i,j)\) entry is the number of paths between nodes \(i\) and \(j\) that have exactly \(p\) steps in the path.
Or, if the edges represent distances, build a distance matrix \(D\), where each entry \(D_{i,j}\) is the length of the edge between \(i\rightarrow j\) (or \(\infty\) if there is no edge.) With a slight modification, we can use the matrix powers \(D^p\) to compute the shortest path between any two nodes. Just redefine arithmetic operations so that addition of two numbers instead computes their minimum, and multiplication of two numbers instead computes their sum. Then the matrix product \(D^p\) is a matrix whose \((i,j)\) entry is the length of the shortest route between \(i\) and \(j\) that has exactly \(p\) steps in the path.
Love triangles require same-gender attraction. Assume reductively that there are two genders. If we draw a diagram using dots (people) linked by arrows (attraction), a love triangle obviously requires three people and three arrows—where in any pair of people, one of them is attracted to the other.
No matter which way the arrows are facing, your love triangle will always have a pattern of the form "A likes B and B likes C".
If that pattern contains same-gender attraction, we're already done. Otherwise, the pattern implies that A and C are the same gender; hence the arrow between A and C (or vice-versa) constitutes same-gender attraction, and we're done in this case, too.
Efficient roll call in MTG. Each species of creature in Magic: The Gathering has a certain set of roles they can fulfill. One species might be able to fulfill only the Cleric role; one might be able to fulfill either the Cleric or Rogue role; and one might not be able to fulfill any role.
An assignment assigns each creature to at most one of the roles it's capable of fulfilling. For a given set of creatures, your party size is the greatest number of distinct roles you can possibly assign, i.e. it's the number of distinct roles you fulfill when your assignment maximizes the number of distinct roles.
I wondered how computationally difficult party size is in the abstract case: suppose you have k roles, and n creatures each capable of satisfying some (possibly empty) subset of those roles. How can you compute the party size?
I was delighted to notice that this is a maximal matching problem on a bipartite graph: make a bipartite graph where one side contains a node for every creature, and the other side contains a node for each distinct role; wherever a creature can satisfy a role, make a link between them. In a bipartite graph, a maximal matching can be found efficiently: You treat it as a network flow problem and solve it (in polynomial time) using the greedy Ford-Fulkerson algorithm. The party size emerges as the maximum flow rate of the network.
Not Fibonacci! Can you find a set of numbers where the sum of any two distinct elements is unique? For example, the set {2,7,11} has this property because each sum (such as 13=2+11) can be uniquely decomposed—you can uniquely infer what the summands were.
You can make an infinitely long sequence with this property. The smallest13 such sequence seems to follow a familiar pattern:
1, 2, 3, 5, 8, 13, 21, 30, 39, 53, …
Strangely, this sequence isn't the Fibonacci sequence—it just happens to agree with it for seven terms. I am not sure why. The Fibonacci sequence does seem to satisfy the "distinct sum" property; it's just not the minimal sequence that does.
(Originally, I wanted to make a symbolic nomogram where instead of addition of numbers, I had combination of discrete symbols. To do so, you need a way to map symbols covertly onto numbers.)
Diverse denominations. Here's a numismatic problem: you want to assemble a collection of coins that can be variously combined to make any integer amount of money between (say) $1 and $100. You may choose coin denominations of any integer amount (e.g. you can have a $3 coin if you want), and you can have multiples of the same denomination (e.g. multiple $4 coins). One allowable, if extreme, solution would be to have a collection of 100 coins for $1 each. Find a solution that uses as few coins as possible.
(Example: In a simpler version of this problem, you need to make any integer amount of money between $1 and $10. You can do so using the collection of coins [$1, $2, $2, $5].)
Answer: (hidden in footnote) 14
Yarn counting. Every planar graph gives rise to an alternating knotwork, as discussed here. The knotwork is a tangle of some number of separate threads. To count the number of threads, you can use the formula: \[|T(-1,-1)| = 2^{c-1}\]
Where T is the Tutte polynomial of the planar graph, and c is the number of threads. Because the Tutte polynomial is a graph invariant, the number of threads stays the same no matter how the graph is drawn/embedded.
- Disintegrating water. (The sea of Theseus) Very rarely, a water molecule can tear apart into a proton and hydroxide ion. For this process, a water molecule has a half-life of around 7.7 hours. Based on that figure, you can calculate how long it would take to be 99% certain that every molecule of water in some container had disintegrated at least once. For 1mL of water, it comes out to around 26 days. Every time you double the amount of water, you (basically) add another half life to the total. For a human body with 50L of water, it takes around a month—31.1 days for all the water to turn over. Amazing!
Footnotes:
By the way, P problems are ones that are easy to solve. For example: is this string a well-formed graph without any syntax errors? In contrast, NP-complete problems are the hardest problems that still have easy-to-verify solutions. For example, is there a path through this graph that visits every node exactly once? It's a hard problem, but verifying a candidate solution is easy. Here's another NP-complete problem: Is this graph a subgraph of that one? Hard in general, but verifying a proposed correspondence is easy.
Proof: Check, by hand, that you can make the first 34 numbers with programs that don't cost more than the number and that use only the digits 1…5 (For any smaller set of digits, this part fails because 5 costs more than 5 to make.) For cases larger than 34, a stronger property emerges: the optimal 1…5 program for each integer costs less than half the integer itself, minus one (!). You can prove this by induction. Check cases 34 through 256 by hand. Then if the theorem is true for every integer between 34 and some power of two, it is true for every integer between that power of two and the next one. Indeed, any integer in that range can be written as the sum of two numbers larger than 34, and by the induction hypothesis, the program which generates those two numbers then adds them costs less than half the integer.
Incidentally, the ace/pan functors have further adjunctions when, and only when, there are no genders. In this case, pan and ace become equivalent and the adjunctions form a cycle.
Suppose you have droplets of one material suspended in another material. Parallel light rays passing into a droplet will refract according to Snell's law. Some light will bounce off the back of the droplet and exit the front of the droplet, refracting as it leaves. The difference between the entry and exit angles (the 'scattering angle') varies. The angular extent of the rainbow is just the minimal scattering angle—because this critical point is where the incoming light rays will be bunched closest together, forming a bright band.
For example, swapping the hour and minute hands at 3:00 puts the hands in an invalid position, because when the minute hand points at 3, the hour hand never points directly at 12. (At 12:15, the hour hand is a quarter of the way toward 1.).
Note: When proving the quotient rule, it will help to multiply by a "complex conjugate" \((g(a)-\delta g^\prime(a))\).
This type combo from Gen II also happens to be resistant to the newly-introduced Fairy type as well: our combo has one Dark type (Fairy is 2x effective) but two Poison and one Steel (Fairy is 0.5x effective.) Hence this type is overall resistant to the Fairy type as well.
Amazingly, among Generation
I & II Pokemon, there are only five Pokemon species you can use to
make such a team—all the others have some conflict.
You need at least \(\log_2(n)\) coins to make all the different numbers between 1 and n, because k coins can make up to 2k different sums. Binary denominations will work (1,2,4,8,…). Better still to use this recursive recipe: To make a set of coins that generates all numbers between 1 and \(n\), include a coin with denomination \(\lceil n/2 \rceil\) plus the coins needed to make all numbers between 1 and \(\lfloor n/2\rfloor\). This uses just as many coins as the binary, but because the total value of all the coins is \(n\) instead of a higher power of two, some sums can be made in more than one way. This redundancy is convenient for a person with a wallet. For our $100 case, we'd need $50, $25, $13, $7, $4, $2, $1. Incidentally, this optimal redundancy justifies why gymnasiums commonly have weights in 5,10,25,45lb denominations. | http://logical.ai/other/org/morsels.html | CC-MAIN-2022-27 | refinedweb | 10,106 | 61.36 |
On 03/06/2016 01:27 AM, Max Reitz wrote:
Sorry that I wasn't so pedantic last time; or maybe I should rather be sorry that I'm so pedantic this time.
Hi Max Welcome all your comments : )
On 16.02.2016 10:37, Changlong Xie wrote:From: Wen Congyang <address@hidden> In some cases, we want to take a quorum child offline, and take another child online. Signed-off-by: Wen Congyang <address@hidden> Signed-off-by: zhanghailiang <address@hidden> Signed-off-by: Gonglei <address@hidden> Signed-off-by: Changlong Xie <address@hidden> Reviewed-by: Eric Blake <address@hidden> Reviewed-by: Alberto Garcia <address@hidden> --- block.c | 50 +++++++++++++++++++++++++++++++++++++++++++++++ include/block/block.h | 5 +++++ include/block/block_int.h | 5 +++++ 3 files changed, 60 insertions(+) diff --git a/block.c b/block.c index efc3c43..08aa979 100644 --- a/block.c +++ b/block.c @@ -4399,3 +4399,53 @@ void bdrv_refresh_filename(BlockDriverState *bs) QDECREF(json); } } + +/* + * Hot add/remove a BDS's child. So the user can take a child offline when + * it is broken and take a new child online + */ +void bdrv_add_child(BlockDriverState *parent_bs, BlockDriverState *child_bs, + Error **errp) +{ + + if (!parent_bs->drv || !parent_bs->drv->bdrv_add_child) { + error_setg(errp, "The node %s doesn't support adding a child",As I said in my reply to v9's patch 3 (and I see you've followed it), I don't quite like contractions in error messages, so I'd rather like this to be "does not" instead of "doesn't".
Okay
If you don't decide to change this patch, then feel free to leave this as it is, because that way you can keep Eric's and Berto's R-bs.+ bdrv_get_device_or_node_name(parent_bs)); + return; + } + + if (!QLIST_EMPTY(&child_bs->parents)) { + error_setg(errp, "The node %s already has a parent", + child_bs->node_name); + return; + } + + parent_bs->drv->bdrv_add_child(parent_bs, child_bs, errp); +} + +void bdrv_del_child(BlockDriverState *parent_bs, BlockDriverState *child_bs, + Error **errp)I wondered before and now I'm wondering why I didn't say anything. Why is this function taking a BDS pointer as child_bs? Why not just "BdrvChild *child"? Its only caller will be qmp_x_blockdev_change() which gets the child BDS from bdrv_find_child(), which could just as well return a BdrvChild instead of a BDS pointer. I see two advantages to this: First, it's a bit clearer since this operation actually does not delete the child *BDS* but only the *edge* between parent and child, and that edge is what a BdrvChild is.
That's convincing.
And second, some block drivers may prefer the BdrvChild over the BDS itself. They can always trivially get the BDS from the BdrvChild structure, but the other way around is difficult. The only disadvantage I can see is that it then becomes asymmetric to bdrv_add_child(). But that's fine, it's a different function after all.
As you said, they are different fuctions at all. So i don't think it's a big deal.As you said, they are different fuctions at all. So i don't think it's a big deal.
bdrv_add_child() creates a BdrvChild object (an edge), bdrv_del_child() deletes it. (I don't know whether you had this discussion with someone else before, though. Sorry if you did, I missed it, then.)+{ + BdrvChild *child; + + if (!parent_bs->drv || !parent_bs->drv->bdrv_del_child) { + error_setg(errp, "The node %s doesn't support removing a child", + bdrv_get_device_or_node_name(parent_bs));Again, optional s/doesn't/does not/.
okay
+ return; + } + + QLIST_FOREACH(child, &parent_bs->children, next) { + if (child->bs == child_bs) { + break; + } + } + + if (!child) { + error_setg(errp, "The node %s is not a child of %s", + bdrv_get_device_or_node_name(child_bs), + bdrv_get_device_or_node_name(parent_bs));Is there a special reason why you are using bdrv_get_device_or_node_name() for the child here, while in bdrv_add_child() you directly use the node name?.
Neither seems wrong to me. A child is unlikely to have a BB of its own, but if it does, printing its name instead of the node name may be
bdrv_get_device_or_node_name() can do that. Thanks -Xie
appropriate. I'm just wondering about the difference between bdrv_add_child() and bdrv_del_child(). Max+ return; + } + + parent_bs->drv->bdrv_del_child(parent_bs, child_bs, errp); +} diff --git a/include/block/block.h b/include/block/block.h index 1c4f4d8..ecde190 100644 --- a/include/block/block.h +++ b/include/block/block.h @@ -582,4 +582,9 @@ void bdrv_drained_begin(BlockDriverState *bs); */ void bdrv_drained_end(BlockDriverState *bs); +void bdrv_add_child(BlockDriverState *parent, BlockDriverState *child, + Error **errp); +void bdrv_del_child(BlockDriverState *parent, BlockDriverState *child, + Error **errp); + #endif diff --git a/include/block/block_int.h b/include/block/block_int.h index 9ef823a..89ec138 100644 --- a/include/block/block_int.h +++ b/include/block/block_int.h @@ -305,6 +305,11 @@ struct BlockDriver { */ void (*bdrv_drain)(BlockDriverState *bs); + void (*bdrv_add_child)(BlockDriverState *parent, BlockDriverState *child, + Error **errp); + void (*bdrv_del_child)(BlockDriverState *parent, BlockDriverState *child, + Error **errp); + QLIST_ENTRY(BlockDriver) list; }; | https://lists.gnu.org/archive/html/qemu-block/2016-03/msg00096.html | CC-MAIN-2020-29 | refinedweb | 777 | 57.37 |
Answered by:
Request for instructions on modifying the social games pack
The package was uploaded and works well, however :
- Even after going through the game .js codes a few time I fail to understand most of it ; how do I represent it visually ? Isn't there a design mode in visual studio ? (I searched the web but I coudln't find it...)
- It was my understanding that visual studio "takes away the need to focus on code" and allow with the social games pack a quick start to develop social games ; how do I for example add a simple quiz question (a Javascript pop-up I guess) that would be sent to the winner of the tic-tac-toe game, allowing him to bet his "point" for the question, if sucessful that would give him two points.
So basically I'm asking how to ask the question to the winner, verify the answer with the included dictionary (I think I'd need to add "recognized" words to it in VS) and send back two points instead of one.
I think if I would understand how to do this then I could extrapolate the technique and make other modifications as I see fit ; thanks in advance for the help !
Question
Answers
All replies
Hi,
I am not familiar with Social Game pack. But currently Visual Studio doesn’t offer a visual designer for JavaScript applications (except for Windows 8 Metro style JavaScript applications). Thus, please run the application to see the result.
As for how to create a quiz question or other tasks related to build the game, I would like to know whether you have any issue with Windows Azure or not. From my experience, what you need is pure JavaScript programming. For example, to create a popup, you can use jQuery UI’s Dialog component:. If you’re new to JavaScript, you can get started from. While the documents primarily target IE, they will work for other modern browsers as well.
In addition, for the questions that about JavaScript development, you can also post them on.
Best Regards,
Ming Xu.
Please mark the replies as answers if they help or unmark if not.
If you have any feedback about my replies, please contact msdnmg@microsoft.com.
Microsoft One Code Framework
What does visual studio offer as an alternative ?
It's kind of an issue because when you visit the web page they use the "ease of producing a social game" I guess thats how I should have formulated the question :
We are pointed at the social games pack to insure our experience on developping a social game is "visual studio" and straight forward, yet when I ask for the "next step" its hard to understand where to go ! Then why was I told that I needed to buy visual studio professional so I could run the social games pack so it would be easy and "take away the need to focus on pure code". I am indeed not expecting a miracle or an all easy solution, I know how to program basically I am just looking for assistance with this...
I'm sure someone around here has looked into the games pack, if you want it would probably not take you long to check it, but this is far from simple javascript... OR does microsoft as an alternative to this, right ?
What about the rest of the games pack, its HTML5... MVC?, isn't there a "frontpage" type editor ?
Hi,
I'm not sure what your expectation is. Essentially, Visual Studio offers a very advanced IDE that helps us to setup project, architect, write code, debug, deploy, and so on. As for the social game toolkit, it offers some samples applications that we can use without a single line of code. We can also extend those samples, so we don't need to write the core game logic manually.
If we want to write a complete different game, then we still need to write the code. The toolkit also offers a framework that simplifies the working with Windows Azure storage, as pointed out on.
If you're looking for a designer, then we can create a lot of a project that gives us a designer. For example, ASP.NET Web Forms, Silverlight, WPF, or if we are using Windows 8, Metro. But even then, designer can only help us to construct a UI, not the game logic.
Best Regards,
Ming Xu.
Please mark the replies as answers if they help or unmark if not.
If you have any feedback about my replies, please contact msdnmg@microsoft.com.
Microsoft One Code Framework
It was my understanding that the toolkit was built using ASP.NET MVC ; when I start a brand new "Azure project" I can access a designer and modify at least the UI... but what I don't see it where to go to get help on understanding any of the logic inside the kit...
The designer is turned off on the toolkit, there is no access to .net "site_master"... where is it ?
And how am I supposed to understand and write the code... Just to understand what I mean you will have to check the toolkit yourself I think... its full of JS controllers and scripts which are all separate and very counter-intuitive.
I understand basic javascript programming but this is totally different ; I would not even know where to begin !
Please take 5 minutes to install the games pack its very easy, and you will see what I mean ! Here is a short clip :
TicTacToeGame.prototype.isTie = function () {
if (this.hasWinner())
return false;
for (var x = 0; x < 3; x++)
for (var y = 0; y < 3; y++)
if (this.board[x][y] == TTTColor.Empty)
return false;
return true;
};
TicTacToeGame.prototype.hasWinner = function () {
return this.getWinner() != TTTColor.Empty;
};
TicTacToeGame.prototype.getWinner = function () {
var winner;
for (var row = 0; row < 3; row++) {
winner = inRow(this, row, 0, 0, 1);
if (winner != TTTColor.Empty)
return winner;
winner = inRow(this, 0, row, 1, 0);
if (winner != TTTColor.Empty)
return winner;
}
winner = inRow(this, 0, 0, 1, 1);
if (winner != TTTColor.Empty)
return winner;
winner = inRow(this, 2, 0, -1, 1);
return winner;
function inRow(game, x, y, dx, dy) {
var color = game.getColor(x, y);
for (var k = 1; k < 3; k++)
if (game.getColor(x + dx * k, y + dy * k) !== color)
return TTTColor.Empty;
return color;
There is simply no way for me to even begin to understand the game logic, and even if I wanted to write my own "game logic" I'd have to understand how it relates to other .js scripts in the assembly, there is a board script, a controller script a viewmodel script, a game service script, a server interface, a user service.
And even then I have no idea how the userservice talks to any of those and how it connects to the ACS namespace, how it calls the .cs repositories !
Beleive me I searched the web for endless hours, trying to get just an idea on how it's "intuitive" to create a social game on azure.
Why use all this complex assembly, why not make the tic tac toe in MVC instead ? Do I absolutely need this complex assembly to just make a HTML wrapper and login system for my game ? I'm glad that such an assembly is available don't get my wrong, the deployment script and all is wonderful... but :namespace Microsoft.Samples.SocialGames.Web.Services
{
using System;
using System.Collections.Generic;
using System.Json;
using System.Linq;
using System.Net.Http;
using System.Web.Mvc;
using Microsoft.Samples.SocialGames.Entities;
using Microsoft.Samples.SocialGames.Repositories;
using Microsoft.Samples.SocialGames.Web.Extensions;
This is the list of dependancies I think for the gameservice.cs ; you see what I mean ? if I modify the simplest game logic I have to understand all those systems like the bottom of my pocket ?
Heck I developped social games in frontpage back in 2000 (with ease and an intgrated designer)... I can't beleive there isn't a more intuitive way to make a game now with all this new technology. I have made a game very easily in FLEX - AIR actionscript, published it without any effort using facebook Heroku... but then I was sold to windows azure, because honestly it looks well made and far superior to Heroku.
To be honest I have been on this tic-tac-toe for 3 months... and I haven't even begun to have a clue on what to do, even with the technical support incident I opened, noone seems to even know how I should proceed.
Noone even knows how I could bring my ready AIR application in the cloud ! And I tried to do this too... some say appfabric, others say use amethyst, others say use tofino, others say use fluorine FX ; others tell me you don't even need any of this if you understand AJAX-JSON... but when I ask for further help all I get is pointers to other companies or basic tutorials I already know by heart... I don't mean to sound frustrated out here but do you think I would have brought 3000$+ of software from microsoft to have to turn around and learn very complex javascript programming which works just fine without any microsoft tools ?!
Heroku integrated my AIR application on facebook literally in the snap of a finger inside a database ready PHP website under an hour of work, facebook runing perfectly with the SDK integrated in the AIR application. I would already be on the market by now...
3 months of work later on Azure, and I have not ONE prospect of a solution, I mean I don't even know where to look to reproduce my success. Thats not even mentioning the social games pack...
I guess I just have no clue...
Well if it's not supported by microsoft its a big colored button right on the webpage... I give you an example I want to start programming a game on azure ; I go to your webpage and its said even for free I can develop (with webdev express, which is not true because you need NuGET); even better someone made a package with a deployment script to make sure you can "start" game developping very easily (which is not true you have to learn javascript anyways, not even a designer to help setup the structure).
I end up here 4 weeks later having had all the trouble in the world just to get it working and now I get told I'm supposed to go and learn javascript programming... this is extemely misleading in any way you look at it.
Thanks for the clarifications...
By the way I found another solution so there is no urgency or complaint... it just was so extreemly frustrating of an experience ! | http://social.msdn.microsoft.com/Forums/windowsazure/en-US/e1705249-71b2-458d-baf5-a3f858a46d60/request-for-instructions-on-modifying-the-social-games-pack?forum=windowsazuredevelopment | CC-MAIN-2013-48 | refinedweb | 1,815 | 71.55 |
Section (3) pcre2posix
Name
PCRE2 — Perl-compatible regular expressions (revised API)
Synopsis
#include <pcre2posix.h> int pcre2_regcomp(regex_t *
preg, const char *
pattern, int
cflags); int pcre2_regexec(const regex_t *
preg, const char *
string, size_t
nmatch, regmatch_t
pmatch[], int
eflags); size_t pcre2_regerror(int
errcode, const regex_t *
preg, char *
errbuf, size_t
errbuf_size);
DESCRIPTION
This set of functions provides a POSIX-style API for the PCRE2 regular expression 8-bit library. There are no POSIX-style wrappers for PCRE2_zsingle_quotesz_s 16-bit and 32-bit libraries. See the pcre2api(3) documentation for a description of PCRE2_zsingle_quotesz_s native API, which contains much additional functionality.
The functions described here are wrapper functions that
ultimately call the PCRE2 native API. Their prototypes are
defined in the
pcre2posix.h
header file, and they all have unique names starting with
pcre2_. However, the
pcre2posix.h header also
contains macro definitions that convert the standard POSIX
names such
regcomp() into
pcre2_regcomp() etc. This means
that a program can use the usual POSIX names without running
the risk of accidentally linking with POSIX functions from a
different library.
On Unix-like systems the PCRE2 POSIX library is called
libpcre2-posix, so
can be accessed by adding
−lpcre2−posix to the command for
linking an application. Because the POSIX functions call the
native ones, it is also necessary to add
−lpcre2−8.
Although they are not defined as protypes in
pcre2posix.h, the library does contain
functions with the POSIX names
regcomp() etc. These simply pass their
arguments to the PCRE2 functions. These functions are
provided for backwards compatibility with earlier versions of
PCRE2, so that existing programs do not have to be
recompiled.
Calling the header file
pcre2posix.h avoids any conflict with other
POSIX libraries. It can, of course, be renamed or aliased as
regex.h, which is the correct
name, if there is no clash. It provides two structure types,
regex_t for compiled internal
forms, and regmatch_t for returning
captured substrings. It also defines some constants whose
names start with REG_; these are used for setting options
and identifying error codes.
USING THE POSIX FUNCTIONS descriptions below use the actual names of the
functions, but, as described above, the standard POSIX names
(without the
pcre2_ prefix) may
also be used.
COMPILING A PATTERN
The function
pcre2_regcomp()
is called to compile a pattern into an internal form.
pcre2
pcre2
pcre2_regcomp()
is zero on success, and non-zero otherwise. The
preg structure is filled in on success, and
one other member of the structure (as well as
re_endp) is public:
re_nsub contains the number of capturing
subpatterns in the regular expression. Various error codes
are defined in the header file.
MATCHING NEWLINE at end yes PCRE2_DOLLAR_ENDONLY $ matches in middle no PCRE2_MULTILINE ^ matches in middle no PCRE2_MULTILINE
This is the equivalent table for a POSIX-compatible pattern matcher:
Default Change with
. matches newline yes REG_NEWLINE newline matches [^a] yes REG_NEWLINE $ matches at end no REG_NEWLINE $ matches in middle no REG_NEWLINE ^ matches in middle no REG_NEWLINE
This behaviour is not what happens when PCRE2 is called via its POSIX API. By default, PCRE2_zsingle_quotesz_s behaviour is the same as Perl_zsingle_quotesz_zsingle_quotesz_s
pcre2_regcomp() function causes
PCRE2_MULTILINE to be passed to
pcre2_compile(), and REG_DOTALL passes
PCRE2_DOTALL. There is no way to pass
PCRE2_DOLLAR_ENDONLY.
MATCHING A PATTERN
The function
pcre2_regexec()
is called to match a compiled pattern
preg against a given
string, which is by default terminated by a
zero byte (but see REG_STARTEND below), subject to the
options in
eflags. These can
be:
REG_NOTBOL
The PCRE2
pcre2_regexec() are ignored (except
possibly as input for REG_STARTEND).
The value of
nmatch may be
zero, and the value
pmatch may
be NULL (unless REG_STARTEND is set); in both these cases
byte
pcre2_regerror()
function maps a non-zero errorcode from either
pcre2_regcomp() or
pcre2_regexec() to a printable message. If
preg is not NULL, the error
should have arisen from the use of that structure. A message
terminated by a binary zero is placed in
errbuf.
pcre2_regfree() frees all such memory,
after which
preg may no longer
be used as a compiled expression. | https://manpages.net/detail.php?name=pcre2posix | CC-MAIN-2022-21 | refinedweb | 670 | 62.17 |
Creator Design mode doesn't show the QML components coming from a plugin
Hi,
I built a qml plugin where I created a Image.qml file that just extends the original Image qml component.
My Image.qml:
@
import QtQuick 1.0
Image {
id:root
}
@
The issue I have is that it doesn't show up in the Design mode when I use it.
my test file :
@import QtQuick 1.0
import com.mpsa.components 2.0
Rectangle {
width: 400
height: 400
Image { source: "picto.png" }
}
@
In the design mode I just get a full white preview....
But if I comment the "import com.mpsa.components 2.0" line it will the Image from QtQuick and will appear in the Designer.
So is there something special to do to get components from a qml plugin appear in the design mode ?
- alexander.merkel
I have the same problem and it is a little discouraging to see that there does not seem to be a solution. Does anyone know how the Design mode really works and how it resolves its imports.
The problem does not seem to exist when you import something from Qt like QtQuick.Controls 1.0. Somehow one must be able to tell Design mode additional imports. Does it take a QtCreator plugin to accomplish this?
Thanks
Qt Quick Designer uses an external process called qml(2)puppet for the rendering. In the latest SDK we ship qml(2)puppet as part of Qt and use those.
This is why rendering QtQuick.Controls works even though they are not shipped together with Qt Creator. Qt Creator might even be build with Qt 4.
The Qt Quick Designer uses the QML code model to resolve imports, so the QML code model has to "know" the plugin. There is a tool called qmlplugindump for this.
For the rendering to work, the Qt currently configured for the project, has to know about the plugin and has to have a qml(2)puppet.
The safest way is to install the plugin for your import in your Qt like we do it for e.g. QtQuick.Controls.
Setting QML_IMPORT_PATH is another option. Also .pro and .qmlproject files support setting additional import paths for QML.
The qml(2)puppet is usually build in release mode, so you also have to make sure you plugin has a release version.
If your plugin is a pure QML plugin (no C++) just setting the correct import path in the .pro or .qmlproject file works.
- alexander.merkel
Thank you for your help
It took me a while to implement your suggestions, but that was mostly due to not getting plugins to work at all.
One problem arose because I have a declarative project that has a main method where I use an Instance of a class that inherits from QDeclarativeView which then loads my qml files.
In this case the QML_IMPORT_PATH does not do any good. Neither the IDE nor the actual running programm knows about my plugin.
but:
@view.rootContext()->engine()->addImportPath("c:/.../importPath");@
(view is a QDeclarativeView)
is doing the trick at least for the running program. But not for the design mode. If I try to import it somewhere in a .qmlproject based project, the design mode works perfectly.
By the way importing a module like QtTest results in components not being displayed as well. So I think i am missing something fundamental.
I have exactly the same problem. I played around with qmldump and co and it was not able to get my components into the Qt Designer. Can you please take a look at my code to figure out what I am doing wrong? Btw. I also copy the plugins inside the Qt folder and they are recognized by Qt Creator (just not showing up in Qt Designer). I studied the code from QtQuick.Controls but was able to find out what it does differently.
What I actually try to achieve is to get a entry in Qt Designer with a custom name e.g. Machinekit - Controls.
Yep, same problems here, too.
- What is necessary to preview own QtQuick controls at design time in QtQuick Designer? If I define a QML Control, eg. Control.qml, then I can drag and drop it in QtQuick Designer to the canvas. But there is no preview rendering available. In my case, Control.qml uses a QMLCanvas to render complex painter code. But very simple controls doesn't have a preview too..
-> Is it necessary to wrap my controls in a plugin, even they only consists of one QML File without any C++ extensions?
- Is there a way to provide a kind of "design-time" implementation for each control, which is used by QtQuick designer to render the preview?
Thank you very much in advance!
Frime
There is a small test case that shows how to integrate a pure qml plugin in the designer and adding the items to the item library:
"Example":
bq. Is there a way to provide a kind of “design-time” implementation for each control, which is used by QtQuick designer to render the preview?
This is something we plan to do. My current workaround would be to provide a .qmlproject file with a different import path for the mockup plugins.
Thank you very much! That helped me a lot :)
Hi again!
I tried two different QtCreator versions, 3.2.2 and 2.8.1 .. The older one is able to render the preview, but doesn't show the specifics. The newer one shows the specifics, but does not render the preview. It shows only a white rectangle..
My problem: i need both /:
-The control uses a QML SceneGraph c++ extension plugin for rendering. The older QtCreator has no problems with that...
-The module folder is located in <Qt>/gcc/qml/
-Compiling and running works fine with all permutations of Qts and Creators.
First thought: The newer QtCreator is based on Qt. 5.3.2 .. So I recompiled my extensions with that Qt version and made a module copy in the appropriate Qt folder. With no success..
So.. Does anybody has an idea what's going wrong here? Or did I encounter a regression?
Thank you very much in advance!
All the best,
Frime
Hi,
can you check this option for Qt Quick Designer:
Always use the QML emulation layer provided by Qt Creator
To run C++ plugins you have to make sure to use a qml2puppet build with the correct Qt version:
Yep, it works now.
I unchecked "Always use the QML emulation layer provided by Qt Creator". After that, QtDesigner built a new and working qml2puppet layer. Thank you very much, again!
Greetings to Berlin,
Frime
Yep, it works now.
I unchecked "Always use the QML emulation layer provided by Qt Creator". After that, QtDesigner built a new and working qml2puppet layer. Thank you very much, again!
Greetings to Berlin,
Frime | https://forum.qt.io/topic/12450/creator-design-mode-doesn-t-show-the-qml-components-coming-from-a-plugin/4 | CC-MAIN-2019-18 | refinedweb | 1,148 | 75.71 |
This documentation is archived and is not being maintained.
Microsoft Dynamics
Troubleshooting Microsoft Dynamics CRM
Aaron Elder
At a Glance:
- Illustrating a Solution Architecture
- Fundamental troubleshooting principles
- Tools for diagnosing server issues
- Steps to resolving CRM errors.
1. A problem or error is identified and reproduced.
- Have you identified the problem and have you read the error message?
- Is the error message generic? If so, have you taken steps to find the "real error"? Hint: If the error says "Something happened, contact your System Administrator," remember that you are probably that System Administrator and therefore need to do more digging to find the real error. Before you move to Step 3, you must be sure you are dealing with the actual error.
2. The problem needs to be understood.
- Did you read and comprehend what the error message is saying?
- Do you have a consistent set of steps to reproduce the issue reliably?
3. The problem needs to be isolated.
- What systems in your System Architecture can you rule out as a cause of or influence on the problem?
- What components of the Solution Architecture can you rule out as a cause of or influence on the problem?
4. The fix needs to be identified and understood.
- Are you able to find support articles, blog posts, or newsgroup postings that suggest fixes that apply to your exact problem?
- Before applying a fix, do you understand why it will correct the problem?
5. The fix needs to be applied and verified.
- Does the applied fix resolve the issue? You will need to be able to reproduce the issue (Step 2) in order to be sure. Because you understand the fix, have you re-tested other areas of the system that might be affected?
Troubleshooting Server Issues
With an understanding of the troubleshooting process, we can now move on to the tools needed for diagnosing problems within Microsoft CRM.
DevErrors—When Microsoft Dynamics CRM submits data to the server, information is passed to ASP.NET and processed. Any errors are handled by a global exception handler at the ASP.NET layer. For usability and sometimes security reasons, the real error is hidden from the caller (that's you or your user) and a "pretty error" is displayed instead. Typically this error says something like "You do not have sufficient privileges" or "The requested record was not found." Unfortunately, these pretty errors come from a "white list." Of the hundreds of thousands of errors that could be thrown by CRM or any related component (SQL, SRS, .NET, Windows, and so on), only error codes that the CRM team thought might happen have a pretty string associated with them. The rest get handled by the dreaded catchall "An error has occurred, please contact your System Administrator." This, of course, is not of much use to you, the System Administrator.
Since one of our ground rules is to get the real error, you need to be able to tell when CRM is lying or at least not telling you the whole truth. The truth serum is to enable DevErrors via the web.config. This is done by modifying the [CRMWEB]\web.config file like so:
Be sure to keep your System Architecture in mind when doing this. If you have two servers configured in a load-balanced environment, you will want to isolate the server where the error is happening or, alternatively, be sure to enable DevErrors on both servers. Once DevErrors is enabled, you will see errors that look something like the one in Figure 3.
Figure 3 A Microsoft CRM Error Report
Figure 3 shows several items on the left that provide different sets of information:
The Detailed Error—The first screen (the default) shows you the real error from Microsoft Dynamics CRM's point of view. This includes the Date, Time, and Server name where the error occurred, as well as the Error Description, Call Stack, Error Number (if available), the Source File and Line Number where the error occurred (if available), and the URL that was requested—all useful when trying to figure out what went wrong.
The ASP.NET Error—The next item is the real error from ASP.NET's perspective. This provides much the same information as the CRM error, but adds the options to "Show Detailed Compiler Output" and "Show Complete Complication Source."
Diagnostic Info—The third screen, shown in Figure 4, provides basic information about the server, where the error occurred and details about the client and user that made the request. This information includes server operating system, .NET runtime version, server name, and the path to where CRM is installed. Information on the specific CRM database used and settings in the web.config also is included. For the client, the screen shows the browser version, screen resolution, bit depth, and more. Information on the user making the request (at least from CRM's point of view) includes the user's domain and name, CRM user name, CRM User ID, Business Unit ID, and Organization ID.
Figure 4 The Diagnostic Info Screen
What the User Would Have Seen—The final item, shown in Figure 5, allows you to see from the perspective of the end user, as if DevErrors were turned off.
Figure 5 The Error Message the User Would Have Seen
Please note that DevErrors helps only with errors that happen during the processing of a Web application request and only those requests that involve a full page submit to the server. AJAX requests, such as with a publish of customizations, a workflow, or a grid action, do not support DevErrors. For these, you will have to use tracing.
TIP: If the information on the DevErrors page is cut off and you can't resize the window to see more, simply double-click anywhere on the page and a resizable window will open.
Tracing—If a CRM error happens anywhere other than from a direct Web request, the best way to get the real error is to use CRM tracing. Tracing can be enabled and configured by following the steps in the "How to enable tracing in Microsoft Dynamics CRM" article at support.microsoft.com/kb/907490. Or you can use a tool such as CrmDiagTool, available at box.net/shared/6oxfqi2ida.
TIP: In CRM 4.0, the "Trace Directory" is ignored.
Tracing can be scary for the novice, so don't get frustrated. In general, tracing should be used only when troubleshooting an issue. Depending on how you configure tracing, there can be a significant performance impact when it is running, and if you have verbose logging on, a heavily used system can easily create hundreds of megabytes of logs per hour. The article mentioned above provides a detailed explanation of all the ways to configure tracing and how to enable tracing for client and server.
TIP: When emailing out trace logs for help, be sure to compress them first. Log files are just text and usually compress by 90 percent or more.
Log File Structure—When tracing is enabled on the server, logs will be placed in the Trace folder, which is located where you installed CRM. Each service has its own log file and each file will by default grow to 10MB before a new file is started. Since the log files are actively being written to by the various CRM processes, you will not get the absolute latest trace information until the corresponding service (either IIS or Async Service) is stopped. When you open the folder you will see files such as
-CRMDEV-VPC-CrmAsyncService-bin-20090415-1.log
-CRMDEV-VPC-w3wp-CRMWeb-20090415-1.log
The naming convention is [MACHINE NAME] – [CRM PROCESS] – [YEAR MONTH DAY] – [SEQUENCE].LOG
The log file contains loads of information, with items written in chronological order. Note that the trace log writes the latest event at the bottom of the file, while within a call stack items are written in reverse chronological order (newest item first).
TIP: When looking for errors in the log, try searching for ": Error" (a colon followed by a space, then Error.
Event Log—The Windows Event Log is another place to look for errors that occur within Microsoft Dynamics CRM, its dependent components, or other areas of the system. Just like the Trace Log, the Event Log will generally provide more details about errors that occur within the system.
Microsoft CRM does not log all errors to the Event Log. For example, a disabled user trying to log in is logged while an attempt to update a record that no longer exists is not logged. Though this isn't documented, CRM logs errors to the Event Log from the following subsystems:
-MSCRMPerfCounters
-MSCRMPlatform
-MSCRMKeyArchiveManager
-MSCRMKeyGenerator
-MSCRMEmail
-MSCRMDeletionService
-MSCRMReporting
-MSCRMWebService
-MSCRMAsyncService
-ASP.NET 2.0
The ASP.NET 2.0 bucket acts as a "catch most" for Application layer errors. In addition, the Microsoft Dynamics CRM Email Router Service has its own Event Log (MSCRMEmailLog) that can be configured independently to log a wide range of information, warnings, and errors.
Since Event Logging does not need to be turned on, it is a good starting place to look for issues.
Reading a Call Stack—Call stacks come in all shapes and sizes and all too often are overlooked by nondeveloper troubleshooters. It is not uncommon for system engineers to simply "ignore the developer stuff" and research only the error message or code. I recommend that you not do this—even though the call stack looks like code, it is designed to be human readable and to tell what happened right up until the error occurred. Look at the following example:
[ReportServerException: The Report Server Windows service 'ReportServer' is not running. The service must be running to use Report Server. (rsReportServerServiceUnavailable)] at Microsoft.Reporting.WebForms.ServerReport.SetDataSourceCredentials(DataSourceCredentials[]credentials) at Microsoft.Crm.Web.Reporting.SrsReportViewer.SetExecutionCredentials(ServerReport report) [CrmReportingException: The Report Server Windows service 'ReportServer' is not running. The service must be running to use Report Server. (rsReportServerServiceUnavailable)] at Microsoft.Crm.Web.Reporting.SrsReportViewer.SetExecutionCredentials(ServerReport report) at Microsoft.Crm.Web.Reporting.SrsReportViewer.ConfigurePage())
What you see here is a list of all the things the system did (the calls) listed in reverse chronological order (the stack) up until the last thing it "tried" to do. In this case, the first thing that happened—the call at the bottom of the stack—was a call to System.Web.UI.Page.ProcessRequestMain().
When reading call stacks, it is important to read the name of each call. For each call listed, the words between the last period and the parenthesis are the method name. Words before the method name are the namespace, and the items within the parentheses, the parameters. In this case, the method ProcessRequestMain was called first; this method is in the System.Web.UI.Page namespace; and this method expects two Boolean (True/False) parameters. Right away, by the reading the namespace, we know that this call is not to any Microsoft Dynamics CRM code; this is actually calling code in the base .NET Framework (denoted by the System root namespace) and specifically to ASP.NET (denoted by the Web namespace). As we read "up" the stack, we see that ProcessRequestMain then called PreRenderRecursiveInternal, which then called OnPreRender. The OnPreRender method is the first method that is actually a part of the Microsoft Dynamics CRM code base, as denoted by the Microsoft.Crm namespace. As we continue up the call stack, we see that CRM actually makes a call into the SQL Reporting Services method SetDataSourceCredentials. This method then throws an exception of type ReportServerException with the error that the Report Server is not running. As you can see, by reading the call stack, you can tell that this error is not coming from CRM at all, but is instead coming from SQL Server Reporting Services (SSRS) and is then being "bubbled up" through CRM as a CrmReportingException. Based on your system architecture, you will have to determine where SSRS is running in order to know where to go start the service to resolve the issue.
Reading call stacks in this manner can help you isolate where an error is actually coming from. The final call in the stack might be something like YourCompany.Crm.Extensions.UpdateRecord(); this would tell you that the error appears to be coming from either code written by your developers or perhaps an ISV solution you purchased.
It is not uncommon for CRM errors to actually come from SQL Server in the case of referential integrity (RI) or other SQL level constraints, or from the .NET Framework itself.
Play at Home Example
Now let's give you a chance to play at home. Let's assume you have created a new user in CRM and that user is trying to use the system for the first time and is getting the error as shown in Figure 6.
Figure 6 A CRM Error Received By a First-Time User
What steps would you take to solve this problem? To resolve this issue, let's follow our basic troubleshooting workflow.
1. A problem or error is identified and reproduced.
You should ask the user what he was trying to do when he received the error, then attempt to reproduce the steps to see if you can recreate the error.
2. The problem needs to be understood.
Let's read the error message from the troubleshooter's point of view: "the logged-on user does not have the appropriate security permissions."
To understand the problem, you have to be able to answer two questions: Who is "the logged-on user"? What "security permission" does he "not have"?
3. The problem needs to be isolated.
In this case, you can answer both questions by using CRM tracing. You know that tracing is needed because this error page is in a dialog and does not provide the information that DevErrors would. CRM does not log privilege errors like this to the Event Log. Let's enable tracing and reproduce the issue using the same user. The Trace Log provides the following detailed error:
MSCRM Error Report: Error: Exception has been thrown by the target of an invocation. Error Number: 0x80040220 Error Error Source File: Not available Line Number: Not available Request URL:{906C2F37-8D28-DE11-8D9F-0003FFB23445} Stack Trace Info: [CrmSecurityException:] at Microsoft.Crm.BusinessEntities.SecurityLibrary.CheckPrivilege(Guid user, Guid privilege, ExecutionContext context) …
From this error and by reading the call stack details, you can see that the problem is caused by a CRM Check Privilege failure. You can see the GUID of the user who made the request as well as the GUID of the privilege he tried to use.
If you perform a Live Search on the Privilege 7863e80f-0ab2-4d67-a641-37d9f342c7e3, the first hit is to the Microsoft CRM SDK.
Following this link, you can see that the privilege the user needs is prvWriteAccount, which is the privilege that grants the user update rights on the Account entity. The same method would work for any of the hundreds of out-of-the-box privileges, as the GUIDs are all known. If you search for the Privilege ID and it was not found, the privilege might be on one of your custom entities, in which case you will need to query your local SQL Server to find out what privilege is being requested. The following script will yield the same information:
Now that you know what privilege is needed, you just need to verify which user is missing the privilege. While you can sometimes assume that the calling end user is the one, you can't always be sure, such as when actions are performed via code, plug-ins, or custom extensions. In such cases, you may want to do a query to find the name of the user CRM thought was trying to use the privilege. The following script will handle this:
TIP: If the user GUID is all zeros (00000000-0000-0000-0000-000000000000), the user is probably the SYSTEM account and this means the calling user was probably an account such as Network Service. System accounts do not typically get CRM roles; instead they are granted elevated privileges via the PrivUserGroup in Active Directory.
4. The fix needs to be identified and understood.
You can now go into CRM and check to see what roles the user has, as shown in Figure 7.
Figure 7 User Roles in CRM
You can then drill down and see that the Salesperson role is indeed missing the Write on Account privilege as shown in Figure 8.
Figure 8 Core Records of the Salesperson Role shows it’s missing the Write privilege under Account.
5. The fix needs to be applied and verified.
To fix the issue, you simply need to grant the Write privilege to this role and save it. Be careful to make sure you understand which other users this will affect. Once you apply the fix, you can ask the user to try again to verify the problem has been resolved. You should then disable tracing and call the case closed.
Wrapping Up
Troubleshooting Microsoft Dynamics CRM means following basic ground rules and a methodology that includes identifying the real issue, narrowing scope, isolating the issue, and understanding the fix. You'll find the DevErrors, Event Logging, and Tracing tools in Microsoft Dynamics CRM critical in your troubleshooting efforts.
Aaron Elder (Microsoft Dynamics CRM MVP) works for Ascentium, a technology consulting and interactive marketing agency. Visit the Ascentium blog at ascentium.com/blog/crm.
Show: | https://technet.microsoft.com/en-us/library/2009.08.dynamics.aspx | CC-MAIN-2017-04 | refinedweb | 2,929 | 61.56 |
How can I avoid creating a column as "Discriminator" inside the database , If I inherit my business class from model class ( model class is mapped on database table).
Because, at the moment, if I inherit my business class ( e.g Specifics) to an existing model class ( i.e DataSpecific ), It asks for code first migration. In the migration, I can see discriminator as new column. I really don't want this. Because, original model class is being used in the whole application and that code works fine.
How can I stop the creation of "descriminator" column
C# Code :
Model Class
public class DataSpecific
{
}
public class Specific
{
}
AddColumn("dbo.Consignments", "Discriminator", c => c.String(nullable: false, maxLength: 128)); | https://codedump.io/share/gxVRWehBRUsN/1/how-can-39discriminator39-column-be-avoidable-in-code-first-entity-framework | CC-MAIN-2017-43 | refinedweb | 117 | 60.31 |
Final Fantasy XI
Macro Guide by nemes1s
Version: 0.9 | Updated: 05/10/04 | Search Guide | Bookmark Guide
############ ############ ############ ####### ####### ######## ##### ##### #### ______ __ __ __#### __ #### #### / ____//_//\ / //____ \#/ / #### #### / /___ __ / \ / /_____/ // / #### #### / ____// // . ' // ___ // /# #### #### / / / // / \ // /__/ // /### #### #### /_/ /_//_/ \//_____.//_____/##### #### ______ _____ __ ____######__ _____ _______#### __ / ____//____ \ /\ / //____ \\ __//____ \ / _____// /# / / / /___ _____/ // \ / /_____/ // / _____/ // /____ / /## / / / ____// ___ // . ' // ___ // /##/ ___ //___ // /###/ / / / / /__/ // / \ // /__/ // / #/ /__/ /_____/ // /###/ / /_/ /_____.//_/ \//_____.//_/ /_____.//______//_____ / ____________________________####______####______________#/ / /__________________________________________________________/# #### #### #### ##### ##### #### ####### ####### ######## ############ ############ ############ ---------------------- M A C R O G U I D E ---------------------- version 0.9 nemes1s (aka hpsolo) Midgardsormr / Sylphine INTRODUCTION This is a (small) guide to using macros in Final Fantasy XI. It is by no means complete, though I do hope it is useful to some/most of you. Feel free to send in your own macro combo that you find useful. I'll add it and credit it to you if it is not already listed. So why use macros? Macros can mean the difference between casting Cure II just in the nick of time, or the death of a party member. It may also mean getting a skill chain for extra damage. Sometimes you may find that a macro is much easier to stop the pulling of another monster, or warn the party of possible aggro's -- as typing might take too long to do so. Anyway, let's just cut to the chase... Eventually this will become a full-blown and in-depth guide on macros. I also hope to have virtually complete list of the most common and useful macros tailored for specific job classes. ACCESSING MACRO SETS There are 10 sets of macros, with each set having 20 slots -- 10 that are bound to the CTRL key and 10 bound to the ALT key. The CTRL set can be selected via L2 on the PS2 controller, and the ALT set are accessible via R2. To switch between macro sets, either: 1. Hold down the L2 or R2 button and when you see the macro menu, press up/down on the PS2 controller (digital pad), or 2. Hold CTRL or ALT on the keyboard and press up/down on the PS2 controller (digital pad) USING A MACRO 1. select which macro set to use 2. (a) if you pressed L2/R2, then a macro window should pop up; just select which macro within that set to use (b) press and hold CTRL or ALT (to select the subset of macros) followed by 1 through 0 (for macros 1 through 10 respectively) EDITING MACROS To open up the macro editing tool, press the square button on the PS2 controller twice and select MACROS. You will see two rows of squares. The top row is bound to CTRL (or L2) and the bottom row is bound to ALT (or R2). Highlight the macro you wish to edit and you will obtain a window that looks like: +--------------------------------------------------------------+ | <- PREV ________________________ NEXT -> | | [#Macro] |#0______________________| | | __________________________________________________________ | | |#1________________________________________________________| | | |#2________________________________________________________| | | |#3________________________________________________________| | | |#4________________________________________________________| | | |#5________________________________________________________| | | |#6________________________________________________________| | +--------------------------------------------------------------+ #Macro e.g. Ctrl 1 (currently editing macro 1 from the Ctrl set) #0 name of the macro (shows up on the macro set window) #1-#6 up to six commands to be used when calling this macro To edit a specific macro set, select the set by pressing and holding L2 or R2 and then pressing up or down on the digital pad. Then select and edit a macro within the set as described above. WHAT CAN MACROS BE USED FOR? * sending your party pertinent battle information such as how much MP/HP you have, when Provoke is ready, your TP, etc. * streamlining weapon skills and magic casting (for bursts) so that you do not have to navigate through the menus * personalized emotes * shortcuts to avoid using the menu interface to do common tasks BASIC MACROS WHICH YOU SHOULD HAVE FOR BATTLE * "Stat Ping" Tell your party your current MP/HP/TP /p HP: <hp> TP: <tp> MP: <mp> USAGE: This is the best way to relay your personal info. This works best if everyone uses the order listed above. That way, you automatically know where to look (left, middle, or right) if you are asking for certain stats. This is a must if you plan to renkei (where TP levels need to be known) or chain (MP and HP info needed). The way this macro SHOULD be used is for everyone to respond (like pinging a machine on a network) with the same macro listing their stats. Mages will likely only need to report MP (as they often do not build TP and shouldn't be getting hit so that HP reporting is also not needed). However, they should still have empty spaces so that the "MP: <mp>" appears on the far right (if that is where your party chooses to have MP listed). My party rarely reports HP, since the healers keep their eyes on the HP meter of every member in the party anyway. I do not recommend using <hpp> (hit point percentage) or <mpp> (mana point percentage) since that value is more or less use- less. Your party has a better idea of how many Cures you have left if you report MP:50/100 as opposed to 50%. (Someone with MP:10/20 reporting 50% may be misleading their party in terms of number of Cures) Melee characters generally report only their TP as this is the most important stat during a battle. Don't spam your TP info if you've only got 10% TP or something low. It is best if you wait til near 100% or above 100% before reporting. Some people (myself included) like to report their TP along with their weapon skill. This is really nice because it also lets your party members know what weapon skill is ready to go in case you have several skillchains. For example, a samurai builds TP extremely quickly, as does a ninja. It may be that there are two separate skillchains you want to use, so something like: /p <call20> #2 Blade: Retsu >>> TP: <tp> The "#2" denotes Blade: Retsu being used as the second weapon skill in the skill chain. * "Aggro Warning" Sends audio and (optional) vibrational signal to party members to warn about unexpected links /p WARNING!!! POSSIBLE AGGRO!!! <call0> USAGE: Save this for when your party gets ambushed or runs into trouble because of uninvited guests. It can also help to wake up members who have fallen asleep (in real life). You can also use this (with the obvious replacement message) if you're a mage and are low on MP. Sometimes when the fun is a bit too much, people forget about their mages' MP limits. If you are pulling, then use something like: /p I'm about to pull a <t>! Get ready! <call1> This should more or less make everyone aware of what's about to happen next should they get sidetracked with chit-chat or get back from being AFK. More info on the 'call' "command" (in quotes since it's not really a command) can be found below. ADVANCED MACROS (MAGIC AND WEAPONSKILLS) When you get higher levels and obtain more magic spells and job and weapon abilities, it will be very painfully slow to navigate through the menus in order to use a spell or skill -- there will be too many. To save time, you can bind most often used spells to macros. * Magic Macro /ma "Spell Name" [target] Eamples: /ma "Cure II" <t> Cast Cure II on current target /ma "Protectra III" <me> Cast Protectra III on yourself /ma "Curaga II" <p2> Cast Curaga II (centered on third party member) /ma "Poisana" <st> Cast Poisona after selecting a party member NOTES: Certain spells require the target be yourself or party members. Play around with them to figure out what the target values can be. The name of the spell should be in quotes if it contains whitespace; case (upper vs lower) matters; and the names MUST match the names of the spells in your spell list. * Job Ability Macro /ja "Job Ability" [target] Examples: /ja "Benediction" <me> Use Benediction (centered on yourself) NOTES: Job abilities which are still in their cooldown state will not execute and return (in purple text as default) the amoun of in-game time remaining until the next use. * Weapon Skill Macro /ws "Weapon Skill" [target] Examples: /ws "Fast Blade" <t> Use Fast Blade on target These are the three main types of battle macros that you will end up using the most. Oftentimes these commands are accompanied with some messages to the party. Take for example: /p Gather up for Protectra III !!!!! <call0> /wait 5 /ma "Protectra III" <me> This macro tells your party members to gather around you so you can cast Protectra III. The /wait 5 just pauses execution for 5 real-time seconds (this is to allow everyone to have time to react and gather near you). Then the last line executes the magic casting. The /wait command can be used to wait from 0 to 20 seconds. You cannot use /wait with an argument exceeding 20 (it will be treated like 0). There are several reasons to have the /wait command. If your macro is "skipping" some commands, it is likely that you need to add /wait 1 in between commands. This is normally the case if you end up using two commands with /p. For example, /p Hey what's up? /p How are you? will only output "Hey what's up?" to other characters in your party, and you will then see an error message about the second message not being able to be sent. The correct way is: /p Hey what's up? /wait 1 /p How are you? USING ERRORS IN MACROS TO SAVE ROOM Eventually, you will find that even the 10 sets of macros are insufficient. Here are a few ways to make use of the errors generated by macros. Suppose you have both WHM and BLM leveled fairly highly and you often switch between the two as your main job. Let's say you have Aero II bound to a macro, but when you are WHM, you can only use up to Aero. If you use: /ma "Aero II" <t> /wait 1 /ma "Aero" <t> If you're a BLM, this macro will cast Aero II and error out of the Aero spell since the /wait between is too short. As a WHM you'll get an error on Aero II since the BLM subjob will likely not be able to case Aero II (presuming your WHM is not too high in level). Instead, you'll end up casting Aero. WHEN TO USE CAPS AND WHEN NOT TO USE CAPS While it is bad netiquette to use all caps for speech, sometimes all caps is warranted. In battles, using all caps should be allowed and encouraged. When you're fighting, lots of battle messages are scrolling by. The cyan text helps, but your party members may not catch it in time. Using all caps will make your messages stand out so that you don't have to continue to repeat yourself. (Battle messages get really bad if you're fighting near other parties since you also see THEIR battle messages.) However, if you have a macro for, say, Protectra II and Shellra, and you add /p Gather for Protectra II then you should probably not use caps. These spells are often cast before battles, so there is not really any need for caps. As another example, note the use of /p Provoke is now ready. and /p PROVOKING --> <t> The first is just information for the party so that they are aware that provoke is ready. The second, however, is in caps because it needs to be seen by everyone so that two or more people don't use provoke immediately after a provoke use. Caps are more pronounced and stand out -- so use them accordingly. ORGANIZING YOUR MACRO SETS Macros can be useful if you organize them. If you scatter them about, they can actually do more harm than good. Use your sets to categorize your macros. Some suggestions for categories include: solo, curative spells, black magic, healing spells (e.g. Poisana), enfeeble spells, melee. USING YOUR MACROS IN A BATTLE This section may be a bit lengthy, but you should read throug it to see how powerful macros can be within a group. We will assume our party consists of at least a white mage a few melee players, one of which is a warrior with provoke. When you find a good party to level up, you will presumably have someone who will act as the puller. That is, he/she is the single person to go out and look for creatures to kill, and lures them back to a spot where your party is safely camping. The puller ideally should warn the party he is about to pull, and have macros set up to do so accordingly. I suggest: /p Get ready! Luring <t>! <call> so that your party knows what to expect. This way, any white mage or red mage know what to use for enfeebling or any barspells, etc. Also within the party should be someone at camp who is the lookout. The purpose of a lookout is to make sure enemies which aggro or link don't spawn before the puller gets back. You do NOT want the puller to be towing a creature back to camp and have him link the spawns as well. This makes a mini-train that may spell doom for you and your party. The lookout should use: /p WARNING!! <t> just spawned near camp! <call> NOTE: The party should agree on the sounds and what the designate. Also, you may wish to use <scall> instead of <call> in order to be curteous to anyone using the rumble feature (PS2 only). The lookout (and presumably any/all mages) should, during battle, turn off the locking feature so they can turn the camera and continue looking out for the party. In case new aggro appears, I suggest using: /p WARNING!! POSSIBLE AGGRO/LINK!! <call> These should each be in separate macros. This should provide your team with a good messaging system. Now on for the finer details of battle... Since most battles (should) start with enfeeblement, you don't want, say, two people casting Dia (should your party be lucky enough to have two white mages). When using enfeeble spells, I recommend that you use a message ONLY IF THERE IS SOMEONE ELSE WITH THE SAME SPELLS. That is, if you have two white mages, try using /p PARALYZE --> <t> /ma Paralyze <t> If you're the only one in your party enfeebling, then you may want to not use /p PARALYZE --> <t> because it can add some spam to the logs. However, with two people capable of enfeeblement, the messages help prevent wasted MP. The other way to go is to decide that only one person enfeelbes (the one whose skill is higher, of course). Again, the messaging is only suggested if you have several enfeeblers. At higher levels, the MP lost due to overlapping spells is minimal, so messaging is not recommended. You DEFINITELY DO NOT WANT two red mages both casting Dispel, for example (and yes, I am aware they have Convert -- but wasted MP is still wasted MP). RENKEI / TP / MAGIC BURST This is where macro is KEY. Your party will perform considerably better when you set up a good Renkei system. The following will use the example: Fast Blade -> Burning Blade -> Flat Blade which produces: Liquifaction [Fire] -> Fusion [Fire/Light] Your party must already be familiar with the Renkei system, and in particular the order of the weapon skills. The mages must be aware of the elements of each Renkei effect so they can magic burst. I recommend each person in the Renkei use the following "TP Ping" macro: /p [Fast Blade] TP: <tp> and replace Flast Blade with the appropriate weapon skill. This allows all melee characters to know exactly which weapon skill has what TP percentage. When one perons "pings" their TP, every one else should do the same. Note that the TP is reported on the far right side and the weapon skill name on the far left. Not only is it important to have good macros, but spacing and the presentation of the information is just as important. (If you party up with Linkshell members often, your Linkshell [LS] should try to set up some sort of standard on reporting info such as TP, MP, etc.) With every weapon skill and its corresponding TP being reported you will never have a case when someone accidentally goes too early. Moreoever, the mages (if they did their homework) will know what element to use for magic bursting if they can see which weapon skills are being used. Once your party is ready to Renkei, the first person to go should use something like: /p RENKEI IN 2 SECONDS! <call> /wait 2 /p Using Fast Blade /ws "Fast Blade" <t> The next person to go should have /p Using Burning Blade <call> /ws "Burning Blade" <t> The third person should ehave /p Using Flat Blade <call> /ws "Flat Blade" <t> Notice the wait of 2 seconds. This allows for everyone to get their weapon skill macro ready, and the mages to prepare their spells for bursting. You may optionally leave out the <call>'s as this may become annoying to the ears :P If your party is more experienced, you can optionally leave out the /wait 2. Your log will show the weaponskill being used, but you should message that anyway because the cyan colored text will show up much more clearly than the yellow (most people will have the font colors set to default). ACIENT MAGIC AND MAGIC BURSTS With ancient magic, you'll find that the cast time is EXTREMELY long. In fact, it is normal to cast ancient magic like Freeze long before the skillchain even starts. Of course this makes skillchains very hard to do if you don't have good timing. However, macros make this a breeze. The idea is that the melees will rely on the mage casting ancient magic to get their timing down. You'll first need to practice a few rounds to get an idea of the timing. Something like: /ma "Ancient Magic Spell Name" <t> /p <call> 10 seconds standby on the skillchain! /wait 10 /p <call> Begin first weapon skill! /wait 3 /p <call> Begin second weapon skill! Again, the time for the first /wait argument will depend on how long it takes the black mage to cast the spell. You will also need to factor into the equation the reaction time, as well as the time required to see the skillchain effect when the melee characters finish. Remember, the strength of the burst is dependent on when the spell lands after you see the skillchain effect. HATE MANAGEMENT It is generally good to have the tank continue to use the Provoke ability as this naturally builds up his/her hate level. This keeps hate on one person, and allows the healer to concentrate on keeping that one person healed to an accpetable level. The tank's Provoke macro should look like /p PROVOKE --> <t> /ja "Provoke" <t> /wait 15 /p Provoke ready in 15 seconds /wait 15 /p Provoke ready <call4> This macro has several important features: (1) it tells the user when his Provoke ability is ready, and (2) it lets the black mage know whether or not he/she should cast that "uber" spell that will cause massive hate. You don't want to be a mage getting the brunt of the hits with no provoke for 30 seconds -- especially against a hard hitting creature. Thieves are also capable of managing hate using their Sneak and Trick attack combos. The thief needs a team member to whom he/she can pass hate, so the thief's macro should let everyone know that the Sneak/Trick combo is about to be used -- so no one moves around. During the battle, your melee characters should surround the enemy on all sides, thus allowing the thief to choose a good "target" for hate. In general, I recommend one tank facing the enemy directly, and a second melee (with high HP) directly behind the enemy. These two should be the main tanks in the party. For the Sneak/Trick + weaponskill combo, I suggest: /p Setting up Sneak/Trick combo! /ja "Sneak Attack" <me> /wait 2 /ja "Trick Attack" <me> Then follow up with your normal weapon skill /p Using Viper Bite /ws "Viper Bite" <t> LIST OF ALL COMMANDS Below are all the commands available. Most of them have a short version (for example, /t can be used in place of /tell). Not all commands listed below make much sense in a macro, but I'll list them here for completeness. Also, there are some system arguments which can be used along with some of the commands. They are listed below as well. System arguments are surrounded by < and > (e.g. <t> for current target) SYSTEM ARGUMENTS <p0>, <p1>, ... , <p5> These denote party members 1 through 6 where your own character is always considered to be party member 1 (i.e. <p0> = you). p1 is the second person appearing on the party list at the bottom right of your screen (from top to bottom), and p5 is the last person on the list. Example: /ma "Cure" <p1> (cures person who appears just below your own character's name on the party list) <st> Select target for command. Example: /ma Cure <st> (selects the spell Cure and allows you to choose a person to cure; best used for healers who have to fight from time to time) <t> Current target Example: /p Guys, take a look at the <t>!!! (suppose a Yagudo Initiate is targeted; this macro sends the message "Guys, take a look at the Yagudo Initiate!!!" to your party/alliance) <hp> Your current hit point as a ratio of your current HP over your max HP. Example: /p My current HP is: <hp> (suppose your current HP is 401 and your max HP is 510; displays a message saying "My current HP is: 401/510") <hpp> The same as <hp> except it is a percentage and not a ratio. <tp> Your current TP (as a percent). <mp> Your current MP as a ratio of the remaining amount of MP over the max amount of MP. <mpp> The same as <mp> except it is a percentage and not a ratio. <call0>, <call1>, <call2>, <call3> Sends an audible whistling sound to all party members (can only be used in conjunction with /p). Also sends a vibration signal to each party member's controller if they have that option turned on. Example: /p WARNING!! POSSIBLE AGGRO!! <call0> (sends out a whistle signal, vibration signal, and displays a message saying "WARNING!!! POSSIBBLE AGRRO!! <call0>" <scall0>, <scall1>, <scall2>, <scall3> Same as <call0> - <call3> except the vibration signal is not sent (i.e. only audibles) <me> Your character; equivalent to <p0> <pos> Your current grid location. If you look on the map, you will appear as a red arrow inside a square. The square will have coordinates specified by a row (letter) and column (number). Example: /p I'm currently at <pos> (suppose you are at I-10; sends a party message saying "I'm currently at I-10") NOTE: Some dungeons have several "floors" so that I-10 may not necessarily be meaningful (e.g. a person at I-10 on the third floor and a person at I-10 on the first floor will both report I-10 for <pos> and yet not see each other.) <mpos> Position on map when using airship or vessels over water. COMMANDS /? USAGE: /? /[command_name] -> Gives a detailed explanation of specified command. Abbreviations can be used. If a command name is incomplete or does not exist, similar commands will be listed. * All names used with these commands must be one word, or in quotation marks. /ver USAGE: /ver -> Displays the current version number. /servmes (or /smes) USAGE: /servmes -> Displays today's server message (the messaged displayed when in) in the log window. /lsmes (or /linkshellmes) USAGE: /lsmes [subcommand] "[mes.]" -> Allows PC to edit and view their current linkgroup's welcome message. Only authorized members can change these messages. >> Subcommands: nothing Display currently set message set "[mes.]" Changes message to specified message clear Clear set mesages level [auth_level] Sets authority level >> Authority Levels: ls Linkshell holder ps Linkshell and pearlsack holders. all All members. /linkshell (or /l) USAGE: /linkshell [mes.] -> Sends a message to all members of your current linkshell group, regardless of their location. /party (or /p) USAGE: /party [mes.] -> Sends a message to all members of your current party and alliance, regardless of their location. /say (or /s) USAGE: /say [mes.] -> Sends a message to all PCs within a small radius. The message will not be displayed if a PC has their [Say] chat filter turned on. /shout (or /sh) USAGE: /shout [mes.] -> Sends a message to all PCs within a large radius. The message will not be displyaed if a PC has their [Shout] chat filter turned on. /tell (or /t) USAGE: /tell [PC_name] [mes.] -> Sends a message to a specific PC within the same world. This message cannot be seen by any other players. /emote (or /em) USAGE: /emote [mes.] -> Sends your PC name and a message as an emote within a [Say] radius. This message will not be displayed if a PC has their [Emotes] chat filter turned on. /chatmode (or /cm) USAGE: /chatmode [chat_mode] -> Changes chat mode default settings. [Shout] will be reset after using once. When using [Tell], specify a PC name. If you do not specify a chat mode, your current settings will be displayed. * Valid chat modes: s, sh, l, p, t [PC_name] /nominate (or /propose) USAGE: /nominate [chat_mode] "[qst]" "[opt1]" ... (up to 8 options) -> Asks a question to all PCs within the designated chatmode, and give them a variety of answers to choose from. The answers can be chosen with the /vote command. Acessible chat modes are Say, Shout, Party, and Linkshell. You can stop the voting by reentering /nominate. /vote USAGE: /vote [PC_name] [number] -> Answers a question from the /nominate command. If a PC name is entered, you will answer that PC's question. If you do not enter a PC name, you will answer the most recently asked question. If there is no number after /vote, the question will be displayed again. /volunteer (or /vol) -> An exclusive command for volunteers. It cannot be used by regular players. /echo USAGE: /echo "[mes.]" -> Displays a message that only you can see. /random USAGE: /random -> Displays a random number between 0 and 999. This number can be seen by PCs within the [Say] radius. /attack USAGE: /attack [subcommand] -> Turns on auto-attack of the selected target on/off. Toggles on and off when no subcommand is specified. >> Subcommands: on Turn on auto-attack. off Turn off auto-attack. /attackoff USAGE: /attackoff -> Cancels auto-attack /wait target ta targetpc targetnpc magic ma weaponskill ws ninjutsu nin son so jobability ja pet heal fish dig dismount assist as help h range shoot throw ra check c search sea logout friendlist blacklist blist playtime playlog clock makelinkshell makeli breaklinkshell breakli item equip keyitem quest mission map regionmap rmap supportdesk sd helpdesk pol tribune partycmd pcmd alliancecmd acmd automove follow lockon invite inv autogroup ag autotarget join decline anon online away busy hide invisible names bank mailbox deliverybox layout garden EMOTES /point /bow /salute /kneel /laugh /cry /no /nod /yes /wave /goodebye /farewell /welcome /joy /cheer /clap /praise /smile /poke /slap /stagger /sigh /comfort /surprised /amazed /stare /blush /angry /disgusted /upset /muted /doze /panic /grin /dance /think /fume /doubt /sulk /psych /huh /shocked The commands listed above are emotes. For example, /point makes your character do a pointing motion. If /point is used without any arguments, a message such as: "[your character's name] points [direction you're facing]." will appear on the log of every PC within [Say] range. These emotes can optionally take the argument [target]. So for example, /point <t> will cause your character to use a pointing motion and the message: "[your character's name] points at [the target]." You can also use the option "motion" so that no message such as the one above appears, though your character will still do the animation associated with that emote. The animation varies on your race, so that an female Elvaan using /laugh will have a different animation from a male Elvaan or femal Taru, etc. You can create your own emote with full animation. For example, you can use (for Elvaan females): /joy motion /wait 1 /emote slaps the crap out of <t>. and target Elvaan males with this emote to get a slapping action along with a message saying "[your character's name] slaps the crap out of [target]." Of course, this emote macro works well only on other tall characters as the motion of /joy makes the female Elvaan's hands swing high (i.e. this would look silly used on a Taru).
FAQ Display Options: Printable Version | http://www.gamefaqs.com/pc/555735-final-fantasy-xi/faqs/26086 | CC-MAIN-2016-40 | refinedweb | 4,896 | 78.48 |
Details
Description
A set of static methods to perform primality test, factorization and prime number generation. Currently it is limited to the int data type, extension to long/BigInteger will follow.
Activity
After a very quick look at the code, some remarks about style:
- "if"-blocks must not be on the same line as the condition check, even if there is a single statement.
- There must be one space characted before an opening bracket.
- Closing brackets must be on the following line.
- "assert" statements should be replaced by precondition checks (raising an appropriate exception if they fail).
Design question:
Wouldn't it be useful to create an interface Primes<T extends Number> that would define all the methods to be implemented for each type (Integer, Long, BigInteger, ...)? Your "Primes" class then becomes
public class IntegerPrimes implements Primes<Integer> { // ... }
Implementation (and performance) question: Is it useful to have this functionality for "int" rather than just for "long". I mean: Is the "int" implementation faster in any actual application?
If not, what would it take to convert all your proposed code to work with "long"?
Thanks for the review, I will apply the requested formatting next time. So I guess I am not running checkstyle correctly, because I did not see any of those errors in the report. I run it from command line "mvn checkstyle:checkstyle", and I have modified my local copy of pom.xml with the following:
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-checkstyle-plugin</artifactId> <version>2.9.1</version> <configuration> <configLocation>checkstyle.xml</configLocation> </configuration> </plugin>
inserted in <build>. Is there something I am missing ?
About "assert", In the case of private or package private methods, is it also required to turn them into runtime checks ? Is it acceptable to simply comment them if the performance impact is significant ?
interface Primes<T extends Number> -> agreed
implementation/performance question: I expect implementation for long to be significantly slower, as it is the case for gcd. int implementation uses long for some internal values, so a long implementation will need to use BigInteger at those places, that should slow down things... Also current int implementation contain an array with all primes smaller or equal to the cubic square of Integer.MAX_VALUE. Doing the same for Long.MAX_VALUE is going to significantly increase the size of the array, I am not sure if this is desirable -> in short some performance tricks applicable to int don't scale well. In case of isPrime, the trick to get a provable result using Miller-Rabin works well for int, but I have to search additional reference to get the magic numbers to scale it to long, and even after that, maybe we will end up with something slower than a true provable algorithm.
I am more inclined to share the same implementation for long and BigInteger.
I have modified my local copy of pom.xml [...]
That should not be necessary, the "pom.xml" in "trunk" already contains the necessary configuration.
But I'm not sure that those formatting rules which I referred to above are enforced by CheckStyle. I just did a manual detection!
About "assert" [...]
This an interesting question. Maybe you should raise the issue on the "dev" ML.
AFAIK, there is no policy for the use of "assert" within the CM code.
In the case of a library like CM, robustness is important; I guess that it is less safe to use "assert" since an application could silently fail if assertions are not enabled.
In cases where the method is for internal use only, and we are sure that the CM code calls it correctly, my preference would be to just remove the unused statement, and replace it with an appropriate comment stating why an explicit check is not necessary.
In cases where the method is for internal use only, and we are sure that the CM code calls it correctly, my preference would be to just remove the unused statement, and replace it with an appropriate comment stating why an explicit check is not necessary.
Interesting! I was about to ask the same question on the ML for another issue (incomplete beta function).
I really would like to have this point discussed more widely, as I tend to prefer assertions over simple comments (assertions could be turned on (at least, locally) during testing).
Of course, I'm in favor of an additional comment stating that explicit check is deemed unnecessary for private or package private methods. In my case, some package private methods provide approximations of some functions over a specific interval. I would then state in the javadoc the interval, and also that it is the responsibility of the user to make sure that this approximation is not called outside its domain.
@Sébastien: since you first asked the question, would you like to start a thread on the ML?
Best regards,
Sébastien (another one
)
[...] I tend to prefer assertions over simple comments (assertions could be turned on (at least, locally) during testing).
IMO, neither "assert" statements nor simple comments are useful for testing (or more precisely, debugging). What we'd need is logging.
"assert" aborts the program, but does not tell you how the wrong value made it there.
I think that "assert" is very useful, but in applications (meaning: don't bother with the rest of the computation, as I know that someting went wrong).
By contrast, in CM, no "assert" should ever be triggered from internal calls. Furthermore, no "assert" should ever be triggered from external calls, as that would mean that unsafe (if assertions are disabled) code can be called.
To be robust, CM raises a "MathInternalError" at places no code path should ever lead to; but if one does, at least something predictable happens.
One thing to check in the first place is whether a precondition check actually slows down things in an "unbearable" way.
Fixed in subversion repository as of r1454920.
Patch applied with a few changes:
- replaced assert by comments
- formatting (spaces, braces, control statements on one line...)
- very long performance tests not committed
- updated tests to Junit 4
As the latest comments suggested it would not be easy to extend this package to long or BigIntegers, I have left the Primes class as first proposed, without an upper parameterized interface.
Thanks for the suggestion and for the patch!
Closing issue as version 3.2 has been released on 2013-04-06.
Implementation of three methods: primality test, factorization and prime generation (nextPrime method). Following the suggestion of Gilles, it is in a new package rather than inserted in existing files. It contains an improved version of Pollard's rho method. After breaking my head to get it work, I found out that it is not faster than trial division, the int range must be too small to see the benefits. I included it anyway, it may be more adapted for dealing with long and BigInteger types. | https://issues.apache.org/jira/browse/MATH-845?page=com.atlassian.jira.plugin.system.issuetabpanels:all-tabpanel | CC-MAIN-2015-22 | refinedweb | 1,157 | 62.78 |
doctest is a fully open source light and feature-rich C++98 / C++11 single-header testing framework for unit tests and TDD. A complete example with a self-registering test that compiles to an executable looks like Listing 1.
And the output from that program is in Listing 2.
Note how a standard C++ operator for equality comparison is used – doctest has one core assertion macro (it also has macros [Catch], which is currently the most popular alternative for testing in C++ (along with googletest [GoogleTest]) – check out the differences in the FAQ [Doctest-1]. Currently a few things which Catch has are missing but doctest aims to eventually become a superset of Catch.
Motivation behind the framework: how it is different
doctest is inspired by the unittest {} functionality of the D programming language and Python’s docstrings – tests can be considered a form of documentation and should be able to reside near the production code which they test (for example in the same source file a class is implemented).
A few reasons you might want to do that:
- Testing internals that are not exposed through the public API and headers of a module becomes easier.
- Lower barrier for writing tests. You don’t have to:
- make a separate source file
- include a bunch of stuff in it
- add it to the build system
- add it to source control
You can just write the tests for a class or a piece of functionality at the bottom of its source file – or even header file!
- Faster iteration times – TDD becomes a lot easier.
- Tests in the production code stay in sync and can be thought of as active documentation or up-to-date comments, showing how an API is used.
The framework can still be used like any other even if the idea of writing tests in the production code doesn’t appeal to you – but this is the biggest power of the framework, and nothing else comes close to being so practical in achieving this.
This isn’t possible (or at least practical) with any other testing framework for C++: Catch [Catch], Boost.Test [Boost], UnitTest++ [UnitTest], cpputest [CppUTest], googletest [GoogleTest] and many others [Wikipedia]. Further details are provided below.
There are many other features [Doctest-2] and a lot more are planned in the roadmap [Doctest-3].
What makes doctest different is that it is ultra light on compile times (by orders of magnitude – further details are in the ‘Compile time benchmarks’ section) and is unobtrusive.
The key differences between it and the others are:
- Ultra light – below 10ms of compile time overhead for including the header in a source file (compared to ~430ms for Catch); see the ‘Compile time benchmarks’ section
- The fastest possible assertion macros – 50 000 asserts can compile for under 30 seconds (even under 10 sec)
- Offers a way to remove everything testing-related from the binary with the
DOCTEST_CONFIG_DISABLEidentifier
- Doesn’t pollute the global namespace (everything is in the doctest namespace) and doesn’t drag any headers with it
- Doesn’t produce any warnings even on the most aggressive warning levels for MSVC / GCC / Clang
-Weverythingfor Clang
/W4for MSVC
-Wall
-Wextra
-pedanticand over 35 other flags not included in these!
-)
So if doctest is included in 1000 source files (globally in a big project) the overall build slowdown will be only ~10 seconds. If Catch is used – this would mean over 350 seconds just for including the header everywhere.
If you have 50 000 asserts spread across your project (which is quite a lot) you should expect to see roughly 60–100 seconds of increased build time if using the normal expression-decomposing asserts or 10–40 seconds if you have used the fast form [Doctest-5] of the asserts.
These numbers pale in comparison to the build times of a 1000 source file project. Further details are in the ‘Compile time benchmarks’ section.
You also won’t see any warnings or unnecessarily imported symbols from doctest, nor will you see a valgrind or a sanitizer error caused by the framework. It is truly transparent.
The main() entry point
As we saw in the example above, a
main() entry point for the program can be provided by the framework. If, however, you are writing the tests in your production code you probably already have a
main() function. Listing 3 shows how doctest is used from a user
main().
With this setup the following 3 scenarios are possible:
- running only the tests (with the
--exitoption)
- running only the user code (with the
--no-runoption)
- <typename T> \ (see Listing 4).
The following text will be printed:
opening the file seeking closing... (by the destructor) opening the file reading closing... (by the destructor)
As you can see the test case was entered twice – and each time a different subcase was entered. Subcases can also be infinitely nested. The execution model resembles a DFS traversal – each time starting from the start of the test case and traversing the ‘tree’ until a leaf node is reached (one that hasn’t been traversed yet) – then the test case is exited by popping the stack of entered nested subcases.
Examples of how to embed tests in production code
If shipping libraries with tests, it is a good idea to add a tag in your test case names (like this:
TEST_CASE("[the_lib] testing foo")) so the user can easily filter them out with
--test-case-exclude=*[the_lib]*
if he wishes to.
- If you are shipping a header-only library there are mainly 2 options:
- You could surround your tests with an
ifdefto check if doctest is included before your headers like Listing 5.
- You could use a preprocessor identifier (like
FACT_WITH_TESTS) to conditionally use the tests like Listing 6.
- If you are developing an end product and not a library for developers, then you can just mix code and tests and implement the test runner like described in the section ‘The main() entry point’. You could define the
DOCTEST_CONFIG_DISABLEpreprocessor identifier in the Release config so no tests are shipped to the customer.
- If you are developing a library which is not header-only, you could again write tests in your headers like shown above, and you could also make use of the
DOCTEST_CONFIG_DISABLEidentifier to optionally remove the tests from the source files when shipping it – or figure out a custom scheme like the use of a preprocessor identifier to optionally ship the tests -
MY_LIB_WITH_TESTS.
Compile time benchmarks
So there are 3 types of compile time benchmarks that are relevant for doctest:
- cost of including the header
- cost of assertion macros
- how much the build times drop when all tests are removed with the
DOCTEST_CONFIG_DISABLEidentifier
In summary:
- Including the doctest header costs around 10ms compared to 250–460ms of Catch – so doctest is 25–50 times lighter
- 50 000 asserts compile for roughly 60 seconds, which is around 25% faster than Catch
- 50 000 asserts can compile for as low as 30 seconds (or even 10) if alternative assert macros [Doctest-5] are used (for power users)
- 50 000 asserts spread in 500 test cases just vanish when disabled with
DOCTEST_CONFIG_DISABLE– all of it takes less than 2 seconds!
The lightness of the header was achieved by forward declaring everything and not including anything in the main part of the header. There are includes in the test runner implementation part of the header but that resides in only one translation unit – where the library gets implemented (by defining the
DOCTEST_CONFIG_IMPLEMENT preprocessor identifier before including it).
Regarding the cost of asserts – note that this is for trivial asserts comparing 2 integers – if you need to construct more complex objects and have more setup code for your test cases then there will be an additional amount of time spent compiling. This depends very much on what is being tested. A user of doctest provides a real world example of this in his article [Wicht].
In the benchmarks page [Doctest-4] of the project documentation!
Note that Catch 2 is on its way (not public yet), and when it is released there will be a new set of benchmarks.
The development of doctest is supported with donations.
References
[Boost]
[Catch]
[CppUTest]
[Doctest-1]
[Doctest-2]
[Doctest-3]
[Doctest-4]
[Doctest-5]
[GoogleTest]
[UnitTest]
[Wikipedia]
[Wicht] | https://accu.org/index.php/journals/2343 | CC-MAIN-2019-47 | refinedweb | 1,380 | 52.73 |
Important: Please read the Qt Code of Conduct -
Implementation of qFuzzyCompare and zero values
Hello all,
I'm using qFuzzyCompare(a, b) in order to handle all floating point comparisons, but it has severe limitations when a or b may be zero.
Somewhere in the docs it is recommended to add +1 to the values, but this is not a really useful suggestion because some of the values might be -1.0, resulting in 0.0 after the addition.
So far, in each file which needs to perform floating point comparisons, I'm using the following macro:
@
#include <QtGlobal> // qMax, qMin, qFuzzyCompare
#define qFuzzyCompare(a, b) (qFuzzyIsNull(a) && qFuzzyIsNull(b)) || qFuzzyCompare((a), (b))
@
But instead of ad-hoc workarounds, IMHO this caveat should be fixed straight in the implementation of the qFuzzyCompare() function. A really old bug report already exists: "QTBUG-16819": it is open but it seems that discussion ended on 2011 for some reason.
Could anyone add a bit more on this subject?
- JKSH Moderators last edited by
Hmm... I'm not familiar with this issue, but it does look like something that could be handled better by the library itself.
You can post to the "Development mailing list": to start a discussion with Qt's engineers.
- tonyorourke last edited by
My guess is the good folks at Qt aren't interested because the good folks at Qt don't use qFuzzyCompare themselves; instead, they favour a set of 'qFsk...' routines which you'll find here -
C:\Qt3d\src\threed\geometry\qvector_utils_p.h
(or somewhere like it, depending on where your Qt3d source code is)
The routines you find there should solve your problems. | https://forum.qt.io/topic/29738/implementation-of-qfuzzycompare-and-zero-values | CC-MAIN-2021-31 | refinedweb | 276 | 60.14 |
The Bayesian Information Criterion, often abbreviated BIC, is a metric that is used to compare the goodness of fit of different regression models.
In practice, we fit several regression models to the same dataset and choose the model with the lowest BIC value as the model that best fits the data.
We use the following formula to calculate BIC:
BIC: (RSS+log(n)dσ̂2) / n
where:
- d: The number of predictors
- n: Total observations
- σ̂: Estimate of the variance of the error associate with each response measurement in a regression model
- RSS: Residual sum of squares of the regression model
- TSS: Total sum of squares of the regression model
To calculate the BIC of several regression models in Python, we can use the statsmodels.regression.linear_model.OLS() function, which has a property called bic that tells us the BIC value for a given model.
The following example shows how to use this function to calculate and interpret the BIC for various regression models in Python.
Example: Calculate BIC of Regression Models in Python
Suppose we would like to fit two different multiple linear regression models using variables from the mtcars dataset.
First, we’ll load this dataset:
from sklearn.linear_model import LinearRegression import statsmodels.api as sm import pandas as pd #define URL where dataset is located url = "" #read in data data = pd.read_csv(url) #view head of data data.head() model mpg cyl disp hp drat wt qsec vs am gear carb 0 Mazda RX4 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4 1 Mazda RX4 Wag 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4 2 Datsun 710 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1 3 Hornet 4 Drive 21.4 6 258.0 110 3.08 3.215 19.44 1 0 3 1 4 Hornet Sportabout 18.7 8 360.0 175 3.15 3.440 17.02 0 0 3 2
Next, we’ll fit the following two regression models:
- Model 1: mpg = β0 + β1(disp)+ β2(qsec)
- Model 2: mpg = β0 + β1(disp)+ β2(wt)
The following code shows how to fit the first model and calculate the BIC:
#define response variable y = data['mpg'] #define predictor variables x = data[['disp', 'qsec']] #add constant to predictor variables x = sm.add_constant(x) #fit regression model model = sm.OLS(y, x).fit() #view BIC of model print(model.bic) 174.23905634994506
The BIC of this model turns out to be 174.239.
Next, we’ll fit the second model and calculate the BIC:
#define response variable y = data['mpg'] #define predictor variables x = data[['disp', 'wt']] #add constant to predictor variables x = sm.add_constant(x) #fit regression model model = sm.OLS(y, x).fit() #view BIC of model print(model.bic) 166.56499196301334
The BIC of this model turns out to be 166.565.
Since the second model has a lower BIC value, it is the better fitting model.
Once we’ve identified this model as the best, we can proceed to fit the model and analyze the results including the R-squared value and the beta coefficients to determine the exact relationship between the set of predictor variables and the response variable.
Additional Resources
Two other metrics that are commonly used to compare the fit of regression models are AIC and adjusted R-squared.
The following tutorials explain how to calculate each of these metrics for regression models in Python:
How to Calculate AIC of Regression Models in Python
How to Calculate Adjusted R-Squared in Python | https://www.statology.org/bic-in-python/ | CC-MAIN-2021-39 | refinedweb | 607 | 65.22 |
I am brand new to programming and am working through the "Automate the Boring Stuff" book for Python 3. I've seen several other people with questions on the 'Comma Code' project but not my specific problem. I have come up with a 'working' bit to start off but I can't figure out why my print function gives me int values rather than the strings in the list.
def reList(items):
i = 0
newItems = str()
for items[i] in range(0,len(items)):
newItems = newItems + items[i] + ', '
print(newItems)
i=i + 1
items = ['apples', 'bananas', 'tofu', 'cats']
reList(items)
def reList(items): #i = 0 # no need to initialize it. newItems = str() for i in range(0,len(items)): # i not items[i] newItems = newItems + items[i] + ', ' print(newItems) #i=i+1 # no need to do items = ['apples', 'bananas', 'tofu', 'cats'] reList(items)
range(0,len(items)) returns number 0, 1, 2.. upto
len(items) (excluding)
for items[i] in range(0,len(items)) was making
items[i] 0, 1, 2...
That's why it was print numbers.
for i in range(0,len(items)) make i as 0, 1, 2... and
items[i] gets you item at
ith position of the list. So now you get the strings instead of numbers.
A better way would be -
def reList(items): newItems = str() for it in items: newItems = newItems + it + ', ' print(newItems) items = ['apples', 'bananas', 'tofu', 'cats'] reList(items) | https://codedump.io/share/VAwblI9J9TfH/1/my-print-function-from-a-list-returns-int-values-instead-of-the-strings-in-the-list | CC-MAIN-2016-50 | refinedweb | 238 | 78.38 |
Most professional software developers understand the academic definitions of coupling, cohesion, and encapsulation. However, many developers do not understand how to achieve the benefits of low coupling, high cohesion and strong encapsulation, as outlined in this article. Fortunately, others have created.
Have you ever played Jenga? It’s that game of wooden blocks that are stacked on top of each other in rows of three. In Jenga you try to push or pull a block out of the stack and place it on top of the stack without knocking the stack over. The player that causes the stack to fall loses.
Have you ever thought you were playing a game of Jenga when you were writing or debugging software? For example, you may need to change one field on one screen. You study the stack of code, you look for that little space of light peaking between the classes, and you make the change in the one place that you thought would be safe. Unfortunately, you didn’t realize that the code you were changing was referenced in several critical processes through some strange levels of indirection. The resulting crash of the software stack has left you the loser, cleaning up the mess with your boss breathing down your neck about the customer being upset about their lost data, and … How many times have you been there? I can’t even begin to count how often it’s happened to me.
Software development does not have to be like a game of Jenga.
There is good news, though: software development does not have to be like a game of Jenga. In fact, software development should not be like any game where there are winners and losers. What you want, instead, is a sustainable pace of software development where everyone wins. You want to ensure that you don’t overwork the developers, that you don’t pressure managers to say “just get it done,” and the customer gets the software they want in a timeframe they agree to.
A Sustainable Pace
When trying to set a sustainable pace in any endeavor, you first need to understand how far you need to go. You also need to know how fast you need to get there. For example, if you want to run a 50-meter dash, you should run as fast as you possibly can and then push yourself to try to run faster. However, if you want to run an 800-meter race you should set a somewhat slower pace. When you start talking about significant distances like a marathon, the pace becomes significantly slower. For such a distance, you want to set a pace that you can maintain throughout the race.
In software development, you can think of the pace you need to run as the timeline of the project combined with the expected features and functionality.
In software development, you can think of the pace you need to run as the timeline of the project combined with the expected features and functionality. For shorter timeframes, you need to run faster. However, you also have to consider how much functionality you can reasonably add to your system, given a short timeframe. If you only need a few features and you need to get it done quickly, you may need to sprint toward the goal. If your customer expects you to cram too many features into a short timeframe, you have a higher likelihood of burning out. Imagine trying to sprint for the duration of a marathon, or even a 1600-meter race. The probability of sustaining that pace for that distance is going to approach zero as you continue moving forward. You need to work with your management, your team, and your customers to set the expectations of how fast you can run for a given period.
Assuming that you have a reasonable number of features for a given timeframe, you now have to set the pace for feature development in your daily activities. Object-oriented software development has various principles, patterns and practices that help you achieve the sustainable pace you need. The principles include coupling-the extent to which the parts of the system rely on each other; cohesion-the extent to which the parts of a system work together for a single purpose; and encapsulation-the extent to which the details of implementation are hidden. Built on top of these principles are various design and implementation patterns such as strategy, command, bridge, etc. When you combine these principles, patterns and practices they will help you to create systems that are well factored, easy to understand, and easy to change.
The Object-Oriented Principles
Ideally, you want to ensure that your systems have low coupling and high cohesion. These two principles help you to create the building blocks of a software system. You also want to ensure that you have self-contained building blocks-that is, they are well encapsulated. You don’t want the concerns of one building block leaking into other blocks. If you create building blocks that have the correct size and shape, you can put them together in meaningful ways to solve your problems.
Often it seems that developers only discuss these principles in academic settings. Most universities with degrees that cover software development provide at least a cursory introduction to them. However, many software developers seem to miss their correct usage, causing more problems than they solve. Indeed, developers can very easily misapply these principles in the wrong place at the wrong time. To avoid this situation, you need to understand how coupling, cohesion, and encapsulation correctly play into developing software solutions.
Low Coupling
Coupling in software development is defined as the degree to which a module, class, or other construct, is tied directly to others. For example, the degree of coupling between two classes can be seen as how dependent one class is on the other. If a class is very tightly coupled (or, has high coupling) to one or more classes, then you must use all of the classes that are coupled when you want to use only one of them.
You can reduce coupling by defining standard connections or interfaces between two pieces of a system. For example, a key and a lock have a defined interface between them. The key has a certain pattern of ridges and valleys, and the lock has a certain pattern of pins and springs. When you place the right key in the lock, it pushes the pins into a position that allows the mechanism to lock or unlock. If you place the wrong key into the lock, the pins will not move into the correct position and the mechanism won’t move.
In software development, developers also work with standard connections and interface definitions. Object-oriented languages such as C++, C#, Java, and Visual Basic have some constructs that allow you to define those interfaces implicitly and explicitly. Whether it’s a class’ public methods and properties, an abstract base class, an explicit interface or other form of abstraction, these constructs allow you to define common interaction points between parts of your system. Without abstraction to decouple these common points of interaction, you are left with pieces of the system that must know about each other directly. Basically, this means you are stuck with a key that is welded directly to the pins of a lock, preventing you from removing the key, and compromising the security of that lock.
Imagine that you are working with the structure in Figure 1. The software works fine, at the moment, and you can fix bugs when you need to. Then your boss hands you a new requirement and you realize that the module highlighted in red can handle most of the requirement. You would like to reuse that module but you don’t need any of the surrounding modules for this new feature. When you try to pull out the module in red, though, you quickly realize that you’ll have to bring several more modules with it due to the high coupling between this module and the ones surrounding it.
Now imagine a class that has zero coupling. That is, the class depends on nothing else and nothing else depends on it. What benefit does that offer? For one, you can use that class anywhere you want without having to worry about dependencies coming along with it. However, you essentially have a useless class. With zero coupling in the class, you won’t be able to get any information into or out of it. Try to create a class in .NET that does not rely on anything-not an integer, not a string, not a Console or Application static reference; not even the implied object inheritance of every construct in .NET. Go ahead… try it… see how useful that is in your system.
Coupling is not inherently evil. If you don’t have some amount of coupling, your software will not do anything for you.
Coupling is not inherently evil. If you don’t have some amount of coupling, your software will not do anything for you. You need well-known points of interaction between the pieces of your system. Without them, you cannot create a system of parts that can work together, so you should not strive to eliminate coupling entirely. Rather, your goal in software development should be to attain the correct level of coupling while creating a system that is functional, understandable (readable by humans), and maintainable.
High Cohesion
Cohesion is the extent to which two or more parts of a system are related and how they work together to create something more valuable than the individual parts. Think of the old adage, “The whole is greater than the sum of the parts.”
People seek high cohesion in sports teams, for example. They want to have a team of basketball players that know how and when to pass the ball, and how and when to score. Everyone expects the individual players to play together as a team to increase the chances of the team winning the game. Companies also seek cohesion in their project teams at work. They put developers and user interface designers together with business analysts and database administrators, along with other roles and responsibilities. The intent of creating teams of cross-functional skill sets is to use the strengths of each team member to counter the weaknesses of others. You likely also look for cohesion in the technology you are using and the software that you are writing. You probably want a database system that connects easily to your programming language of choice. You also want a user interface technology that makes it easy to wire up the business logic and data access. Cohesion is all around. You only need to recognize it for what it is.
In software systems, developers talk about high-level concerns and low-level implementation details. This scale of concern can help you understand the many perspectives of cohesion within your software. How well do the lines of code in a method or function work together to create a sense of purpose? How well do the methods and properties of a class work together to define a class and its purpose? How well do the classes fit together to create modules? How well do the modules work together to create the larger architecture of the system? Understanding the perspective that you are dealing with at any given time will help you understand the extent to which the pieces are cohesive.
Understanding the perspective that you are dealing with at any given time will help you understand the extent to which the pieces are cohesive.
Examine the puzzle-picture of my son in Figure 2. If you separate all of the individual pieces, what do you have? You have a series of pieces that provide very limited value on their own. The intrinsic value of an individual piece is only that it can be combined with other pieces. I’m not interested in playing with a single piece, though. I want to have enough pieces to complete the puzzle in question. I want a highly cohesive system of pieces.
A complete puzzle has much more value than the all of the individual pieces. Knowing that the puzzle pieces should create a picture of my son also provides a higher level of value to me-more value than any other random puzzle. A puzzle where all of the pieces are black, or a puzzle that shows a picture of a field, will not inspire the feelings of love in me the way a picture of my son will. This desire to complete the picture of my son provides motivation to not only put the puzzle together, but to put the right pieces in the right places.
If cohesive systems-software, puzzles, or otherwise-have multiple parts coming together to create more value than then individual parts, it stands to reason that you cannot create a highly cohesive system out of large, all-in-one pieces. For example, a software system cannot be cohesive if it is made up of excessively large “god” classes. These types of classes tend to have too many concerns within them to create any cohesion outside of themselves. A single class that does all of the actions in the following bullet list has far too many concerns to be cohesive with anything else.
- Load data from a file or database
- Process the data into a structure
- Display the data to the user
- Obtain input from the user on what to do with the data
- Perform the actions requested by the user
- Persist the changes back to the file or database
The processes listed here are very common. Many software systems use some form of this basic workflow. However, including all of these processes in a single class would make it difficult to create a cohesive system. You might see cohesion between high-level processes but you lose the ability to create cohesion at lower levels such as methods and classes.
To create a more cohesive system from the higher and lower level perspectives in this example, you can break out the various needs into separate classes. You might separate the user interface needs, the data loading and saving needs, and the processing of the data. Having these smaller parts, each with their own value in the overall process, gives you a much more cohesive system from the various perspectives.
Encapsulation
Most developers define encapsulation as information hiding. However, this definition often leads to an incomplete understanding and implementation of encapsulation. It seems that many people see the word information and think data or properties. Based on this they try to make public properties that wrap around private fields, or make properties private instead of public. This perspective, unfortunately, misses out on a tremendous opportunity that encapsulation provides: to hide not just data, but process and logic as well.
Strong encapsulation is evidenced by the ability for a developer to use a given class or module by its interface, alone. The developer does not, and should not, need to know the implementation specifics of the class or module. Figure 3 represents a well-encapsulated process where the calling objects, represented by blue boxes, do not have to know about the implementation detail of the red box. The red box should be free to change its implementation without fear of breaking the code that is calling it, so long as the public interface or the semantics of that interface do not change.
Encapsulation helps reduce duplication of data and processes in your system. Whether you have a business process, a single point of common data, or a technical or infrastructure process, you should have one and only one implementation to represent the item in question..
In situations where you need to use a process in more than one location, proper encapsulation combined with low coupling will help to ensure that you have a part that can create cohesion in the system. For example,. The saw has encapsulated the process of causing the blade to turn through a simple, public interface-the handle with the trigger. Additionally, the saw itself contains other forms of encapsulation such as the connection points between the saw blade and the motor. This allows you to replace the saw blade without having to reconstruct the motor, the trigger mechanism, or any other part of the saw.
Object-Oriented Principles in Our Day to Day Jobs
Developers hear about these and other principles of object-oriented development fairly regularly during their professional career. These real-world discussions often center around how the principles would be “nice to achieve,” though, relegating them to the realms of the ivory tower academic. When it comes to the everyday work of software development, it seems that most developers either don’t understand how to get to these principles or don’t think it’s possible in a reasonable time frame. However, these principles are not just for the academics. Developers should apply them to their development efforts. The question should change from “Can you apply the principles, here?” to “How do you correctly apply the principles, here?”
S.O.L.I.D. Stepping Stones
When you start asking the question of how, it’s a little like looking at a marathon race and wondering how you end up at the finish line. Obviously, for a marathon you arrive at the finish line by running one step at a time. Software development lets you move one step at a time toward your object-oriented goals, as well. The steps are composed of additional principles and implementation goals, such as those outlined in the SOLID acronym:
- S: Single Responsibility Principle (SRP)
- O: Open-Closed Principle (OCP)
- L: Liskov Substitution Principle (LSP)
- I: Interface Segregation Principle (ISP)
- D: Dependency Inversion Principle (DIP)
Originally compiled by Robert C. Martin in the 1990s, these principles provide a clear pathway for moving from tightly coupled code with poor cohesion and little encapsulation to the desired results of loosely coupled code, operating very cohesively and encapsulating the real needs of the business appropriately.
The Single Responsibility Principle says that classes, modules, etc., should have one and only one reason to change. This helps to drive cohesion into a system and can be used as a measure of coupling as well.
The Open-Closed Principle indicates how a system can be extended by modifying the behavior of individual classes or modules, without having to modify the class or module itself. This helps you create well-encapsulated, highly cohesive systems.
The Liskov Substitution Principle also helps with encapsulation and cohesion. This principle says that you should not violate the intent or semantics of the abstraction that you are inheriting from or implementing.
The Interface Segregation Principle helps to make your system easy to understand and use. It says that you should not force a client to depend on an interface (API) that the client does not need. This helps you develop well-encapsulated, cohesive set of parts.
The Dependency Inversion Principle helps you to understand how to correctly bind your system together. It tells you to have your implementation detail depend on the higher-level policy abstractions, and not the other way around. This helps you to move toward a system that is coupled correctly, and directly influences that system’s encapsulation and cohesion.
Throughout the rest of this article, I will walk through a scenario of creating a software system. You will see how the five SOLID principles can help you to achieve strong encapsulation, high cohesion, and low coupling. You will see how you can start with a 50-meter “get it done now” dash, and end with a long term marathon of updates to the system’s functionality.
Setting the Pace: A 50-Meter Dash
To help understand how you can achieve the goal of an object-oriented system through the use of the SOLID principles, I’ll walk you through a simple scenario, a solution, and the resulting expectations.
Scenario: Email an Error Log
One day at the office, your manager walks into your cube and looks like his hair is on fire. He informs you that his manager, the CTO, just got off the phone with a very irate customer. Apparently, one of your company’s hosted applications is throwing exceptions and preventing the customer from being able to complete their work.
The CTO has informed your manager that he needs immediate knowledge of the exceptions being thrown from this system, and personally wants to see an email in his inbox for every exception thrown, until the system is fixed. Your manager, worried about keeping his job, now wants you to create a quick-and-dirty application that allows a network operations person to send the contents of a log file to the CTO. Furthermore, this thing has to be out the door and in the hands of the network operations person before lunch-a couple of hours from now. Using a running analogy, you are now engaged in a 50-meter dash. You need to crank this code out and deliver it as quickly as possible.
Solution: Select a File and Send It
A few hours after that conversation with your manager, you have produced a very simple system that allows the user to select a file and send the contents of that file via email (Figure 4).
The implementation of this application is very crude by your own standards: you coded the entire application in the form’s code, did no official testing, and did the bare minimum of exception handling (Listing 1). However, you got the job done.
New Expectation: All Errors Emailed
A week after you wrote that quick-and-dirty email sending application, your boss is back in your cube to talk about it again. This time, he informs you that your application was a smashing success and the CTO has mandated that all systems send error log emails to a special email address for collecting them. The CTO wants you, specifically, to handle this since your original application was received so well.
Resetting the Pace
As your first assignment, after hearing about this new mandate from the CTO, you want to figure out what log files the network operations personnel will need to send, and how they want to facilitate this. After some discussion with the operations group lead, you have agreed to add two new aspects of functionality of the system:
- The operations people want an API to code against for some of their automation scripts.
- They need to parse the contents of an XML file to make it a little more human-readable.
You have also negotiated a slightly better timeframe with the network operations people than your manager gave you for the original application. They have agreed to a delivery date of close-of-business, tomorrow.
With this new deadline and the new requirements in mind, you decide to settle in for a slightly longer race than the original 50-meter dash. The code you started with was sufficient at the time, but now you need to enhance and extend it. You could consider this a 100- or possibly a 400-meter race at this point. The good news is that you know how to set your pace according to the situation you find yourself in.
Single Responsibility Principle
The Single Responsibility Principle says that a class should have one, and only one, reason to change.
This may seem counter-intuitive at first. Wouldn’t it be easier to say that a class should only have one reason to exist? Actually, no-one reason to exist could very easily be taken to an extreme that would cause more harm than good. If you take it to that extreme and build classes that have one reason to exist, you may end up with only one method per class. This would cause a large sprawl of classes for even the most simple of processes, causing the system to be difficult to understand and difficult to change.
When the business perception and context has changed, then you have a reason to change the class.
The reason that a class should have one reason to change, instead of one reason to exist, is the business context in which you are building the system. Even if two concepts are logically different, the business context in which they are needed may necessitate them becoming one and the same. The key point of deciding when a class should change is not based on a purely logical separation of concepts, but rather the business’s perception of the concept. When the business perception and context has changed, then you have a reason to change the class. To understand what responsibilities a single class should have, you need to first understand what concept should be encapsulated by that class and where you expect the implementation details of that concept to change.
Consider an engine in a car, for example. Do you care about the inner working of the engine? Do you care that you have a specific size of piston, camshaft, fuel injector, etc? Or, do you only care that the engine operates as expected when you get in the car? The answer, of course, depends entirely on the context in which you need to use the engine.
If you are a mechanic working in an auto shop, you probably care about the inner workings of the engine. You need to know the specific model, the various part sizes, and other specifications of the engine. If you don’t have this information available, you likely cannot service the engine appropriately. However, if you are an average everyday person that only needs transportation from point A to point B, you will likely not need that level of information. The notion of the individual pistons, spark plugs, pulleys, belts, etc., is almost meaningless to you. You only care that the car you are driving has an engine and that it performs correctly.
The engine example drives straight to the heart of the Single Responsibility Principle. The contexts of driving the car vs. servicing the engine provide two different notions of what should and should not be a single concept-a reason for change. In the context of servicing the engine, every individual part needs to be separate. You need to code them as single classes and ensure they are all up to their individual specifications. In the context of driving a car, though, the engine is a single concept that does not need to be broken down any further. You would likely have a single class called Engine, in this case. In either case, the context has determined what the appropriate separation of responsibilities is.
Separating the Email Application
After some quick analysis of your existing application’s code, you decide that the new requirements are really two distinct points of change. Following the Single Responsibility Principle, these two points show you where you need to separate the existing code into multiple classes (Figure 6).
A new EmailSender object will provide the ability for the network operations personnel to have an API to code against. Additionally, separating out the format reading from the form is necessary to allow the form or the API to read the file format.
To simplify the API that the network operations people need, you decide to put the file reading code into the email sender (Listing 2). This will provide a simple enough interface and let you get the functionality out the door in a timely manner.
In the interest of time and not neglecting your other responsibilities, you decide to go ahead and create a single FormatReader class to handle both of the file formats. This code only needs to know if the contents are valid XML. A quick hack to load the contents into an XmlDocument should be sufficient for this small application.
string messageBody; try { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(fileContents); messageBody = xmlDoc. SelectSingleNode("//email/body") .InnerText; } catch (Exception) { messageBody = fileContents; } return messageBody;
The lesson to remember in this release of the application is that the Single Responsibility Principle is driven by the needs of the business to allow change. “A single reason to change” helps you understand which logically separate concepts should be grouped together by considering the business concept and context, instead of the technical concept alone.
Extensibility and Coming Requirements
A few days after delivering the API set to your network operations department, your manager is back in your cube with good news-the operations personnel love what you have done for them. The API you delivered was very simple and they were able to get the email process up and running in no time at all.
With this success in mind, your manager has been trying to drum up additional uses for your new application. In this effort, he has heard some rumbling about needing to send log messages from more than flat files or XML files. He expects the official request for features to come in soon, and wants you to get a head start on being able to extend the application in this manner.
Given the operations group capabilities-they write some code, though it is usually some sort of scripting-you decide that they should be able to extend the supported file formats whenever they need to. After a quick discussion with the operations personnel, they agree and appreciate your confidence in their abilities. From that discussion and the direction from your manager, you decide to move forward on the ability to add new file formats as needed.
Open-Closed Principle
The Open-Closed Principle says that a class should be open for extension, but closed for modification. In other words, you should be able to easily change the behavior of the class in question without having to modify it.
The next time you are at a hardware store, look at the power tools. You will notice that there are a wide range of saw blades that can attach to a single saw. One blade compared to another may not look very different at first, but a closer inspection may reveal some significant differences. Some blades are constructed with different metals, the number of teeth or edges may vary, and the material that is used for the teeth is often designed for special purposes. No matter what the difference, though, if you are comparing two blades that attach to the same type of saw, they will have one thing in common: how they attach to the saw-the interface between the saw and the blade.
The individual differences of the blades are what make each type of blade unique. One blade may cut through wood extremely quickly, but leave the edges rough. Another blade may cut wood more slowly and leave the edges smooth. Still others may be suited for cutting metal or other materials. The wide variety of blades, combined with the common method of attaching them to the saw, allows you to change the behavior of the saw without having to modify the mechanical portion of the saw.
So, how do you allow a class’s behavior to be modified without actually modifying the class? The answer is surprisingly simple and there are several methods for doing this.
Have you ever implemented an interface in a class and then passed an instance of that class into another object? Perhaps you implemented the IPrincipal interface for custom security needs. Or, you may have written your own interface such as the classic example of IAnimal, and implemented a Cat and a Dog object from this interface. The ubiquitous nature of explicit interfaces in .NET, as well as abstract base classes, delegates, and other forms of abstraction, all provide different ways of allowing custom behavior to be supplied to existing classes and modules. You can use design patterns such as Strategy, Template, State, and others to facilitate the behavioral changes through the use of such abstractions. There are still other patterns and abstractions, and other methods of injecting behavior and altering the class at runtime. Chances are, if you have written an application that required even a small amount of flexibility, you have either provided a custom behavior implementation to an existing class, or have written a class that required a custom behavior to be supplied.
Restructuring for Open-Closed
Given the need for multiple, unknown file types to be parsed, you decide to supply an interface that can be implemented by any number of objects, from any number of third parties, including the network operations personnel. In addition to the actual file parsing, you will need the interface to tell you whether or not the specific implementation can handle the current file contents. Your resulting application structure looks more like Figure 7, with the IFileFormatReader interface defined as follows:
public interface IFileFormatReader { bool CanHandle(string fileContents); string GetMessageBody(string fileContents); }
Since you know that there are multiple file formats being read now, you also decide to move the existing code that reads the flat file and XML file formats into two separate objects. The flat file reader can handle any non-binary log file, so you decide that this handler does not need to determine if it can handle the file contents sent to it. It only needs to say that it can handle the format, and then send the original content back out. You rewrite the implementation of the flat file format reader as follows:
class FlatFileFormatReader: IFileFormatReader { public bool CanHandle(string fileContents) { return true; } public string GetMessageBody( string fileContents) { return fileContents; } }
The XML file format reader will contain a check to see if the XML is valid. The GetMessageBody method will then parse the XML for the content, as shown in Listing 3.
Next, you want to introduce the FileReaderService class. This will use the various IFileFormatReader implementations and is where the behavioral change will occur when the various format readers are supplied.
To support an unknown number of file format readers, you decide to store the list of registered format readers in a simple collection:
IList<IFileFormatReader> _formatReaders = new List<IFileFormatReader>(); public void RegisterFormatReader( IFileFormatReader fileFormatReader) { _formatReaders.Add(fileFormatReader); }
The RegisterFormatReader method allows any code that calls the FileReaderService API to register as many format readers as they need. Then, when a file needs to be parsed, a call to a GetMessageBody method is made, passing in the contents of the file as a string. This method runs through the list of registered format readers and checks to see if the current one can handle the format. If it can, it calls the GetMessageBody method of the reader and returns the data.
public string GetMessageBody(string fileContents) { string messageBody = string.Empty; foreach(IFileFormatReader formatReader in _formatReaders) { if (formatReader.CanHandle(fileContents)) { messageBody = formatReader .GetMessageBody(fileContents); break; } } return messageBody; }
At this point, if there is no registered reader that can handle the file contents, an empty string is returned. You realize that you need to add a default file reader. The intention is to ensure that all log files are handled, regardless of the content. If a file can’t be handled by any other reader, you will want to return all of the content through the flat file format reader.
By adding a separate RegisterDefaultFileReader method, you can ensure that only one default exists. Listing 4 shows the resulting GetMessageBody implementation.
Finally, you need to update the usage of the FormatReader object in your EmailSender. You need to register both the XML file format reader and the flat file format reader in the constructor of the email sender class.
private readonly FileReaderService _fileReaderService = new FileReaderService(); public EmailSender() { _fileReaderService.RegisterFormatReader( new XmlFormatReader()); _fileReaderService. RegisterDefaultFormatReader( new FlatFileFormatReader()); }
Happy Consumers and More Requirements
A few days after releasing this version of the application and API, you hear that the operations group loves your IFileFormatReader and the extensibility it brings to the table. They have successfully implemented several format readers and are planning on more.
A short time later, a new request comes in that you were not expecting. One system the operations group must support logs all of its errors to a database, not a text file. Moreover, according the operations personnel, they cannot write code that hits the database in question. Apparently, that’s “above their pay grade.” They need someone on the development staff to do it, and are asking for your help.
The most challenging part of this new requirement is the CTO being involved, again. Due to the high visibility of this project and the potential for lost revenue if errors are not proactively corrected, he wants your application updated to support reading from the database, immediately. According to your manager, when the CTO says “immediately” he usually means before the end of the day. It’s only a few hours before the day ends and you’ve been running on very little sleep for the last few days, but you think you can bang out a working version and get it to the operations group in time to make the CTO happy.
Liskov Substitution Principle
The Liskov Substitution Principle says that an object inheriting from a base class, interface, or other abstraction must be semantically substitutable for the original abstraction. Even if the original abstraction is poorly named, the intent of that abstraction should not be changed by the specific implementations. This requires a solid understanding of the context in which the interface was meant to be used.
To illustrate what a semantic violation may look like in code, consider a square and a rectangle, as shown in Figure 8. If you are concerned with calculating the area of a resulting rectangle, you will need a height, a width and an area method that returns the resulting calculation.
public class Rectangle { public virtual int Height { get; set; } public virtual int Width { get; set; } public int Area() { return Height * Width; } }
In geometry, you know that all squares are rectangles. You also know that not all rectangles are squares. Since a square “is a” rectangle, though, it seems intuitive that you could create a rectangle base class and have square inherit from that. But what happens when you try to change the height or width of a square? The height and width must be the same or you no longer have a square. If you try to inherit from rectangle to create a square, you end up changing the semantics of height and width to account for this.
public class Square : Rectangle { public override int Height { get { return base.Height; } set { base.Height = value; base.Width = value; } } public override int Width { get { return base.Width; } set { base.Width = value; base.Height = value; } } }
What happens when you use a rectangle base class and assert the area of that rectangle? If you expect the rectangle’s area to be 20, you can set the rectangle’s height to 5 and width to 4. This will give you the result you expect.
Rectangle rectangle = new Rectangle(); rectangle.Height = 4; rectangle.Width = 5; AssertTheArea(rectangle); private void AssertTheArea(Rectangle rectangle) { int expectedArea = 20; int actualArea = rectangle.Area(); Debug.Assert(expectedArea == actualArea); }
What if you decide to pass a square into the AssertTheArea method, though? The method expects to find an area of 20. Let’s try to set the square’s height to 5. You know that this will also set the square’s width to 5. When you pass that square into the method, what happens?
Rectangle square = new Square(); square.Height = 5; AssertTheArea(square); private void AssertTheArea(Rectangle rectangle) { int expectedArea = 20; int actualArea = rectangle.Area(); Debug.Assert(expectedArea == actualArea); }
You get the wrong result because 5 x 5 is 25, not 20. That is too high, so now try a height of 4 instead. You know that 4 x 4 is 16. Unfortunately, that’s too low. So the question is, “how can you get 20 out of multiplying two integers?” The answer is: you can’t.
The square-rectangle issue illustrates a violation of the Liskov Substitution Principle. You clearly have the wrong abstraction to represent both a square and a rectangle for this scenario. This is evidenced by the square overriding the height and width properties of the rectangle, and changing the expected behavior of a rectangle.
What, then, would a correct abstraction be? In this case, you may want to use a simple Shape abstraction and only provide an Area method, as shown in Listing 5. Each specific implementation-square and rectangle-would then provide their own data and implementation for area allowing you to create additional shapes such as circles, triangles, and others that you don’t yet need. By limiting the abstraction to only what is common among all of the shapes, and ensuring that no shape has a different meaning for “area” you can help prevent LSP violations.
A Quick-and-Dirty Database Reader
After fuelling up with another energy drink and shaking off the sleep you so desperately want, you dive into the code for the database reader. Given the short time frame, you decide to take a shortcut and not introduce a new abstraction or a new method to the API. Rather, you decide to hard code the behavior of reading from the database into the application, facilitated by the use of a special file format reader. You know it’s not the brightest moment in your career, but you just want to get it out the door and go home for the night. What should have been an 800-meter race has now become a 50-meter dash in your mind. Listing 6 shows the result.
You deliver the working code on time, and manage to make it home before falling asleep while driving. Overall, you consider it to be a successful day.
The following week, you hear word that the network operations personnel liked the ability to read from a database. In fact, they liked it so much that they told another department about this feature. What they didn’t know, though, was that the code you delivered was written for one very specific database and didn’t actually read the connection string from a file. You knew that the security guys would have your head if you stored the real connection information in a plain text file, so you hard coded it into the file reader service. You created the “server=” content of the file as a placeholder to let you know that you should use the database connection reader.
So, when the network operations personnel gave your code to the other department, everyone started wondering why the other department was now reading log files from the network operations center. All eyes are now looking squarely at you.
Revisiting the Database Reader
All of the eyes looking squarely at you were from your friends in the company, fortunately. After explaining the stress and sleeplessness that undermined your ability to code that day, they all laughed and asked when you would have a new version ready for them. Remembering that sprinting out of the gate during a marathon race is likely to cause the same problems again, you inform them that you’ll need a day or two to get the situation sorted out correctly. There’s no immediate need or CTO putting on the pressure at this point, so everyone agrees to the general timeline and waits patiently while you work.
After a quick discussion with some coworkers, you realize that you had changed the semantics of the file format reader interface and introduced behavior that was incompatible. After a little more discussion, you end up with the design represented by Figure 9, and the change turns out to be fairly simple.
By introducing a separate database reader service, you can remove the type-checking code from the file reader service.
By introducing a separate database reader service, you can remove the type-checking code from the file reader service. You can set up the database reader to read the required connection string from the company standard storage for sensitive data. That decision makes the people in network operations, security, and the other department that wants to use the code, happy.
Next, you update the UI to include a “Send From Database” button as shown in Figure 10. This button calls into the same email sender object that you’ve been using as the public API. However, the email sender now has a ReadFromDatabase method along with a ReadFromFile method. This keeps the public API centralized while still providing the functionality that the various departments need.
public class EmailSender { public void ReadFile() { /* ... */ } public void SendEmail() { /* ... */ } public void ReadDatabase() { /* ... */ } }
With this newly structured system in place, you deliver the solution to both of the waiting departments. Your friends are happy to hear that you’ve been getting more sleep and that the application they’ve been waiting for is “finally done” -a day earlier than promised.
Still More Use for Your Application
Shortly after delivering the updated version of the application with the database reading capabilities, another department gets wind of it and they want to use the API. After a quick conversation with them to find out if your application is what they really need, you deliver the working bits. A day later, one of the developers from that department stops by your cube with a confused look on his face. After some quick chat, you realize that he’s confused by the email sender object. It seems that he doesn’t understand why there’s a “read from database” and “read from file” method on an object that is supposed to send email.
Interface Segregation Principle
The Interface Segregation Principle says that a client (the calling class or module) should not be forced to depend on an interface that it does not need. If there are multiple concerns represented by an interface, or the methods and properties are unclear, then it becomes difficult to know which methods should be called when. Therefore, you should separate the interface into logical pieces, based on the needs of the consumers.
To a certain extent, ISP can be considered a sub-set, or more specific form of the Single Responsibility Principle. The perspective shift of ISP, though, examines the public API for a given class or module. Looking at the IHaveALotOfResponsibilities class in Figure 11, you can see not only a set of methods that you should break into multiple classes for the sake of Single Responsibility, but a very fat interface that may confuse any of the calling clients. If I want to use IHaveALotOfResponsibilities, do I need to call the “Do…” methods? If so, do I need to call them before the “Some…” methods? Or can I just call the “Some…” methods? Or ???
Rather than forcing a developer to know which methods they should call to facilitate the functionality, you should provide a separated set of interfaces that encapsulate the processes in question, independently. This helps to prevent confusion and also helps to cut down on semantic coupling-the idea that a developer has to know the specific implementation of the class to use it correctly.
Violations of ISP are not just found in software, though. Most professional workers in modern society have worked in an office at one time or another. Depending on the size of the office-how many people are working there-you will typically find one or more, very large, all-in-one business machines. These machines print, copy, fax, scan & email, and other functions.
Think back to the last time you had to use one of these large, multi-function machines. They typically have control panels that include 15 to 20 buttons, an LCD display of some sort, and various other forms of input. The number of functions combined with the number of input options often creates a very frustrating user experience. What buttons or controls do you need to operate the machine? How can you ensure that it is going to create a photocopy of a document instead of scanning and emailing it? Do you need to “clear” the current settings? Do you need to type in a number of copies now, or scan the document first and then tell it how many copies to print? What about the brightness, contrast, or paper size of your copy? Did the machine remember the settings from the last user, who wanted to scan a document and email it to someone? The number of options is overwhelming. The instructions are difficult to follow and you’re not always sure that it did what you want. The worst outcome is when an error messages pops up after performing what you believe is the correct sequence of steps. What does “PC LOAD LETTER” mean, anyway?
The large number of capabilities and options that these all-in-one copiers provide may offer some advantages to an office environment. They provide a relatively low cost, high quality, document-centric set of solutions. Unfortunately, they typically come at the cost of a confusing interface. (I, for one, have spent a good number of hours trying to remember how to scan and email a document to myself vs. making a photocopy on the machines in my office.) If manufacturers want to have machines with such a large feature set providing value to so many different users, they should look for ways to separate the interface into each feature so that the user is not led down the wrong path, or led down the right path at the wrong time.
Splitting Up the Email Sender API
After the discussion about your email sender’s API being rolled up into a single class, and the realization that not everyone needs to read from a database or a file, you decide to separate out the objects as shown in Figure 12. When you dive into the code again, you realize that you don’t have to make many changes to your system. The database reader service and the file reader service are both objects on their own, already. The real change that you need to make is to not call them directly from the email sender.
The resulting EmailSender class is significantly smaller. Additionally, you were able to make the message body a parameter of the SendEmail method. This allows for any client of the email sender to provide any message body they need, regardless of the source.
public class EmailSender { public void SendEmail(string messageBody) { SmtpClient client = // new ... client.Credentials = // new ... MailAddress from = // new ... MailAddress to = // new ... MailMessage msg = // new ... msg.Body = messageBody; msg.Subject = // ... client.Send(msg); } }
The file reader service and database reader service classes needed no changes this time around. You simply moved their calls into the code behind of the form for your application (Listing 7). However, the other departments that are using the API need to know that they are responsible for calling the database reader and file reader, directly.
After some discussion with the other departments, there was a little bit of grumbling about how they thought the new API set was more difficult to use. They agreed that a small set of documentation on how to use the API would be sufficient for their needs, though. And honestly, you feel a little more secure knowing that you will have some documentation for the growing API.
Trying to Settle in for a Marathon
After delivering this version of the system, including the new documentation that you wrote for the API set, you decide to step back for a minute and take stock of your system. What you see is rather surprising at this point. You have a growing number of classes and a lot of functionality compared to the original starting point of reading a flat text file and emailing it. Given the attention that you’ve received for this work and the amount of functionality that you have built in, you decide to ask your manager for some official project support. Rather than working this code base on the side of your other responsibilities, you would like to have a dedicated project for this system. This would help provide long-term support for what is now a mission critical part of the company.
Your manager, having received nothing but praise for your hard work and dedication from everyone-including the CTO-happily says yes. He then asks for a timeline to complete the next version. You let him know that you’ll need to think about that for a bit, but off-hand, you expect the code to change when new features are needed, primarily.
On your way back to your desk, another coworker stops you and wants to discuss this project. He’s heard a lot about what you have been doing and likes the direction that you have been taking the code. After a few minutes of discussion, your coworker lets you know that he wants to use this project, but isn’t interested in the current format readers or email sender. He’s mostly interested in the general process and wants to know if he can reuse various parts of the system without having to bring all of your specific implementations along. The current objects and interfaces provide most of what your coworker wants. However, you realize that the big picture of the process is still hard coded and tightly coupled in the current application. Your coworker mentions an idea that revolves around a higher-level process providing an abstraction that lower-level details can implement. This piques your interest and you sit down at your desk, ready to tackle this next challenge..
You would not have a usable set of classes if you had zero coupling..
public interface IMessageInfoRetriever { string GetMessageBody(); } public class FileReaderService : IMessageInfoRetriever { public string GetMessageBody() {/* ... */} } public class DatabaseReaderService : IMessageInfoRetriever { public string GetMessageBody() {/* ... */} }
This interface allows you to provide any implementation you need to the processing service. You then set your eyes on the email service, which is currently directly coupled to the processing service. A simple IEmailService interface solves that, though. Figure 17 shows the resulting structure.
Passing the message info retriever and email service interfaces into the processing service ensures that you have an instance of whatever class implements those interfaces, without having to know about the specific instance types. You can see the end result of this endeavor in Listing 8.
Another Day, Another Delivery
You coworker meets the delivery of this version with great enthusiasm. He’s excited about the possibilities of using the processing service and providing his own email service implementation, format readers, etc. It seems that you have made yet another successful delivery of this ever-evolving solution and you gladly accept your coworker’s thanks.
Heading back to your desk, you realize how high your confidence in this code base, and your ability to continue improving it, actually is. This leads you to wonder what the next change request will be and what new principles and practices you can assimilate into your skill set. It is of little concern, though. Whatever the task, for whoever makes the request, you are certain of your ability to meet their needs.
Summary of Your SOLID Race
When you first set out on the quest to satisfy your CTO, you had no idea that the resulting race would change so many times or so rapidly. You started at a pace to win a 50-meter dash. Soon after, you slowed the pace down for a 400-meter race. You then continued to change the pace as you continued to add features and functionality, realizing the need to restructure the application for long-term maintenance and enhancements. The journey, now at the point where you are settled in for the marathon of a long-term project, has brought you from a system represented by Figure 18, to a system represented by Figure 19.
The difference between these two structures is staggering and looking at them side by side for a moment, you wonder what you’ve actually gained with this sprawl of objects and interfaces. You quickly dismiss the sense of uncertainty, though, as you remember the numerous advantages.
Benefits of the New System Structure
With a set of classes that are small and each providing a valuable function, you are able to construct a larger system that has more value than just the individual parts. It’s like working with a box of LEGO building blocks. Each individual block may be valuable, but they can create something much more valuable when stacked together correctly.
This system is also easily dissectible, and the various parts are easily replaceable. You can change out the specific implementations of the email service, the message info retrieval, and other parts of the system. You can accomplish all of these changes without worrying about adversely affecting the parts of the system that you are not touching.
The ability to segment the system, by both horizontal layers and vertical slices, gives you the ability to focus in to a single point in the system.
The ability to segment the system, by both horizontal layers and vertical slices, gives you the ability to focus in to a single point in the system. This allows you to assign various parts of the system to different team members, with more confidence of the system not falling apart like a game of Jenga.
Achieving Low Coupling
By abstracting many of the implementation needs into various interfaces and introducing the concepts of OCP and DIP, you can create a system that has very low coupling. You can take many of these individual pieces out of this system with little to no spaghetti mess trailing after them. Separating the various concerns into the various object implementations also helps to ensure that you can change the system’s behavior as needed, with very little modification to the overall system-just update the one piece that contains the behavior in question.
Achieving High Cohesion
You can get higher cohesion with a combination of low coupling and SRP-you can stack a lot of small pieces together like building blocks to create something larger and more complex. Any of these individual pieces may not represent much functionality or behavior, but then, an individual puzzle piece isn’t much fun to use without the other pieces. Once separated, DIP allows you to tie the various blocks back together by depending on an abstraction and allowing that abstraction to be fulfilled with different implementations. This creates a system that is much greater than the mere sum of its parts.
Achieving Strong Encapsulation
LSP, DIP, and SRP all work hand in hand to create encapsulation. You can encapsulate the behavioral implementations in many individual objects, preventing them from leaking into each other. You can ensure that the dependencies on those behaviors are encapsulated behind an appropriate interface. At the same time, you do the necessary due-diligence to ensure that you aren’t violating any of the individual abstraction’s semantics or purpose, according to LSP. This helps ensure that you can properly replace the implementation as needed.
A New Utility Belt
In the end, the stepping stones of the SOLID principles offer new insight into object-oriented software development. The principles that you once thought were for the academics are now a set of tools that you can readily grasp. | https://www.codemag.com/article/1001061 | CC-MAIN-2019-47 | refinedweb | 9,919 | 60.35 |
How Visibility Tag work
On 16/03/2017 at 08:20, xxxxxxxx wrote:
I would like to know how exactly the visibility tag work.
Basicly I want to make something that modify only the viewport aspect of an object like the visibility tag does. I starting diving into point cloud, and have really succesfull test with it and result look promising.
My first idea was simply to set visibility viewport on the attached mesh and then make my own stuff.
But in this case I will have no control if I want to hide an object.
About the pointcould impentation for the moment it's only TP particles, but good things with TP is I just have to emit particle and set them into the world position.
But I was thinking to moving to BaseDraw only for speed since it do not have to handle all the TP things. wich is way more cleaner and maybe faster. But I have to redraw everythings on each camera move since point are only 2D and in top of that I must send a ray from the (3d)points to the camera for checking if any object is beetween and if yes don't display the 2d dots. So does it will be really faster? I doubt.
But is There any other way for managing particles instead of TP (cause for now I must allocate a Tp-group, hide it, allow X numbers of particles to be viewed and so on)
Or any other class for making 3d point with a color.
Again if it's not possible in python it's ok :)
Thanks in advance.
On 17/03/2017 at 02:52, xxxxxxxx wrote:
Hello,
there is no "Visibility" tag. Do you mean the "Display" tag?
The "Display" tag actually doesn't do anything. It is just some data container that stores several settings. It is the job of the renderer or the viewport to handle these settings and to display objects accordingly.
If you want to define a point cloud with colors you could create a point object and store the colors per point in an VertexColorTag.
best wishes,
Sebastian
On 17/03/2017 at 03:57, xxxxxxxx wrote:
Thanks you S_Bach for your reply.
Yes sorry I mean the Display tag.
Then for exemple I set the visbility to 0% how to do the same things in my tag?
About VertexColor tag is not a working solution for me since I want them to display everytime. Not only when I'm on point mode, I also select the object and I also select the Vertex Color Tag.
Or maybe I have missed something. here is my code
import c4d def main() : p_obj = c4d.BaseObject(5100) list_pt = [c4d.Vector(0,0,0), c4d.Vector(250, 250, 250)] p_obj.ResizeObject(len(list_pt)) p_obj.SetAllPoints(list_pt) p_obj.Message(c4d.MSG_UPDATE) doc.InsertObject(p_obj) point_count = p_obj.GetPointCount() t_color = p_obj.GetTag(c4d.Tvertexcolor) if not t_color: t_color = c4d.VertexColorTag(point_count) p_obj.InsertTag(t_color) data = t_color.GetDataAddressW() for idx in xrange(point_count) : t_color.SetPoint(data, None, None, idx, c4d.Vector4d(1.0, 1.0, 1.0, 1.0)) c4d.EventAdd() if __name__=='__main__': main()
Then it's not a working solution for me. It's why for me only 2 solutions are Particles or manual drawing.
Basicly I don't want any PointObject I just want a display ;) User won't be able to interact with.
Anyway thanks you :) | https://plugincafe.maxon.net/topic/10020/13486_how-visibility-tag-work/1 | CC-MAIN-2020-05 | refinedweb | 573 | 65.83 |
/* * [] = "@(#)cmdtab.c 8.1 (Berkeley) 6/6/93"; #endif static const char rcsid[] = "$FreeBSD: src/usr.sbin/timed/timedc/cmdtab.c,v 1.3 1999/08/28 01:20:21 peter Exp $"; #endif /* not lint */ #include <sys/cdefs.h> #include "timedc.h" char clockdiffhelp[] = "measures clock differences between machines"; char helphelp[] = "gets help on commands"; char msitehelp[] = "finds location of master"; char quithelp[] = "exits timedc"; char testinghelp[] = "causes election timers to expire"; char tracinghelp[] = "turns tracing on or off"; struct cmd cmdtab[] = { { "clockdiff", clockdiffhelp, clockdiff, 0 }, { "election", testinghelp, testing, 1 }, { "help", helphelp, help, 0 }, { "msite", msitehelp, msite, 0 }, { "quit", quithelp, quit, 0 }, { "trace", tracinghelp, tracing, 1 }, { "?", helphelp, help, 0 }, }; int NCMDS = sizeof (cmdtab) / sizeof (cmdtab[0]); | http://opensource.apple.com/source/remote_cmds/remote_cmds-22.1/timed.tproj/timedc.tproj/cmdtab.c | CC-MAIN-2015-48 | refinedweb | 116 | 60.45 |
Ruby Array Exercises: Check whether there is a 2 in the array with a 3 some where later in a given array of integers
Ruby Array: Exercise-40 with Solution
Write a Ruby program to check whether there is a 2 in the array with a 3 some where later in a given array of integers.
Ruby Code:
def check_array(nums) found1 = false i = 0 while i < nums.length if(nums[i] == 2) found1 = true end if(found1 && nums[i] == 3) return true end i = i + 1 end return false end print check_array([6, 2, 3, 5]),"\n" print check_array([2, 6, 5, 3]),"\n" print check_array([6, 2, 5, 3]),"\n" print check_array([3, 6, 5, 2]),"\n" print check_array([3, 3, 2, 1]),"\n"
Output:
true true true false false
Flowchart:
Ruby Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a Ruby program to check whether a given array of integers contains two 6's next to each other, or there are two 6's separated by one element, such as {6, 2, 6}.
Next: Write a Ruby program to check whether the value 2 appears in a given array of integers exactly 2 times, and no 2's are next to each | https://www.w3resource.com/ruby-exercises/array/ruby-array-exercise-40.php | CC-MAIN-2021-21 | refinedweb | 208 | 50.23 |
Details
- Type:
Improvement
- Status: Closed
- Priority:
Major
- Resolution: Fixed
- Affects Version/s: None
-
- Component/s: core/other
- Labels:None
- Lucene Fields:New
Description.
Activity
- All
- Work Log
- History
- Activity
- Transitions
+1, it's weird that the ctor takes a Reader and we also have a setReader. This is a relic from the pre-reuse days...
+1, but delay this until 5.0. Because there are many Tokenizers outside we should keep backwards compatibility.
Uwe, what's that mean practically? No PR yet? A PR just in trunk? Merging my recent doc to a 4.x branch? A feature branch where this goes to be merged in when the time is ripe?
Benson, he just means the patch would only be committed to trunk. I agree with this...
How about we start by adding ctors that don't require a reader, and do treat them as 4.x fodder?
setReader throws IOException, but the existing constructors don't. Analyzer 'createComponents' doesn't. How to sort this out?
How about we start by adding ctors that don't require a reader, and do treat them as 4.x fodder?
I'd prefer not, because then there needs to be very sophisticated backwards compat to know which one to call. and subclassing gets complicated.
I would really prefer we just choose to fix the API, either 1) 5.0-only or 2) break it in a 4.x release
From my perspective, Benson would be probably be the one most impacted by such a 4.x break. So if he really wants to do this, I have no problem.
setReader throws IOException, but the existing constructors don't. Analyzer 'createComponents' doesn't. How to sort this out?
I dont see the problem. I think createComponents doesnt need to throw exception: instead the logic of Analyzer.tokenStream changes slightly, to call components.setReader(r) in both cases of the if-then-else. Make sense?
OK, I see. If we don't do compatibility, then no one calls setReader in createComponents, and all is well. OK, I'm proceeding.
Why does the reader get passed to createComponents in this model? Should that param go away? is available for your read pleasure to see what these changes look like.
Robert Muir Next frontier is TokenizerFactory.
Do we change #create to not take a reader, or do we add 'throws IOException'? Based on comments above, I'd think we take out the reader.
Michael McCandless I would love help. If you tell me your github id, I'll add you to my repo, and you can take up some of the ton of editing.
Why does the reader get passed to createComponents in this model? Should that param go away?
Yes: please nuke it!
Do we change #create to not take a reader, or do we add 'throws IOException'? Based on comments above, I'd think we take out the reader.
Yes, please. its not like a factory can do anything fancy with it anyway: its only called the first time, subsequent readers are invoked with setReader. so this is just more of the same, please nuke it!
Yes, createComponents should no longer get a Reader, too! Same for factories. The factory just creates the instance, setting the reading is up to the consumer.
The cool thing is: In Analyzer we may simplify things like the initReader() protected method. We should also look at those APIs. Most of the code in Analyzer is to work around the ctor / setReader stuff.
Robert Muir or Michael McCandless I could really use some help here with TestRandomChains.
It does something complex with the input reader in a createComponents. the challenge is to move all that to initReader so that it works. I think I'm too fried from 1000 other edits, I'll look in after dinner but anyone who wants to grab my branch from github and pitch in is more than welcome.
Yes: well the CheckThatYouDidntReadAnythingReaderWrapper can likely be removed. you are removing that possibility entirely. so it should get simpler... ill have a look at your branch tonight and try to help with some of this stuff, its hairy.
I have Solr test failures in PreAnalyzedField, which has some stubborn fondness for the idea of a reader passed to a constructor. But that seems to be all that's broken; a few Solr failures (based on 'ant test').
The changes look great overall. This particular one is tricky. Lemme take a look...
diff --git a/lucene/analysis/common/src/java/org/apache/lucene/analysis/util/AbstractAnalysisFactory.java b/lucene/analysis/common/src/java/org/apache/lucene/analysis/util/AbstractAnalysisFactory.java index 6ac073a..534c166 100644 --- a/lucene/analysis/common/src/java/org/apache/lucene/analysis/util/AbstractAnalysisFactory.java +++ b/lucene/analysis/common/src/java/org/apache/lucene/analysis/util/AbstractAnalysisFactory.java @@ -75,7 +75,7 @@ public abstract class AbstractAnalysisFactory { return originalArgs; } - /** this method can be called in the {@link org.apache.lucene.analysis.util.TokenizerFactory#create(java.io.Reader)} + /** this method can be called in the {@link org.apache.lucene.analysis.util.TokenizerFactory#create()} * or {@link org.apache.lucene.analysis.util.TokenFilterFactory#create(org.apache.lucene.analysis.TokenStream)} methods, * to inform user, that for this factory a {@link #luceneMatchVersion} is required */ protected final void assureMatchVersion() { diff --git a/solr/core/src/java/org/apache/solr/schema/PreAnalyzedField.java b/solr/core/src/java/org/apache/solr/schema/PreAnalyzedField.java index fb741a5..3d3e8e2 100644 --- a/solr/core/src/java/org/apache/solr/schema/PreAnalyzedField.java +++ b/solr/core/src/java/org/apache/solr/schema/PreAnalyzedField.java @@ -290,6 +290,7 @@ public class PreAnalyzedField extends FieldType { @Override public final void reset() throws IOException { + super.reset(); /* This is called after setReader, so here's how we can get the input we care about ... */ this.input = super.input; // NOTE: this acts like rewind if you call it again
Benson's changes, merged up to latest trunk as a patch for review.
I further simplified the PreAnalyzed stuff (only possible due to this change), because it still had problems, and fixed the test for uppercasefilter.
I think this is good to go.
Should I try to get the branch in git to match the .patch, or should I just let you proceed from here? I guess that might depend on reactions of others.
Benson, dont worry about it, I think its good. I just put up the patch so that Uwe might look at it.
I am fine with this patch in trunk only. We can decide later if we backport.
Commit 1556801 from Robert Muir in branch 'dev/trunk'
[ ]
LUCENE-5388: remove Reader from Tokenizer ctor (closes #16)
Marking fixed for 5.0.
Thanks a lot Benson for doing all the grunt work here.
Note: If you really want a backport please just open an issue and hash it out.
+1, its really silly its this way. I guess its the right thing to do this for 5.0 only: i wish we had done it for 4.0, but it is what it is.
Should be a rather large and noisy change unfortunately. I can help, let me know. | https://issues.apache.org/jira/browse/LUCENE-5388 | CC-MAIN-2017-47 | refinedweb | 1,188 | 60.82 |
welshy
Haskell web framework (because Scotty had trouble yodeling)
This package is not currently in any snapshots. If you're interested in using it, we recommend adding it to Stackage Nightly. Doing so will make builds more reliable, and allow stackage.org to host generated Haddocks.
A Haskell web framework heavily influenced by the excellent Scotty, which was in turn influenced by Ruby's Sinatra.
Welshy strives to make it easier to do error handling without overly complicating the control flow. An example:
{-# LANGUAGE OverloadedStrings #-}
import Control.Applicative import Control.Monad import qualified Data.Text.Lazy as T import Network.HTTP.Types import Web.Welshy fibs :: [Int] fibs = 0 : 1 : zipWith (+) fibs (tail fibs) main :: IO () main = welshy 3000 $ do get "/fibs" $ do offset <- queryParam "offset" <|> return 0 length <- queryParam "length" when (offset < 0 || length < 0) (halt $ status badRequest400) when (offset + length > 1000) (halt $ status requestedRangeNotSatisfiable416) let result = take length $ drop offset fibs text $ T.pack $ show result
Some of the features demonstrated here:
You can
haltthe current action at any point and continue with a different one.
Functions like
queryParamand
jsonParamhave built-in error handling.
Welshy's
Actionmonad is an instance of
Alternative. | https://www.stackage.org/package/welshy | CC-MAIN-2017-47 | refinedweb | 194 | 59.19 |
1.Handler message model diagram
Key classes included:
MessageQueue, Handler and Looper, and Message
- Message: the message to be delivered, which can deliver data;
- MessageQueue: message queue, but its internal implementation is not a queue. In fact, it maintains the message list through a single linked list data structure, because the single linked list has advantages in insertion and deletion. The main functions are to deliver messages to the message pool (MessageQueue.enqueueMessage) and take messages from the message pool (MessageQueue.next);
- Handler: Message auxiliary class, which is mainly used to send various message events (Handler.sendMessage) to the message pool and process corresponding message events (Handler.handleMessage);
- Loop: continuously execute loop (loop. Loop), read the message from the MessageQueue, and distribute the message to the target handler according to the distribution mechanism.
Main relationships among the three:
Only one Looper can exist in each thread. The Looper is saved in ThreadLocal. The main thread (UI thread) has automatically created a Looper in the main method. In other threads, you need to manually create a Looper. Each thread can have multiple handlers, that is, a Looper can process messages from multiple handlers. A MessageQueue is maintained in Looper to maintain the Message queue. Messages in the Message queue can come from different handlers.
2.Must know topic
Handler design philosophy
1. The meaning of the existence of handler, why is it designed like this, and what is the use?
The main function of Handler is to switch threads. It manages all message events related to the interface.
To sum up: Hanlder exists to solve the problem that the UI cannot be accessed in the child thread.
2. Why can't I update the UI in the child thread? Can't I update it?
UI control access in Android is non thread safe.
What if you lock it?
- It will reduce the efficiency of UI access: the UI control itself is a component close to the user. After locking, it will naturally block, so the efficiency of UI access will be reduced. Finally, the user end is that the mobile phone is a little stuck
Android has designed a single thread model to handle UI operations, coupled with Handler, which is a more appropriate solution.
3. How to solve the cause of UI crash caused by sub thread update?
The crash occurred in the checkThread method of the ViewRootImpl class:
void checkThread() { if (mThread != Thread.currentThread()) { throw new CalledFromWrongThreadException( "Only the original thread that created a view hierarchy can touch its views."); } }
In fact, it determines whether the current thread is the thread when ViewRootImpl is created. If not, it will crash. The ViewRootImpl is created when the interface is drawn, that is, after onResume. Therefore, if the UI is updated in the child thread, it will be found that the current thread (child thread) and the thread created by View (main thread) are not the same thread and crash.
terms of settlement:
- Update the UI of the View in the thread that creates the new View. The main thread creates the View, and the main thread updates the View.
- Before the ViewRootImpl is created, update the UI of the child thread. For example, update the UI of the child thread in the onCreate method.
- The child thread switches to the main thread to update the UI, such as the Handler and view.post methods (recommended).
MessageQueue related:
1. The function and data structure of messagequeue?
Android uses a linked list to implement this queue, which also facilitates the insertion and deletion of data. No matter which method sends the message, it will go to sendMessageDelayed; return enqueueMessage(queue, msg, uptimeMillis); }
Process of message insertion:
First, set the when field of the Message, which represents the processing time of the Message, and then judge whether the current queue is empty, whether it is an instant Message, and whether the execution time when is greater than the Message time in the header. If any one is satisfied, insert the current Message msg into the header.
Otherwise, you need to traverse the queue, that is, the linked list, find out when is less than a node, and insert it after finding it. Inserting a message is to find the appropriate location to insert the linked list through the execution time of the message, that is, the when field. The specific method is to use the fast and slow pointers p and prev through an endless loop and move backward one grid at a time until we find that the when of a node p is greater than the when field of the message we want to insert, then insert it between p and prev. Or traverse to the end of the linked list and insert it to the end of the linked list.
Therefore, MessageQueue is a special queue structure used to store messages and implemented with a linked list.
2. How is delayed message implemented?
Whether it is an instant message or a delayed message, the specific time is calculated and then assigned to the process as the when field of the message. Then find the appropriate location in the MessageQueue (arrange the when small to large arrangement) and insert the message into the MessageQueue. In this way, MessageQueue is a linked list structure arranged according to message time.
3. How to get messages from messagequeue?
The message is obtained internally through the next() loop, which is to ensure that a message must be returned. If no message is available, it is blocked here until a new message arrives.
The nativePollOnce method is the blocking method, and nextPollTimeoutMillis is the blocking time
When will it be blocked? Two cases:
1. There are messages, but the current time is less than the message execution time
if (now < msg.when) { nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE); } //At this time, the blocking time is the message time minus the current time, and then enter the next cycle to block.
2. When there is no news
nextPollTimeoutMillis = -1;//Indicates that it has been blocked
4. What happens when there is no message in the messagequeue and how to wake up after blocking? And pipe/epoll mechanism?
When the message is unavailable or there is no message, it will be blocked in the next method, and the blocking method is through the pipe/epoll mechanism
It is an IO multiplexing mechanism. The specific logic is that a process can monitor multiple descriptors. When a descriptor is ready (generally read ready or write ready), it can notify the program to perform the corresponding read-write operation. This read-write operation is blocked. In Android, a Linux Pipe is created to handle blocking and wakeup.
- When the message queue is empty and the reader of the pipeline waits for new content in the pipeline to be readable, it will enter the blocking state through the epoll mechanism.
- When there is a message to be processed, it will write content through the write end of the pipeline to wake up the main thread.
5. How are synchronous barriers and asynchronous messages implemented and what are their application scenarios?
Detailed introduction to synchronization barrier blog:
There are three message types in the Handler:
- Synchronization message: normal message
- Asynchronous message: a message set through setAsynchronous(true)
- Synchronization barrier message: a message added through the postSyncBarrier method. The characteristic is that the targe t is empty, that is, there is no corresponding handler.
What is the relationship between the three?
- Under normal circumstances, both synchronous messages and asynchronous messages are processed normally, that is, messages are retrieved and processed according to the time when.
- When the synchronization barrier message is encountered, it starts to look for the asynchronous message from the message queue, and then determines whether to block or return the message according to the time.
In other words, the synchronization barrier message will not be returned. It is just a flag and a tool. When it is encountered, it means to process the asynchronous message first. Therefore, the significance of the existence of synchronous barriers and asynchronous messages is that some messages need "urgent processing"
Application scenario:
In UI drawing: scheduleTraversals
void scheduleTraversals() { if (!mTraversalScheduled) { mTraversalScheduled = true; // The synchronization barrier blocks all synchronization messages mTraversalBarrier = mHandler.getLooper().getQueue().postSyncBarrier(); // Send drawing tasks through Choreographer mChoreographer.postCallback( Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null); } } Message msg = mHandler.obtainMessage(MSG_DO_SCHEDULE_CALLBACK, action); msg.arg1 = callbackType; msg.setAsynchronous(true); mHandler.sendMessageAtTime(msg, dueTime);
6. How to process and reuse message after it is distributed?
After executing the dispatchMessage, there will be: msg.recycleUnchecked(), empty all parameters of msg, release all resources, and insert the current empty message into the sPool header.
sPool is a message object pool. It is also a message with a linked list structure. The maximum length is 50.
**Message reuse process: * * it is directly obtained from the message pool. If it is not obtained, it will be re created.
Looper related:
1. The role of Looper? How do I get the Looper of the current thread? Why not use Map to store threads and objects directly?
Looper is a role that manages message queues. It will constantly find messages from the MessageQueue, that is, the loop method, and return the messages to the Handler for processing, and the loop is obtained from ThreadLocal.
2. How does ThreadLocal work? What are the benefits of this design?
public T get() { Thread t = Thread.currentThread(); ThreadLocalMap map = getMap(t); if (map != null) { ThreadLocalMap.Entry e = map.getEntry(this); if (e != null) { @SuppressWarnings("unchecked") T result = (T)e.value; return result; } } return setInitialValue(); } public void set(T value) { Thread t = Thread.currentThread(); ThreadLocalMap map = getMap(t); if (map != null) map.set(this, value); else createMap(t, value); }
In each Thread, there is a threadLocals variable, which stores ThreadLocal and the corresponding objects to be saved. The advantage of this is that the same ThreadLocal object is accessed in different threads, but the values obtained are different. The internal obtained maps are different. Map and Thread are bound. Therefore, although the same ThreadLocal object is accessed, the accessed maps are not the same, so the obtained values are also different.
Why not use Map to store threads and objects directly?
For example:
- ThreadLocal is the teacher.
- Thread is the classmate.
- Looper (required value) is a pencil.
Now the teacher bought a batch of pencils and wanted to send them to the students. How? Two approaches:
- 1. The teacher wrote the name of each student on each pencil, put it in a big box (map), and let the students find it by themselves when they use it.
This method is to store the students and pencils in the Map, and then use the students to find pencils from the Map.
This approach is a bit like using a Map to store all threads and objects. The bad thing is that it will be very chaotic. There is a connection between each thread, which is also easy to cause memory leakage.
- 2. The teacher sends each pencil directly to each student and puts it in the student's pocket. When using it, each student can take out the pencil from his pocket.
This method is to store the teacher and pencil in the Map, and then when you use it, the teacher says that the students just need to take it out of their pocket. Obviously, this method is more scientific, which is ThreadLocal. Because the pencil itself is used by the students themselves, it is best to give the pencil to the students for safekeeping at the beginning, and each student shall be isolated.
3. What other scenarios will use ThreadLocal?
Choreographer is mainly used by the main thread to cooperate with VSYNC interrupt signal. Therefore, using ThreadLocal here is more meaningful to complete the function of thread singleton.
4. The creation method of looper and the function of the quitAllow field?
Only one Looper can be created for the same thread. If it is created multiple times, an error will be reported.
quitAllow is whether exit is allowed.
When is the quit method usually used?
- In the main thread, you can't exit under normal circumstances, because the main thread stops after exiting. Therefore, when the APP needs to exit, it will call the quit method, and the message involved is EXIT_APPLICATION, you can search.
- In the child thread, if all messages are processed, you need to call the quit method to stop the message loop.
5.Looper is an internal loop. Why won't it get stuck?
- 1. The main thread itself needs to run only because it has to deal with various views and interface changes. Therefore, this loop is needed to ensure that the main thread will continue to execute and will not be exited.
- 2. The operation that will really get stuck is that the operation time is too long when a message is processed, resulting in frame loss and ANR, rather than the loop method itself.
- 3. In addition to the main thread, there will be other threads to handle events that accept other processes, such as Binder thread (application thread), which will accept events sent by AMS
- 4. After receiving the cross process Message, it will be handed over to the Hanlder of the main thread for Message distribution. Therefore, the life cycle of the activity depends on the loop.loop of the main thread. When different messages are received, corresponding measures are taken, such as msg=H.LAUNCH_ACTIVITY, then call the ActivityThread.handleLaunchActivity() method, and finally execute to the onCreate method.
- 5. When there is no message, it will be blocked in the nativePollOnce() method in queue.next() of loop. At this time, the main thread will release CPU resources and enter the sleep state until the next message arrives or a transaction occurs. Therefore, the dead loop will not consume CPU resources in particular.
Handler related:
1. How does message distribute and bind to Handler?
Distribute messages through msg.target.dispatchMessage(msg).
When using Hanlder to send messages, msg.target = this will be set, so target is the Handler that added the message to the message queue.
2. What is the difference between post and sendMessage in handler?
The main sending messages in Hanlder can be divided into two types:
- post(Runnable)
- sendMessage
public final boolean post(@NonNull Runnable r) { return sendMessageDelayed(getPostMessage(r), 0); } private static Message getPostMessage(Runnable r) { Message m = Message.obtain(); m.callback = r; return m; }
The difference between post and sendMessage is that the post method sets a callback for the Message.
Information processing method dispatchMessage:
public void dispatchMessage(@NonNull Message msg) { //1. If msg.callback is not null, when sending a message through the post method, the message will be sent to this msg.callback for processing, and then there will be no follow-up. if (msg.callback != null) { handleCallback(msg); } else { //2. If msg.callback is empty, that is, when sending a message through sendMessage, it will judge whether the current mCallback of the Handler is empty. If not, it will be handed over to the Handler.Callback.handleMessage for processing. if (mCallback != null) { if (mCallback.handleMessage(msg)) { return; } } //3. If mCallback.handleMessage returns false, call the handleMessage method overridden by the handler class. handleMessage(msg); } } private static void handleCallback(Message message) { message.callback.run(); }
Therefore, the difference between post(Runnable) and sendMessage lies in the processing method of subsequent messages, whether to give it to msg.callback or Handler.Callback or Handler.handleMessage.
3. What is the difference between handler.callback.handlemessage and Handler.handleMessage?
The difference is whether the Handler.Callback.handleMessage method returns true:
- If true, Handler.handleMessage will no longer be executed
- If false, both methods are executed.
expand:
1.IdleHandler function and usage scenario?
When there is no message in the MessageQueue, it will be blocked in the next method. In fact, before blocking, the MessageQueue will check whether there is an IdleHandler. If so, it will execute its queueIdle method.
private IdleHandler[] mPendingIdleHandlers; Message next() { int pendingIdleHandlerCount = -1; for (;;) { synchronized (this) { //1. When the message is executed, that is, the current thread is idle, set pendingIdleHandlerCount if (pendingIdleHandlerCount < 0 && (mMessages == null || now < mMessages.when)) { pendingIdleHandlerCount = mIdleHandlers.size(); } //2. Initialize mPendingIdleHandlers if (mPendingIdleHandlers == null) { mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)]; } //Convert mIdleHandlers to array mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers); } // Traverse the array and process each IdleHandler for (int i = 0; i < pendingIdleHandlerCount; i++) { final IdleHandler idler = mPendingIdleHandlers[i]; mPendingIdleHandlers[i] = null; // release the reference to the handler boolean keep = false; try { keep = idler.queueIdle(); } catch (Throwable t) { Log.wtf(TAG, "IdleHandler threw exception", t); } //If the queueIdle method returns false, the IdleHandler will be deleted after processing if (!keep) { synchronized (this) { mIdleHandlers.remove(idler); } } } // Reset the idle handler count to 0 so we do not run them again. pendingIdleHandlerCount = 0; } }
When there is no message processing, it will process each IdleHandler object in the millehandlers collection and call its queueIdle method. Finally, judge whether to delete the current IdleHandler according to the return value of queueIdle.
IdleHandler can handle some idle tasks before blocking when there are no messages to be processed in the message queue.
Common application scenarios:
Start optimization.
- We usually put some events (such as drawing and assignment of interface view) into onCreate method or onResume method. But these two methods are all invoked before the interface is drawn, that is to say, the time consuming of these two methods will affect the start-up time to a certain extent. Therefore, we can put some operations into IdleHandler, that is, call them after the interface drawing is completed, so as to reduce the startup time
2.HandlerThread principle and usage scenario?
public class HandlerThread extends Thread { @Override public void run() { Looper.prepare(); synchronized (this) { mLooper = Looper.myLooper(); notifyAll(); } Process.setThreadPriority(mPriority); onLooperPrepared(); Looper.loop(); } }
HandlerThread is a Thread class that encapsulates Looper.
This is to make it easier for us to use Handler in sub threads.
The purpose of locking here is to ensure thread safety, obtain the Looper object of the current thread, and wake up other threads through notifyAll method after successful acquisition,
3.IntentService principle and usage scenario?
- First, this is a Service
- A HandlerThread is maintained internally, that is, a complete Looper is running.
- The ServiceHandler of a child thread is also maintained.
- After starting the Service, the onHandleIntent method will be executed through the Handler.
- After completing the task, stopSelf will be automatically executed to stop the current Service.
Therefore, this is a Service that can perform time-consuming tasks in the sub thread and automatically stop after the task is executed
4. How does blockcanary work?
BlockCanary is a time-consuming third-party library used to detect application jams.
public static void loop() { for (;;) { // This must be in a local variable, in case a UI event sets the logger Printer logging = me.mLogging; if (logging != null) { logging.println(">>>>> Dispatching to " + msg.target + " " + msg.callback + ": " + msg.what); } msg.target.dispatchMessage(msg); if (logging != null) { logging.println("<<<<< Finished to " + msg.target + " " + msg.callback); } } }
There is a Printer class in the loop method, which prints the log twice before and after the dispatchMessage processes the message. Replace this log class Printer with our own Printer,
5. The memory leak of the handler?
6. How to use Handler to design an App that does not crash?
The main thread crash actually occurs in the processing of messages, including life cycle and interface drawing. So if we can control this process and restart the message loop after a crash, the main thread can continue to run
Handler(Looper.getMainLooper()).post { while (true) { //Main thread exception interception try { Looper.loop() } catch (e: Throwable) { } } }
3. Source code analysis
1.Looper
To use the message mechanism, first create a Looper. When the initialization Looper has no parameters, prepare(true) is called by default; It means that the Looper can exit, and false means that the current Looper cannot exit.
public static void prepare() { prepare(true); } private static void prepare(boolean quitAllowed) { if (sThreadLocal.get() != null) { throw new RuntimeException("Only one Looper may be created per thread"); } sThreadLocal.set(new Looper(quitAllowed)); }
It can be seen here that loopers cannot be created repeatedly, only one can be created. Create Looper and save it in ThreadLocal. ThreadLocal is Thread Local Storage (TLS). Each thread has its own private local storage area. Different threads cannot access each other's TLS area.
Open Looper
public static void loop() { final Looper me = myLooper(); //Gets the Looper object stored in TLS if (me == null) { throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread."); } final MessageQueue queue = me.mQueue; //Gets the message queue in the Looper object Binder.clearCallingIdentity(); final long ident = Binder.clearCallingIdentity(); for (;;) { //Enter the main loop method of loop Message msg = queue.next(); //It may block because the next() method may loop indefinitely if (msg == null) { //If the message is empty, exit the loop return; } //`BlockCanary ` is a time-consuming third-party library used to detect application jams. The custom Printer is set Printer logging = me.mLogging; //The default value is null. The output can be specified through the setMessageLogging() method for the debug function if (logging != null) { logging.println(">>>>> Dispatching to " + msg.target + " " + msg.callback + ": " + msg.what); } msg.target.dispatchMessage(msg); //Get the target Handler of msg and use it to distribute messages if (logging != null) { logging.println("<<<<< Finished to " + msg.target + " " + msg.callback); } final long newIdent = Binder.clearCallingIdentity(); if (ident != newIdent) { } msg.recycleUnchecked(); } }
loop() enters the loop mode and repeats the following operations until the Message is empty: read the next Message of MessageQueue (about next(), which will be described in detail later); Distribute the Message to the corresponding target.
When next() takes out the next message and there is no message in the queue, next() will loop indefinitely and cause blocking. Wait for a message to be added to the MessageQueue, and then wake up again.
The main thread does not need to create a Looper by itself, because the system has automatically called the Looper.prepare() method when the program starts. View the main() method in ActivityThread. The code is as follows:
public static void main(String[] args) { .......................... Looper.prepareMainLooper(); .......................... Looper.loop(); .......................... }
The prepareMainLooper() method calls the prepare(false) method.
2.Handler
Create Handler
public Handler() { this(null, false); } public Handler(Callback callback, boolean async) { ................................. //Loop. Prepare() must be executed before obtaining the loop object, otherwise it is null mLooper = Looper.myLooper(); //Gets the Looper object from the TLS of the current thread if (mLooper == null) { throw new RuntimeException(""); } mQueue = mLooper.mQueue; //Message queue from Looper object mCallback = callback; //Callback method mAsynchronous = async; //Set whether the message is processed asynchronously }
For the parameterless construction method of Handler, the Looper object in the TLS of the current thread is adopted by default, the callback callback method is null, and the message is processed synchronously. As long as the Looper.prepare() method is executed, a valid Looper object can be obtained.
3. Send message
There are several ways to send messages, but in the final analysis, the sendMessageAtTime() method is called. When sending a message through the Handler's post() method or send() method in the child thread, the sendMessageAtTime() method is finally called.
post method
public final boolean post(Runnable r) { return sendMessageDelayed(getPostMessage(r), 0); } public final boolean postAtTime(Runnable r, long uptimeMillis) { return sendMessageAtTime(getPostMessage(r), uptimeMillis); } public final boolean postAtTime(Runnable r, Object token, long uptimeMillis) { return sendMessageAtTime(getPostMessage(r, token), uptimeMillis); } public final boolean postDelayed(Runnable r, long delayMillis) { return sendMessageDelayed(getPostMessage(r), delayMillis); }
send method
public final boolean sendMessage(Message msg) { return sendMessageDelayed(msg, 0); } public final boolean sendEmptyMessage(int what) { return sendEmptyMessageDelayed(what, 0); } public final boolean sendEmptyMessageDelayed(int what, long delayMillis) { Message msg = Message.obtain(); msg.what = what; return sendMessageDelayed(msg, delayMillis); } public final boolean sendEmptyMessageAtTime(int what, long uptimeMillis) { Message msg = Message.obtain(); msg.what = what; return sendMessageAtTime(msg, uptimeMillis); } public final boolean sendMessageDelayed(Message msg, long delayMillis) { if (delayMillis < 0) { delayMillis = 0; } return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis); }
Even updating the UI in the runOnUiThread() called Activity in the child thread is actually sending the message to notify the main thread to update UI, and eventually calls the sendMessageAtTime() method.
public final void runOnUiThread(Runnable action) { if (Thread.currentThread() != mUiThread) { mHandler.post(action); } else { action.run(); } }
If the current thread is not equal to the UI thread (main thread), call the post() method of the Handler, and eventually call the sendMessageAtTime() method. Otherwise, the run() method of the Runnable object is called directly. Let's find out what the sendMessageAtTime() method does?
sendMessageAtTime()
public boolean sendMessageAtTime(Message msg, long uptimeMillis) { //Where mQueue is the message queue obtained from Looper MessageQueue queue = mQueue; if (queue == null) { RuntimeException e = new RuntimeException( this + " sendMessageAtTime() called with no mQueue"); Log.w("Looper", e.getMessage(), e); return false; } //Call enqueueMessage method return enqueueMessage(queue, msg, uptimeMillis); }
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) { msg.target = this; if (mAsynchronous) { msg.setAsynchronous(true); } //Call enqueueMessage method of MessageQueue return queue.enqueueMessage(msg, uptimeMillis); }
You can see that the sendMessageAtTime() method is very simple. It is to call the enqueueMessage() method of MessageQueue to add a message to the message queue.
Let's look at the specific execution logic of the enqueueMessage() method.
enqueueMessage()
boolean enqueueMessage(Message msg, long when) { // Each Message must have a target if (msg.target == null) { throw new IllegalArgumentException("Message must have a target."); } if (msg.isInUse()) { throw new IllegalStateException(msg + " This message is already in use."); } synchronized (this) { if (mQuitting) { //When exiting, recycle msg and join the message pool msg.recycle(); return false; } msg.markInUse();//Mark as used msg.when = when; Message p = mMessages; boolean needWake; if (p == null || when == 0 || when < p.when) { //If p is null (indicating that there is no message in the MessageQueue) or the trigger time of msg is the earliest in the queue, enter the branch msg.next = p; mMessages = msg; needWake = mBlocked; } else { //Insert messages into the MessageQueue in chronological order. Generally, you do not need to wake up the event queue unless //There is a barrier in the Message queue header, and Message is the earliest asynchronous Message in the queue. needWake = mBlocked && p.target == null && msg.isAsynchronous(); Message prev; for (;;) { prev = p; p = p.next; if (p == null || when < p.when) { break; } if (needWake && p.isAsynchronous()) { needWake = false; } } msg.next = p; prev.next = msg; } if (needWake) { nativeWake(mPtr); } } return true; }
MessageQueue is arranged according to the sequence of Message trigger time. The Message at the head of the queue is the Message to be triggered the earliest. When a Message needs to be added to the Message queue, it will traverse from the head of the queue until it finds the appropriate location where the Message should be inserted, so as to ensure the time sequence of all messages.
4. Get message
After sending a message, the message queue is maintained in the MessageQueue, and then the loop() method is used in the loop to continuously obtain messages. The loop() method is introduced above, and the most important thing is to call the queue.next() method to extract the next message. Let's take a look at the specific process of the next() method.
Message next() { final long ptr = mPtr; if (ptr == 0) { //When the message loop has exited, it returns directly return null; } int pendingIdleHandlerCount = -1; // The initial value is - 1 int nextPollTimeoutMillis = 0; for (;;) { if (nextPollTimeoutMillis != 0) { Binder.flushPendingCommands(); } //Blocking operation will be returned when waiting for nextPollTimeoutMillis for a long time or when the message queue is awakened nativePollOnce(ptr, nextPollTimeoutMillis); synchronized (this) { final long now = SystemClock.uptimeMillis(); Message prevMsg = null; Message msg = mMessages; if (msg != null && msg.target == null) { //When the message Handler is empty, query the next asynchronous message msg in the MessageQueue. If it is empty, exit the loop. It is used together with the synchronization barrier. do { prevMsg = msg; msg = msg.next; } while (msg != null && !msg.isAsynchronous()); } if (msg != null) { if (now < msg.when) { //When the asynchronous message triggering time is greater than the current time, set the timeout length of the next polling nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE); } else { // Get a message and return mBlocked = false; if (prevMsg != null) { prevMsg.next = msg.next; } else { mMessages = msg.next; } msg.next = null; //Set the usage status of the message, that is, flags |= FLAG_IN_USE msg.markInUse(); return msg; //Successfully obtained the next message to be executed in MessageQueue } } else { //No news nextPollTimeoutMillis = -1; } //Message exiting, null returned if (mQuitting) { dispose(); return null; } ............................... } }
nativePollOnce is a blocking operation, where nextPollTimeoutMillis represents the length of time to wait before the next message arrives; when nextPollTimeoutMillis = -1, it indicates that there is no message in the message queue and will wait all the time. You can see next() Method obtains the next message to be executed according to the trigger time of the message. When the message in the queue is empty, blocking operation will be performed.
5. Distribute messages
In the loop() method, after getting the next message, execute msg.target.dispatchMessage(msg) to distribute the message to the target Handler object.
Let's take a look at the execution process of the dispatchMessage(msg) method.
dispatchMessage()
public void dispatchMessage(Message msg) { if (msg.callback != null) { //When the Message has a callback method, call back the msg.callback.run() method; handleCallback(msg); } else { if (mCallback != null) { //When the Callback member variable exists in the Handler, the Callback method handleMessage(); if (mCallback.handleMessage(msg)) { return; } } //Handler's own callback method handleMessage() handleMessage(msg); } }
private static void handleCallback(Message message) { message.callback.run(); }
Distribution message process:
When msg.callback of Message is not empty, the callback method msg.callback.run();
When the Handler's mCallback is not empty, the callback method mCallback.handleMessage(msg);
Finally, calling the callback method handleMessage() of Handler itself, the method is empty by default, and the Handler subclass completes the specific logic by overwriting this method.
Priority of message distribution:
Callback method of Message: message.callback.run(), with the highest priority;
Callback method of callback in Handler: Handler.mCallback.handleMessage(msg), with priority next to 1;
The default method of Handler: Handler.handleMessage(msg), with the lowest priority.
In many cases, the processing method after message distribution is the third case, that is, Handler.handleMessage(). Generally, this method is overridden to realize its own business logic | https://programmer.help/blogs/android-message-distribution-handler-must-know.html | CC-MAIN-2021-43 | refinedweb | 5,061 | 57.87 |
Previously I published Perl and PHP classes for Bayesian Classification which was a key component in a few projects of mine, including managing spamming attempts on this blog.
Seeing that dspam seems to have not seen active development for a while, I needed a new classifier for mail. I've also been messing with pymilter as the basis of my own SMTP filtering. The obvious thing to do was to create a port of my previous Classifiers to Python. That way I also have 3-way comparison testing and database compatibility.
I've been running with this class for a while now and it seems to work as expected after a few things got ironed out. These were largely corner cases which didn't occur with previous projects, but caused my Milter to flake out (raise Exceptions) in all sorts of unexpected ways. Some of these include things like having Transaction Deadlocks when two mails are being processed concurrently and contain the same words. I've also ported these fixes to the original Perl and PHP versions.
This is exactly the same as with the Perl and PHP versions. Databases are created with SQL scripts supplied before. In the case of MySQL we start assuming an empty database with whatever user privileges already set:
$ mysql -u dbuser -pdbpass database < classifier_mysql.sql
or...
$ sqlite3 /path/to/database.db < classifier_sqlite.sql
I have applications using both SQLite and MySQL, but obviously the former is a much easier starting point.
First step is to bring the class onboard. In Perl:
import classifier
Then for each lump of text you want to process then create a new object, in this example reading text from STDIN:
classifier = classifier.classifier ( db, sys.stdin.read() )
Databases are standard Python DB-API, in my case sqlite3 or MySQLdb.
Newer versions have support for stopwords. You can get a list from one of the many places on the web and use that with the classifier to remove low-relevance words such as "the" which don't contribute a lot to the subject matter, normally resulting in better classification.
classifier.removestopwords ( stopwords )
This removes any occurrences of the stopwords from the text you loaded into the class.
As before, you need to teach the classifier about the different types of text you want to process. For this we use the classifier.teach() method. This takes up to 3 arguments:
You can use something like:
classifier.teach ( 5, 0.2, False )
Those train the text as classification 5 with a weight of 0.2 (20% of default) and does not train using word order (False).
Where the weighting can be used is if you want to auto-train on incoming mails. Inbound message gets strong classification (high level of confidence) could be used to train automatically with a low weight of say 0.1 so that it doesn't have a major impact if it's a false classification. Asymmetric training could be used to weight HAM higher than SPAM for safety so that it will classify in favour of HAM.
It is always worth having human input to avoid the system going unstable or being poisoned by spammers.
As before it may be useful to forget some previous training (eg. correcting a misclassification). example could be:
scores = classifier.classify ( [ 1, 2, 5, 8 ], 0.3 )
These will classify the text under classes 1, 2, 5 and 8 with a proportion of 0.3 (30%) of the word ordering classification and the remaining 0.7 (70%) of the word frequency classification.:
classifier.unbiased = True
As before, there are two more methods which can be useful. Degrading existing data so that newer training takes precedence (eg. done on a CRON job or via a maintenance URL that is periodically pinged on a site):
classifier.degrade ( 0.9 )
That weights the existing data by 0.9 each time it's called giving training a half-life of 1 week if it's called daily.
The other method is the word Quality score update. This always runs from the word that has been longest since it's Quality score was last updated. It has one optional argument which is the number of words to process else it does them all:
classifier.updatequality ( 200 )
That will update 200 words each time it's run. This is ideal for slow background updating. The word quality is not used in the classifier currently, but it may be of interest for other types of classification.
I've bundled everything into one tarball to make it easier. There is also a Perl and PHP command-line example that uses SQLite. There are also SQL files for both MySQL and SQLite3 to create all the database tables needed.
Download: Python Bayesian Classifier Class & CLI tool on GitHub | https://www.pitt-pladdy.com/blog/_20150707-214047_0100_Bayesian_Classifier_Classes_for_Python/ | CC-MAIN-2019-26 | refinedweb | 797 | 65.42 |
Grouping XML technologies
Some ten years ago, when XML was peaking as one of the hottest technologies around, it was inconceivable that in a decade, XML would be so important, plus you can find many XML-related technologies that are just as interesting. In fact, you can view the various XML technologies through several paths.
The traditional XML groups
You can group XML-related technologies into a few basic groups, or focus areas:
- Document authoring: This group is for the folks that spend most of their time actually authoring XML. Whether they create original XML data, or represent existing data in an XML format, the focus here is pure XML, and takes little notice of the programming tasks that might use those documents. Here's where the core of XML sits, along with specific XML vocabularies, like MathML or some of the scientific XML vocabularies.
- Processing XML: These are the technologies like XSL that allows XML to be transformed, massaged, or migrated from one format to another. Again, the focus is the XML documents and data within them, although programming languages are sometimes used to accomplish these transformations.
- Reading/writing XML (and persisting data): This is the more programming-centric grouping of technologies, ranging from low-level APIs like SAX and DOM to data binding technologies like JAXB and Castor. This is where XML is seen as a data storage mechanism, and in a lot of ways, a means to an end.
Until recently, these were the big categories...with most new technologies and specifications adding to one of these three groupings.
Moving XML to a first-class data citizen
One of the big problems with XML, though—and a limitation to the three groups
above—was the lack of good search support. If you wanted to search through your
data, and the data was in XML, it's been a problem. In fact, the general solution was to force together a few of the groupings above. Document authors might struggle through using a command-line tool like
grep, which is a lousy way to perform searches. Programmers might read in the XML (another grouping), and then use their programming language (like Java or C#) to search through the data in a non-XML format. That's workable, but still reveals a limitation of XML.
Fortunately, the introduction and now popularity of XPath (and XQuery, mentioned late in this article) have introduced a new group:
- Searching XML: This is where XPath and XQuery come in. These specifications/technologies allow you to search XML documents in what amounts to an XML manner. In other words, the searches are capable of working with XML semantics, and can search through not only the data in an XML document, but the structure of those documents, as well.
With XPath and XQuery, you're not stuck pulling data from XML into a programming language, and then using that language's tools to search the data. In addition to the constraint of your programming language with that approach, you typically lose most of the XML semantics and structure, such as what element was a child of what other element, and so on. XPath and XQuery allow you to search XML without needing a programming language.
All that said, though, there's still a need for programming languages and interacting
with XPath and XQuery from Java (and other) languages. While XPath and XQuery give you
great XML-aware searching capabilities, you still need a way to use these technologies
if you're a programmer. Simply launching a command-line process with a system-aware
command like
exec() is a pain, and prone to all sorts of
errors you can't handle. Worse yet, it probably makes working with the results of a
search nearly impossible (if not actually impossible). That's where XPath meets
the Java (or C# or Perl) language. This is a Java-specific article. (If you want to see
articles about those other languages, tell us in the feedback section of this article!).
If you're reading this article, you should at least be familiar with XPath. Check out Resources for links to a good two-part introductory tutorial on XPath, if you've never used the technology before, and then come back to this article.
It's at this point—the intersection of XPath and Java technology—that Sun has done Java programmers a big favor. They're integrated XPath support into the Java 5 environment. Even better, you don't need to download the enterprise edition, or a supplemental package (like Sun used to do with parts of JDBC). If you've got Java 5 software on your machine, you've got XPath support, in a very Java-centric way. In fact, it's part of JAXP, the Java API for XML Processing, something you're probably already familiar with.
Make sure you've got the Java 5 release
If you're not sure what version of Java technology you have, or what version of Java
technology runs on the machine (perhaps on a remote server) that you write code on, you can find out easily. Just run
java with the
-version flag. Listing 1 shows what that should look like.
Listing 1. Making sure you've got Java 5 or later
As long as the version is 1.5 or greater, you're ready to work through this article.
Note that 1.5 is equivalent to 5.0, and it's not completely clear (to me or most Java
developers) why all the public literature says "Java 5", but the
java command still returns 1.5. Still, if you've got 1.5.x or even
1.6.x, you're in great shape. If not, check Resources for links
to download Java 5 technology.
Make sure you've got XPath support
Next, you need to make sure that you have XPath support. That probably sounds like a
redundancy; you just checked to see if you've got at least Java 5 software, right? Still, there
are tons of developers who have a different Java version on their system path than
their development environment is using. Or Eclipse, your IDE, is running something other
than your Web application server. And on and on...the best way to avoid problems like this sneaking up on you is to build a tiny program to test things out. Listing 2 shows a program that does nothing more than create a new instance of the XPath factory,
XPathFactory. This also ensures things like parsers and an implementation are set up and running.
Listing 2. A very simple XPath test class
Compile this class and run it. You should get the very basic output in Listing 3.
Listing 3. Successful output of the test class from Listing 2
This is pretty trivial, but you can take this class and try it on your Web server, your application server, your four mirrored production servers...and anywhere else you want your XPath code to run. If the class runs on those machines, then you're safe to develop more complex XPath apps. If the test class doesn't run, spend your time getting XPath support working before spending hours on writing code that might not work when it counts.
An overview of the XPath API
Understanding the XPath part of the JAXP API is really dependent upon understanding how JAXP handles all XML parsing, processing, and transformations.
You'll recall that the basic steps to work with XML are:
- Get a factory class to provide instances of a vendor-specific JAXP implementation.
- Get a parser or transformer instance from the factory.
- Set configuration options on or around that parser or transformer (validation, namespace-awareness, stylesheet to use, and so on).
- Create an object to hold, store, or reference the XML to be operated on (usually through some type of
InputSource.
- Parse or transform the XML.
This usually resembles Listing 4 in code, which shows a simple XML parse, using a command-line argument as the filename of the XML document to parse.
Listing 4. Using the SAXParserFactory
If you're building a DOM tree, the process still follows the same model. Listing 5 shows code to create a DOM tree of an XML document, and the steps are very similar, even though the class and method names change.
Listing 5. Using the document builder factory
In both cases, you get a factory, use that to create a new parser/processor instance, and then operate on that instance.
The workflow is very similar when you write XPath code:
- Get an XPath factory class to provide instances of a vendor-specific XPath implementation.
- Get an XPath evaluator instance from the factory.
- Create a new XPath expression. (This step is different from the parsing model, although it still aligns with assigning a stylesheet in the XML transformations model.)
- Build a DOM tree of the XML document to evaluate the XPath expression against.
- Evaluate the XPath expression.
Let's walk through this process step-by-step, build up a basic program for parsing XPath expressions, and then you can evaluate any of your own XPaths, or any of the XPaths you wrote when you worked through the XPath tutorial (those links are in Resources).
Feed a DOM tree to your XPath
You need to keep in mind a few suppositions that apply to the program you'll build in this article:
- You have an XML document that you can easily convert into a DOM tree. This article's example reads in an XML document from the command line, and converts it to a DOM tree, but you can just as easily build a DOM tree from a network URI, a set of SAX events, or any other source. If you're rusty on how to get a DOM tree from various sources using JAXP, check out Resources for some helpful links.
- An XPath you want to evaluate. This article assumes you already have an XPath, or at least know how to construct one. There's no substantive discussion about how to build XPaths, but more on how to evaluate them.
Once you take care of these things, you're ready to write code.
Get an XML document to evaluate your XPath against
Begin with a simple program that reads in a filename from the command-line. You'll use that name to build a DOM tree from the XML document the filename references. There's nothing XPath- or even JAXP-specific here; just some simple I/O and program plumbing. Listing 6 is the beginning of your program; save this as XPathEvaluator.java.
Listing 6. Initial version of program to evaluate XPaths
Convert your XML into a DOM tree
The XPath API—at least in its current form in JAXP—requires a DOM tree to operate upon. All XPaths require some sort of in-memory model to operate upon, because XPaths are fundamentally about the hierarchy of an XML document. DOM provides this, in the form of a navigable tree of elements, attributes, and text nodes.
Since you're already using JAXP for XPath support, you get DOM support as well, for
free. Use the
DocumentBuilder class (and its associated
factory,
DocumentBuilderFactory) to convert the string reference to an XML document into an in-memory DOM tree. Listing 7 shows the additions to
XPathEvaluator to take care of this.
Listing 7. Creating a DOM tree from the input XML document
Most of the code is just DOM-based JAXP parsing; if you're unclear on what's going on here, check Resources specifically for the links on general JAXP parsing and transformation articles.
A note on namespace awareness
XPath, as is the case with most XML specifications that are fairly modern and current, is namespace aware. That means that namespace prefixes on elements (like
iTunes:artist) can be part of your XPaths. Even if you're not using namespaced documents, though, you should ensure that you have this capability for the future.
To do that, though, you must ensure that your DOM tree is namespace aware. In other words, you ensure that the input to your XPath evaluations is namespace-aware, so your evaluations can be. To ensure that, always turn on namespace awareness when you build your DOM tree. Listing 8 shows a single-line addition to accomplish that.
Listing 8. Adding namespace awareness to building the DOM tree
Represent an XPath in the Java environment
Once you've got a DOM tree to evaluate, you need to take your XPath—which is
just a textual string—and create a Java representation of that. Of course, that
doesn't just mean that you create a
String variable and stuff the XPath into it. You need an actual Java object that can either evaluate itself, or be evaluated by some other XPath-aware component, against the DOM tree you've now got. That's where JAXP's new API additions come into play.
Start with an XPath factory
Here's where that sequence of events from earlier comes into play. You begin all your XPath work—outside of getting a DOM tree ready, which technically can be done anytime before actual XPath evaluation—with a new class,
javax.xml.xpath.XPathFactory.
Specifically,
XPathFactory is an interface, and you need an implementation of that interface. That implementation will be vendor-specific; Sun provides a default implementation, Apache might have an implementation, Oracle might have an implementation...but none of that code belongs in a nice, vendor-neutral piece of code. Instead, you can abstract vendor specifics away with
XPathFactory, and its
newInstance() method, which handles getting an implementation of
XPathFactory for you.
Listing 9 takes care of that. Note that this listing shows only the
evaluateXPath() method. You'll need to add a few
import statements to your code to make this work, all in the
javax.xml.xpath package.
Listing 9. Getting an instance of XPathFactory
Next up, you need an
XPath object. This object is capable of
evaluating XPaths, and is the cornerstone of your XPath-aware Java programs. Just as you
get a
DocumentBuilder from a
DocumentBuilderFactory, you get an
XPath
from an
XPathFactory. Listing 10 shows this minimal code.
Listing 10. Getting an XPath object
With this object, you're ready to evaluate your XPath, and work with the results.
Evaluate an XPath expression
Once you have an
XPath instance, you can evaluate XPaths, get a resulting node set, and do some work with those results.
You evaluate an XPath (not the Java object, but a string path referring to an XML document) with the
evaluate method on the
XPath Java object. That's a bit confusing: you use
XPath to evaluate an XPath. So in a truer sense, the
XPath object is an XPath evaluator.
The
evaluate() method takes two arguments: a string XPath, a DOM tree to evaluate that XPath against, and an XPath constant indicating the return type. The return type turns out to be pretty inflexible; the specification of a return type is really for future compatibility; for now, always use
XPathConstants.NODESET, to have your results returned as a DOM
NodeList structure.
See the code to evaluate an XPath in Listing 11, added to the
evaluateXPath method.
Listing 11. Evaluating an XPath
Listing 11 includes lots of new additions, all important:
- The method now returns an
org.w3c.dom.NodeList. Be sure to add an
import org.w3c.dom.NodeList;statement to your code to make this work.
NodeListis the structure used to return the list of nodes from the evaluation of your XPath.
- The entire code block is wrapped in a
try/catchblock, and the exception that can result from XPath evaluation—
javax.xml.xpath.XPathExpressionException—is caught and rethrown as an
IOException. You'll come back to the reasoning behind this shortly.
evaluate()is called with the XPath string passed into the method, the DOM tree you built in the class's constructor, and the constant indicating to return results as a list of nodes.
- The result of
evaluate, which is an
Object, is cast to the DOM
NodeListtype, and returned.
Despite several things happening, they're all pretty straightforward, and nothing that should trip you up.
XPath-specific, DOM-specific, JAXP-specific?
One interesting point is the decision to return any exceptions from this method, as well as any that arise in the constructor, as
IOExceptions. That's a design decision, and not really XPath-specific, but it's important. With that decision, you can insulate users of this class—through the command line or another program—from having to know, import, or directly use any XPath classes or interfaces.
In fact, you abstracted away all JAXP classes, DOM classes, SAX classes, and XPath classes...except the
NodeList class from the DOM. That's pretty powerful, as other programmers don't need to be familiar with the JAXP or XPath API to get XPath evaluation. It takes your program from an interesting programming exercise to a reusable tool, and that's a pretty important distinction.
If you take this principle and want to go even a bit further, you could take the returned
NodeList and iterate through it, and dump the results into a Java
List. That would abstract away the details about DOM completely, and remove even the current small dependency on
org.w3c.dom.NodeList.
Work with the results of evaluation
Once you get the results of an XPath evaluation, you're ready to work with those results...in whatever format you like. For the sake of example, you'll look at just iterating through the results and printing them out. Of course, you can expand on this as much as you like.
A very simple iteration through result nodes
Each member of a
NodeList is in fact a DOM
Node (
org.w3c.dom.Node), and you can then find out the name of the node, its type, and pretty much anything else about that node you want. Listing 12 shows a very basic addition to the
XPathEvaluator class that passes in an XPath to evaluate, gets the results, and prints them out.
Listing 12. Completing the XPathEvaluator program (take one)
If you read the two-part tutorial on XPath, you'll recognize this XPath as selecting several properties. You should download the example file xerces-build.xml (available in Resources if you don't already have it) to run this example, as shown in Listing 13.
Listing 13. Running XPathEvaluator program (take one)
These results look pretty bland, especially if you compare them to Figure 1, a screen capture from the tutorial where this same expression was evaluated graphically using a tool for evaluating XPaths.
Figure 1. Evaluating an XPath expression in a graphical tool
However, that printed out view of elements is deceptively simple.
A node has more than just a name
Remember that while all the sample program did was print out a node's name, type, and possibly its value (depending on that type), you've still got a complete
Node object. Further, that node isn't in isolation; it's a reference to a node in an in-memory DOM tree (even if you don't see that DOM tree from a usage perspective; it's hidden internally in the
XPathEvalutor code).
What that means is that for each
Node, you've really got a location pointer within the complete XML document you handed off to
XPathEvaluator. That means you can navigate to a node's children, see what attributes exist on an element node, find out the name of a text node's parent element, and perform any other DOM operation that's allowed on a
Node. You don't just have a node, you have a reference to that node in its full DOM context. It's up to you to determine what you do with that node, and the context within which it's positioned.
About those earlier JAXP, DOM, and XPath abstractions...
You might have noticed that all the work intimated above to avoid DOM-specific references now goes out the window. In fact, that's why
XPathEvaluator abstracts XPath details away from users of the class, but still returns a DOM
NodeList. You can safely insulate your users from JAXP and XPath, but to do much with the results of an XPath evaluation, you'll need to work with the DOM.
For that reason, it's best to return DOM structures, but avoid requiring XPath-specific input or providing XPath-specific output. Let your users work with the DOM, and nothing else, at least in terms of your requirements for your class functioning.
Developers like you and me are a short-tempered, anxious lot. As you begin to get the feel and command of using XPath from the Java environment, you're probably already thinking about what you can't do with XPath. Particularly complex relationships between data aren't easy to deal with (using SQL-like joins is at the outer extremes of what XPath is built to do), you must do ordering of nodes and further filtering in the Java environment, and readability of XPath is pretty difficult if you're not already familiar with the specification.
Thankfully, you can take a very natural step from XPath to the next thing which addresses all of these limitations, and does it in a way that is reminiscent of what you've already don. XQuery adds more of an XML-ized version of SQL, allowing you to build queries, sort and order results, and use actual WHERE statements in your queries. XQuery also builds on XPath, meaning everything you've learned about nodes, predicate matching, and how elements and attributes relate to each other applies to XQuery.
And, just as XPath does, XQuery has an API for its inclusion in Java programmers: the XQuery for Java (XQJ) API. For a lot more on XQuery, check out Resources, which has links to articles and tutorials on XQuery and XQJ. And once you feel you've gotten your head firmly around XPath, take a look at XQuery to add even more power to your XML-related application code.
Much of using XPath from Java technology is simply to learn new syntax, get an API and a few tools configured, and then apply what you already know about XPath. That shouldn't make you think that using XPath in the Java environment is trivial, though. Beyond a need for complexity, XPath offers a tremendous amount of flexibility when you work with XML from Java programming. It certainly moves you far beyond what most basic SAX, DOM, JAXP, JDOM, or other., implementations provide (although some vendors and projects provide XPath-capable extensions to the basics that those specs and APIs offer).
And, XPath offers a wonderful gateway to the more complex XQuery language, and Java and XQuery combinations (using the XQJ API). Rather than immediately move on to XQuery, you'll do well to polish your XPath skills, and learn to select complex node sets from within your Java applications, and manipulate those as needed. You'll find lots of cases where you don't need anything beyond XPath. On top of that, XQuery builds upon XPath—both from a lexical perspective and in terms of the XQJ API, which can actually evaluate XPaths as well as execute XQueries—so you're improving your XQuery skills implicitly. Most of all, have fun with the increased flexibility that XPath offers, especially when evaluated from the Java environment.
Information about download methods
Learn
- If you're unfamiliar with XPath, take this two-part tutorial:
- Locate specific sections of your XML documents with XPath, Part 1 (Brett McLaughlin, Sr., developerWorks, June 2008): Explore XPath basics. Easily locate and refer to specific data in a document and its various selectors and semantics, in an example-driven, hands-on manner.
- Locate specific sections of your XML documents with XPath, Part 2 (Brett McLaughlin, Sr., developerWorks, June 2008): Add predicates to your XPath skills to find exact nodes as you evaluate attribute values plus the parent and child nodes of a target element.
- XPath 1.0: Read the formal definition of XPath in the original specification.
- XPath 2.0: Read the online specification for the most current version of XPath.
- Tutorial on XPath: Understand how XPath is fundamental to much advanced XML usage with this useful but brief tutorial from the W3C.
- Online function reference for XPath, XQuery, and XSLT: Once you understand how predicates and functions work, visit this great resource to look up syntax and find functions that aren't commonly discussed.
- Sun's XQuery for API: Move from XPath to XQuery when you check out this page, which details the complete XQuery for Java API.
- DataDirect resource page: From DataDirect, the hosts of xquery.com, explore implementations of both an XPath evaluator (Stylus Studio), and an XQuery for Java (XQJ) engine, plus related work on XQuery and XPath.
- DataDirect online help system: Visit this indexed, searchable resource that's great for finding out about particular DataDirect objects and methods.
- Understanding DOM (Nicholas Chase, developerWorks, March 2007): Dig deeper into manipulating XML from a node-based API in an excellent SE: Download for integrated XPath support on your system.
- Java 6 software: If you're considering upgrading to Java 5 technology, just skip version 5 and go straight to the very latest version, if at all possible.
- Stylus Studio 2008 XML: Download to start with XPath and XML documents on the Windows platform.
- AquaPath: Download to enable easy XPath location evaluation on Mac OS X.
- DataDirect's XQuery for Java implementation: Download and get started with XQuery and Java searches.
- Java & XML, Third Edition (Brett McLaughlin and Justin Edelson, O'Reilly Media, 2006):. | http://www.ibm.com/developerworks/library/x-xpathjava/ | crawl-002 | refinedweb | 4,296 | 60.45 |
Hi Everyone!
My name is Andy Luhrs, and I'm one of the Program Managers on Debugging Tools for Windows. Our team has decided to start up a blog to get some more tips and tutorials out to people around updates and changes to our debugging tools (WinDbg, kernel debugging, AppVerifier, etc.) There's tons of blogs about debugging difficult or weird issues (Raymond's is my favorite), and the main goal of this isn't to cover that type of stuff. The plan is to have a few people across our team contribute, so expect to see a variety of perspectives. We're largely aiming to look at and highlight some of the under the hood type changes that doesn't fit in our normal MSDN documentation, and talk about features in the preview releases of the SDK that don't have full documentation written for them yet. We'll do our best to update our blog posts to point to official documentation when it's available.
So here's a few quick tips to get started:
- Stay up to date! We make a lot of changes behind the curtains that improve command performance, reliability, and output. It's definitely worth staying on the SDK preview versions of WinDbg when they're available.
- Try running 'dx Debugger' and click around the DML links and learn what's the in the namespaces there. We'll be going a bit more in-depth on what's possible with 'dx' and what some of the more interesting namespaces are in future posts. Or even better, try 'dx -r3 @$cursession.Devices.DeviceTree' while in a kernel session.
- If you're using something like a laptop or Surface, you might hate that it doesn't have a "Break" key. We added Alt+Delete as an alternative key combination to break-in.
We're aiming to make posts with every SDK preview release that has major changes, when we have a question that gets asked frequently, and when we have good tutorials or tips that we want to share out. Feel free to use comments to ask for elaboration or details, and we'll do our best to follow-up.
-Andy Luhrs
@aluhrs13
Hello!
0: kd> dx -r1 @$cursession.Devices.@”DeviceTree”
@$cursession.Devices.@”DeviceTree” :
Error 0x80004005 occurred.
There was a typo in the original post, the actual command is “dx -r3 @$cursession.Devices.DeviceTree”, but that typo wouldn’t give you that error. What version of the debugger are you using?
0: kd> dx -r3 @$cursession.Devices.DeviceTree
@$cursession.Devices.DeviceTree :
Error 0x80004005 occurred.
0: kd> version
Windows 10 Kernel Version 10586 MP (2 procs) Free x64
Built by: 10586.494.amd64fre.th2_release_sec.160630-1736
Machine Name:
Kernel base = 0xfffff800`b0e0b000 PsLoadedModuleList = 0xfffff800`b10e8cf0
Debug session time: Fri Aug 12 12:33:52.474 2016 (UTC + 3:00)
System Uptime: 0 days 0:24:01.273
Remote KD: KdSrv:Server=@{},Trans=@{COM:Port=\\.\pipe\10-64-P-b10586-EN,Baud=19200,Pipe,Timeout=4000,Resets=2}
Microsoft (R) Windows Debugger Version 10.0.10240.9 AMD64
command line: ‘windbg.exe -k com:pipe,port=\\.\pipe\10-64-P-b10586-EN -WF E:\Work\Debug\WinDBG\10-64-P-b10586-EN.wew -loga E:\Work\Debug\WinDBG\10-64-P-b10586-EN.log -c “g”‘ Debugger Process 0x44A4
dbgeng: image 10.0.10240.16399, built Thu Jul 23 04:51:27 2015
[path: C:\Program Files (x86)\Windows Kits\10\Debuggers\x64\dbgeng.dll]
dbghelp: image 10.0.10240.16399, built Thu Jul 23 04:49:35 2015
[path: C:\Program Files (x86)\Windows Kits\10\Debuggers\x64\dbghelp.dll]
DIA version: 40116
Extension DLL search Path:
C:\Program Files (x86)\Windows Kits\10\Debuggers\x64\WINXP;C:\Program Files (x86)\Windows Kits\10\Debuggers\x64\winext;C:\Program Files (x86)\Windows Kits\10\Debuggers\x64\winext\arcade;C:\Program Files (x86)\Windows Kits\10\Debuggers\x64\pri;C:\Program Files (x86)\Windows Kits\10\Debuggers\x64;C:\Program Files (x86)\Windows Kits\10\Debuggers\x64\winext\arcade;C:\ProgramData\Oracle\Java\javapath;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\ATI Technologies\ATI.ACE\Core-Static;C:\Program Files (x86)\Skype\Phone\;C:\Windows\system32\config\systemprofile\.dnx\bin;C:\Program Files\Microsoft DNX\Dnvm\;C:\Program Files (x86)\Windows Kits\8.1\Windows Performance Toolkit\;C:\WinDDK\8.0\Windows Performance Toolkit\;C:\Program Files (x86)\Windows Phone TShell\;C:\Program Files (x86)\Windows Kits\10\Windows Performance Toolkit\
Extension DLL chain:
dbghelp: image 10.0.10240.16399, API 10.0.6, built Thu Jul 23 04:49:35 2015
[path: C:\Program Files (x86)\Windows Kits\10\Debuggers\x64\dbghelp.dll]
ext: image 10.0.10240.16399, API 1.0.0, built Thu Jul 23 04:50:27 2015
[path: C:\Program Files (x86)\Windows Kits\10\Debuggers\x64\winext\ext.dll]
exts: image 10.0.10240.16399, API 1.0.0, built Thu Jul 23 04:49:59 2015
[path: C:\Program Files (x86)\Windows Kits\10\Debuggers\x64\WINXP\exts.dll]
kext: image 10.0.10240.16399, API 1.0.0, built Thu Jul 23 04:49:56 2015
[path: C:\Program Files (x86)\Windows Kits\10\Debuggers\x64\winext\kext.dll]
kdexts: image 10.0.10240.16399, API 1.0.0, built Thu Jul 23 05:05:16 2015
[path: C:\Program Files (x86)\Windows Kits\10\Debuggers\x64\WINXP\kdexts.dll]
You’re using a debugger that’s a bit over a year old. Installing the most recent SDK should fix your issue, you can find it at
Hello!
Doesn’t help.
0: kd> version
…
Microsoft (R) Windows Debugger Version 10.0.14321.1024 X86
….
0: kd> dx -r3 @$cursession.Devices.DeviceTree
@$cursession.Devices.DeviceTree
The error disappeared, but the command output is empty.
Hi, looking forward to your upcoming posts.
One question I have is how developers will be able to obtain checked OS builds of current releases… any word on that?
Andy, I am seeing a problem with the new build 14901. The Miracast drivers are missing or the ability to use wifi to connect to TVs is missing. Do you have a work around for this??
I’d recommend directing this feedback to the Feedback Hub or forums, this blog is focused on Debugging Tools for Windows:
Andy,
I just commented on your episode in Channel9’s Defrag Tools. It is not directly related to your team, but if you could give a brief overview to get started on LINQ & Natvis, it will be great!
Hope this blog will be great like other great blogs out there! Good luck!
Welcome to the blogging world. I just watched you guys on Defrag Tools and found out about this blog.
I use WinDbg almost daily in my work, so I’m sure you’re blog will be most useful to me.
It was never easy following the scattered crumbs of information from the Debugger Tools team, so it’ll be great to have direct communication here.
Looking forward to upcoming posts.
Looking forward for most articles!! | https://blogs.msdn.microsoft.com/windbg/2016/08/05/hello-world/ | CC-MAIN-2017-43 | refinedweb | 1,189 | 59.9 |
#include <CbcLinked.hpp>
Inheritance diagram for OsiUsesBiLinear:
This is used so can make better decision on where to branch as it can look at all objects.
This version sees if it can re-use code from OsiSimpleInteger even if not an integer variable. If not then need to duplicate code.
Definition at line 1080.
Set bounds to fix the variable at the current value.
Given an current value, set the lower and upper bounds to fix the variable. Returns amount it had to move variable.
Reimplemented from OsiSimpleInteger.
Add all bi-linear objects.
data Number of bilinear objects (maybe could be more general)
Definition at line 1131 of file CbcLinked.hpp.
Type of variable - 0 continuous, 1 integer.
Definition at line 1133 of file CbcLinked.hpp.
Objects.
Definition at line 1135 of file CbcLinked.hpp. | http://www.coin-or.org/Doxygen/CoinAll/class_osi_uses_bi_linear.html | crawl-003 | refinedweb | 135 | 61.43 |
Go to the first, previous, next, last section, table of contents.
For applications using
autoconf the standard macro
AC_CHECK_LIB can be used to link with GSL automatically
from a
configure script. The library itself depends on the
presence of a CBLAS and math library as well, so these must also be
located before linking with the main
libgsl file. The following
commands should be placed in the `configure.ac' file to perform
these tests,
AC_CHECK_LIB([m],[cos]) AC_CHECK_LIB([gslcblas],[cblas_dgemm]) AC_CHECK_LIB([gsl],[gsl_blas_dgemm])
It is important to check for
libm and
libgslcblas before
libgsl, otherwise the tests will fail. Assuming the libraries
are found the output during the configure stage looks like this,
checking for cos in -lm... yes checking for cblas_dgemm in -lgslcblas... yes checking for gsl_blas_dgemm in -lgsl... yes
If the library is found then the tests will define the macros
HAVE_LIBGSL,
HAVE_LIBGSLCBLAS,
HAVE_LIBM and add
the options
-lgsl -lgslcblas -lm to the variable
LIBS.
The tests above will find any version of the library. They are suitable for general use, where the versions of the functions are not important. An alternative macro is available in the file `gsl.m4' to test for a specific version of the library. To use this macro simply add the following line to your `configure.in' file instead of the tests above:
AX_PATH_GSL(GSL_VERSION, [action-if-found], [action-if-not-found])
The argument
GSL_VERSION should be the two or three digit
MAJOR.MINOR or MAJOR.MINOR.MICRO version number of the release
you require. A suitable choice for
action-if-not-found is,
AC_MSG_ERROR(could not find required version of GSL)
Then you can add the variables
GSL_LIBS and
GSL_CFLAGS to
your Makefile.am files to obtain the correct compiler flags.
GSL_LIBS is equal to the output of the
gsl-config --libs
command and
GSL_CFLAGS is equal to
gsl-config --cflags
command. For example,
libfoo_la_LDFLAGS = -lfoo $(GSL_LIBS) -lgslcblas
Note that the macro
AX_PATH_GSL needs to use the C compiler so it
should appear in the `configure.in' file before the macro
AC_LANG_CPLUSPLUS for programs that use C++.
To test for
inline the following test should be placed in your
`configure.in' file,
AC_C_INLINE if test "$ac_cv_c_inline" != no ; then AC_DEFINE(HAVE_INLINE,1) AC_SUBST(HAVE_INLINE) fi
and the macro will then be defined in the compilation flags or by including the file `config.h' before any library headers.
The following autoconf test will check for
extern inline,
dnl Check for "extern inline", using a modified version dnl of the test for AC_C_INLINE from acspecific.mt dnl AC_CACHE_CHECK([for extern inline], ac_cv_c_extern_inline, [ac_cv_c_extern_inline=no AC_TRY_COMPILE([extern $ac_cv_c_inline double foo(double x); extern $ac_cv_c_inline double foo(double x) { return x+1.0; }; double foo (double x) { return x + 1.0; };], [ foo(1.0) ], [ac_cv_c_extern_inline="yes"]) ]) if test "$ac_cv_c_extern_inline" != no ; then AC_DEFINE(HAVE_INLINE,1) AC_SUBST(HAVE_INLINE) fi
The substitution of portability functions can be made automatically if
you use
autoconf. For example, to test whether the BSD function
hypot is available you can include the following line in the
configure file `configure.in' for your application,
AC_CHECK_FUNCS(hypot)
and place the following macro definitions in the file `config.h.in',
/* Substitute gsl_hypot for missing system hypot */ #ifndef HAVE_HYPOT #define hypot gsl_hypot #endif
The application source files can then use the include command
#include <config.h> to substitute
gsl_hypot for each
occurrence of
hypot when
hypot is not available.
Go to the first, previous, next, last section, table of contents. | http://www.gnu.org/software/gsl/manual/gsl-ref_44.html | CC-MAIN-2014-52 | refinedweb | 572 | 65.22 |
One of the things that I have been casually thinking about over the last several months is XML and Jscript, especially in the context of WebServices.
JScripts and writing our the likes of XML is just an undertaking that is tedious and time consuming, especially when you compare it to programming languages such as C#.
For those of you that are familiar with the .Net framework and have mucked around with parsing XML you’ve probably come across the System.XML.Serialization assembly. It is a very handy way to allow you to convert the properties of an object to XML and then be able to read that XML in to an object.
This means with larger projects you don’t need to write a heap of custom code to read and write the data, you can just create some objects and then dump them in a single command. It will even handle the nesting of objects and their properties, so you can have a list of values and it will parse out the collect.
This was rather challenging trying to figure out how to use the attributes of the XmlSerializer to control the output. The attributes allow you to control the names of the elements (they default to the property name) and if a property is included or ignored. For examples of the attributes you can use your favourite search engine ()
We will populate the object with some data, create a TextWriter class, serialise our class writing it out to a file. Then we shall read the file back in to illustrate deserialising the xml file before we output some of the retrieved data.
Things of note in our object it has XMLClass which has a couple of properties.
public class XMLClass { public var Data : String; public XmlElement(ElementName="Test") var Data2 : String; public XmlElement("List") var ListData : System.Collections.ArrayList; }
Data property will create an element called “Data” in our output.
Data2 will be renamed to “Test” in our output through using this statement: XmlElement(ElementName=”Test”)
ListData will be renamed “List” and will have the contents
Anyways, enough jibber-jabber, code and xml below – code is commented, if in doubt experiment 🙂 Make small changes. Take careful note that the default output path is to D: drive.
import System; import System.Windows; import System.Windows.Controls; import MForms; import System.Xml; import System.Xml.Serialization; import System.Xml.Serialization.XmlArrayAttribute; import System.IO; package MForms.JScript { class XMLTests { // we are going to write our test out to D:\XMLTest.xml var gstrPath : String = "d:\\XMLTest.xml"; public function Init(element: Object, args: Object, controller : Object, debug : Object) { // var xmcWriteClass : XMLClass = new XMLClass(); // populate the string with "Hello World" xmcWriteClass.Data = "Hello World!"; // populate the second string xmcWriteClass.Data2 = "This is a new beginning"; // this is a collection of objects - to see how this looks in XML xmcWriteClass.ListData = new System.Collections.ArrayList(); var xecExample : XMLExampleClass2 = new XMLExampleClass2(); // populate the collection objects first object with some data xecExample.ClassData2 = "Some Class Data"; // add the object to the collection xmcWriteClass.ListData.Add(xecExample); // here we need to define the types of objects // so the serialiser doesn't throw an exception // XMLClass is defined against the serialiser directly var tp : Type[] = new Type[1]; // typeof doesn't seem to work, so I create an object of the // class we want to add and then do a GetType() tp[0] = (new XMLExampleClass2).GetType(); // create a streamwriter to write out our data var twWriter : TextWriter = new StreamWriter(gstrPath); // create the XmlSerializer - this will take our object and convert it // in to XML. We get the type of our main class and add the types of any // other classes var xmsSerial : XmlSerializer = new XmlSerializer(xmcWriteClass.GetType(), tp); // Serialise to XML to the text writer xmsSerial.Serialize(twWriter, xmcWriteClass); // close the writer twWriter.Close(); // now lets read the file, create a reader var trReader : TextReader = new StreamReader(gstrPath); // deserialize the xml from the reader in to an object var xmcReadClass : XMLClass = xmsSerial.Deserialize(trReader); // close the reader trReader.Close(); // output some of the data that we read debug.WriteLine("What we read from the file: " + xmcReadClass.Data + " & " + xmcReadClass.Data2); } } public class XMLClass { public var Data : String; public XmlElement(ElementName="Test") var Data2 : String; public XmlElement("List") var ListData : System.Collections.ArrayList; } public class XMLExampleClass2 { public XmlElement(ElementName="TestX") var ClassData2 : String; } }
XML Output
<?xml version="1.0" encoding="utf-8"?> <XMLClass xmlns: <Data>Hello World!</Data> <Test>This is a new beginning</Test> <List xsi: <TestX>Some Class Data</TestX> </List> </XMLClass>
Enjoy!
Hi Scott. Thanks for the example. I have some more examples in this post as well:
Ah, my google-fu is acting up, I should have looked harder 🙂 | https://potatoit.kiwi/2013/01/28/jscripts-and-xml/ | CC-MAIN-2017-39 | refinedweb | 786 | 56.15 |
Is AT&T Building the Ultimate Walled Garden?
samzenpus posted more than 2 years ago | from the you-can-checkout-any-time-you-like-but-you-can-never-leave dept.
.'"
How is this different? (0, Troll)
DCTech (2545590) | more than 2 years ago | (#38669328)
How is this different
How is this different from when Google uses open source? There's a great article about the supposed openness by Google here [seobook.com]
Some good points from it:
Where Google is losing you can count on them pushing the open label in order to build momentum & destroy the asymmetrical information advantages of existing market leaders. But where Google leads non-transparency is the norm.
-! [thinkoutsidein.com]
- Android is open but internal Google emails revealed that carriers were getting wise to Google using compatibility as a club.
-.
A Self-serving Bias You Can Count On
When Google enters a market it might buy out a competitor, buy out a supplier, bundle, use predatory pricing [brianshall.com], grant themselves superior search placement, adjust the relevancy algorithms and/or editorial guidelines, violate IP [techcrunch.com], scrape 3rd party content, work with sketchy advertisers [fool.com] & publishers to undermine competing business models, or any combination of the above.
They are rarely transparent with their interests when they enter a market. Almost everything is labeled as "a beta" and "just a test." They promise to "act appropriately" [bloomberg.com] & you may not be aware of the steamroller until you are under it.
Google can bundle themselves into markets [thenextweb.com], but when others do the same it is a big no no [wsj.com]:
A Google spokesman said "applications that are installed without clear disclosure, that are hard to remove and that modify users' experiences in unexpected ways are bad for users and the Web as a whole."
Google's founding research highlighted how bad ad-driven search engines were [seobook.com] & then Google's core revenue engine of paid search was built on their violation of Overture's patent [cnet.com]. They keep buying swaths of patents [seobythesea.com] to protect against their other violations [blogspot.com]
.
The business model of "violate & then buy protection" has helped lead to a protection-racket styled marketplace in patents that makes the risk of innovation for smaller players so expensive that it drives them under.
Their "quality content" thesis could have come across as being honest if they weren't still pre-paying Demand Media to upload "content" to YouTube [seobook.com].
I suggest you read the whole article. It tells you about the very dark side of Google.
Re:How is this different? (5, Insightful)
leoplan2 (2064520) | more than 2 years ago | (#38669370)
As if all other companies were honest, and they don't have a very dark side. Troll harder
Re:How is this different? (-1)
Anonymous Coward | more than 2 years ago | (#38669390)
Re:How is this different? (1)
Anonymous Coward | more than 2 years ago | (#38672554)), and B) being very insecure about himself and so feeling an irrational need to defend everything, even when the attacks were only imaginary. (Not at all usual for geeks, but still a sad sad failure.)
I guess you were too caught up in your own irrational emotions, but: You only made yourself look bad with that comment. So bad in fact, that if you were my horse, I'd have to shoot you now.
Correction:s/^No/^So/; s/ usual/ UNusual/ (0)
Anonymous Coward | more than 2 years ago | (#38672568)
#include <MOARcoffee>
s/^No/^So/; s/ usual/ UNusual/
Re:How is this different? (1, Insightful)
Anthony Mouse (1927662) | more than 2 years ago | (#38669462)
Go away, troll. Nobody is going to read a post that long full of one-sided astroturf, so all you're succeeding in doing is inhibiting people from having a discussion about the actual subject of the article.
Re:How is this different? (0)
Fluffeh (1273756) | more than 2 years ago | (#38669552)
Hmmmm, very high userID, massive first post with many links and presenting a rather one sided argument, fresh smell of grass clippings in the air.
I think I smell some astroturfing coming from a shill.
Re:How is this different? (1)
mcgrew (92797) | more than 2 years ago | (#38673682) will be no more walled gardens? Does it affect their smartphone service only, or does it include their home internet delivery?
TFS is short on info, and in the past I've found IT World to be pretty info-free as well, so I'll thank anyone who can give me a detal or two, especially since AT&T is my ISP.
Re:How is this different? (1)
Fluffeh (1273756) | more than 2 years ago | (#38678882) it difficult to imagine how they might go to their manager and show what it is that they have accomplished through the week. Surely "Hey, I made all these good points in an online forum..." doesn't cut it?
Re:How is this different? (1)
mcgrew (92797) | more than 2 years ago | (#38691464)
My karma is, too, so there's no reason to worry about it. As to the shills, big bureaucracies like a huge corporation always have at least a few arrogant dummies in management who thing they're intelligent. "50 posts today? Attaboy!!"
Re:How is this different? (1)
erick99 (743982) | more than 2 years ago | (#38676538)
Re:How is this different? (1)
Fluffeh (1273756) | more than 2 years ago | (#38682466)
Well, my ID is almost double yours, but I (and likely a lot more folks) wouldn't consider myself a newcomer here
:)
Re:How is this different? (-1)
Anonymous Coward | more than 2 years ago | (#38670704)
"Maybe you need a real man to open that?" cooed Emily as I struggled to open the twist off cap of my beer bottle.
Blushing at her derogatory tone I hissed back "It's not my fault, it's these stupid nails you made me wear!" Frankly I was mighty pissed at Emily, the girl I had fantasized so vividly about only for ages until, two days ago she invited me the party.
"Let's see who can help a pathetic little sissy open the big bad bottle of beer shall we?" although an amazingly pretty girl, Emily had a hitherto unseen mean streak and was delighting in my suffering beside her, dressed in way too frilly party attire comprising of a frilly satin blouse in a pale pink color, straining around my unnaturally large bust, a petticoat fluffed pink skirt complete with a large pink bow around my waist, a , white microfiber tights, and pink Mary Jane's atop a moderate three inch heel.
Blushing a darker pink than the blush Emily had applied to my freshly denuded face, I struggled against the one inch nail extensions, the same obligatory frosted pink as my seemingly enlarged lips, but my unfamiliarity with the dainty talons and multiple rings adorning my pretty fingers made it nigh on impossible for me to get a good grip on the reluctant bottle top. The myriad of silver, white and pink bangles jangled merrily on my wrists as I struggled in vain, not really paying Emily any attention until she barked at me.
"Sissy!" Sissy? Since when had I become Sissy? Resigning myself to having to find a bottle opener, I gave Emily my full attention and was startled to see her standing by a hulking great giant of a man.
"Sissy" she continued seeing they now had my undivided attention, "Sissy, this Winston, he can open your beer bottle for you."
Stunned in to silence by the sheer size of the man now towering over me, even atop my patent leather heels, I dumbly held the Budweiser beer bottle out to him. In a single fluid motion Winston reached out a massive black hand, more than covering the whole beer bottle, save the top, which he effortlessly twisted free before taking a long drink from it before handing it back down to me.
"Here, let me" smiled Emily, taking the bottle she poured it into a glass, plopped a long curly pink straw in it and handed it back to me. "Here you go Sissy, just the way you like it. Now remember, only two beers, you know how silly you get when you drink!"
Still gaping foolishly up at the spectacle of the man giant Winston I paid her no heed as I unthinkingly slipped the childish crazy straw between my painted lips and sucked some deliciously cold beer.
"See Winston, I told you she was crazy for you!" whispered the evil architect behind the conspiracy that now had me standing in a room full of strangers dressed head to foot in the type of attire fully fitting the wretched name Emily insisted on calling me. For it was the promise of possible intimacy, if not actual sexual congress with the gorgeous Ms. Dempsey that had persuaded me to don the ridiculously feminine attire I now sported to the evenings (alleged) costume party.
"Sissy, shut your mouth, you're staring at Winston like a Bitch in heat..." turning back to Winston she added' not that isn't a somewhat accurate description, you should hear how she's been gabbing on about that 'gorgeous specimen of black manhood' whenever you're close!"
"Emily!" I gasped at her blatant lies "that's not...:
"I know, I know, I promised I wouldn't tell anyone Sissy," she talked over me, ignoring my feeble protests, "but come on, it's no big secret. After all, if not for Winston, who else did you get all gussied up like a proper little black cock worshipping sissy for?"
Beer shot up and out of my nose, incapacitating me to shoot down the horrendous lies she was using to throw me under a very large, black and undoubtedly masculine bus!
For here was I, a one hundred percent hetero-sexual male, sure not the biggest or most confident of the species, but none the less, someone who's desire to get in to Emily pretty pink panties had, alas succeeded in ways I never envisioned or hoped for. For now here I was standing here, being referred to by the terribly derogatory name 'sissy' by the woman who, up until about thirty minutes ago was to be the forever love of my life, but is now trying to suggest I have been heartily lusting after a six foot eight, three hundred pound negro named Winston, while I stand there feeling pathetically inadequate dressed as I am in a form fitting of Emily's pretty pink panties!
Thoroughly enjoying herself, Emily continued to play the role of concerned friend as she slapped me heartily on my back, pushing me into Winston's chest as she commented "There, there Sissy, there's no reason to get so excited, as you can see Winston's still here, you lucky little boy..."
Tripping atop the unfamiliar heels, I stumble and foolishly, instinctively, make more effort to save my beer than my balance, and so bump into the wall that is Winston, my silicone falsies buffering some of the force of my hitting an immovable black silk shirt clad barrier.
"Easy there little lady" comes a voice as dark and rich as molten dark chocolate and impossibly thick arms effortlessly catch me and return me to my state of precarious balance. Looking up through the hideous thickly mascaraed false lashes, my baby blues peeking out through way too much eye shadow, liner and mascara, I stammer a diminutive "Thank you... Winston" before Emily starts back in.
"Go on then Sissy, kiss him, kiss those 'big thick lips' you were gushing about to me mere minutes ago"
"Emily" I hiss, sounding a good deal more feminine than I would want, even to my jangling earring attenuated ears.
"What?" she laughs, "don't go criticizing your best friend for trying to get you what you're too much of a little girly boi to go get by yourself!" As I stand there, furiously self-conscious in my pretty little pink party dress.
"But I... I mean you..." I stammer pathetically.
Turning to Winston, who unnoticed by me in my confusion, still has a protective hand on my shoulder, Emily continues, "You wouldn't believe what she was saying about you earlier Winston. Telling me how her little clitty was getting all hard just thinking about being forced in to your servitude! I mean I've known sissy for years, even before she 'came out' and declared she was a little girl trapped in an inadequate little boy's body, but in all this time I have never, and I mean never, heard her so infatuated with one man, and his..." here she acted all coy, and cast a furtive glance down towards Winston's dark purple pants clad crotch, which, as I inadvertently followed the direction of Emily's gaze, noticed appeared to be in proportion with the rest of the man; BIG!
I caught myself blushing furiously as Winston noticed the direction of my gaze and smiled knowingly, as his paw slipped from my shoulder to my waist, pulling me closer.
Smiling at how well her evil plan is progressing, Emily continued, "Oh yes, little Sissy has been going on in great length, if you'll pardon the pun!" she steals me a wantonly wicked, but none too subtle glance here, noting how Winston has his great hand upon my pink bow encircled waist and seems bent on pulling me as close to him as possible. "Yes, great length on how she just dreams about being forcibly made to serve a great hulking man like you, someone to bend her own pathetically inadequate will to theirs, someone to subjugate her, humiliate her like every little sissy boy dreams of, a REAL man to force her become the little sissy slave she's always longed to be. So tell me Winston, are you that man, will you take our little sissy boi here and make her yours, enslave her with your big black cock?"
"Emily!" I was speechless, aghast, floored by the lies she was telling this man. It was his words that fully drove home the fact of how much trouble I was truly in.
"Yes Miss, I am that man" He rumbled.
What" I looked up at him in amazement, and was totally unprepared by him pulling me fully to him as he lowered his mouth over mine. As his hot tongue forced its way between my pink lips and on in to the confines of my mouth, I realized how truly powerless I was against this mountain of a man, for he had to bend a good ways down to reach me, even elevated as I was atop the heels Emily had tricked me into wearing.
As I struggled in vain, beating my prettily manicured fists against his great chest, my bracelets making more noise than my voice was through his thick lips sealing my own, Emily bent in close and whispered in my ear "Have fun little sissy, I will leave you some condoms, to go with the lubricant and spare pair of panties already in your purse, but I believe your new boyfriend prefers riding his bitches bare back - if you know what I mean?! And I am afraid there's no money, credit cards or keys in your purse, so be good to Winston, he's the only ride you have... both home and in bed tonight! I'm off now, my work here is done, but I have so much more to do back at your flat. Have fun, I'll see you later to hear all the gory details!"
Out of the corner of my eye I saw her slip a packet of condoms in to my little pink clutch all purse, wink knowingly at the two of us as Winston, pausing to nod his thanks to Emily, did his best to devour me whole, his hands now taking deliberate liberties with my daintily presented body as I felt the hem of dress being worked up over my panty clad ass before his rough hands slipped under the elastic below my right buttock.
Breaking off his oral rape of my mouth for a moment Winston sighed "Damn it girl, you sure know how to get you man hot!"
Taking this opportunity to explain Emily's perfidy, I gasped "Listen Winston, Emily's a liar I
..."
"Shut it bitch, go get us some drinks, I'll have a cold beer, get yourself something girly and alcoholic." He snapped, cutting me off.
"But listen
..." I tried again.
"No" he barked "you listen to me you stupid cunt." My face paled at the violence of his words "I know exactly what kind a little sissy tease you are, you play me all doe eyes from across the room but when a brother chooses to act, you back off with all your hoity-toity attitude, well listen here, and listen good Sissy, you made your bed and our damn well gonna lie in it. Lie in it, fuck in it and any damn thing else I chose in it, is that clear?
But I had to make him see t was Emily who had set me up, this wasn't me at all, I hadn't been making eyes at him at all, I didn't even notice him, well OK that wasn't true, it was hard not to notice him, he was so damn big! "But you have to..."
"Don't you listen bitch, I don't have to do a damn thing you do! Now get your faggot white ass over to the bar and get us our drinks. I'll say this only one time more; I'll have a cold one, but you get yourself something suitably sissy and alcoholic, make it a Sex on the Beach or something similarly girly, something befitting a cock sucking little sissy, 'cause get me right here, that's exactly what you are. Now you got that, or do I need make myself any clearer?" the undisguised violence smoldering behind his brown eyes persuaded me that now was not the time to broker further argument, so like a good little sissy I sashayed over to the bar and ordered him a Budweiser and a Sex on the Beach for myself, having no clue as to what it contained, never having been a drinker. I received several amused glances, dressed as I was yet still pretty obviously male my demeanor and voice.
Teetering atop the unfamiliar heels I turned to find Winston had moved and was now occupying a good two thirds of a two-seater love chair. Oh great I thought, as I headed over, realizing I would be expected to squeeze into the vacant third beside him.
"And another thing" he began as I handed him his beer, not even bothering to thank me, "I think you should talk more befitting your new position in life, so start lisping."
"Lisping, oh come on..." I never got to finish the sentence as his big hand shot up and grabbed me by the throat.
"Yes lisping. You got a problem with that sweetcakes? And another thing, you better quit your questioning my every command, you got that too? " not even pausing to let me answer as I stood there dumbly before him clutching my tall bright pink drink, complete with a large white orchid and slice of orange in a highball glass, he pressed on "the next time you question me, no matter where we be, I'm gonna haul you down over my lap, pull up your pretty little skirt and give your pantied ass one hell of a whupping. Is that clear?
Pausing only long enough to take a bracing sip of my cocktail, actually enjoying its peach flavored sweetness, I obediently answer "Yes... Sir." such is the assault upon my senses, I unwittingly add the respectful acknowledgment of his higher status over my submissive self.
He grins knowingly at my unconscious submission to his dominance, "That's better, but try it again with the lips this time, and I prefer to Master as my title, but good girl for adding the Sir, now try it again and then get your pretty ass done here besides me."
Once more my cheeks burn their recently all too familiar bright shade of pink, nicely complimenting my pink lip stick and matching eye shadow (Emily, while still feigning interest in me as a male, had gone to great lengths to convince me that all pink cosmetics would better serve to hide my true gender, now I realized it was just yet another ruse to make me appear as big a sissy as possible)
Biting back my natural impulse to answer him back, I passively responded "Yesss Masster, but I have to pay for our drinksss, Emily didn't leave me any money."
"Well that's your problem Sissy, not mine. Go see the bar man and see what you can do to work off the debt, tell him I'll vouch for you. And make sure you lisp, and in future always refer to yourself in the third party as Sissy. Got that?"
Fearing exactly what such a confession to the barman will entail, I once again lisp out my concession "Yes, Master, I... Sissy understands." Once more I sway my way over to the bar, already blushing about what I have to say. I try to position myself at a quieter corner of the bar, but just as the barman notices me, three teenage girls crowd in to the space I've secured. "You got my money?"
"Burning a most vivid shade of crimson I lisp my answer as instructed "No, I'm afraid Sissy doesn't have any money, but... Master Winston says to tell you he can vouch for this Sissy."
"Christ, what a pathetic freak" laughs one of the girls beside me who, despite my best efforts had no trouble over hearing my declaration. Her friends agree and epithets such as 'fag', 'freak' and 'pussy' rain upon me as the barman considers his options.
"Tell you what" he finally opines as I struggle to stop the girls pulling up the hem of my dress to reveal my true gender. "Come back here after ten and you can pay me then."
His emphasis of the word 'pay' leave little doubt it will not be a cash transaction. Having no option other than to agree quickly, so as to prevent the three bitches further degrading me at the bar, I quickly answer "Thank you Sir, Sissy will pay you at 10:00."
Batting off the hands plucking at my hem and neckline and ignoring their outrageous taunts, I quickly return to Winston, temporarily grateful for his protection. He smiles, having witnessed the whole spectacle he inflicted upon me, pats the seat next to his broad thigh and says "Sit your pretty little ass down here Sissy and I'll tell you how it's going to be from here on."
Grimacing at how quickly my life has spiraled out of control, I turn and sit down next to him. Due to his size and weight, the too small seat and the fact I struggle to keep my fruity cocktail from spilling all over us, I cannot help but slide right up against him, innocently giving the impression to anyone watching, and following the debacle at the bar there are quite a few watching with amusement the display I unintentionally provide, as my legs unconsciously slide open, providing all and sundry an uninhibited view up my dress. The tight restriction of Emily's too small panties and tights serve to pin my manhood completely out of sight, completing the appearance of femininity to those enjoying the spectacle I am providing them.
Placing one enormous arm around my shoulder, his palm resting upon where my left breast resides under the large silicone falsie he is now gently squeezing, "OK, your new number one rule is this; give me your hand."
Fearing the worst, I gingerly hold out my right hand to him. He takes it, surprisingly gently, but then steers it down to his left thigh where he forces it down upon some sort of thick tube seemingly strapped to his thigh. It is only when I notice the heat it is generates does it dawn on me that it is not a tube at all, but his enormous penis. I balk and try to pull away.
"Oh no you don't Bitch, that there's your new best friend, your new reason for living, the main reason you get up every day. For from now on you is a total bitch slave to my beautiful black cock. Let me hear you say it bitch, tell me what the single most important thing in your whole wide sissy world is, and tell me proper."
While issuing this shocking edict, he has been working my hand up and down the considerable length of his monstrous trouser snake. Even with the hideous acrylic nails, painted the obligatory vivid pink of course, my hand can barely encompass its girth and it has to be a good six to eight inches long flaccid. Oh my God, what has Emily got me in to?
Pushing back such concerns for the moment, I dutifully swallow my pride and recite, complete with compulsory lisp and syntax "Thank you Master, the most important thing in this sissy's whole wide world is your big black cock."
"Good, but louder."
Again I repeat "Thank you Master, the most important thing in this sissy's whole wide world is your big black cock."
"Louder!"
"Thank you Master, the most important thing in this sissy's whole wide world is your big black cock."
"Again!"
"Thank you Master, the most important thing in this sissy's whole wide world is your big black cock." By now the majority of the people in our immediate area are staring at me open mouthed or just plain openly laughing at my seemingly willing subjugation and servitude to this giant of a man.
"Good girl, now use both hands."
"What? Oh, yes at once, sorry master." I have to turn forty-five degrees to accommodate this last instruction, causing my short skirt to slip yet further up my white clad thigh and me to slid yet closer to my aggressor. With both hands now employed running up and down his growing length, I am powerless to prevent my sliding up and against him, my angled body molding against his while my upturned face presses in to his chest and neck. 'My Gog' I think, it must look like I am totally feasting on him!
I do my best to filter out the ribald heckling from the three girls at the bar, now backs turned to the bar so as to better enjoy the spectacle I am providing, as I commence to massage his manhood with both my pink taloned hands
Ignoring my obvious discomfort as his disgusting penis stirs further below my reluctant ministrations he continues "So before we get started on the `new you' Sissy, tell me about the old you, and make damned certain you follow the rules we've established so far. Now answer me these questions, and don't even think `bout lying to me you hear?"
"Yes Master"
"So, you ever been with a man before Sissy?"
Blushing still deeper red, I answer in the negative.
"Oh I see, just unrealized fantasies, well that's cool." A single hand, palm held outwards, silences my objections. "When you're not out trawling for black cock, what do you do Sissy?"
I stammer "I'm a, I mean Sissy is a programmer, a computer programmer..."
"I know what a fucking programmer is" he growls "Which company do you work for?"
"Sissy is self-employed Master"
"Oh, so you work from home then?"
"Yes Master, Sissy has a small office in her... in Sissy's condo..." Did I really just refer to myself as a `her?!
"Perfect, I see young Emily chose well..."
With a sickening lurch in the pit of my stomach I realized I had been truly set up, that Emily, and quite likely Winston too, had planned my demise well in advance, that I was merely a pawn, albeit an unknowing one, in the schemes.
Ignoring my increased discomfort Winston pressed with this unending
,list
of questions, "Do you have any family in the area?" No. "Had I ever been
with a black man or woman before?" No. "Oh, so you're a racist then?" No,
I... "What was the biggest cock I'd sucked?" But I never... "Did I like
anal?" No! "We'll see about that. How big was my clitty" seeing my look of
incomprehension he added "Your cockette, that pathetic thing you have
between your legs?"
When I hesitated to, partly through shame of my tiny size I will admit, he blew up, grabbed my wrist and before I could voice an objection had hauled me in to his lap. Thankfully sitting in it and not across it prior to a public spanking as I'd feared. My relief was short lived as he unceremoniously thrust my legs apart, thrust his hand up between my splayed thighs and proceeded to pull down my tights and panties in the front revealing my freshly denuded crotch (thanks again Emily!) to the flabbergasted stares of the partiers around us.
My mouth was formed in a perfect 'O' as my cheeks flared a brilliant red as he commenced to free my shamed cock and balls from their previous position pinned tightly beneath me. "Oh my, I can see why you feel you're more female than male Sissy, these really are pathetic!"
My ready loaded objections that this had gone far enough were lost at the sting of this wretched comment as, taking my 'manhood' between a thick finger and thumb, he pulled painfully upon it "I think we might even consider gender realignment surgery, you've got so little too lose poor lass. No wonder you're so frustrated, this thing's tiny!"
I was helpless. I could only sit there, leaning back off balance into the chest of this monster, legs akimbo, to show all and sundry my pathetically small genitalia as I was all too aware of his monstrous manhood as it did it's level best to lift my physically from his lap. Locking my feet beneath his huge calves, Winston moved his hands under my blouse, pulling it free from the waist of my skirt, and proceeded a most public exploration of my artificially bolstered chest while I was powerless to do anything about these ever increasing liberties.
"We'll have to see about getting these plastic titties replaced with some real ones" he cooed before locking his lips over my unprotected neck and sucking hard enough to draw the blood to the surface in a vivid hickey. Releasing his bite before selecting another spot on my pale skin, he cooed "Yes. I like some big ol' silicone jus on my bitches, with bog ol' pointy nipples that'll take your eye out if you not careful. How you like that Sugar, how you like some big ol' titties that make ALL the men stare at you with hunger?"
I could think of few things more unpleasant, but could physically sense the challenge he'd left hanging, just daring me to answer in the negative. Fighting back a sob that I knew would only anger him, I lisped my answer "Yes please Master, Sissy would love some big titties to make the man stare at her..."
"Good girl" he cooed, before defiling yet another spot on my neckline. "Maybe we get you a nice ol' fat ass to go with it, I loves my bitches to pack a little junk in the trunk you know! Get them hips o' yours filled out a bit too, I know a great Doctor down in Tijuana who do all this work, and get them lips padded out a little better for sucking on my cock, he's cheap, fast and always available since he lost his license to work Stateside. Oh yes, I see us spending a few weeks with the good Doctor Wu, het you all tricked out just the way I like `me."
While one hand continued a most open exploration of my chest, my red bra clearly visible to any not too disgusted by the display we were providing, his other began an equally indiscreet manipulation of my groin under my short skirt which was stretched around my splayed hips so as to provide little or no cover. This time his ministrations were gentle as he massaged my bared genitalia, all the while alternately feeding upon my pale neck, asking vile questions, or the worst, muttering visions of my future under his `protection.'
His comment, "Once Emily has finished with your apartment, not even you will recognize it" scared me silly, how much planning had gone into my once seemingly innocent party date with Miss Emily? Sure, I though it a really mean trick to convince me to dress up like a little girl so we could head on out to a fictitious fancy costume party, but now I was coming to realize that was just the tip of the iceberg. As Winston told me how, even as we sat there and he slowly stroked my poor naked cockette so that it had no alternative but to inevitably respond to his ministrations, Emily was even now arranging for the disposal of my every male garment to some thrift shop I'd never have hear of, and how, after redecorating my rooms in the frilliest, prettiest, pinks, yellows and powder blues, my closet drawers were being restocked with an assorted combination of garish sissy frills and white trash hooker attire. How my driving license, passport and even rental agreement for my apartment was being reissued in my new identity; that of Sissy Bleaujorb!
As he went on to describe the hideous regimen of female hormones and other drugs that would become my daily routine, of continued hypnosis therapy to bury hidden commands and mannerisms deep within my subconscious, ensuring I would unwittingly act, move and behave as the wanton cock serving sissy he wanted at all times, of the painful surgeries I had ahead to mold me in to this sickos vision of the perfect sexual slave. While all this was being outlined to me, he continued to manipulate me to my tiny state of arousal.
"See Sissy, we knew this is what you deep down sought, the lifestyle that you secretly, maybe even unconsciously desired. Oh you might deny it now, but you'll see, this is what you really need in your meaningless life, a strong man to take command of your pathetic life, to make you his, to make you serve what you've always really wanted, to serve a Masterful Big Black Cock" and with that, despite the many looks of scorn and derision I was receiving spread wide upon his lap for all to see and ridicule, I came, my tiny cock twitching furiously as it shot my sallow seed into my panties and tights.
Maybe he was right...
Re:How is this different? (0)
Anonymous Coward | more than 2 years ago | (#38671212)
Y'know, it wasn't the story that got me horny, it was the poster who posted this story as a sick joke that got me horny. C'mere bitch; ever had some black cock before? I'll fuck you across the internet and I know you'll like it.
Re:How is this different? (1)
Maow (620678) | more than 2 years ago | (#38671234)
Looks like InsightIn140Bytes is back after the holiday break.
Got a new Slashdot ID for xmas?
Maybe this post [slashdot.org] made InsightIn140Bytes go away?
Re:How is this different? (0)
Anonymous Coward | more than 2 years ago | (#38672676)
I've been keeping track.
;) [slashdot.org] [slashdot.org] [slashdot.org] [slashdot.org] [slashdot.org] [slashdot.org]
Though, I think I'm missing a few of the accounts.
Re:How is this different? (1)
heinousjay (683506) | more than 2 years ago | (#38673516).
Shai Hulud wills it! (5, Funny)
Anonymous Coward | more than 2 years ago | (#38669372)
The data must flow. He who controls the stack, controls the universe.
Re:Shai Hulud wills it! (1)
khallow (566160) | more than 2 years ago | (#38669454)
Re:Shai Hulud wills it! (1)
kirbini (147112) | more than 2 years ago | (#38675752)
IN: Battle Cat, Teela, Man-at-Arms and He-man.
Out: Skeletor, Panthor, Mer-man, Evil-Lyn, TrapJaw
Re:Shai Hulud wills it! (4, Funny)
ColdWetDog (752185) | more than 2 years ago | (#38669456)
The data must flow. He who controls the stack, controls the universe.
"You can't stop the signal, Mal. Everything goes somewhere, and I go everywhere. "
Re:Shai Hulud wills it! (2)
postbigbang (761081) | more than 2 years ago | (#38669624)
For the record, AT&T doesn't control OpenStack, and Rackspace doesn't either--- although interestingly, it's situated *right in the middle of old Southwest Bell* territory.Hmmmmmmmmmm.
Re:Shai Hulud wills it! (0)
Anonymous Coward | more than 2 years ago | (#38669550)
To control your own universe, use CloudI!
Re:Shai Hulud wills it! (0)
Anonymous Coward | more than 2 years ago | (#38669774)
Interesting link. Still a bit confused though. It sounds good and open source is always welcome. What does it do? A new protocol to replace http?
Re:Shai Hulud wills it! (0)
Anonymous Coward | more than 2 years ago | (#38670322)
No, that would be silly. CloudI is a type of cloud that you can run both privately and publicly, so you don't need to depend on a large cloud (i.e., virtualization) service provider. Instead you have less overhead within a language agnostic, fault-tolerant application server, providing scalability across the services you declare (i.e., SOA).
Re:Shai Hulud wills it! (1)
icebraining (1313345) | more than 2 years ago | (#38671998)
To control your universe, you need to have your own pipes. This is why AT&T will achieve what Google and Apple never could.
Re:Shai Hulud wills it! (0)
Anonymous Coward | more than 2 years ago | (#38677074)
Re:Shai Hulud wills it! (1)
icebraining (1313345) | more than 2 years ago | (#38681016)
Yeah, as long as you only have one office and no employees working from home or the field. That leaves a lot of companies out.
Re:Shai Hulud wills it! (5, Interesting)
gl4ss (559668) | more than 2 years ago | (#38670638):Shai Hulud wills it! (2)
NeutronCowboy (896098) | more than 2 years ago | (#38671332) knowing how much the offerings suck they're consuming.
I'm wondering if Apple or Google will buy one of the smaller telcos to combat this. If they don't - they'll be toast.
Kinda funny that AOL's business model is making a comeback, killing off the very thing that killed off AOL.
Re:Shai Hulud wills it! (0)
Anonymous Coward | more than 2 years ago | (#38672762)
Kinda funny that AOL's business model is making a comeback, killing off the very thing that killed off AOL.
This is exactly what they are trying to do. Have to love regression.
Re:Shai Hulud wills it! (1)
mcgrew (92797) | more than 2 years ago | (#38677648) different; technological advances made it succeed the second time around.
I hope you're wrong, I fear you may be right.
Re:Shai Hulud wills it! (1)
gl4ss (559668) | more than 2 years ago | (#38686870) (5, Interesting)
Anonymous Coward | more than 2 years ago | (#38669402):Screw AT&T, I could care less what they do (3, Insightful)
Anonymous Coward | more than 2 years ago | (#38669696):Screw AT&T, I could care less what they do (2)
Anonymous Coward | more than 2 years ago | (#38669942)
You can use an iPhone in any country outside of North America without a data plan. The data plan is added because "fuck you we're the phone company".
Re:Screw AT&T, I could care less what they do (-1)
Anonymous Coward | more than 2 years ago | (#38670346)
"Now you have the audacity to blame AT&T for your blatant stupidity."
Actually, your lack of knowledge has caused you to think I am stupid when the truth is that it is
you who are both stupid, ill-informed, and a smart-mouthed cunt.
As the poster below points out, AT&T screws customers in a way that doesn't happen
outside of the US.
By the way, if you talk in person like you talked in your post, you'd better have dental insurance
because you are going to need it some day.
Re:Screw AT&T, I could care less what they do (0)
Anonymous Coward | more than 2 years ago | (#38673802)
Well, At least you're arrogant enough to be blind to your own stupidity. Take that as some sort of comfort.
Re:Screw AT&T, I could care less what they do (3, Interesting)
Rich0 (548339) | more than 2 years ago | (#38670452):Screw AT&T, I could care less what they do (2)
subreality (157447) | more than 2 years ago | (#38671300)
My other half has an old iPhone on TMobile, no data plan. It works just fine. There's no visual voice mail but it knows the number to call to retrieve it the old way.
Re:Screw AT&T, I could care less what they do (1)
oPless (63249) | more than 2 years ago | (#38672050)
I think in the UK only O2 has 'visual voicemail'
Don't want it, don't need it.
Why the hell can't I edit/override my own APN data on the iPhone?
Re:Buy Unlocked Smartphones/Android In Factory Box (-1)
Anonymous Coward | more than 2 years ago | (#38672892).
Buy Unlocked Smartphones/Android In Factory Box.
Albert-Techie(UK)"Now on Sales"Smartphones/Android Phones...We export internationally and
Offer Promo to all interested International buyers; We make delivery right to your Doorstep
at affordable Rates including Customs Duties Charges.
See Below Details For Price Listing:
iPhone 4s:
16GB,,,$510
32GB,,,$620
64GB,,,$725: Albert_Tech@techie.com
Re:Screw AT&T, I could care less what they do (1)
EvilBudMan (588716) | more than 2 years ago | (#38676206):Screw AT&T, I could care less what they do (1)
TemporalBeing (803363) | more than 2 years ago | (#38678996)
AT&T's contract with Apple for getting the iPhone first was that they had to require a data plan with it, and a very specific data plan at that. It's not public about whether any other phone manufacturer did that too, but not likely. More likely than not, AT&T just used it as a way to move all smart phones to requiring data plans, which they do - anything with a keyboard or touch screen requires a data plan of some kind; if just a keyboard then a very cheap text-only plan; but any touch screen requires a full-on data plan.
That's not to say you can't skirt it. I have no data services enabled period on my plan for any of my phones. Yet I have an Nexus One myself (everyone else has a feature phone at the moment); but no data plan for even the Nexus One. AT&T knows about the Nexus One; but again, they don't see any data traffic (I removed the settings, and disabled it so it only uses Wifi for data).
What I did with my N1 is probably harder to do with an iPhone; but the OP shouldn't have been too surprised. Next time they should buy an Android phone that way instead.
Re:Screw AT&T, I could care less what they do (1)
Rich0 (548339) | more than 2 years ago | (#38684532):Screw AT&T, I could care less what they do (1)
TemporalBeing (803363) | more than 2 years ago | (#38685214) iPhone is there and to keep from sanctions they just go ahead and start charging what is required per the contract.
I do agree that they should not be allowed to do that; but until someone takes them to court over it and wins without settling, they'll probably continue to do so.
Re:Screw AT&T, I could care less what they do (0)
Anonymous Coward | more than 2 years ago | (#38671200)
You can save money if you use a non-AT&T iPhone. As long as the IMEI is not in AT&T's database, they won't charge you the ridiculous iphone tax. You can tell if it's in their database or not by logging into your online account. It will show if the IMEI is identified, or not.
If your IMEI is not identified, and you tell the phone support folks that you have some old piece of junk phone, they'll offer you unlimited data for $15 per month. That sure beats $20 for having a iphone plus more money for data on top of that. And you can opt to not get either fee, of course. Who said AT&T didn't have unlimited data? You have to be only slightly smarter than the person at the other end of the line.
Anyways the real problem is that carriers are now making deals with their smartphone manufacturers to pay fees back to them. That's what the $20 iPhone tax started, now every smartphone manufacturer wants to get a monthly kick back for each subscriber. Even though AT&T and Apple started this problem, they also make it easy to avoid, by the very nature of the open standard network.
Re:Screw AT&T, I could care less what they do (0)
Anonymous Coward | more than 2 years ago | (#38672552)
People do stupid shit just to get an iphone. news at 11.
Re:Screw AT&T, I could care less what they do (5, Insightful)
PopeRatzo (965947) | more than 2 years ago | (#38669952):Screw AT&T, I could care less what they do (0)
Anonymous Coward | more than 2 years ago | (#38670560)
"When you get to your new provider, you will see that sometimes having "a choice" is really no choice at all"
I readily admit you are 100% correct. The US is fucked, because of the incestuous relationship
between government and corporations. This is not new nor is it likely to change anytime soon,
because the vast majority of Americans are gutless sheep, who walk willingly to the slaughter.
However, I'll be making the change not to improve my telecomm circumstances but only so I can tell AT&T in no uncertain terms
that they can take their policies and shove them up their collective asses. None of this is going to change the world
of course, but every time I get my phone bill I'm going to feel better, and that's enough to make this action worthwhile
for me. I'd rather use Edge on my feet than use 3G on my knees, verstanden ?
Re:Screw AT&T, I could care less what they do (2)
PopeRatzo (965947) | more than 2 years ago | (#38672542)
There is no inherent incestuous relationship between government and corporations. That relationship is between corporations and politicians. Break that relationship and you stop the incest.
Re:Screw AT&T, I could care less what they do (0)
Anonymous Coward | more than 2 years ago | (#38671252)
Sorry, but cell phone companies don't suck because the lack government regulation or because the government is doing something wrong.
They are highly regulated in several aspects. Even if they take part in writing the regulations (which made sense in the distant past, when the only experts actually worked at the phone company), it doesn't give them the advantage that you think it does.
The problem is that these companies SUCK, plain and simple. They are driven by greed and aggregate totals covering huge swaths of the population. If you regulate them to death, it won't make them better.
The phone system relied on government regulation to keep its monopoly, the long distance carriers after 1984 were the first major competitor to Ma Bell. The long haul fiber networks and the cell phone carriers were the second and untied the monopolies well before the internet helped to decimate the remaining pieces.
Government regulation was much less tight on the cellular carriers for a long time. They suck either way. Neither the government, the constitution, Ron Paul or Ralph Nader can fix that.
Re:Screw AT&T, I could care less what they do (3, Interesting)
icebraining (1313345) | more than 2 years ago | (#38672026) (4, Interesting)
guttentag (313541) | more than 2 years ago | (#38670844):Screw AT&T, I could care less what they do (1, Flamebait)
NotQuiteReal (608241) | more than 2 years ago | (#38670904)
Bullshit.
Re:Screw AT&T, I could care less what they do (1)
Jafafa Hots (580169) | more than 2 years ago | (#38671176):Screw AT&T, I could care less what they do (1)
EvilBudMan (588716) | more than 2 years ago | (#38676304) (0)
dutchwhizzman (817898) | more than 2 years ago | (#38671282)
Apple and Google could roll out their own networks (1)
Nova Express (100383) | more than 2 years ago | (#38669410) (5, Interesting)
olsmeister (1488789) | more than 2 years ago | (#38669468)
Re:Apple and Google could roll out their own netwo (1)
cshark (673578) | more than 2 years ago | (#38670994)
S2? (0)
Anonymous Coward | more than 2 years ago | (#38669426)
Amazon have lost an S somewhere?
I'm confused (3, Insightful)
viperidaenz (2515578) | more than 2 years ago | (#38669450)
Re:I'm confused (5, Funny)
ColdWetDog (752185) | more than 2 years ago | (#38669516):I'm confused (1)
Attila Dimedici (1036002) | more than 2 years ago | (#38672592):I'm confused (0)
Anonymous Coward | more than 2 years ago | (#38673314)
And usernames like "433234"
Re:I'm confused (1)
ColdWetDog (752185) | more than 2 years ago | (#38676530) (4, Interesting)
Charliemopps (1157495) | more than 2 years ago | (#38670512)
Re:I'm confused (1)
tlhIngan (30335) | more than 2 years ago | (#38674308)
All carriers do that. In fact, "featurephones" have always been walled gardens of pain. If you're a developer, you have to make individual contracts with every carrier if you want to publish a mobile game. And every phone has its own quirks, so even though a carrier may offer say, 20 different phones right now, you really only can support 4 or 5, and none of last month's series of phones.
Ditto media. Hell, some carriers charged to have you download your photos from your cameraphone (before everyone standardized on USB - proprietary cables were everywhere and cost a ton of money just to copy your photos off).
With the proliferation of smartphones though, even walled gardens like Apple's are much easier to break into for the average joe than for featurephones.
Re:I'm confused (1)
EvilBudMan (588716) | more than 2 years ago | (#38676402):I'm confused (1)
gl4ss (559668) | more than 2 years ago | (#38670660):I'm confused (1)
EvilBudMan (588716) | more than 2 years ago | (#38676320)
AT&T will just not allow you to sideload off of Amazon unless Amazon gives them a kickback.
missing an important part (4, Insightful)
khallow (566160) | more than 2 years ago | (#38669498)
Re:missing an important part (0)
Anonymous Coward | more than 2 years ago | (#38669766)
With this sort of thing it is a lock into an interface that you use to scale your application across servers. This is more akin to competing against Amazon, Akamai and Verizon in this space.
Re:missing an important part (0)
Anonymous Coward | more than 2 years ago | (#38669796)
Cloud services is what I am guessing they are talking about. AT&T could provide far better bandwidth to their own systems.
Re:missing an important part (4, Interesting)
berashith (222128) | more than 2 years ago | (#38670344):missing an important part (1)
khallow (566160) | more than 2 years ago | (#38671326)
ATT can circumvent those by supplying their own store with access to all of their customers ( which is a huge base)
Why are their customers going to buy apps? That's not why they're customers.
Re:missing an important part (1)
berashith (222128) | more than 2 years ago | (#38672266) (1)
TaoPhoenix (980487) | more than 2 years ago | (#38672474):missing an important part (1)
CAIMLAS (41445) | more than 2 years ago | (#38670750). I'm implementing it locally because, again, it's good sense. I fail to see what this has to do with walled gardens or how it's different than, say, a shitton of physical hardware in that regard.
Re:missing an important part (1)
Etcetera (14711) | more than 2 years ago | (#38671010)... (5, Insightful)
Electrawn (321224) | more than 2 years ago | (#38669620)
... Just ask the friendly NSA guy in the datacenter for a copy of your data.
Seriously, would anyone trust their (cloud) data to T after the NSA thing?
In doubt... (4, Insightful)
migla (1099771) | more than 2 years ago | (#38669668).
Afro GPL (-1)
Anonymous Coward | more than 2 years ago | (#38669794)
The Afro GPL is for nigras
Re:In doubt... (1)
Teckla (630646) | more than 2 years ago | (#38677942).
Re:In doubt... (1)
TemporalBeing (803363) | more than 2 years ago | (#38679166) compatible for licenses. OpenOffice proper (Sun->Oracle->Apache) is under a CLA; as is most Apache software to my understanding; as such Sun could transfer to Oracle which could transfer to Apache all the official OpenOffice code; meanwhile LibreOffice does not have a CLA and as such they cannot necessarily contribute their changes back to OpenOffice (the individual authors have to in order to make the license switch to the Apache license) and they may find themselves in a fractured state as a result at some point. But again - the jury is out on whether that is a good or bad thing.
In my experience... (2)
feepness (543479) | more than 2 years ago | (#38669772)
AT&T to take on AWS? (2)
AlienSexist (686923) | more than 2 years ago | (#38669828)
Re:AT&T to take on AWS? (1)
dave562 (969951) | more than 2 years ago | (#38670552) (2)
Slashdot Parent (995749) | more than 2 years ago | (#38670210)
Simple Storage Service. S3. There is no S2.
Good luck with that (3, Informative)
JoeCommodore (567479) | more than 2 years ago | (#38670228) (3, Insightful)
Ramin_HAL9001 (1677134) | more than 2 years ago | (#38670306) (1)
dave562 (969951) | more than 2 years ago | (#38670542)
AT&T has data centers all over the globe. They already offer managed hosting services, in additional to traditional co-location agreements. A technology like OpenStack that allows users to self provision infrastructure services seems like a no brainer to me.
Re:It makes sense to me (0)
Anonymous Coward | more than 2 years ago | (#38671448)
Yup. If anything AT&T already had the makings of a semi-walled garden (for customers that chose to use all of their stuff), and this OpenStack deal *decreases* lock-in. OpenStack is, in fact, an open standard. If you write your infrastructure configuration to deploy on AT&T's OpenStack-based services, that means it will be relatively easy to pick up and move to a different OpenStack-based cloud provider.
Amazon's the one building the walled garden. Luckily they don't take issue with people copying and genericizing their API, but still, once you go full-on AWS with your infrastructure, there's a level of inherent lock-in because a good number of AWS services have no counterpart in competing clouds.
lol brian profitt again? (0)
Anonymous Coward | more than 2 years ago | (#38670746)
Yay! Slashdot picks up another idiotic article from freetarded turd Brian Profitt. So how many of his grand predictions have been correct? Right, not many if any.
bashing (0)
Anonymous Coward | more than 2 years ago | (#38671218)
Since when is anything made built by AT&T considered a "garden"?
Damn (0)
Anonymous Coward | more than 2 years ago | (#38671878)
I'm tired of this "walled garden" thing. Can't you people make up other words for closed environments?
Why is it an issue since it is openstack? (2)
buchanmilne (258619) | more than 2 years ago | (#38672312):Why is it an issue since it is openstack? (1)
Anonymous Coward | more than 2 years ago | (#38672336)
Because "walled garden" is a buzzword. What else would you expect from bullshit press like ITWorld? Prioritizing synergized deep innovative buzzword integration in headlines and articles incentivizes target audience, which provides better monetization opportunities for social media, increasing RoI.
Walled Ass (0)
Anonymous Coward | more than 2 years ago | (#38672960)
The thing Apple and to a smaller part Google can provide that AT&T can't is interoperability with other devices in the home. THis is only going to expand and will keep these companies and maybe Samsung ahead of anything they try. We've just come off of a carrier only system and it didn't go so well. Apple and Google have innovated and changed the market. They've made the carriers more money than ever but they're still not happy not controlling the whole pie.
Hey Carriers you've failed at this game before. | http://beta.slashdot.org/story/163128 | CC-MAIN-2014-15 | refinedweb | 9,573 | 66.57 |
Created on 2011-04-07 16:15 by fabioz, last changed 2017-06-30 16:52 by gvanrossum. This issue is now closed.
Right now, when doing a test case, one must clear all the variables created in the test class, and I believe this shouldn't be needed...
E.g.:
class Test(TestCase):
def setUp(self):
self.obj1 = MyObject()
...
def tearDown(self):
del self.obj1
Ideally (in my view), right after running the test, it should be garbage-collected and the explicit tearDown wouldn't be needed (as the test would garbage-collected, that reference would automatically die), because this is currently very error prone... (and probably a source of leaks for any sufficiently big test suite).
If that's accepted, I can provide a patch.
You don't have to clear them; you just have to finalize them. Anyway, this is essentially impossible to do in a backward compatible way given that TestCases are expected to stay around. do get the idea of the backward incompatibility, although I think it's really minor in this case.
Just for some data, the pydev test runner has had a fix to clear those test cases for quite a while already and no one has complained about it (it actually makes each of the tests None after run, so, if someone tries to access it after that, it would be pretty clear that it's not there anymore).
2011/4/7 Jean-Paul Calderone <report@bugs.python.org>:
>
> Jean-Paul Calderone <invalid@example.invalid> added the comment:
>
> thought unittest was just handed a bunch of TestCase instances and
couldn't do much about insuring they were garbage collected.
> I thought unittest was just handed a bunch of TestCase instances and couldn't do much about insuring they were garbage collected.
True. But unittest could ensure that it doesn't keep a reference to each TestCase instance after it finishes running it. Then, if no one else has a reference either, it can be garbage collected.
A TestSuite (which is how tests are collected to run) holds all the tests and therefore keeps them all alive for the duration of the test run. (I presume this is the issue anyway.)
How would you solve this - by having calling a TestSuite (which is how a test run is executed) remove members from themselves after each test execution? (Any failure tracebacks etc stored by the TestResult would also have to not keep the test alive.)
My only concern would be backwards compatibility due to the change in behaviour.
The current code I use in PyDev is below -- another option could be not adding the None to the list of tests, but removing it, but I find that a bit worse because in the current way if someone tries to access it after it's ran, it'll become clear it was removed.
def run(self, result):
for index, test in enumerate(self._tests):
if result.shouldStop:
break
test(result)
# Let the memory be released!
self._tests[index] = None
return result
I think the issue with the test result storing the test is much more difficult to deal with (because currently most unit test frameworks probably rely on having it there), so, that's probably not something I'd try to fix as it'd probably break many clients... in which case it should be expected that the test is kept alive if it fails -- but as the idea is that all has to turn green anyways, I don't see this as a big issue :)
Here's Trial's implementation:
Not keeping tests alive for the whole run seems like a good thing and either implementation seems fine to me. I'd be interested to hear if anyone else had any backwards compatibility concerns though.
> Not keeping tests alive for the whole run seems like a
> good thing
+1
> and either implementation seems fine to me.
I slightly prefer Fabio;s assignment to None approach (for subtle reasons that I can't articulate at the moment).
So Michal, it seems no objections were raised?
Sure, let's do it. Fabio, care to provide patch with tests and doc changes? (For 3.3.)
Sure, will try to get a patch for next week...
Patch attached using setting test to None after execution.
The patch looks good to me, although there probably needs to be a note in the TestSuite docs too. I'll apply this to Python 3.4, which leaves plenty of time for people to object.
Note that people needing the old behaviour can subclass TestSuite and provide a dummy implementation of _removeTestAtIndex.
Just to be self-referential here's a link to #17908.
If the iterator for 'self' were de-structive, if it removed (popped) the test from whatever structure holds it before yielding it, the messiness of enumerate and the new ._removeTestAtIndex method would not be needed and 'for test in self' would work as desired. If considered necessary, new method .pop_iter, used in 'for test in self.pop_iter', would make it obvious that the iteration empties the collection.
Terry: I would not be in favor of using the normal iter, since iterating a collection doesn't normally empty it, and there may be tools that iterate a test suite outside of test execution. Adding a pop_iter method would be a backward compatibility issue, since "replacement" test suites would not have that method. I think the current patch is the best bet for maintaining backward compatibility.
Michael Foord <fuzzyman <at> voidspace.org.uk> writes:
> On 2 Aug 2013, at 19:19, Antoine Pitrou <solipsis <at> pitrou.net> wrote:
> > The patch is basically ready for commit, except for a possible doc
> > addition, no?
>
> Looks to be the case, reading the patch it looks fine. I'm currently on
> holiday until Monday. If anyone is motivated to do the docs too and
> commit that would be great. Otherwise I'll get to it on my return.
It looks like the patch is based on what will become 3.4. Would backporting it to 2.7 be feasible? What's involved in doing so?
I took a crack at the docs. I'm attaching an updated patch.
This smells like a new feature to me (it's certainly a fairly significant change in behaviour) and isn't appropriate for backporting to 2.7.
It can however go into unittest2.
I agree with David that a destructive iteration using pop is more likely to cause backwards-compatibility issues.
The doc patch looks good, thanks Matt. I'll read it through properly before committing.
Looks good but review comments worth to be applied or rejected with reasonable note.
Andrew,
I didn't understand your message. Are you asking me to change the patch somehow? Or asking Michael to review and apply it?
Best,
Matt
Matt, I've added new patch.
Will commit it after tomorrow if nobody object.
Go ahead and commit. The functionality and patch are good.
Matt, would you sign licence agreement ?
The Python Software Fondation is asking all contributors to sign it.
Thanks.
Andrew,
I signed the agreement as matthewlmcclure and as matthewlmcclure-gmail. Is there any way I can merge those two user accounts?
I believe the original patch was Tom Wardill's. I just updated his patch.
There is no easy way to merge accounts in roundup. If you've submitted the agreement, your "*" should show up in a bit :)
New changeset 1c2a37459c70 by Andrew Svetlov in branch 'default':
Issue #11798: TestSuite now drops references to own tests after execution.
This seems to be producing a test failure in test_doctest. eg:
This might fix it (untested):
diff -r d748d7020192 Lib/test/test_doctest.py
--- a/Lib/test/test_doctest.py Sat Aug 03 10:09:25 2013 -0400
+++ b/Lib/test/test_doctest.py Wed Aug 28 15:35:58 2013 -0400
@@ -2329,6 +2329,8 @@
Now, when we run the test:
+ >>> suite = doctest.DocFileSuite('test_doctest.txt',
+ ... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
>>> result = suite.run(unittest.TestResult())
>>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Traceback ...
New changeset 17f23cf029cf by Andrew Svetlov in branch 'default':
Fix tests for #11798
Sorry. Tests are fixed now.
I see some regressions when reference leak hunting with -j './python -j8 -R :'
test test_ast crashed -- Traceback (most recent call last):
File "/home/meadori/src/cpython/Lib/test/regrtest.py", line 1265, in runtest_inne
r
huntrleaks) File "/home/meadori/src/cpython/Lib/test/regrtest.py", line 1381, in dash_R
indirect_test()
File "/home/meadori/src/cpython/Lib/test/regrtest.py", line 1261, in <lambda> test_runner = lambda: support.run_unittest(tests)
File "/home/meadori/src/cpython/Lib/test/support/__init__.py", line 1683, in run_
unittest
_run_suite(suite)
File "/home/meadori/src/cpython/Lib/test/support/__init__.py", line 1649, in _run
_suite
result = runner.run(suite)
File "/home/meadori/src/cpython/Lib/test/support/__init__.py", line 1548, in run
test(result)
File "/home/meadori/src/cpython/Lib/unittest/suite.py", line 76, in __call__
return self.run(*args, **kwds)
File "/home/meadori/src/cpython/Lib/unittest/suite.py", line 114, in run
test(result)
File "/home/meadori/src/cpython/Lib/unittest/suite.py", line 76, in __call__
return self.run(*args, **kwds)
File "/home/meadori/src/cpython/Lib/unittest/suite.py", line 114, in run
test(result)
TypeError: 'NoneType' object is not callable
Good catch!
That's because -R run the same test suite several times.
I'm working on patch.
New changeset 868ad6fa8e68 by Andrew Svetlov in branch 'default':
Temporary disable tests cleanup (issue 11798).
Er... your latest commit broke this issue's own tests!
All the buildbots are failing due to changeset 868ad6fa8e68 - I'm going to back it out.
New changeset 7035b5d8fc0f by Tim Peters in branch 'default':
Back out 868ad6fa8e68 - it left all the buildbots failing.
New changeset 39781c3737f8 by Andrew Svetlov in branch 'default':
Issue #11798: fix tests for regrtest -R :
Now 'regrtest.py -j4 -R : ' passes.
Do we need to add parameter for disabling tests cleanup to TestSuite, TestLoader and TestProgrm constructors?.
Ok. Let's close issue.
>.
That sounds like a completely disproportionate solution. Why would you have to override the TestSuite class just to change an option and restore old behaviour? Why don't you simply expose the cleanup flag on TestSuite instances?
For the record, this change broke the --forever option in Tulip's test script, which is why I'm caring. Setting the _cleanup flag to False seems to restore old behaviour, except that _cleanup is (obviously) a private API.
Note: ideally, the --forever flag wouldn't reuse TestCase instances but rather create new ones.
Can that be fixed in tulip?
Yes, but that's not the point. Legitimate use cases can be broken by the change, so at least there should be an easy way to disable the new behaviour.
If we're sure suite._cleanupis a *good* api for this then fine to expose it (and document) it as a public api. I'll take a look at it in a bit.
Test suites will still have to do *some* monkeying around to set suite.cleanup (presumably in load_tests), so I'm not sure it's much more convenient...
Ideally, test specification should be separate from test execution. That is, it should be possible to keep the TestCase around (or whatever instantiates it, e.g. a factory) but get rid of its per-test-execution attributes.
Perhaps restoring the original __dict__ contents would do the trick?
That would only be a shallow copy, so I'm not sure it's worth the effort. The test has the opportunity in the setUp to ensure that initial state is correct - so I would leave that per test. Obviously sharing state between tests is prima facie bad, but any framework reusing test suites is doing that already.
>.
> Obviously
> sharing state between tests is prima facie bad, but any framework
> reusing test suites is doing that already.
What do you mean?
On 19 Sep 2013, at 14:06, Antoine Pitrou <report@bugs.python.org> wrote:
>
> Antoine Pitrou added the comment:
>
>>.
>
If the object state includes mutable objects then restoring the previous dictionary will just restore the same mutable (and likely mutated) object. To *properly* restore state you'd either need to deepcopy the dictionary or reinstantiate the testcase (not reuse it in other words). I'd rather leave it up to each test to ensure it reinitialises attributes in setUp than add further complexity that only does part of the job.
>> Obviously
>> sharing state between tests is prima facie bad, but any framework
>> reusing test suites is doing that already.
>
> What do you mean?
Any framework that is currently reusing test suites is re-using testcase instances. They are already sharing state between the runs.
In fact messing with testcase dictionaries is a further possible cause of backwards incompatibility for those suites.
>
> ----------
>
> _______________________________________
> Python tracker <report@bugs.python.org>
> <>
> _______________________________________
> If the object state includes mutable objects then restoring the
> previous dictionary will just restore the same mutable (and likely
> mutated) object.
I don't understand what you're talking about. Which mutable objects
exactly? I'm talking about copying the dict before setUp.
> >> Obviously
> >> sharing state between tests is prima facie bad, but any framework
> >> reusing test suites is doing that already.
> >
> > What do you mean?
>
> Any framework that is currently reusing test suites is re-using
> testcase instances. They are already sharing state between the runs.
They are not sharing it, since setUp will usually create the state
anew. What we're talking about is cleaning up the state after tearDown
is run, instead of waiting for the next setUp call.
Ah right, my mistake. Before setUp there shouldn't be test state. (Although tests are free to do whatever they want in __init__ too and I've seen plenty of TestCase subclasses using __init__ when they should be using setUp.)
Essentially though _cleanup is a backwards compatibility feature - and suites that need _cleanup as a public api are already living without testcase dict cleanup.
That said, I agree that the __dict__ proposal is a hack, but as is the current _removetestAtIndex mechanism.
The only clean solution I can think of would be to have two separate classes:
- a TestSpec which contains execution-independent data about a test case, and knows how to instantiate it
- a TestCase that is used for the actual test execution, but isn't saved in the test suite
Maybe it's possible to do this without any backwards compat problem by making TestSuite.__iter__ always return TestCases (but freshly-created ones, from the inner test specs). The main point of adaptation would be TestLoader.loadTestsFromTestCase().
Having TestLoader.loadTestsFromTestCase() return a "lazy suite" that defers testcase instantiation until iteration is a nice idea..
addTests() could easily be tweaked to recognize that it gets passed a
TestSuite, and special-case that.
Also, TestCase objects could probably get an optional "spec" attribute
pointing to their TestSpec.
This seems to break BaseTestSuite.countTestCases when invoked after the TestSuite has been run:
...
File "Lib/unittest/suite.py", line 42, in countTestCases
cases += test.countTestCases()
AttributeError: 'NoneType' object has no attribute 'countTestCases'
Attached patch attempts to fix it.
No answer to Xavier's regression? The way this issue is being treated is a bit worrying.
New changeset b668c409c10a by Antoine Pitrou in branch 'default':
Fix breakage in TestSuite.countTestCases() introduced by issue #11798.
What's the purpose of _removed_tests in your fix, it doesn't appear to be used?
It is used, see countTestCases().
Ah yes, I see - sorry.) | https://bugs.python.org/issue11798 | CC-MAIN-2020-16 | refinedweb | 2,583 | 67.04 |
Opened 11 years ago
Closed 11 years ago
#3486 closed (worksforme)
Cryptic error message
Description
class Conference(models.Model): name = models.CharField(maxlength=100, unique_for_year=start) # slug = models.SlugField(prepopulate_from=('name',)) start = models.DateField('Date on which to start the schedule') finish = models.DateField('Date on which to end the schedule') def __str__(self): return '%s %s' % (self.name,self.start.year) class Admin: pass
yields:
ProgrammingError: ERROR: relation "auth_user" does not exist
Change History (11)
comment:1 Changed 11 years ago by
comment:2 Changed 11 years ago by
I think it was just a syncdb
comment:3 Changed 11 years ago by
I cant't reproduce this. I'd say it is obviously related to another
part of the
models.py file the reporter didn't include in the excerpt
he posted.
There is a suer error (with the use of the
unique_for_year option) that
syncdb detects and reports but I don't think this ticket is the place to talk
about that.
comment:4 Changed 11 years ago by
It's not possible to find out whether this is a bug or a usage error with the information you provide. As it smells a bit for a usage error, can you please try your luck on django-users and reopen the ticket if this was found to be an error in django?
comment:5 Changed 11 years ago by
It's certainly a usage error!
start should have been quoted. The complaint is about the quality of the error message, which ought to tell me if a string field name is required to be passed rather than the field itself.
comment:6 follow-up: 9 Changed 11 years ago by
I'm not entirely certain how we're getting from an unquoted string to
auth_user...
I'm also not certain why you're not immediately getting a
NameError that
start isn't bound to anything at the time you're trying to use it.
This one's gonna need some digging.
comment:7 Changed 11 years ago by
I still don't see how to produce this message. I get this:
$ python manage.py syncdb Error: Couldn't install apps, because there were errors in one or more models: testproj.testapp: name 'start' is not defined
and that's because in the first line, the variable 'start' has not been defined.
Please explain how you get this message.
comment:8 Changed 11 years ago by
There were other things in the global namespace, obviously. I don't know if I
can reconstruct the scenario exactly, but what happens if you precede the declaration with
start = 1
?
comment:9 Changed 11 years ago by
Replying to ubernostrum:
I'm not entirely certain how we're getting from an unquoted string to
auth_user...
I'm also not certain why you're not immediately getting a
NameErrorthat
startisn't bound to anything at the time you're trying to use it.
This one's gonna need some digging.
I don't understand your decision to reopen this bug. In my opinion, this is a clear 'worksforme'.
comment:10 Changed 11 years ago by
I reopened it because it seemed to have been closed based only on a misunderstanding of the report (the comment asked me to determine whether it was usage error or a django bug). If I were a django devel who wanted to close it, it would be on the grounds that the reporter didn't provide enough info to fully reproduce the problem, not "worksforme," since the example, as written, clearly can't work. Personally I'd be eager to find out why the error message isn't more useful, but it's your project.
comment:11 Changed 11 years ago by
Well. As much as I try, I cannot reproduce it. Please reopen when you have found a way to reproduce it.
What do you have to do in order to make the error message appear? | https://code.djangoproject.com/ticket/3486 | CC-MAIN-2018-05 | refinedweb | 660 | 72.05 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.