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
Hi guys! I recently made a game. (really corny!) But, I want to package it and give it to my friends I know that I can create a jar of it and add the images to the folder, but what I would... Hi guys! I recently made a game. (really corny!) But, I want to package it and give it to my friends I know that I can create a jar of it and add the images to the folder, but what I would... Never mind guys, I fixed it :D Guess I'm the javamaster The problem I am having is that I have a character peter griffin that runs into a burger, and when he does, he and the burger are supposed to reset to a random position. The game runs, other things... Hi! Thanks for your reply Unfortunately, that didn't solve it for me :( Here is an example program: import javax.swing.*; import java.awt.*; class SwingT extends JComponent { public void... Whenever I make something in Swing, I always need to resize the window for me to see the graphics on the window. I have been told to use the pack() method on it, which I have, but the problem with it... I couldn't really figure out the easiest way to display an image. I tried the following way (in my code below), and it runs with no error but does not display the image. The image is called... So, I have to extend JComponent? I wrote a program to display a rectangle within a window, but it won't show. Is it because I didn't call the paint() method? Sorry for indentation, I am using a text editor import javax.swing.*;... I can't figure it out could you fix it? Ok, my new code is: import javax.swing.*; import java.awt.*; import java.awt.event.ActionListener; import javax.swing.Timer; public class Square extends JFrame { Ok. I know i'm not supposed to really explicitly ask, but do you think you could make my code work? I know you're one of the best on the site and could do it in an instance(no pun intended :P ).... Where should I define the setBackground and repaint methods? Oh, ok. Does this only apply to the paint method though? For all others you have to explicitly call them in the main method? Thanks Norm, and i read a part Hi Norm. I know what constructors are, and realize that doing new Carz() is just calling the constructor. What I don't get is how paint method is executed without being called. Thank you. Hey guys! I had a question on two things. First, can you explain the parameters part of public void paint(Graphics g){} ? I don't understand graphics g? Is it an object? It doesn't have an instance... ok here is the code.. import javax.swing.*; import java.awt.*; import java.awt.event.ActionListener; import javax.swing.Timer; It still does not work I made it an action listener I did and it still doesn't work. Hey! I redid the code as you asked, and now I only get one error. Could you help me figure out how to fix this error? Below is the code. import javax.swing.*; import java.awt.*; import... Hello I am new to the forum and hope you can help me I put my code and then the errors I receive thank you so much import javax.swing.*; import java.awt.*; import javax.swing.Timer; public...
http://www.javaprogrammingforums.com/search.php?s=8b214f6673db72a5974dabcbbefc6871&searchid=2051787
CC-MAIN-2016-07
refinedweb
592
83.15
Palms are sweaty, knees weak, arms are heavy, There's vomit on his Patagucci already These are the types of tech interview questions my friends used to tell me about that would make me freeze up. The way it's phrased just seems like such a lot of work and hidden complexity. And, I'm sure there is - if you really wanted to knock it out of the park -- but today, at approximately 4 hours into a task that I found more annoying than complex, I realized I'd done just this (sorta, at a very low level). T, why were you creating a custom router? That's a great question, I'm glad you asked 🕺🏽. SO I'm currently working on a project where we're creating a bunch of babby API's to CRUD (Create, Retrieve, Update, Delete) some things from DynamoDB tables. From a bunch of reasons, not least of which including the fact that I am the sole engineer on this project - I'm trying to win sales, earn bonuses and make hella money move quickly and maintain as little "live-infrastructure" as possible. Because of this, I came to the following conclusion(s)/decision(s) on how I would proceed: TIRED 😰 - Running a node.js webserver (and associated infra and management) to effectively broker CRUD requests to a DynamoDB? WIRED ☕️ - Setting up an AWS API Gateway that would trigger a Lambda to CRUD the required things from DynamoDB WIRED We're $erverle$$ baaaabyyyyy INSPIRED ✨ Anyways, the TL:DR on this is that there's going to be an API Gateway that gets HTTP requests and then sends them to a Lambda function which decides to how to deal with the request before brokering the interaction with DynamoDB. I have a single set of resources projects that exist in DynamoDB (in a single projects) table, and my Lambda needs to be able to listen to the request and get the things from DynamoDB. From skimming my original blue-print above, you might think: This seems easy enough. And you'd be right, if I only ever had to deal with one entity projects. As the project went on, now I have a second entity to deal with: status(es?) and more are soon to come. Originally I'd thought: 1 lambda per resource. /resourceswill go to the resources-lambda, and /statuswill go to the status-lambda. However this approach leads to a few issues: - For every endpoint/lambda, you need to create 3x API gateway references - For every endpoint/lambda, you need to make more IAM accommodations. - Deployments would get annoying because I would need to update a specific lambda, or multiple lambdas to implement one feature in the future (i.e. if i needed to add a new field to the statuswhich makes use of projects) I ultimately decided: No, we're going to have the API gateway send all (proxy) traffic to a single lambda 1 lambda to rule them all (as a proxy resource), and then the lambda can decide how to handle it. This is why I needed to create a router, so that my Lambda function could figure out what it's being asked to do before doing the appropriate response. For example, it would have to handle: GET /projects- get me all projects in the database. GET /projects:name- get me details on a single project. GET /status- get me all the status entries in the database. GET /status/:name- get me the status of a single project in the database. Having worked with Node (and specifically Express) before, I knew there existed a way to specify routes like this: app.get('/users/:userId/books/:bookId', function (req, res) { res.send(req.params) }) And similarly for Lambda, there seemed to exist a specific node module for this case: import * as router from 'aws-lambda-router' export const handler = router.handler({ proxyIntegration: { routes: [ { // request-path-pattern with a path variable: path: '/article/:id', method: 'GET', // we can use the path param 'id' in the action call: action: (request, context) => { return "You called me with: " + request.paths.id; } }, { // request-path-pattern with a path variable in Open API style: path: '/section/{id}', method: 'GET', // we can use the path param 'id' in the action call: action: (request, context) => { return "You called me with: " + request.paths.id; } } ] } }) However, unfortunately - proxy path support is still a WIP :( This would seem to imply that ❌ I wouldn't be able to get at route params like the name in GET /projects/:name WOMP WOMP ❌ It's also annoying that if you're using custom node-modules, you have to upload it as a zip every single time (as opposed to being able to code / test live if you're using native / vanilla Node). Well Lambda, I think it's just you (-r event parameters) and me at this point. This would just mean that I'd need to create my own router, and thankfully obviously?, the event payload that's passed into a Lambda function by the API gateway contains all the information we could need. Specifically, all you really need for a router is three things (to start); - HTTP Method: GET, POSTetc - Resource: projects|| status - Params (a.k.a keys): :name Once I got these pieces extracted out from lambda by doing the following: let method = event.httpMethod let resource = event.path.split("/")[1] let key = event.path.split("/")[2] The actual logic of the router wasn't too hard. And I guess, just like in a tech interview -- I came up with 2 "solutions". V1 - Switch on 1, add more detail inside let method = event.httpMethod let resource = event.path.split("/")[1] let key = event.path.split("/")[2] switch (resource) { case "projects": if (key == undefined) { body = await dynamo.scan({ TableName: PROJECTS_DB_TABLE }).promise(); } else { let name = key; body = await db_get("projects",name) } break; case "status": break; default: body = { defaultCase: "true", path: event.path, resource: event.path.split("/")[1], }; break; } This approach was cool because it allowed me to use the path as the main selector and then code the logic for the required methods as they came up. However.it doesn't... look great. On first glance, it looks gross, convoluted, and that's just with a single resource and a single method. Secondly, for any new engineers coming onboard - this doesn't immediately seem like a a router when compared to any previous work they may have done. Going back to the drawing board, and wanting to get closer to the "gold-standard" I was used to, like in express-router. I wanted to come up with something that would simply specify: - Here's the route that we need to handle - Here's it's associated handler. With that in mind, I came up with V2 - Filter on 2 conditions, add more methods as they arise let method = event.httpMethod let resource = event.path.split("/")[1] let key = event.path.split("/")[2] if (method == "GET" && resource == "projects") { body = await db_get(dynamo, "projects", key) } else if (method == "GET" && resource == "status") { body = await db_get(dynamo, "status", key) } else { body = { method, resource, key, message: "not supported at this time" } } I like this because it's the closest I was able to get to express-router: app.get('/users/:userId/books/:bookId', function (req, res) { res.send(req.params) }) And has the benefit of being concise, and much more recognizable as a router on first-glance. Things I'd Improve I'd probably want to do way more clean-up for an actual interview "REAL" router, but it was still a cool thought exercise. Some definite things I'd want to add / handle: - The get-me-allcase is handled by checking for an undefined key. This could probably be guarded for better. - There's currently no guard against someone adding in more than a 1st level parameter (i.e. /projects/name/something/elsewould still get sent to the DB. Thats not great. - THIS IS ALL IN A GIANT IF-ELSE STATEMENT?? That doesn't seem great. - Limitations: There's no way to do middleware, auth, tracing and a bunch of things that you'd be able to do with express-router (and other routers) Conclusion Routers are just giant if-else statements? Idk - this was fun tho. Discussion (2) Hmm, that's a good point! It just need to be one policy that could be applied for all the lambdas to access what they need. I just meant for the fact that for example, if the projectslambda needed to access a different DynamoDB table than the statustable.
https://practicaldev-herokuapp-com.global.ssl.fastly.net/tratnayake/and-for-this-interview-build-me-a-custom-router-for-a-web-application-30l1
CC-MAIN-2021-31
refinedweb
1,429
69.82
Last Updated on September 3, 2020 Word embeddings are a modern approach for representing text in natural language processing. Word. Kick-start your project with my new book Deep Learning for Natural Language Processing, including step-by-step tutorials and the Python source code files for all examples. Let’s get started. Need help with Deep Learning for Text Data? Take my free 7-day email crash course now (with code). Click to sign-up and also get a free PDF Ebook version of the course. Start Your FREE Crash-Course. It is hard to pull much meaning out of the graph given such a tiny corpus was used to fit the model. - gensim Python Library - models.word2vec gensim API - models.keyedvectors gensim API - scripts.glove2word2vec gensim API - Messing Around With Word2vec, 2016 - Vector Space Models for the Digital Humanities, 2015 - Gensim Word2vec Tutorial, 2014. thank you for your wonderful tutorial, please sir can I download the pdf of these tutorials regards Try some web2pdf plug-ins. Do you have an example? I will release a book on this topic soon. Hi Jason, I started reading your website for my learning. It is written in a level such that any beginner like me can easily can understand these topics. Thanks and appreciate your sincere effort on this. I would like to ask you for a help or suggestion, I need to write an algorithm that converts or extracts the text into conditions, arguements and actions : For Example: Input to the algorithm : “If A is greater than 100 then set B as 200” Output from the algorithm: INPUT_VAR1 CONDITION INPUT1_VALUE1 ACTION OUTPUT_VAR1 OUTPUT1_VALUE1 —————————————————————————————————————– A > 100 SET B 200 Basically what i am looking is how to intrepret the text and extract the actions, input and output told in the text. Sounds like a fun project. Perhaps an Encoder-Decoder LSTM would be appropriate. You can get started with LSTMs here: You can get started with deep learning for NLP here: Ran the example, however not sure what the 25 by 4 Vector represents or how the plot should be read. The vectors are the learned representation for the words. The plot may provide insight to the “natural” grouping of the words, perhaps it would be more clear with a larger dataset. Thank you, Jason. Very clear, interest and igniting. Thanks Alexander. Thanks for great tutorial I’ve question. ‘GoogleNews-vectors-negative300.bin.gz’ implemented by which algorithm skip-gram or CBOW? I’m not sure Rose, I’m sure the details are on the w2v page: Very structured and even for a beginner to follow. Thanks a lot. I highly appreciate your work! Thanks. Hi Jason, Thanks for your detail explanation ! For the “Scatter Plot of PCA Projection of Word2Vec Model” image, I had different result comparing with yours. I am not sure if there is any wrong with my code. Actually, I copied code from yours. This is mine Could you please take a look and give your comment ? Thanks a lot ! The algorithm is stochastic: Thanks a lot, Jason ! Great tutorial, thank you a lot! A question, is there similar to GloVe embeddings but based on other languages then English? There may be, I am not aware of them, sorry. You can train your own vector in minutes – it is a very fast algorithm. Thanks for the simple explanation 🙂 I’m glad it helped. hi, I am trying to combine my own corpus with the above Glove embeddings. I haven’t really found a solution/example where I can leverage the GloVe 6b for the known embeddings and then ‘extend’ or train on my own Out of Vocab tokens (These tend to be non language words or machine generated). Any help is appreciated. Thanks Hi Rob, one way would be to load the embeddings into an Embedding layer and tune them with your data while fitting the network. Perhaps Gensim lets you update existing vectors, but I have not seen or tried to do that, sorry. @Rob Hamilton-Smith, I’m working on a similar problem that I encountered,Can you help me with it if you had found a solution Thanks Thanks for the great tutorial (as usual). Are you going to make a post about word embeddings for complete documents using doc2vec and/or Fasttext? I am particularly interested in using pre-trained word embeddings to represent documents (~500 words). This allows leveraging from huge corpuses. However, it’s well known that simple averaging is only as good (or even worse) than classic BOW in classification tasks. Apparently you could do better by first PCA-transforming word2vec dictionary (paper “In Defense of Word Embedding for Generic Text Representation”), but so far I haven’t seen anyone else using that trick… I hope to cover Fasttext in the future. When model skill is the goal, I recommend testing every trick you can find! Let me know how you go. This tutorial helped me a lot !! Thank you very much! Thanks Guy, I’m glad to hear that. Another excellent article. I have been struggling for a long time to get a knack of word2vec & this helped me a lot. I’m glad to hear that! Dear Sir, 1) I have an 8GB RAM and i5 processor system. How long should it take for the google news corpus to be trained using the model? 2) In the demo example you described, your dataset used was in the form you inputted on your own. If I want to train the model using any corpus, how do I process the corpus? Like the Brown corpus? Or if I have any arbitrary corpus, how do I process it so as to feed the corpus to the word2vec model in a suitable form for processing? I don’t know how long it takes to train on the google corpus sorry, perhaps ask the google researchers? You should be able to load the learned google word vector in a minute, given sufficient resources. To learn your own corpus, tokenize the text the way you need for your application and use the Gensim code above. hats off to Jason for clear and pricise explanation of a very complicated topic Thanks! Hey Jason, How do I incorporate ngrams into my vocabulary. Does gensim provide a function to do so ? You can extract them from your dataset manually with a line or two of Python. There may be tools in Gensim for this, I’m not aware of them though. Thank you so much for such detailed explaination You’re welcome. Hi Jason, Could you give some idea about language modelling for Question , answer based model, Thanks in advance.. Thanks for the suggestion, I hope to cover it in the future. I have small question , te glove based word to vector don’t provide model.score functionaloty Correct. how to convert a sentence into vector by using word2vec (google pre-trained). Each word is converted int a vector. Hello my name is Yazid a just wana know how to update googleNews model with new words Best Regard You could train vectors with your new works and take the union of the vectors for the words that interest you. Thank you, such a great explanation. Jason, a quick question please: Suppose we are pretraining embeddings ourselves (without glove/google). Which of the following would be better? 1) pretrain using gensim, and feed into the keras embedding layer, trainable=False. 2) train as part of the neural network in embedding layer? Kindly advise. These would be pre-trained word embeddings. Sorry to tell, but gensim embedding pretraining proved to be actually worse. (In case of a dataset of 1.5 M small texts.) So, those randomly initialized weights in case of Embedding layer as part of a NN show much better results. My justification would be: – It makes sense to use pretrained word embeddings only if using GloVe/Google or such. – It makes sense to use pre-trained word embeddings only on dataset with relatively big texts. (i.e. not on tweets or small messages) What would be your opinion please? Cheers! Nice. Sounds reasonable. Very nice tutorial. Could you please let me know if there is a way of getting the sentences that were used in training a model? I have a doc2vec model M and I tried to fetch the list of sentences with M.documents, like one would use M.vector_size to get the size of the vectors. Also, having a doc2vec model and wanting to infer new vectors, is there a way to use tagged sentences? I see on gensim page it says: infer_vector(doc_words, alpha=0.1, min_alpha=0.0001, steps=5)¶ Infer a vector for given post-bulk training document. Document should be a list of (word) tokens. But I would like to use tagged sentences. Thank you very much! I’m not sure I follow, sorry. You will have the training data for the model that you can access directly? I downloaded a doc2vec model trained on a wikipedia dump. I was wondering if the model stores the sentences too and if yes, how can I access them. Thank you very much. Perhaps ask the person you downloaded it from? How to generate word embeddings for a complete review sentence? I mean in word2vec we will get 300dim vector for each word. Other than computing the average of vectors of all words in a sentence, any good technique to achieve good representation of vector for sentence. I believe there are methods for this. Sorry, I don’t have examples at this stage. Hi Jason, Since past few days i had been facing issue regarding word embedding using word2vec and glove. I went through alot of post, but its messy. Yesterday i came across this post, and wow! it helped me alot! I also came to know that you have a book “Deep Learning for Natural Language Processing”.Looks great! I am interested to purchase it! But i wanted to connect to you directly to understand whether this book fits my requirement. Tasks that I work on like Word2Vec, Doc2Vec, mapping one document to another using embedding for recommendation,etc I just need fundamental understanding so that i can take the next step and create by my own idea/analysis. The book covers word2vec models and how to use them in deep learning. It does not cover doc2vec. I always refer to your site when ever i start new topic. Thank You Thanks. Can I build that model by Indonesian language? Sure. Nice post. Very easy to understand and very informative. Thanks. I have questions regards similarity. If I apply w2vec to convert words to vectors. How I can find similarities between words. I know I can use most. Similar() function to find similarity for specific word but How I can achieve that among all words in documents. Perhaps iterate over all words and calculate similarity manually to all other words in the vocab (e.g. write two for-loops). Why wold you want this? One more questions. Can I apply w2vec to convert unigrams and bigrams to vectors ? It might be easier to learn a bigram model and a unigram model separately, and if still needed, learn a mapping between them (e.g. a model). Thanks Jason for amazing blog! Do you know any paper or implementation of the bigram embedding? Not offhand, sorry. Thanks for replying! No problem. Hello, Jason i have a question about the selection of dimensions of word vectors.let say 300-dimensions they will be same for all words? On which criteria we select these dimensions? Yes, all words will have the same dimensionality. Hi, it might be silly question but the sentences you pass to Word2Vec to train on ,they consist of all the sentences (i.e. train,validate as well as test) right? Also when you create an embedding matrix/dictionary for your sentences,it should also contain the words of test sentences? Thirdly when evaluating the model,test sentences would also be converted to sequences or integers? Thanks Yes, sentences are split, then encoded for use in modeling. The training dataset should be representative of the broader domain. This applies generally, not just in NLP. Thank you for this nice tutorial. is there a way to revert the word embedding transformation ? I am feeding the embedded matrix ‘ X = model[model.wv.vocab]’ to an autoencoder model. I will get also as result a matrix. I want to interpret that matrix by applying the inverse word2vec transformation so I can compare the input to the output results. Any ideas ? Sure, you could search for the closest one or set of vectors for a given vector. Thank you for the reply. But can you explain more. Did you mean something like this : for i in range(len(X)): inverted.append([argmax(decoded_tags[i, :])]) You can use a distance measure like euclidean distance or dot product to find the closest vectors. Can you provide an example please ? or a link that can help me do that I’m eager to help, but I don’t have the capacity to write custom code for you, I explain more here: Hi Jason, the tutorial was awesome as the others, but tell you the truth when I applied your commands : model = Word2Vec(sentences, min_count=1) words = list(model.wv.vocab) print(words) it works fine when I use your dataset, but when I apply my own dataset which structure is such as this: a folder which name is diseases, in this folder I have 2 sub-folder which are blood cancer and breast cancer. in each subfolder such as blood cancer, there are many txt files which include at least 20 sentences, unfortunately when I apply your commands model = Word2Vec(vocab_dic, size=100, window=5, workers=8, min_count=1) and words = list(model.wv.vocab) print (‘words’ , words) the printed words are as follows:’] whereas I expect to have words instead of charachters. I know you do not have the capacity to write custom code for me or check everyone’s commands but please look at my few commands to find out the problem as I am a beginner ans I have already tried to find it but I could not. I use keras in ubuntu 17.10 to write commnads breast= glob.glob(‘/home/mary/.config/spyder-py3/BinaryClassClassification/breastcancer/*.txt’) blood=glob.glob(‘/home/mary/.config/spyder-py3/BinaryClassClassification/bloodcancer/*.txt’) breast_samples_text = [load_file(file) for file in breast] bloodـsamples_text= [load_file(file) for file in blood] vocab_dic = breast_samples_text + blood_samples_text model = Word2Vec(vocab_dic, size=100, window=5, workers=8, min_count=1) words = list(model.wv.vocab) printed words are as these:’] waiting for your answer as I need it necessarily. Best Regards Maryam I believe your data is in a different format. Perhaps focus on data loading and confirm the data in memory has the same structure as the data in the tutorial first? import re from nltk.tokenize import TweetTokenizer, sent_tokenize tokenizer_words = TweetTokenizer() tokens_sentences = [tokenizer_words.tokenize(t) for t in nltk.sent_tokenize(text)] Use this piece of code and you’ll get the output you wanted. I had the same issue as you Hi Jason, I have modified it with this command and gave me a correct output::[ def load_file(file_name): cleaned_txt = re.sub(“[^a-zA-Z]+”, ” “, open(file_name, ‘r’, encoding=”utf8”).read()).lower() return cleaned_txt def gen_vocab_dic(all_text): voc = set() for record in all_text: for word in record.split(): voc.add(word) voc_dic = {} index = 1 # we start from 1 for i in voc: voc_dic[i] = index index = index + 1 return voc_dic,voc breast= glob.glob(‘/home/mary/.config/spyder-py3/Dataset#2_BinaryClassClassification breasrcancer_disease/*.txt’) bloodcancer=glob.glob(‘/home/mary/.config/spyder-py3/Dataset#2_BinaryClassClassification/bloodcancer_disease/*.txt’) breast_samples_text = [load_file(file) for file in breast] bloodـsamples_text= [load_file(file) for file in blood] vocab_dic = gen_vocab_dic(breast_samples_text + bloodـsamples_text) model = Word2Vec(vocab_dic, size=100, window=5, workers=8, min_count=1) words_list = list(model.wv.vocab) print (‘words_list’ , words_list)== ‘subcategory’, ‘disproportionally’, ‘alen’ and etc. but I do not know how i can refer the label of each class to each word? in other words How to tag any sample which belongs to each class? I have already provided x_train or x_ test but I do not know how I should provide y_dataset ?? Jason, please help me with this kind of dataset as I have never seen a tutorial to teach word2vec for this kind of structure for a dataset. the structure of my dataset is as follows: a folder which name is diseases, in this folder I have 2 sub-folder which are blood cancer and breast cancer. in each subfolder such as blood cancer, there are many txt files which include at least 20 sentences, as I mentioned in the latter post. waiting for the reply as I need it and sorry to ask you the request. Best Maryam Sorry, I don’t know about your prediction problem. Perhaps you could summarize it for me? How do you decide how many negative words to use? which is the criteria? What do you mean exactly? Hi Jason, thank you for offering us one of the best tutorials about word2vec. but I think there is a limitation in your tutorial as follows: when you create a model via word2vec such this: model = Word2Vec(sentences, size=100, window=5, workers=8, min_count=1) you should have explained how we are able to apply vectors of words after embedding them by word2vec model. for example, when we use embedding keras layer, z = Embedding(vocab_dic_size, 100, input_length=seq_length, name=”embedding”) we can apply in this way. but I do not know how i can use the model which you created by word2vec in order to embed words and giving them weights?? sorry I got confused so if you write an instance about using the model = Word2Vec( ) like the example I wrote above by keras embedding layer, It will be a great guidance as I have already searched about it but I did not understand. I am sorry to write a big comment such as this but plz consider that I a beginner and found your tutorial as the best one in clearness. I show how to fit the model ten make predictions with the in this tutorial: Hi. I am a newbie in data science & going through your post I think you are the best person who can guide me for my project. I want to create a dictionary that incorporates all the words related to gold-market for which I am collecting text of 1000 articles on gold-news. Can word2vec be used for this situation as simple word tokenization won’t help. Perhaps you can extract all words from all articles, then see which are the 1000 most frequently used across all articles? Hi Jason, I love your articles. I built the following comparison for different document representations. Your feedback will be appreciated. I don’t have the capacity to review and debug your code sorry. Hey, The article is a great help. Thanks. I require to train a RNN for classification of Name, Address, Age, DOB etc. from raw OCR output of an identity card. I want the classifier to be generic and work on most kind of id’s. As names, address etc. won’t be available in a pre-trained model, I decided to train my own word embedding. I have around 50 variants of ID cards and will be generating training data from those by altering details in it. I find out someone did similar – “We hash the text of the word into a binary vector of size 2^18 which is embedded in a trainable 500 dimensional distributed representation using an embedding layer” So I understand the “Word Hashing” part, but how they embedded those binary feature vectors in a 500 dims., I mean how will your convert those 2^18 dims. features to 500 dims. Your help would be really appreciated. Please suggest some other alternative if you have. Perhaps this intro on word embeddings will help: I have got caught up in a really results of gensim Word2Vec. I have formatted the question and asked here: . would it be possible to train gensim on multiple languages and still get the right similarity result? My Result says no. Also I want to ask that the random weights when we train Word2Vec from gensim, do they remain same or they change every time we train the model ? I don’t know about cross-language models. Sounds like deeper thought is required. Weight are learned via training on the provided dataset. what is the “alpha” in those code? tell me more about that. “alpha” is initialized “0.025” . what is the use of that ? I am building a domain-specific word2vec model using more or less the same steps. Given a word, I know what the similar words should be. I also don’t have a dataset. What I am doing is trying to overfit the model based on very small variations. When I plot thegraph, I see that the words I need are grouped together. For eg, words a,b and c are grouped together in a single cluster. So I assume when I input a, I should get b and c as the similar words. However, words farther away from the cluster in question have a better score and are displayed first. How can I change this behaviour? Any help is appreciated. Thanks The model has parameters, try tuning them and see if they have a desired effect? Perhaps you need new/different training data? Perhaps your assumptions or scoring have flaws? Hi Jason, Thank you for your awesome tutorials. I have a question about dimensions of vectors. Can we visualize the dimensions. Kindly guide me. What do you mean exactly? All vector have the same dimensions. If you mean visualize the word vectors, the above tutorial shows you how. Hi, word2vec or Glove algorithm its usefull for non-english word/language (i.e.Russian) Yes, as long as you have the data to train it. I am trying to built a “text classifier” where I am trying to categorize it into two classes. I have created the model using word2vec but how can I use the model to predict the other data. Other models like SVM, logistic regression have “predict” to do the work but word2vec doesn’t have it. Any way that we can use word2vec along with SVM to use it? The word2vec vectors can be used as an input to any model, including an SVM. I don’t have a worked example, sorry. Hi Jason, Would Word2Vec provide us with a vector if a new word out of corpus is given as input to the model trained with a set of corpus. Thanks No, new words cannot be mapped. Can we give input as word vectors created by word2Vec algorithm to LDA modal training ? Let me know. Thank you in advance !!! Maybe, I don’t know sorry. How to prepare input for large corpus? I have a csv file with 50k arcticles (each row with an article). As mentioned in , Keeping the input as a Python built-in list is convenient, but can use up a lot of RAM when the input is large. Perhaps load articles into memory progressively in order to prepare them, instead of all at once. Is it possible to define my own loss function? In Gensim? Perhaps. I would recommend checking the API documentation. Mr. Jason I am working on a Project that does sentiment analysis on the social media platforms and helps in the detection of cyberbullying, can u tell me if I need to train my own word vectors or the GLoVe pre-trained word Vector on twitter tweets will do? I recommend try both approaches and see what works best for your specific dataset. Tthank you very much for your explanation. I have a question please. Once we got the model how can we extract the vectors of a list of words? I show in the above tutorial how to extract vectors for words. Hey, i want to have word embedding for a tagged corpus which is not in English but an Indian language. how to do that using gensim? Sorry, I cannot help you with this. nice post man. I do have a question can we check a whole new document for a word such as “java” with the trained word2vec model? I don’t understand sorry, can you elaborate? Hi Mr Jason,I’m working on the project sentiment analysis (categorization of aspects and their polarities in comments) and i use deep learning and skip-gram model of word embedding can you help me, i need some tutorials for these approaches . Does the above tutorial help? What problem are you having exactly? Hey Jason, I am having this code : I am getting data in this format I want to apply word2vec on data coming in filename only . how can i do that? Sounds like a simple programming question, rather than an ML question? Perhaps post your code and error to stackoverflow? hi Jason, thanks for your tutorial. Very well explained. I just wanna ask you one thing about my use-case. I have a corpus of 1.8k sentences, with a vocabulary of 2k words. Do you think are enough to train my own custom embedding with Gensim, or it’s better to use a pre-trained model? because i’ve trained it (with gensim Fast-text), passing then the weights in thekeras embedding layer (trainable=True) with a Conv1D layer. I got very good results. Is it possible despite i have a small corpus? because usually these embedding are trained on very large vocabulary. Thanks in advance for your answer Perhaps try it and compare results to using a Keras learned embedding? Fast-text pre-trained embedding –> 89 % of accuracy Fast-text learning embedding with my own corpus with gensim train –> 93 % accuracy it seems despite my corpus it’s not enough big, learning an embedding from scratch lead to better results. So thanks, i discovered that Fast-text using n-gram gives better results also with small vocabulary. Nice finding, thanks for sharing. result = model.most_similar(positive=[‘man’,’woman’], negative=[‘beer’], topn=1) print(result) [(‘victim’, 0.7144894003868103)] really?? 🙂 That is surprising (if it was a real result)! Remember the model and in turn the results are only as good or bad as the data used to train it. Hello, The post is very informative which i used to develop a model in python using keras. Later i want to use this model in java. I) from gensim.models import KeyedVectors glove_w2vec = KeyedVectors.load_word2vec_format(‘glove.word2vec’, binary=False) I want to reproduce the same in java as well. I tried using dl4j how to start page. But i keep getting errors such as 1. no jnind4jcpu in java.library.path 2.no jnind4jcpu in java.library.path . I am not able to find solution anywhere.It would be very useful if you could help me with this if possible. Perhaps load it in python then save it in a format that is easier for you to read in Java? how i calculate the “average” word in sentence by using Word2Vec that is already trained model Retrieve the vector for each word and calculate their average. Hi, I see that this post was posted on October 6, 2017. Is it still up to date now? i.e. Gensim is still the way for developing your own word embedings? In the examples of the blog the list of sentences with separated words is of course a small one. you point out that when thre is a lot of data an iterator can be use. That would be normally the case, i.e. a lot of data. The devil is in the details and I dont find in the net an example of code build as iterator passing sentences to word2vec model constructor. The other thing that might be helpfull is how to know a bit about the practicalities of how to proceed when the calculation of the embedings are going to take many many hours, bucause it might be worth to save now an again what is already calculated just in case “SOMETHING HAPPEND”, am I right? thanks Yes. Also Keras for learned embeddings in deep learning models: Great suggestion, thanks. Hi I have a question about the plot that built based on W2V. It is not clear for me that what is axis? They are a unit less, e.g. eigenvectors or a projection of the data. Hi Jason, First, I’d like to thank you about this useful tutorial. I know the difference between both the cbow and the skip gram. However, I want to ask you about the difference between developing the embedding matrix in gensim using cbow and skip gram. What do you mean exactly? The difference between the algorithms? I mean the difference between using word2vec with cbow and using word2vec with skip gram The difference is the choice of algorithm used to prepare the distributed representation. Sir , what to do if a word is not present in one of these pre trained models? It throws an error saying , word not in vocabulary You can mark unknown words as “0” or unknown. Hi Jason, Are there APIs available to use the word2vec (generated using gensim) with various sklearn classifiers (not keras neural networks with embedding layer) like MultinomialNB, MLPClassifier etc.? Not as far as I know. Hi Jason, thanks for the amazing tutorial. Is it possible to update your tutorial with a snippet that can visualize the GloVe embeddings in 2d without converting them to Word2Vec? You could extract the vectors and create a PCA projection directly. By the way, do you have a tutorial for skipgram with negative sampling? I read it is significantly better than GloVe. I don’t believe so, sorry. first of all, thank you very much for such an awesome article then I want to cluster the vocabularies based on similarities from top to bottom any idea is appreciated. Sorry, I don’t have tutorials on clustering. Perhaps in the future. Thank you for this amazing article. I am getting some warning in code. and while plotting, my corpus words are not visible. getting warning on this line as: X = model[model.wv.vocab] DeprecationWarning: Call to deprecated __getitem__(Method will be removed in 4.0.0, use self.wv.__getitem__() instead). and while plotting: RuntimeWarning: Glyph 2414 missing from current font. What I need to do to resolve it? You can ignore them for now. dear Jason thank you so much for a awesome explanation. i have a doubt on:if we do in coding such as model = Word2Vec(sentences, min_count=4) and model = Word2Vec(sentences, min_count=3) will give the same result for vector representation of that example you have taken? No, it is a stochastic method and will give different vectors each time it is run. how could I convert my dataset to be in the same sentences format, I mean the senetences separated by column and each sentence in [], and the sentences words are tokenize? This tutorial will help you prepare your data: I read in one of your articles how to print both predicted labels and actual labels, but I forgot in which one, could you please show me that portion of code, or that article..please? thank you, you are my inspirational Sure, when you say labels, what are you referring to exactly? Embeddings? Class labels? class labels I want to see where the misclassification happens… You can predict classes with model.predict_classes() then print the value. Perhaps this will help: I trained my own word2vec model on my own dataset, I run the same code twice, in each time the vector of the same word has a different value, is this acceptable or not? e.g. the word “country” appear in the first run with values [-0.019637132 0.041940697 -0.06441503 0.0151868425 0.011437362 0.05516808 0.030604098 ….] and second, run with values: [-0.026120335 0.032587618 0.12853415 0.026889715 -0.02893926 0.013117478 0.06197646 …] Yes, this is to be expected. Why it is expected, I am looking to create my own word2vec model, like Glove and Google word2vec. However, if it is expected to get different vector for the word each time I run the code on the same dataset without any change in the code, why they make it general or universal? I meant if Google and Glove run their code multiple times and they have got a different vector for the same word why they make their model general? it seems that they have the same vector for the word each time, but I have extracted the wrong vector for my words…there is something wrong, I followed exactly your way (4. Train word2vec Embedding) and at the end, I added this code to save the words and their corresponding vectors: model.wv.save_word2vec_format(’embedding_word2vec_Mydata.txt’, binary=False) and each time I run it I got a different vector for the same word, I feel like I missunderstand something … sorry for this long question, Thanks, prof.Jason They are stochastic algorithms, they give a different result each time they are run, but the same general patterns on average. The methods learn the general patterns in slightly different ways each time the code is run. Hi Jason, can you help me understand, when to use Word2Vec and for what purpose(i mean for cases like sentiment analysis, text classification). and i also wanted to know how to convert word2vec into doc2vec in a simplest way. this will be of great help to me. thanks. Word2Vec is a distributed representation for words, useful whenever you have words as input to your model. I can’t help you with doc2vec, I don’ have examples yet sorry. Hi Jason, Do you have an example on how to train your own word embeddings on Glove model? Thanks Not at this stage. I trained my own word2vec on 200000 sentences corpus, then I trained it on a 1 million sentence corpus, I am working on a classification problem using your tutorial, surprisingly the f1-score of my deep model remains the same… even though the corpus size becomes very large. what could be the problem? Well done! Perhaps the word2vec you trained does not add value to the model? Hi, How to use the created models using word2vec? I created a word2vec model but iam not able to find the syntax to find the score of other words by using this model. Can you explain me once. What do you mean “the score”. a word2vec will return a vector for each word, not a score. Do you have any tutorial of using word2vec with machine learning like SVM,LR..? I don’t think so, off hand. I need the source code. How can i download the code? See this: hi, what if I only want to plot those words that occur at least n times overall sentences. Also how do I make the plot bigger such that you can actually see whats happening? You can use an if-statement on the frequency counts of the words. You can specify the size to matplotlib, perhaps check the API documentation. How can I do the same if I store the glove file on s3? Perhaps try it and see? There’s a memory issue when you try to read the object the traditional way using file.get()[‘Body’].read() Will try some way to streamread it if possible Good luck! Hi jason, It would be very helpful for me if you give some examples in python to find semantic similarity between the medical terms. I am building disease predictor in nlp. For example,I want to find whether “fever” and “high temperature” or “fever” and “raise in temperature” are same. This is not possible with ordinary similarity measures. Please help me out. Eagerly expecting your reply. Thanks in advance Why not start with euclidean distance between the word vectors? Or if you mean because you have single word to multiple words, perhaps check the literature on word vectors to see how this case is handled? I don’t recall off hand sorry. A word like “of ” do not exist in the model of google is it normal ? Super common connecting words are often removed. They add little. okay thank you Dear Jason Thanks for this interesting post. You mentioned “Rather than loading a large text document or corpus from file, we will work with a small, in-memory list of pre-tokenized sentences”. I run your code by loading the content of a text-file (each line with a sentence), but in this case, as the output put of print(words), letters are printed instead of words. Do you have any idea why it happens? Sorry to hear that, perhaps this will help: Thanks. I know it is not reasonable to ask you debug our codes. Therefore I will do my best to find the error and I am sure I will. Good luck! Thanks for your positive energy. I solved the error by the help of stackoverflow! My mistake was using sentences = “” instead of sentences = [] before loading the content of my textfile into sentences variable. Well done! Hi Jason, Thanks for this wonderful tutorial! How can I use the below array you used above to train a neural network? [ -4.61881841e-03 -4.88735968e-03 -3.19508743e-03 4.08568839e-03 -3.38211656e-03 1.93076557e-03 3.90265253e-03 -1.04349572e-03 4.14286414e-03 1.55219622e-03 3.85653134e-03 2.22428422e-03 -3.52565176e-03 2.82056746e-03 -2.11121864e-03 -1.38054823e-03 -1.12888147e-03 -2.87318649e-03 -7.99703528e-04 3.67874932e-03 2.68940022e-03 6.31021452e-04 -4.36326629e-03 2.38655557e-04 -1.94210222e-03 4.87691024e-03 -4.04118607e-03 -3.17813386e-03 4.94802603e-03 3.43150692e-03 -1.44031656e-03 4.25637932e-03 -1.15106850e-04 -3.73274647e-03 2.50349124e-03 4.28692997e-03 -3.57313151e-03 -7.24728088e-05 -3.46099050e-03 -3.39612062e-03 3.54845310e-03 1.56780297e-03 4.58260969e-04 2.52689526e-04 3.06256465e-03 2.37558200e-03 4.06933809e-03 2.94650183e-03 -2.96231941e-03 -4.47433954e-03 2.89590308e-03 -2.16034567e-03 -2.58548348e-03 -2.06163677e-04 1.72605237e-03 -2.27384618e-04 -3.70194600e-03 2.11557443e-03 2.03793868e-03 3.09839356e-03 -4.71800892e-03 2.32995977e-03 -6.70911541e-05 1.39375112e-03 -3.84263694e-03 -1.03898917e-03 4.13251948e-03 1.06330717e-03 1.38514000e-03 -1.18144893e-03 -2.60811858e-03 1.54952740e-03 2.49916781e-03 -1.95435272e-03 8.86975031e-05 1.89820060e-03 -3.41996481e-03 -4.08187555e-03 5.88635216e-04 4.13103355e-03 -3.25899688e-03 1.02130906e-03 -3.61028523e-03 4.17646067e-03 4.65870230e-03 3.64110398e-04 4.95479070e-03 -1.29743712e-03 -5.03367570e-04 -2.52546836e-03 3.31060472e-03 -3.12870182e-03 -1.14580349e-03 -4.34387522e-03 -4.62882593e-03 3.19007039e-03 2.88707414e-03 1.62976081e-04 -6.05802808e-04 -1.06368808e-03] What do you mean? hi small doubt about Gensim train words some times how to handle this words machine learning ,artificial intelligence words how to spaces handling? please any one help me model.wv.most_similar(“Artificial intelligence”) KeyError: “word ‘Artificial intelligence’ not in vocabulary” how two words handling please help me We typically remove spaces and just model the words. Hi Jason, I experimented with your code using the gensim library, the pca dimensional reduction and the visualization. I modified it a bit and fed it with the german play ‘Faust I’ from Goethe and visualized some interesting words like Himmel (heaven), Hölle (hell), Gott (god), Teufel (devil) and so on and was curious, what kind of neighbor relations I would see. First of all I was surprised that the 2d mapping changed on every run, even changing what was lying next to each other. So, I changed the pca command by defining the solver: pca = PCA(n_components=2, svd_solver=’full’). This led to more stability in the neighbor relations, but did not give a unique result. Actually, I do not really understand, why this is so. Generally, I was a bit disappointed that my expectations like finding the devil close to the hell did not work out. Obviously, the maths behind the vectorization is not as philosophical as I hoped it would be. Anyway, great tutorial! Thanks! Nice investigation! Perhaps the dataset is too small or the choice of the configuration for the model needs tuning to give a more stable model over multiple runs. Best things are always free… Thank you Dr Jason. You explain the things in a very simple and effective way. Thanks! Can you convert the tutorial to GenSim 4? Here are some things that needs to be updated: #GenSim 3 #words = list(model.wv.vocab) #GenSim 4 words = model.wv.index_to_key #GenSim 3 #print(model[‘sentence’]) #GenSim 4 normed_vector = model.wv.get_vector(“sentence”, norm=True) # GenSim 3 #X = model[model.wv.vocab] # GenSim 4 X = model.wv.get_normed_vectors() Here is an example:
https://machinelearningmastery.com/develop-word-embeddings-python-gensim/?utm_campaign=&utm_source=&utm_medium=&utm_content=
CC-MAIN-2021-04
refinedweb
6,908
66.13
The correlation coefficient is a way to determine the strength of the linear association between two variables, such as "X" and "Y." The correlation will always be between the numbers "-1" and "1." If the correlation is negative, then there is a negative relationship. If the correlation is "0," then there is a neutral relationship. If the correlation is positive, then there is a positive relationship. Write out the numbers of the "X" and "Y" values you want the correlation coefficient of: X Values Y Values 20 4.1 21 4.6 Count the total number of "X" and "Y" values; in this case, there are four, so "N"=4. Multiply "X" by "Y," "X" by "X" and "Y" by "Y" for all four values with a calculator: XY=204.1=82 XY=214.6=96.6 XX=2020=400 XX=2121=441 YY=4.14.1=16.81 YY=4.64.6=21.16 Add up the "X" values, the "Y" values and all of the multiplied "X" and "Y" values; find the square roots of the "X" and "Y" values and add them together: X+X=20+21=41 Y+Y=4.1+4.6=8.7 XY=204.1=82 and XY=214.6=96.6 and 82+96.6=178.6 XX=2020=400 and XX=2121=441 and 400+441=841 YY=4.14.1=16.81 and YY=4.64.6=21.16 and 16.81+21.16=37.97 Plug the numbers into the formula (r) =[ NΣXY - (ΣX)(ΣY) / Sqrt([NΣX^2 - (ΣX)^2][NΣY^2 - (ΣY)^2])] and make the calculations with the calculator: Correlation(r)=((4)(178.6)-(41)(8.7)) / square-root ([4)(841)-(4141)][(4)(37.97)-(8.7*8.7)]) Correlation(r)=(714.4-356.7) / square-root ([3364-1681)*[151.88-75.69) Correlation(r)=357.7 / square-root (1683*76.19) Correlation(r)=357.7 / square-root (128227.77) Correlation(r)=357.7 / 358.089 Correlation(r)=0.9989 Tips & Warnings - Use a square root calculator, such as Math.com's, to get the square roots of large numbers; simply enter the number and press "Calculate," and the square root will appear. - Remember to plug the numbers you get from the calculator into their correct places within the formula; you won't get the proper correlation coefficient otherwise, and any number you get that is either below -1 or above 1 is an incorrect coefficient. Related Searches References Resources You May Also Like - How to Sketch the Graph of Square Root Functions, ( f(x)=√ x ) This Article will show how to Sketch the graphs of Square Root Function by using only three different values for ' x... - How to Calculate Correlation Coefficient Between Two Data Sets The correlation coefficient is a statistical calculation that is used to examine the relationship between two sets of data. The value of... - How to Calculate Spearman Rho and Kendall Tau Coefficients in SPSS or R The Spearman and Kendall rank correlation coefficients are well-known methods for quantifying correspondences between lists of ordinal data. How are they calculated,... - How to Compute the Spearman Rank Correlation Coefficient Spearman's Rank Correlation Coefficient is a number between -1 and +1 that represents the strength of the relationship between two variables in... - How to Calculate IRR on an HP-12c Calculator Businesses use internal rate of return (IRR) to calculate potential return rates for projects and thus compare two or more projects. If... - How to Calculate the Correlation Between Two Variables The correlation between two variables describes the likelihood that a change in one variable will cause a proportional change in the other... - How to Calculate Correlation Coefficients on the TI-83 British Prime Minister Benjamin Disraeli famously said, according to Mark Twain, "There are three kinds of lies: lies, damned lies and statistics."... - How to Calculate the Significance of a Correlation Coefficient A correlation coefficient, r, is a number between -1 and +1 that indicates an idea of the strength or degree of a... - How to Extract the Square Root Solution A square root is any mathematical expression which contains the √ or radical symbol. The number in the radical is called the... - How to Find Correlation Coefficient & Coefficient of Determination on the TI-84 Plus The TI-84 Plus is one of a series of graphic calculators made by Texas Instruments. In addition to performing basic math functions,...
http://www.ehow.com/how_8156739_calculate-coefficient-correlation-calculator.html
CC-MAIN-2017-04
refinedweb
735
55.34
Question: I've noticed that if you try to send an email to an invalid address, an exception is raised: MailAddress To=new MailAddress("invalidemailaddress","recipientname"); throws: "The specified string is not in the form required for an e-mail address" This means that there must be a .Net function which is executed in MailAddress to check if the email address is valid or not. Is there a way to call this 'validate' function directly? This way I won't need to create my own IsValid function. Solution:1 Yes, there is such a .Net function, but its functionality is unaccessible by "standard" means: MailAdress uses a private ParseAddress method, which in turn uses System.Net.Mime.MailBnfHelper. The latter is an internal class, so it's not (easily) accessible outside the framework itself. Thus, the only way to use these functions would be to use reflection, which I strongly advise against. Since these functions are undocumented and unaccessible without reflection, their implementation might change and your code might break in future versions of the framework. Solution:2 No but you can make one: public bool ValidateEmailAddress (string email) { if (string.IsNullOrEmpty (email)) return false; try { MailAddress to = new MailAddress (email); return true; } catch (WhateverException e) { return false; } } Answering comments. I am aware this technique is regarded as a bad one and with reason. What I would like to point out is that this approach will give you 100% guarantee the .NET mailing library will be able to send to a validated address lately. The problem with Regexes (of which there are plenty) is that each one addresses one particular subset of the set of technically correct addresses as per specification. One would be narrower, the other one would be wider than the subset defined internally in .NET. If you were to use Regex validation, then in the first case your Regex would cut off a portion of the valid addresses (as seen by .NET), in the latter case the validaton will let through addresses that the .NET mailing library won't treat as invalid per its own internal validation. The one true way to make sure you valid set 100% matches the .NET set (or of any other third party library you would use) is to fall for the try/catch approach, unless of course this third party library offers some validation method already. Solution:3 There's a good example of an email validation function on CodeProject. Original Source Code written by Vasudevan Deepak Kumar: public static bool isEmail(string inputEmail) { inputEmail = NulltoString(inputEmail); string strRegex = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" + @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" + @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$"; Regex re = new Regex(strRegex); if (re.IsMatch(inputEmail)) return (true); else return (false); } Solution:4 Unfortunately, there is no way to get at that functionality without reverse-engineering it or using that specific exception, sadly. The traditional way to validate an email address has always been with regular expressions, but there are lengths you can go beyond that to validate emails even further, if you so wish: The Forgotten Art of Email Address Validation Solution:5 You could write your own class: class EmailAddress { private MailAddress _email; public string Address { get { return _email == null ? string.Empty : _email.Address; } } public string DisplayName { get { return _email == null ? string.Empty : _email.DisplayName; } } public string Host { get { return _email == null ? string.Empty : _email.Host; } } public string User { get { return _email == null ? string.Empty : _email.User; } } public EmailAddress(string email) { try { _email = new MailAddress(email); } catch (Exception) { _email = null; } } public EmailAddress(string email, string displayName) { try { _email = new MailAddress(email, displayName); } catch (Exception) { _email = null; } } public EmailAddress(string email, string displayName, Encoding displayNameEncoding) { try { _email = new MailAddress(email, displayName, displayNameEncoding); } catch (Exception) { _email = null; } } public bool IsValid() { return _email == null ? false : true; } public override string ToString() { return this.Address; } } Now you use it just as MailAddress but there is now no exception when the Email address is not valid. Instead you call the IsValid method: var email = new EmailAddress("user@host.com"); if (email.IsValid()) { ... } else { ... } Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com EmoticonEmoticon
http://www.toontricks.com/2018/02/tutorial-in-aspnet-is-there-function-to.html
CC-MAIN-2018-09
refinedweb
709
53
#include "ltwrappr.h" #include "LTCPDFComp.h" virtual L_INT LPDFCompressor::ImageCallBack (nPage, pSegment) This callback function is called every time a segment is added to the PDF document. Index of the page on which the segment is being written. This is a zero-based index. Pointer to the SEGMENTINFO structure that contains the segment information. This callback is called each time an MRC segment is added to the PDF file in memory, by calling LPDFCompressor::InsertMRC, if LBase::EnableCallBack was set to TRUE. The user should return SUCCESS to add the current segment and continue with the process, or FAILURE, to not add this segment and proceed with the next one. Required DLLs and Libraries For an example, refer to LPDFCompressor::InsertMRC. Direct Show .NET | C API | Filters Media Foundation .NET | C API | Transforms Media Streaming .NET | C API
https://www.leadtools.com/help/sdk/v22/mrc/clib/lpdfcompressor-imagecallback.html
CC-MAIN-2022-27
refinedweb
138
59.4
Many programming languages have a way to tell the compiler that a piece of data is constant. A constant is useful for two reasons: A field that is both static and final has only one piece of storage that cannot be changed.. Heres an example that demonstrates final fields: //: c06:FinalData.java // The effect of final on fields. import com.bruceeckel.simpletest.*; import java.util.*; class Value { int i; // Package access public Value(int i) { this.i = i; } } public class FinalData { private static Test monitor = new Test(); private static Random rand = new Random(); private String id; public FinalData(String id) { this.id = id; } // Can be compile-time constants: private final int VAL_ONE = 9; private static final int VAL_TWO = 99; // Typical public constant: public static final int VAL_THREE = 39; // Cannot be compile-time constants: private final int i4 = rand.nextInt(20); static final int i5 = rand.nextInt(20); private Value v1 = new Value(11); private final Value v2 = new Value(22); private static final Value v3 = new Value(33); // Arrays: private final int[] a = { 1, 2, 3, 4, 5, 6 }; public String toString() { return id + ": " + "i4 = " + i4 + ", i5 = " + i5; } public static void main(String[] args) { FinalData fd1 = new FinalData("fd1"); //! fd1.VAL_ONE++; // Error: can't change value fd1.v2.i++; // Object isn't constant! fd1.v1 = new Value(9); // OK -- not final for(int i = 0; i < fd1.a.length; i++) fd1.a[i]++; // Object isn't constant! //! fd1.v2 = new Value(0); // Error: Can't //! fd1.v3 = new Value(1); // change reference //! fd1.a = new int[3]; System.out.println(fd1); System.out.println("Creating new FinalData"); FinalData fd2 = new FinalData("fd2"); System.out.println(fd1); System.out.println(fd2); monitor.expect(new String[] { "%% fd1: i4 = \\d+, i5 = \\d+", "Creating new FinalData", "%% fd1: i4 = \\d+, i5 = \\d+", "%% fd2: i4 = \\d+, i5 = \\d+" }); } } ///:~ Since VAL_ONE and VAL_TWO are final primitives with compile-time values, they can both be used as compile-time constants and are not different in any important way. VAL_THREE is the more typical way youll see such constants defined: public so theyre usable outside the package, static to emphasize that theres only one, and final to say that its. Just because something is final doesnt when you run the program. Note that the values of i4 for fd1 and fd2 are unique, but the value for i5 is not changed by creating the second FinalData object. Thats because its static and is initialized once upon loading and not each time a new object is created. The variables v1 through v3 demonstrate the meaning of a final reference. As you can see in main( ), just because v2 is final doesnt mean that you cant change its value. Because its a reference, final means that you cannot rebind v2 to a new object. You can also see that the same meaning holds true for an array, which is just another kind of reference. (There is no way that I know of to make the array references themselves final.) Making references final seems less useful than making primitives final.. Heres an example: //: c06:BlankFinal.java // "Blank" final fields. class Poppet { private int i; Poppet(int ii) { i = ii; } } public class BlankFinal { private final int i = 0; // Initialized final private final int j; // Blank final private final Poppet p; // Blank final reference // Blank finals MUST be initialized in the constructor: public BlankFinal() { j = 1; // Initialize blank final p = new Poppet(1); // Initialize blank final reference } public BlankFinal(int x) { j = x; // Initialize blank final p = new Poppet(x); // Initialize blank final reference } public static void main(String[] args) { new BlankFinal(); new BlankFinal(47); } } ///:~ Youre forced to perform assignments to finals either with an expression at the point of definition of the field or in every constructor. That way its guaranteed that the final field is always initialized before use.); } } ///:~ The methods f( ) and g( ) show what happens when primitive arguments are final: you can read the argument, but you can't change it. This feature seems only marginally useful, and is probably not something youll use.
http://www.linuxtopia.org/online_books/programming_books/thinking_in_java/TIJ308_012.htm
CC-MAIN-2015-40
refinedweb
674
53.81
On 2/2/11 6:40 PM, Alex Karasulu wrote: >. Note : The control OID and visibility fields are common to every controls. We decided to hide the value, and we don't expose the getValue() setValue() and hasValue() in the Control interface. >(); > } The OID does not have to be exposed this way. The Subentries implementation can also have a constructor like : public class SubentriesImpl extends AbstractControl implements Subentries { private String OID = "..."; public SunbentriesImpl() { super( OID ); } } Note that I extend AbstractControl, but we could also decide to extend BasicControl. But that's not the point. Let me comment further later in this mail. >. Well, my vision is that we have a couple of Interface/Implementation for every specific control : ManageDsaITImpl implements ManageDsaIT etc... The only class we don't have this is the BasicControl class which is not a final class and does not have an interface except the Control interface. In fact, it's also used as a parent class for some of the controls, but not for all of them (most certainly an error) : public class ManageDsaITImpl extends BasicControl implements ManageDsaIT public class BasicControl implements Control public interface ManageDsaIT extends Control and for a control with a Value part (well, once encoded, not in the real control, as the value is expressed through some additional fields in the specific control): public class EntryChangeImpl extends BasicControl implements EntryChange public class BasicControl implements Control public interface EntryChange extends Control What bother me here is that someone who wants to create a new control (with or without additional fields) must instanciate a BasicControl directly, and we won't be able to make a difference between such a control and another specific control except by checking its OID. Making the BasicControl an Abstract class, and creating a ControlImpl class for 'opaque' controls make it easier. Doing a (control instanceof ControlImpl) will filter out all the specific controls, while (control instanceof BasicControl ) won't make a difference between all the specific controls and opaque ones. > . To me, this OpaqueControl will be the ControlImpl. No need to call it Opaque, which carries some weird semantic, IMO. But yes, we need such a class (whatever its name is) > (2) For case #2 above, create a concrete Control implementation > class called BaseControl. This control should be part of the codec SPI > instead of in the model. It should not even be exposed by the codec > API IMO. BaseControl in the codec ??? I'd rather have an Abstract control class, which won't be instanciated. Such a class is not part of the Codec package, I think. > > APPROACH BENEFITS > ------------------------------------ > > o Users intuit the OpaqueControl is one whose value cannot be handled. Agreed. > o The final OpaqueControl class prevents users from accidental extension. Well, we may allow a user to extend this class. Not sure... >. Agreed. > o The BaseControl is hidden and can only be used by codec > extenders as part of the SPI Again, I don't see why we should hide the BaseControl in the codec. We already have decorators for that. And if this OpaqueControl has a getValue() setValue() methods, the getValue() method will return a byte[], so it does not need to have a specific encoder/decoder. Although we need to create an OpaqueControlDecorator to manage the envelop encoding. > o When the codec cannot handle a control it creates the OpaqueControl type. Agreed. > On another note we might need a final OpaqueControlDecorator which > does not need to keep a value member as it's own member but can access > the value via OpaqueControl.getValue(). Absolutely. -- Regards, Cordialement, Emmanuel Lécharny
http://mail-archives.apache.org/mod_mbox/directory-dev/201102.mbox/%3C4D499ED4.3040406@apache.org%3E
CC-MAIN-2016-07
refinedweb
594
52.6
Python library for efficient multi-threaded data processing, with the support for out-of-memory datasets. “There were 5 Exabytes of information created between the dawn of civilization through 2003, but that much information is now created every 2 days”:Eric Schmidt If you are an R user, chances are that you have already been using the data.table package. Data.table is an extension of the data.frame package in R. It’s also the go-to package for R users when it comes to the fast aggregation of large data (including 100GB in RAM). The R’s data.table package is a very versatile and a high-performance package due to its ease of use, convenience and programming speed. It is a fairly famous package in the R community with over 400k downloads per month and almost 650 CRAN and Bioconductor packages using it(source). So, what is in it for the Python users? Well, the good news is that there also exists a Python counterpart to the data.table package called datatable which has a clear focus on big data support, high performance, both in-memory and out-of-memory datasets, and multi-threaded algorithms. In a way, it can be called as data.table’s younger sibling. Datatable Modern machine learning applications need to process a humongous amount of data and generate multiple features. This is necessary in order to build models with greater accuracy. Python’s datatable module was created to address this issue. It is a toolkit for performing big data (up to 100GB) operations on a single-node machine, at the maximum possible speed. The development of datatable is sponsored by H2O.ai and the first user of datatable was Driverless.ai. This toolkit resembles pandas very closely but is more focussed on speed and big data support. Python’s datatable also strives to achieve good user experience, helpful error messages, and a powerful API. In this article, we shall see how we can use datatable and how it scores over pandas when it comes to large datasets. Installation On MacOS, datatable can be easily installed with pip: pip install datatable On Linux, installation is achieved with a binary distribution as follows: # If you have Python 3.5 pip install # If you have Python 3.6 pip install Currently, datatable does not work on Windows but work is being done to add support for Windows also. For more information see Build instructions. The code for this article can be accessed from the associated Github Repository or can be viewed on my binder by clicking the image below. Reading the Data The dataset being used has been taken from Kaggle and belongs to the Lending Club Loan Data Dataset. The dataset consists of complete loan data for all loans issued through the 2007–2015, including the current loan status (Current, Late, Fully Paid, etc.) and latest payment information. The file consists of 2.26 Million rows and 145 columns. The data size is ideal to demonstrate the capabilities of the datatable library. # Importing necessary Libraries import numpy as np import pandas as pd import datatable as dt Let’s load in the data into the Frame object. The fundamental unit of analysis in datatable is a Frame. It is the same notion as a pandas DataFrame or SQL table: data arranged in a two-dimensional array with rows and columns. With datatable %%time datatable_df = dt.fread("data.csv") ____________________________________________________________________ CPU times: user 30 s, sys: 3.39 s, total: 33.4 s Wall time: 23.6 s The fread() function above is both powerful and extremely fast. It can automatically detect and parse parameters for the majority of text files, load data from .zip archives or URLs, read Excel files, and much more. Additionally, the datatable parser : - Can automatically detect separators, headers, column types, quoting rules, etc. - Can read data from multiple sources including file, URL, shell, raw text, archives and glob. - Provides multi-threaded file reading for maximum speed - Includes a progress indicator when reading large files - Can read both RFC4180-compliant and non-compliant files. With pandas Now, let us calculate the time taken by pandas to read the same file. %%time pandas_df= pd.read_csv("data.csv") ___________________________________________________________ CPU times: user 47.5 s, sys: 12.1 s, total: 59.6 s Wall time: 1min 4s The results show that datatable clearly outperforms pandas when reading large datasets. Whereas pandas take more than a minute, datatable only takes seconds for the same. Frame Conversion The existing Frame can also be converted into a numpy or pandas dataframe as follows: numpy_df = datatable_df.to_numpy() pandas_df = datatable_df.to_pandas() Let’s convert our existing frame into a pandas dataframe object and compare the time taken. %%time datatable_pandas = datatable_df.to_pandas() ___________________________________________________________________ CPU times: user 17.1 s, sys: 4 s, total: 21.1 s Wall time: 21.4 s It appears that reading a file as a datatable frame and then converting it to pandas dataframe takes less time than reading through pandas dataframe. Thus, it might be a good idea to import a large data file through datatable and then convert it to pandas dataframe. type(datatable_pandas) ___________________________________________________________________ pandas.core.frame.DataFrame Basic Frame Properties Let’s look at some of the basic properties of a datatable frame which are similar to the pandas’ properties: print(datatable_df.shape) # (nrows, ncols) print(datatable_df.names[:5]) # top 5 column names print(datatable_df.stypes[:5]) # column types(top 5) ______________________________________________________________ (2260668, 145) ('id', 'member_id', 'loan_amnt', 'funded_amnt', 'funded_amnt_inv') (stype.bool8, stype.bool8, stype.int32, stype.int32, stype.float64) We can also use the head command to output the top ‘n’ rows. datatable_df.head(10) The colour signifies the datatype where red denotes string, green denotes int and blue stands for float. Summary Statistics Calculating the summary stats in pandas is a memory consuming process but not anymore with datatable. We can compute the following per-column summary stats using datatable: datatable_df.sum() datatable_df.nunique() datatable_df.sd() datatable_df.max() datatable_df.mode() datatable_df.min() datatable_df.nmodal() datatable_df.mean() Let’s calculate the mean of the columns using both datatable and pandas to measure the time difference. With datatable %%time datatable_df.mean() _______________________________________________________________ CPU times: user 5.11 s, sys: 51.8 ms, total: 5.16 s Wall time: 1.43 s With pandas pandas_df.mean() __________________________________________________________________ Throws memory error. The above command cannot be completed in pandas as it starts throwing memory error. Data Manipulation Data Tables like dataframes are columnar data structures. In datatable, the primary vehicle for all these operations is the square-bracket notation inspired by traditional matrix indexing but with more functionalities. The same DT[i, j] notation is used in mathematics when indexing matrices, in C/C++, in R, in pandas, in numpy, etc. Let’s see how we can perform common data manipulation activities using datatable: #Selecting Subsets of Rows/Columns The following code selects all rows and the funded_amnt column from the dataset. datatable_df[:,'funded_amnt'] Here is how we can select the first 5 rows and 3 columns datatable_df[:5,:3] #Sorting the Frame With datatable Sorting the frame by a particular column can be accomplished by datatable as follows: %%time datatable_df.sort('funded_amnt_inv') _________________________________________________________________ CPU times: user 534 ms, sys: 67.9 ms, total: 602 ms Wall time: 179 ms With pandas: %%time pandas_df.sort_values(by = 'funded_amnt_inv') ___________________________________________________________________ CPU times: user 8.76 s, sys: 2.87 s, total: 11.6 s Wall time: 12.4 s Notice the substantial time difference between datable and pandas. #Deleting Rows/Columns Here is how we can delete the column named member_id: del datatable_df[:, 'member_id'] #GroupBy Just like in pandas, datatable also has the groupby functionalities. Let’s see how we can get the mean of funded_amount column grouped by the grade column. With datatable %%time for i in range(100): datatable_df[:, dt.sum(dt.f.funded_amnt), dt.by(dt.f.grade)] ____________________________________________________________________ CPU times: user 6.41 s, sys: 1.34 s, total: 7.76 s Wall time: 2.42 s With pandas %%time for i in range(100): pandas_df.groupby("grade")["funded_amnt"].sum() ____________________________________________________________________ CPU times: user 12.9 s, sys: 859 ms, total: 13.7 s Wall time: 13.9 s What does .f stand for? f stands for frame proxy, and provides a simple way to refer to the Frame that we are currently operating upon. In the case of our example, dt.f simply stands for dt_df. #Filtering Rows The syntax for filtering rows is pretty similar to that of GroupBy. Let us filter those rows of loan_amntfor which the values of loan_amnt are greater than funded_amnt. datatable_df[dt.f.loan_amnt>dt.f.funded_amnt,"loan_amnt"] Saving the Frame It is also possible to write the Frame’s content into a csv file so that it can be used in future. datatable_df.to_csv('output.csv') For more data manipulation functions, refer to the documentation page. Conclusion The datatable module definitely speeds up the execution as compared to the default pandas and this definitely is a boon when working on large datasets. However, datatable lags behind pandas in terms of the functionalities. But since datatable is still undergoing active development, we might see some major additions to the library in the future. References - R’s data.table - Datatable documentation - Getting started with Python datatable: A wonderful Kaggle Kernel on the usage of datatable
https://parulpandey.com/2019/06/02/an-overview-of-pythons-datatable-package/
CC-MAIN-2022-21
refinedweb
1,559
59.19
I'm trying to use the Multimapping feature of dapper to return a list of ProductItems and associated Customers. [Table("Product")] public class ProductItem { public decimal ProductID { get; set; } public string ProductName { get; set; } public string AccountOpened { get; set; } public Customer Customer { get; set; } } public class Customer { public decimal CustomerId { get; set; } public string CustomerName { get; set; } } My dapper code is as follows var sql = @"select * from Product p inner join Customer c on p.CustomerId = c.CustomerId order by p.ProductName"; var data = con.Query<ProductItem, Customer, ProductItem>( sql, (productItem, customer) => { productItem.Customer = customer; return productItem; }, splitOn: "CustomerId,CustomerName" ); This works fine but I seem to have to add the complete column list to the splitOn parameter to return all the customers properties. If I don't add "CustomerName" it returns null. Am I miss-understanding the core functionality of the multimapping feature. I don't want to have to add a complete list of column names each time. I just ran a test that works fine: var sql = "select cast(1 as decimal) ProductId, 'a' ProductName, 'x' AccountOpened, cast(1 as decimal) CustomerId, 'name' CustomerName"; var item = connection.Query<ProductItem, Customer, ProductItem>(sql, (p, c) => { p.Customer = c; return p; }, splitOn: "CustomerId").First(); item.Customer.CustomerId.IsEqualTo(1); The splitOn param needs to be specified as the split point, it defaults to Id. If there are multiple split points, you will need to add them in a comma delimited list. Say your recordset looks like this: ProductID | ProductName | AccountOpened | CustomerId | CustomerName --------------------------------------- ------------------------- Dapper needs to know how to split the columns in this order into 2 objects. A cursory look shows that the Customer starts at the column CustomerId, hence splitOn: CustomerId. There is a big caveat here, if the column ordering in the underlying table is flipped for some reason: ProductID | ProductName | AccountOpened | CustomerName | CustomerId --------------------------------------- ------------------------- splitOn: CustomerId will result in a null customer name. If you specify CustomerId,CustomerName as split points, dapper assumes you are trying to split up the result set into 3 objects. First starts at the beginning, second starts at CustomerId, third at CustomerName. Our tables are named similarly to yours, where something like "CustomerID" might be returned twice using a 'select *' operation. Therefore, Dapper is doing its job but just splitting too early (possibly), because the columns would be: (select * might return): ProductID, ProductName, CustomerID, --first CustomerID AccountOpened, CustomerID, --second CustomerID, CustomerName. This makes the spliton: parameter not so useful, especially when you're not sure what order the columns are returned in. Of course you could manually specify columns...but it's 2017 and we just rarely do that anymore for basic object gets. What we do, and it's worked great for thousands of queries for many many years, is simply use an alias for Id, and never specify spliton (using Dapper's default 'Id'). select p.*, c.CustomerID AS Id, c.* ...voila! Dapper will only split on Id by default, and that Id occurs before all the Customer columns. Of course it will add an extra column to your return resultset, but that is extremely minimal overhead for the added utility of knowing exactly which columns belong to what object. And you can easily expand this. Need address and country information? select p.*, c.CustomerID AS Id, c.*, address.AddressID AS Id, address.*, country.CountryID AS Id, country.* Best of all, you're clearly showing in a minimal amount of sql which columns are associated with which object. Dapper does the rest.
https://dapper-tutorial.net/knowledge-base/7472088/correct-use-of-multimapping-in-dapper
CC-MAIN-2019-04
refinedweb
582
55.54
Oct! The custom slot type is used for items that are not covered by Amazon’s built-in set of types and is recommended for most use cases where a slot value is one of a set of possible values. For example, let’s say you needed to create a computer model number with the following list of values: A500, A1000, A2000, A2000HD, A2500, A3000, A600, A1200 and A4000 You could easily create a new slot type of MODEL and then define it within the developer portal on the Interaction Model page. Clicking on Add Slot Type will allow you to create a name for your new Slot Type and its corresponding values. The set of custom values can be anything supported by your skill’s handling of the slot as long as it can be spoken by a user, although words not found in a typical English dictionary may not be recognized. Click Ok, and you will see your new slot type and values displayed for easy use within your Intents and Sample Utterances. In addition to the new custom slot type Amazon now provides built-in support for the following slot types: If your skill uses any of these types, you don’t need to provide sample values in a separate file, you just reference your slots of this type in the Sample Utterances file as necessary. For other data types, a custom slot type is recommended. Note that all built-in types are prefixed with the AMAZON namespace. LITERAL slot type has been renamed to AMAZON.LITERAL. The AMAZON.LITERAL type is maintained primarily for backwards compatibility with skills produced by earlier versions of the Alexa Skills Kit, and is not recommended for most use cases going forward. You should instead use a custom slot type moving rather than AMAZON.LITERAL. Once you have defined your slot types you can immediately use them within your own Intents. For the computer model described earlier you would use them within your intents like so: { "intents": [ { "intent": "GetComputer", "slots": [ { "name": "Model", "type": "MODELS" }, { "name": "Date", "type": "AMAZON.DATE" } ] } ] } In previous versions of the Alexa Skills Kit, it was necessary to include slot values showing different ways of phrasing the slot data in your sample utterances. For example, you might have created sample utterances for the slot MyDate with values such as today, next thursday and september sixteenth: DateIntent schedule an event for {today|MyDate} DateIntent schedule an event for {next thursday|MyDate} DateIntent schedule an event for {september sixteenth|MyDate} The above utterances are identical other than the sample slot value, which was a common practice for getting Alexa to fully understand all of the possible values a LITERAL slot could contain. The new versions of the built-in types handle the different phrases automatically, so you no longer need to include multiple versions of the same utterance with different values! The three utterances shown above are condensed to a single sample utterance: DateIntent schedule an event for {MyDate} That’s the power of custom slots! You can spend more time coding your skill and less time creating Sample Utterances. To learn more about using custom slot types within your Alexa skill click here.. now provides this type of control with Speech Synthesis Markup Language (SSML) support. SSML is a markup language that provides a standard way to mark up text for the generation of synthetic speech. The Alexa Skills Kit supports a subset of the tags defined in the SSML specification. The specific tags supported currently for SSML are: speak, p, s, break, say-as, phoneme, and w. To use SSML, construct your output speech using the supported SSML tags. When sending back a response from your service, you must indicate that it is using SSML rather than plain text: "outputSpeech": { "type": "SSML", "ssml": "<speak>This output speech uses SSML.</speak>" } You can use SSML with both the normal output speech response and any re-prompt included in the response. The SSML you provide must be wrapped within <speak> tags. For example: <speak> Here is a number read as a cardinal number: <say-as12345</say-as>. Here is a word spelled out: <say-ashello</say-as>. </speak> For more information on using SSML within your Alexa skill read the SSML reference here. Migrating to the Improved Built-in and Custom Slot Types An Introduction to the Alexa Skills Kit (ASK) Free Video Training - An Introduction to Amazon Echo and the Alexa Skills Kit Creating an Amazon Echo Adventure Game with the Alexa Skills Kit New Alexa Episode on the AWS Podcast Looking to get hands on with Alexa? Check out these upcoming Alexa events: Sign up for Alexa sessions and Workshops at AWS re:Invent 2015 Join a Local Alexa Hackathons with the Alexa Roadshow -Dave (@TheDaveDev) Want Amazon Developer blogs delivered to your inbox? Stay in the loop on the latest industry best practices, Amazon promotions, and new launches by subscribing to our weekly blog summary here.
https://developer.amazon.com/blogs/post/Tx3A8074G5YB04N/Announcing-New-Alexa-Skills-Kit-ASK-Features-Custom-Slot-Types-and-Speech-Synthe
CC-MAIN-2019-30
refinedweb
829
55.27
...one of the most highly regarded and expertly designed C++ library projects in the world. — Herb Sutter and Andrei Alexandrescu, C++ Coding Standards. As always, the intension is to complement rather than compete with the C++ Standard Library. Should some future C++ standard include <stdint.h> and <cstdint>, then <boost/cstdint.hpp> will continue to function, but will become redundant and may be safely deprecated. Because these are boost headers, their names conform to boost header naming conventions rather than C++ Standard Library header naming conventions. As an implementation artifact, certain C <limits.h> macro names may possibly be visible to users of <boost/cstdint.hpp>. Don't use these macros; they are not part of any Boost-specified interface. Use boost::integer_traits<> or std::numeric_limits<> instead. As another implementation artifact, certain C <stdint.h> typedef names may possibly be visible in the global namespace to users of <boost/cstdint.hpp>. Don't use these names, they are not part of any Boost-specified interface. Use the respective names in namespace boost instead. Revised: 03 Oct 2001
https://www.boost.org/doc/libs/1_33_1/libs/integer/
CC-MAIN-2022-33
refinedweb
177
52.76
I'm trying to write a short code that will take in a string of text, and tell me how many vowels are in it, with the information being passed between a parent and child process using pipes (I am only testing for "a" at the moment until I get that working, then I'll finish the others). I keep getting segmentation fault (Core Dumped). Would you mind checking out my code and pointing me in the right direction? Thank you in advance for any and all assistance. #include <stdio.h> #define READ 0 #define WRITE 1 char* phrase; main () { int fd [2], vCount; char message[80]; int i, j, k = 0; char c; char vowels[80]; printf ("Enter a phrase up to a maximum of 80 characters.\n"); //phrase = gets (message); while (i < 80 && (c = getchar()) != '\n') { message[i] = c; switch(c) { case 'a': vowels[j] = c; j++; } i++; } pipe (fd); if (fork () == 0) { close(fd[READ]); write (fd[WRITE], vowels, (j + 1)); close (fd[WRITE]); } else { close (fd[WRITE]); vCount = read (fd[READ], vowels, 80); printf ("There are %d vowels. They are: %s\n", vCount, vowels); close (fd[READ]); } }
https://www.daniweb.com/programming/software-development/threads/186485/learning-pipes
CC-MAIN-2017-43
refinedweb
191
74.73
Like lists and arrays, tuples are also used to store multiple values. They are created with parentheses and their elements are separated by commas. > ( 1, 2 ) (1,2) > ( "Mia", "Vincent" ) ("Mia","Vincent") Similarly to lists, Elm style guide recommends using a space after ( and a space before ) when creating a tuple. Unlike lists and arrays, tuples can contain values of different kinds. > ( 1, 2.5, 'a', "Butch" ) (1,2.5,'a',"Butch") They can even contain other collections such as lists or arrays or tuples themselves. > ( [ 1, 2 ], [ "Jules", "Wolf" ] ) ([1,2],["Jules","Wolf"]) > array = Array.fromList [ 5, 6 ] Array.fromList [5, 6] > (array, [ 1, 2 ], ( "Jules", "Wolf" ) ) (Array.fromList [5,6],[1,2],("Jules","Wolf")) How about lists? Can they contain tuples? The answer is yes. > [ ( 1, 2 ), ( 3, 4 ), ( 5, 6 ) ] [(1,2),(3,4),(5,6)] Remember lists can only contain values of the same kind. In the example above, all three tuples have two numbers in them. What happens if we have tuples of different sizes? > [ ( 1, 2 ), ( 3, 4, 5 ) ] -------------------------- TYPE MISMATCH -------------------------- The 1st and 2nd entries in this list are different types of values. 7| [ ( 1, 2 ), ( 3, 4, 5 ) ] ^^^^^^^^^^^ The 1st entry has this type: ( number, number1 ) But the 2nd is: ( number, number1, number2 ) As Elm points out, ( 1, 2 ) and ( 3, 4, 5 ) are different types of values because their sizes are different. For tuples to be of the same type in Elm, they must contain the same number and type of values. So this won’t work either: > [ ( 1, 2 ), ( "Sansa", "Ygritte" ) ] -------------------------- TYPE MISMATCH -------------------------- The 1st and 2nd entries in this list are different types of values. 7| [ ( 1, 2 ), ( "Sansa", "Ygritte" ) ] ^^^^^^^^^^^^^^^^^^^^^^ The 1st entry has this type: ( number, number1 ) But the 2nd is: ( String, String ) The first tuple is a pair of numbers, whereas the second is a pair of strings which makes them of different types. And a list can’t have values of different types. Modifying Tuples In the previous sections, we learned that lists and arrays are immutable. Once they are created, we can never change them. However, despite them being immutable, we were still able to add and remove values from them. > myList = [ 1, 2, 3, 4 ] [1,2,3,4] > myList ++ [ 5 ] [1,2,3,4,5] > List.drop 1 myList [2,3,4] How’s that possible? It’s possible because Elm gives us the appearance of adding (or removing) values from a list when in fact behind the scenes it creates a completely new list that contains the new value we appended to the original list. When we print myList, we discover that its values are intact. > myList [1,2,3,4] From practical standpoint all we care about is the ability to add and remove values from a collection. How Elm enables us to do that is of little concern to us. Although, in chapter 4 we will find out that immutability does have far-reaching consequences. It’s at the core of some of Elm’s truly exciting features. Like lists and arrays, tuples are also immutable. But, Elm goes a step further to keep a tuple’s immutability intact. It strips away our ability to even create a completely new tuple containing a value we want to add to the original tuple. Therefore, there are no functions or operators we can use to append or drop values from tuples. When you think about it, it does make sense to put this restriction on tuples. Earlier we discovered that for tuples to be of the same type in Elm, they must contain the same number of values. If we were to add or remove a value from a tuple, we would essentially be changing its underlying type as well which is not the case with list or array. Furthermore, if we could add or remove values from tuples, they would start looking a lot like lists and arrays with only one difference: the ability to hold different types of values. In the next section we will find out that there already exists a data structure called record that can hold different types of values. So without this rigidity, tuples can be easily replaced with other data structures. Because we can’t add or remove values from tuples, we should only use them when we know in advance how many elements we will need. Using Tuples Despite their rigidity, tuples can be quite useful. Listed below are a few scenarios where using tuples makes our lives easier. Representing Complex Data Tuples can be used to represent a wide variety of data. For example, if we want to represent someone’s name, age, and a list of siblings we can easily do that with a tuple. > ( "Jon Snow", 14, [ "Sansa", "Arya", "Bran", "Rob", "Rickon" ] ) ("Jon Snow",14,["Sansa","Arya","Bran","Rob","Rickon"]) Returning Multiple Values From a Function It’s a common pattern in Elm to use tuples for returning multiple values from a function. To see how this works, let’s write a function that determines whether or not a given email is valid. Add the following function definition right above main in Playground.elm. validateEmail email = let emailPattern = Regex.regex "\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}\\b" isValid = Regex.contains emailPattern email in if isValid then ( "Valid email", "green" ) else ( "Invalid email", "red" ) main ... Now change the main function to this: main = validateEmail "thedude@rubix.com" |> toString |> Html.text Finally import the Regex module right below the line that imports the Html module. import Html import Regex Run elm-reactor in terminal from the beginning-elm directory if it’s not running already and go to on your browser. You should see ("Valid email","green"). The validateEmail function uses a regular expression to determine whether a given email is valid or not. It returns a tuple containing two values: If the email is valid, the string “Valid email” is returned, otherwise “Invalid email” is returned. The color to use when displaying the validity status text. As you can see, using a tuple made it very easy for us to return multiple values. Being Explicit About the Structure of Data Let’s say we want to compute the perimeter of a triangle using the formula shown below. One way to represent the sides of a triangle is by using a list. > sides = [ 5, 4, 6 ] [5,4,6] Now let’s write a function that calculates perimeter in the repl. > trianglePerimeter sides = List.sum sides <function> We used List.sum to add up all sides of a triangle. If we apply this function to the sides list we created above, we will get the perimeter. > trianglePerimeter sides 15 Now what happens when we apply the trianglePerimeter function to a list that contains four sides? > trianglePerimeter [ 5, 4, 6, 8 ] 23 It will happily compute the perimeter even though we gave it four sides. If we want to make sure that only three sides are being passed to this function, we will have to write some additional code to verify that an input list has only three elements. But if we use a tuple instead, Elm will do that for us. Let’s try it. > trianglePerimeter ( a, b, c ) = a + b + c <function> > trianglePerimeter ( 5, 4, 6 ) 15 So far so good. Now let’s apply trianglePerimeter to a tuple with four elements. > trianglePerimeter ( 5, 4, 6, 8 ) ------------------------ TYPE MISMATCH ---------------------------- The argument to function `trianglePerimeter` is causing a mismatch. 7| trianglePerimeter ( 5, 4, 6, 8 ) ^^^^^^^^^^^^^^ Function `trianglePerimeter` is expecting the argument to be: ( number, number, number ) But it is: ( number, number1, number2, number3 ) There you go. Elm points out that we need to pass in a tuple with only three elements. Picking a right data structure for the right problem often gets rid of subtle issues like this. Hopefully you understood why tuples could be very useful in a situation like this. Retrieving Values Elm provides two functions ( first and second) for retrieving values from a tuple with two elements also known as a pair. Storing data in pairs is quite common in Elm. first returns the first element in a pair and second returns the second element. > Tuple.first ( 5, 10 ) 5 > Tuple.second ( 5, 10 ) 10 > Tuple.first ( "Pam", "Jim" ) "Pam" > Tuple.second ( "Pam", "Jim" ) "Jim" The repl automatically loads the Tuple module. Therefore, we don’t need to explicitly import it. If we can’t use first and second on tuples that have more than two elements, how else can we read values from them? We have to use pattern matching for that. You already saw an example of this above. Here it is again. > trianglePerimeter ( a, b, c ) = a + b + c <function> > trianglePerimeter ( 5, 4, 6 ) 15 trianglePerimeter uses pattern matching to deconstruct a tuple passed to it and assigns the first, second, and third values to a, b, and c respectively. - Pattern Matching - As mentioned in the Case Expression section, pattern matching is the act of checking one or more inputs against a pre-defined pattern and seeing if they match. The pattern we are checking for in the above example is a tuple that contains three, and only three, numbers. We will look into some more examples of pattern matching with tuples in chapter 4. In most cases, it’s best to use a record instead of a tuple for storing more than two values. It’s much easier to access values in a record than a tuple. However, if we need to make sure that a data structure can contain only certain number of values similar to the trianglePerimeter example above, tuple is our best option. Mapping Pairs The Tuple module also provides two more functions for transforming values in a pair. mapFirst maps the first element and mapSecond maps the second element. > Tuple.mapFirst (\_ -> "Jim") ( "Roy", "Pam" ) ("Jim","Pam") > Tuple.mapFirst String.reverse ( "live", "life" ) ("evil","life") > Tuple.mapSecond (\x -> x + 1) ( "fringe", 100 ) ("fringe",101) > Tuple.mapSecond (String.contains "-") ( "Gamora", "Star-Lord" ) ("Gamora",True) There are no functions available to map values in a tuple that contains more than two values. Tuples really are rigid, aren’t they?
http://elmprogramming.com/tuple.html
CC-MAIN-2017-34
refinedweb
1,703
64.81
#include <ctime> #include <sys/resource.h> #include <sys/time.h> #include <fstream> Include dependency graph for CoinTime.hpp: This graph shows which files directly or indirectly include this file: Go to the source code of this file. Definition at line 67 of file CoinTime.hpp. Referenced by CoinWallclockTime(). Query the elapsed wallclock time since the first call to this function. If a positive argument is passed to the function then the time of the first call is set to that value (this kind of argument is allowed only at the first call!). If a negative argument is passed to the function then it returns the time when it was set. Definition at line 84 of file CoinTime.hpp. References CoinGetTimeOfDay(). Definition at line 93 of file CoinTime.hpp. Referenced by CoinTimer::isExpired(), CoinTimer::isPast(), CoinTimer::isPastPercent(), CoinTimer::restart(), CoinTimer::timeElapsed(), and CoinTimer::timeLeft(). Definition at line 117 of file CoinTime.hpp.
http://www.coin-or.org/Doxygen/Smi/_coin_time_8hpp.html
crawl-003
refinedweb
151
60.82
System Service: Clip to Day One I’m enjoying logging with Day One right now, and getting geeky with it. To that end, I put this project together during the few breaks I’ve had over the last couple of days leading up to the new Engadget live blog launch today1. The result is a practical proof of concept in the form of a System Service for clipping any text to Day One. I figured that this could actually be really handy for more people than just me, so here it is. Dayone uses a very simple XML format in separate files to store your entries. It’s easy to replicate the structure using a script, allowing you to directly generating your own Day One entries from any part of your workflow. I’m bypassing the dayone CLI and dropping the updates in directly for added flexibility. Don’t get me wrong, I absolutely love that Day One comes with a CLI, I just wanted to experiment around it. I’m using the new iCloud support for sync, and this Service is built to work with that folder structure by default. The version below (and in the download) looks in “~/Library/Mobile Documents/” (where iCloud stores documents) for a folder containing the word “dayoneapp.” I don’t know offhand what the bizarre names of the folders indicate, but they differ between accounts, so we have to grep out the matching folder. Assuming your Journal is called Journal_dayone (default) and you’re using iCloud, you shouldn’t have to edit anything. If it doesn’t work, run this in Terminal and copy the resulting path into the “dayonepath” variable: find ~/Library/Mobile\ Documents/ -name "Journal_dayone" If you’re using Dropbox, you’ll just need to make a minor alteration to the “dayonepath” variable. Delete the line starting with “dayonedir” and hardcode the Unix (POSIX) path to the “entries” folder, located directly inside of the Journal.dayone bundle in your Dropbox root folder. It will most likely be /Users/[yourusername]/Dropbox/Journal.dayone/entries/ if you haven’t changed any defaults in Dropbox or Day One. The service itself is available for download at the end of the post, or you can take the script below and home-roll your own in Automator. It should work out of the box, no need for ruby gems or symlinked CLIs. The only configuration you may want to edit is the “starred” variable. This defaults to off because Services aren’t interactive and you probably don’t want to star every entry you clip. If you do, though, just change “starred = false” to “starred = true” and it will make your calendar look like a planetarium. The Service will use /usr/bin/textutil to strip out any rich text artifacts. I’m not certain this is necessary, but I found that when clipping rich text I would lose all of my line breaks and indents. This seems to solve it. The script also looks for text with hard breaks and handles them Github-style, preserving breaks using Markdown line break syntax. If you have Growl running, you’ll get a notification. To be polite, it checks for Growl before attempting any notifications. The check can be slow sometimes, though, so you may want to either remove the check if you always have Growl running, or remove the whole Growl section at the end if you don’t. The script: Here’s the script. The same script can be found in the Service download at the end by opening the .workflow file in Automator. You can easily customize/edit from there, so this is posted just for reference. require 'time' require 'erb' def e_sh(str) str.to_s.gsub(/(?=[^a-zA-Z0-9_.\/\-\x7F-\xFF\n])/n, '\\').gsub(/\n/, "'\n'").sub(/^$/, "''") end input = STDIN.read entrytext = %x{echo #{e_sh input}|textutil -stdin -convert txt -stdout} entrytext.gsub!(/\n([^\n])/," \n\\1") uuid = %x{uuidgen}.gsub(/-/,'').strip datestamp = Time.now.utc.iso8601 starred = false dayonedir = %x{ls ~/Library/Mobile\\ Documents/|grep dayoneapp}.strip <plist version="1.0"> <dict> <key>Creation Date</key> <date><%= datestamp %></date> <key>Entry Text</key> <string><![CDATA[<%= entrytext %>]]></string> <key>Starred</key> <<%= starred %>/> <key>UUID</key> <string><%= uuid %></string> </dict> </plist> XMLTEMPLATE fh = File.new(File.expand_path(dayonepath+uuid+".doentry"),'w+') fh.puts template.result(binding) fh.close growl_running = %x{osascript -e 'tell application "system events" to return (count of (every process whose bundle identifier is "com.Growl.GrowlHelperApp")) > 0'} if growl_running %x{osascript -e 'tell application id "com.Growl.GrowlHelperApp" to register as application "Clip to Day One" all notifications {"Clip Complete"} default notifications {"Clip Complete"} icon of application "Day One"'} %x{osascript -e 'tell application id "com.Growl.GrowlHelperApp" to notify with name "Clip Complete" title "Log to Day One" description "Clipped to Day One" application name "Clip to Day One"'} end Side note: I mentioned to @brianstucki that this Service might contain the necessary ingredients for an Evernote-to-Day-One solution, but I’ve realized it’s really only the last part of the equation. What you’d probably want to do with most RTF/text notes is export HTML, extract the “created on” meta and parse it into the correct date format, then pipe the rest of the contents through markdownify_cli.php, passing the result to dayone new. Then you’ll have nice, Markdown versions of your notes from Evernote, preserving much of the formatting. I tested this, and it works pretty flawlessly for text notes. Download For complete instructions on installing the service (and adding a keyboard shortcut for it), see the how-to posted here. Clip to Day One Service v1.1 Download Clip to Day One Service v1.1 A System Service to clip any text to a Day One journal entry. Updated Wed Nov 06 2013.
http://brettterpstra.com/2012/01/19/system-service-clip-to-day-one/
CC-MAIN-2018-09
refinedweb
970
64
Learn the principles of multi-threading with the GCD framework in Swift. Queues, tasks, groups everything you'll ever need I promise. GCD concurrency tutorial for beginners The Grand Central Dispatch (GCD, or just Dispatch) framework is based on the underlying thread pool design pattern. This means that there are a fixed number of threads spawned by the system - based on some factors like CPU cores - they're always available waiting for tasks to be executed concurrently. 🚦 Creating threads on the run is an expensive task so GCD organizes tasks into specific queues, and later on the tasks waiting on these queues are going to be executed on a proper and available thread from the pool. This approach leads to great performance and low execution latency. We can say that the Dispatch framework is a very fast and efficient concurrency framework designed for modern multicore hardwares and needs. Concurrency, multi-tasking, CPU cores, parallelism and threads A processor can run tasks made by you programmatically, this is usually called coding, developing or programming. The code executed by a CPU core is a thread. So your app is going to create a process that is made up from threads. 🤓 In the past a processor had one single core, it could only deal with one task at a time. Later on time-slicing was introduced, so CPU's could execute threads concurrently using context switching. As time passed by processors gained more horse power and cores so they were capable of real multi-tasking using parallelism. ⏱ Nowadays a CPU is a very powerful unit, it's capable of executing billions of tasks (cycles) per second. Because of this high availability speed Intel introduced a technology called hyperthreading. They divided CPU clock cycles between (usually two) processes running at the same time, so the number of available threads essentially doubled. 📈 As you can see concurrenct execution can be achieved with various techniques, but you don't need to care about that much. It's up to the CPU architecture how it solves concurrency, and it's the operating system's task how much thread is going to be spawned for the underlying thread pool. The GCD framework will hide all the complexity, but it's always good to understand the basic principles. 👍 instantly return and the queue can continue the execution of the remaining tasks (or work items as Apple calls them). 🚧 Synchronous execution When a work item is executed synchronously with the sync method, the program waits until execution finishes before the method call returns. Your function is most likely synchronous if it has a return value, so func load() -> String is going to probably block the thing that runs on until the resources is completely loaded and returned back. Asynchronous execution When a work item is executed asynchronously with the async method, the method call returns immediately. Completion blocks are a good sing of async methods, for example if you look at this method func load(completion: (String) -> Void) you can see that it has no return type, but the result of the function is passed back to the caller later on through a block. This is a typical use case, if you have to wait for something inside your method like reading the contents of a huge file from the disk, you don't want to block your CPU, just because of the slow IO operation. There can be other tasks that are not IO heavy at all (math operations, etc.) those can be executed while the system is reading your file from the physical hard drive. 💾 With dispatch queues you can execute your code synchronously or asynchronously. With syncronous execution the queue waits for the work, with async execution the code returns immediately without waiting for the task to complete. ⚡️ Dispatch queues As I mentioned before, GCD organizes task into queues, these are just like the queues at the shopping mall. On every dispatch queue, tasks will be executed in the same order as you add them to the queue - FIFO: the first task in the line will be executed first - but you should note that the order of completion is not guaranteed. Tasks will be completed according to the code complexity. So if you add two tasks to the queue, a slow one first and a fast one later, the fast one can finish before the slower one. ⌛️ Serial and concurrent queues There are two types of dispatch queues. Serial queues can execute one task at a time, these queues can be utilized to synchronize access to a specific resource. Concurrent queues on the other hand can execute one or more tasks parallell in the same time. Serial queue is just like one line in the mall with one cashier, concurrent queue is like one single line that splits for two or more cashiers. 💰 Main, global and custom queues The main queue is a serial one, every task on the main queue runs on the main thread. Global queues are system provided concurrent queues shared through the operating system. There are exactly four of them organized by high, default, low priority plus an IO throttled background queue. Custom queues can be created by the user. Custom concurrent queues always mapped into one of the global queues by specifying a Quality of Service property (QoS). In most of the cases if you want to run tasks in parallel it is recommended to use one of the global concurrent queues, you should only create custom serial queues. System provided queues - Serial main queue - Concurrent global queues - high priority global queue - default priority global queue - low priority global queue - global background queue (io throttled) Custom queues by quality of service - userInteractive (UI updates) -> serial main queue - userInitiated (async UI related tasks) -> high priority global queue - default -> default priority global queue - utility -> low priority global queue - background -> global background queue - unspecified (lowest) -> low priority global queue Enough from the theory, let's see how to use the Dispatch framework in action! 🎬 How to use the DispatchQueue class in Swift? Here is how you can get all the queues from above using the brand new GCD syntax available from Swift 3. Please note that you should always use a global concurrent queue instead of creating your own one, except if you are going to use the concurrent queue for locking with barriers to achieve thread safety, more on that later. 😳 How to get a queue? import Dispatch DispatchQueue.main DispatchQueue.global(qos: .userInitiated) DispatchQueue.global(qos: .userInteractive) DispatchQueue.global(qos: .background) DispatchQueue.global(qos: .default) DispatchQueue.global(qos: .utility) DispatchQueue.global(qos: .unspecified) DispatchQueue(label: "com.theswiftdev.queues.serial") DispatchQueue(label: "com.theswiftdev.queues.concurrent", attributes: .concurrent) So executing a task on a background queue and updating the UI on the main queue after the task finished is a pretty easy one using Dispatch queues. DispatchQueue.global(qos: .background).async { // do your job here DispatchQueue.main.async { // update ui here } } Sync and async calls on queues There is no big difference between sync and async methods on a queue. Sync is just an async call with a semaphore (explained later) that waits for the return value. A sync call will block, on the other hand an async call will immediately return. 🎉 let q = DispatchQueue.global() let text = q.sync { return "this will block" } print(text) q.async { print("this will return instantly") } Basically if you need a return value use sync, but in every other case just go with async. DEADLOCK WARNING: you should never call sync on the main queue, because it'll cause a deadlock and a crash. You can use this snippet if you are looking for a safe way to do sync calls on the main queue / thread. 👌 Don't call sync on a serial queue from the serial queue's thread! Delay execution You can simply delay code execution using the Dispatch framework. DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(2)) { //this code will be executed only after 2 seconds have been passed } Perform concurrent loop Dispatch queue simply allows you to perform iterations concurrently. DispatchQueue.concurrentPerform(iterations: 5) { (i) in print(i) } Debugging Oh, by the way it's just for debugging purpose, but you can return the name of the current queue by using this little extension. Do not use in production code!!! extension DispatchQueue { static var currentLabel: String { return String(validatingUTF8: __dispatch_queue_get_label(nil))! } } //print(DispatchQueue.currentLabel) Using DispatchWorkItem in Swift DispatchWorkItem encapsulates work that can be performed. A work item can be dispatched onto a DispatchQueue and within a DispatchGroup. A DispatchWorkItem can also be set as a DispatchSource event, registration, or cancel handler. So you just like with operations by using a work item you can cancel a running task. Also work items can notify a queue when their task is completed. var workItem: DispatchWorkItem? workItem = DispatchWorkItem { for i in 1..<6 { guard let item = workItem, !item.isCancelled else { print("cancelled") break } sleep(1) print(String(i)) } } workItem?.notify(queue: .main) { print("done") } DispatchQueue.global().asyncAfter(deadline: .now() + .seconds(2)) { workItem?.cancel() } DispatchQueue.main.async(execute: workItem!) // you can use perform to run on the current queue instead of queue.async(execute:) //workItem?.perform() Concurrent tasks with DispatchGroups So you need to perform multiple network calls in order to construct the data required by a view controller? This is where DispatchGroup can help you. All of your long running background task can be executed concurrently, when everything is ready you'll receive a notification. Just be careful you have to use thread-safe data structures, so always modify arrays for example on the same thread! 😅 func load(delay: UInt32, completion: () -> Void) { sleep(delay) completion() } let group = DispatchGroup() group.enter() load(delay: 1) { print("1") group.leave() } group.enter() load(delay: 2) { print("2") group.leave() } group.enter() load(delay: 3) { print("3") group.leave() } group.notify(queue: .main) { print("done") } Note that you always have to balance out the enter and leave calls on the group. The dispatch group also allows us to track the completion of different work items, even if they run on different queues. let group = DispatchGroup() let queue = DispatchQueue(label: "com.theswiftdev.queues.serial") let workItem = DispatchWorkItem { print("start") sleep(1) print("end") } queue.async(group: group) { print("group start") sleep(2) print("group end") } DispatchQueue.global().async(group: group, execute: workItem) // you can block your current queue and wait until the group is ready // a better way is to use a notification block instead of blocking //group.wait(timeout: .now() + .seconds(3)) //print("done") group.notify(queue: .main) { print("done") } One more thing that you can use dispatch groups for: imagine that you're displaying a nicely animated loading indicator while you do some actual work. It might happens that the work is done faster than you'd expect and the indicator animation could not finish. To solve this situation you can add a small delay task so the group will wait until both of the tasks finish. 😎 let queue = DispatchQueue.global() let group = DispatchGroup() let n = 9 for i in 0..<n { queue.async(group: group) { print("\(i): Running async task...") sleep(3) print("\(i): Async task completed") } } group.wait() print("done") Semaphores A semaphore is simply a variable used to handle resource sharing in a concurrent system. It's a really powerful object, here are a few important examples in Swift. How to make an async task to synchronous? The answer is simple, you can use a semaphore (bonus point for timeouts)! enum DispatchError: Error { case timeout } func asyncMethod(completion: (String) -> Void) { sleep(2) completion("done") } func syncMethod() throws -> String { let semaphore = DispatchSemaphore(value: 0) let queue = DispatchQueue.global() var response: String? queue.async { asyncMethod { r in response = r semaphore.signal() } } semaphore.wait(timeout: .now() + 5) guard let result = response else { throw DispatchError.timeout } return result } let response = try? syncMethod() print(response) Lock / single access to a resource If you want to avoid race condition you are probably going to use mutual exclusion. This could be achieved using a semaphore object, but if your object needs heavy reading capability you should consider a dispatch barrier based solution. 😜 class LockedNumbers { let semaphore = DispatchSemaphore(value: 1) var elements: [Int] = [] func append(_ num: Int) { self.semaphore.wait(timeout: DispatchTime.distantFuture) print("appended: \(num)") self.elements.append(num) self.semaphore.signal() } func removeLast() { self.semaphore.wait(timeout: DispatchTime.distantFuture) defer { self.semaphore.signal() } guard !self.elements.isEmpty else { return } let num = self.elements.removeLast() print("removed: \(num)") } } let items = LockedNumbers() items.append(1) items.append(2) items.append(5) items.append(3) items.removeLast() items.removeLast() items.append(3) print(items.elements) Wait for multiple tasks to complete Just like with dispatch groups, you can also use a semaphore object to get notified if multiple tasks are finished. You just have to wait for it... let semaphore = DispatchSemaphore(value: 0) let queue = DispatchQueue.global() let n = 9 for i in 0..<n { queue.async { print("run \(i)") sleep(3) semaphore.signal() } } print("wait") for i in 0..<n { semaphore.wait() print("completed \(i)") } print("done") Batch execution using a semaphore You can create a thread pool like behavior to simulate limited resources using a dispatch semaphore. So for example if you want to download lots of images from a server you can run a batch of x every time. Quite handy. 🖐 print("start") let sem = DispatchSemaphore(value: 5) for i in 0..<10 { DispatchQueue.global().async { sem.wait() sleep(2) print(i) sem.signal() } } print("end") The DispatchSource object A dispatch source is a fundamental data type that coordinates the processing of specific low-level system events. Signals, descriptors, processes, ports, timers and many more. Everything is handled through the dispatch source object. I really don't want to get into the details, it's quite low-level stuff. You can monitor files, ports, signals with dispatch sources. Please just read the offical Apple docs. 📄 I'd like to make only one example here using a dispatch source timer. let timer = DispatchSource.makeTimerSource() timer.schedule(deadline: .now(), repeating: .seconds(1)) timer.setEventHandler { print("hello") } timer.resume() Thread-safety using the dispatch framework Thread safety is an inevitable topic if it comes to multi-threaded code. In the beginning I mentioned that there is a thread pool under the hood of GCD. Every thread has a run loop object associated with it, you can even run them by hand. If you create a thread manually a run loop will be added to that thread automatically. let t = Thread { print(Thread.current.name ?? "") let timer = Timer(timeInterval: 1, repeats: true) { t in print("tick") } RunLoop.current.add(timer, forMode: .defaultRunLoopMode) RunLoop.current.run() RunLoop.current.run(mode: .commonModes, before: Date.distantPast) } t.name = "my-thread" t.start() //RunLoop.current.run() You should not do this, demo purposes only, always use GCD queues! Queue != Thread A GCD queue is not a thread, if you run multiple async operations on a concurrent queue your code can run on any available thread that fits the needs. Thread safety is all about avoiding messed up variable states Imagine a mutable array in Swift. It can be modified from any thread. That's not good, because eventually the values inside of it are going to be messed up like hell if the array is not thread safe. For example multiple threads are trying to insert values to the array. What happens? If they run in parallell which element is going to be added first? Now this is why you need sometimes to create thread safe resources. Serial queues You can use a serial queue to enforce mutual exclusivity. All the tasks on the queue will run serially (in a FIFO order), only one process runs at a time and tasks have to wait for each other. One big downside of the solution is speed. 🐌 let q = DispatchQueue(label: "com.theswiftdev.queues.serial") q.async() { // writes } q.sync() { // reads } Concurrent queues using barriers You can send a barrier task to a queue if you provide an extra flag to the async method. If a task like this arrives to the queue it'll ensure that nothing else will be executed until the barrier task have finished. To sum this up, barrier tasks are sync (points) tasks for concurrent queues. Use async barriers for writes, sync blocks for reads. 😎 let q = DispatchQueue(label: "com.theswiftdev.queues.concurrent", attributes: .concurrent) q.async(flags: .barrier) { // writes } q.sync() { // reads } This method will result in extremely fast reads in a thread safe environment. You can also use serial queues, semaphores, locks it all depends on your current situation, but it's good to know all the available options isn't it? 🤐 A few anti-patterns You have to be very careful with deadlocks, race conditions and the readers writers problem. Usually calling the sync method on a serial queue will cause you most of the troubles. Another issue is thread safety, but we've already covered that part. 😉 let queue = DispatchQueue(label: "com.theswiftdev.queues.serial") queue.sync { // do some sync work queue.sync { // this won't be executed -> deadlock! } } //What you are trying to do here is to launch the main thread synchronously from a background thread before it exits. This is a logical error. // DispatchQueue.global(qos: .utility).sync { // do some background task DispatchQueue.main.sync { // app will crash } } The Dispatch framework (aka. GCD) is an amazing one, it has such a potential and it really takes some time to master it. The real question is that what path is going to take Apple in order to embrace concurrent programming into a whole new level? Promises or await, maybe something entirely new, let's hope that we'll see something in Swift 6. External sources - Tasks and threads in Swift - Concurrency model in Swift - Dispatch - Apple Developer Documentation - Run Loops - Apple Developer Documentation - Grand Central Dispatch Tutorial for Swift 3 - A deep dive into Grand Central Dispatch in Swift - Grand Central Dispatch (GCD) and Dispatch Queues in Swift 3 - What is the difference between cores and threads of a processor? - Creating Thread-Safe Arrays in Swift - All about Concurrency in Swift - Part 1: The Present
https://theswiftdev.com/2018/07/10/ultimate-grand-central-dispatch-tutorial-in-swift/
CC-MAIN-2019-39
refinedweb
3,024
56.05
finalize() method in Java is called by the garbage collector it gives the last chance to objects for performing its clean up operation. AdsTutorials In this section we will read about the finalize() method. We will read how the finalize() method may used in the programming, why finalize() method is declared as protected and many more things. finalize() method is a protected method of java.lang.Object class so that the finalize() method can be overridden by all classes. This method is defined as protected to apply the encapsulation feature i.e. to hide the internal process of cleaning up operation and to make available for the subclasses to override inside their body. If this method was defined as private, the encapsulation feature will be applied on it but after that it can't be override by the subclasses. There is a way of guaranteed calling of finalize() method by JVM on all object which are eligible for garbage collection is to call the System.runFinalization() and Runtime.getRuntime().runFinalization(). In programming the finalize() method can be override into the subclass but, this method is not chained like a constructor so, it is the responsibility of programmer to call the finalize() method of super class because it is not called itself. The best way is to call the finalize() method of super class inside the finally block. finalize() method should be used where it is required to release the resource like a Java class that holds the I/O devices and required to release after completing their tasks, a Java class where the JDBC connection is made and required to release the resource after completing of process. In such type of programming it is recommended that use the provided close() methods because, there is no guarantee of running of finalize() method in code. Garbage Collection thread calls the finalize before collecting object and determines the object has no more references. The GC thread calls the finalize only once. Following code snippet demonstrate you how the finalize() method can be override. protected void finalize() throws Throwable { try{ //code for releaseing resources, cleanup operation; }catch(Throwable t){ throw t; }finally{ super.finalize(); } } Syntax : protected void finalize() throws Throwable Example Here an example is being given which will demonstrate you about how the finalize() method may override and use inside the class. In this example we have created a Java class named ReadFile.java and then created a method for reading a file. In this class I have also overridden the finalize() method and write the code inside it for releasing resources. Then I have created the main method for executing the class. Inside the main method I have created the object of ReadFile class and called the method readFile() for reading file and finalize() for releasing the resources. ReadFile.java import java.io.*; public class ReadFile { FileInputStream fis = null; File file = null; public void readFile() { file = new File("C:\\Documents and Settings\\bharat\\Desktop\\bipul\\a.txt"); try { fis = new FileInputStream(file); int r ; System.out.print("File Text : "); while ((r = fis.read()) != -1) { System.out.print((char) r); } System.out.println(); } catch(FileNotFoundException e) { e.printStackTrace(); } catch(IOException ioe) { ioe.printStackTrace(); } } @Override protected void finalize() throws Throwable { try{ System.out.println("Calling finalize of Sub Class...."); if(fis != null) { System.out.println("Releasing I/O resource...."); fis.close(); } }catch(Throwable t){ throw t; }finally{ System.out.println("Calling finalize of Super Class...."); super.finalize(); } } public static void main(String args[]) { ReadFile rf = new ReadFile(); rf.readFile(); try { rf.finalize(); } catch (Throwable e) { e.printStackTrace(); } } } Output When you will compile and execute the above example you will get the output as follows : Advertisements We have 1000s of tutorials on our website. Search Tutorials tutorials on our website. Posted on: August 1, 2013 If you enjoyed this post then why not add us on Google+? Add us to your Circles Advertisements Ads Ads Discuss: Java finalize() Method Example Post your Comment
http://roseindia.net/java/beginners/java-finalize-method-example.shtml
CC-MAIN-2017-51
refinedweb
658
57.16
the hard part is, realizing I can't use a lot of the simple commands because I'm not allowed to alter "too much" (how much is too much?)* of the code provided. Anyways, here's the overall problem: I need to create a text editor in Java. Not using Jpanel (I don't think) so it's a little tougher. I need to get the follow commands: Open, Save, Search, Cut, Copy, and Paste. The current problem: I don't even know if I'm on the right path for the Open command. I think I am. The Error: Cannot make a static reference to the non-static method Open(SimpleFileReader) from the type Editor EditorMenuHandler.java /Editor/src line 55 Java Problem And the code: EditorMenuHandler.java /* * comp285 EditorMenuHandler class */ import java.awt.*; import java.awt.event.*; /** * The EditorMenuHandler that handles the events generated by the * menu of the Editor class. * @author Ian A Mason. * @version 1.0 beta * @date 7/02/01 * @see java.awt.event.ActionListener * @see java.awt.event.ItemListener */ class EditorMenuHandler implements ActionListener, ItemListener { int value; int option; String content = null; String name = null; String word; String str; /** * This is the name of the Editor instance whose events this EditorMenuHandler instance is * listening to. It will need to ask it to perform certain tasks according to what * type of event it hears has happened. */ private Editor editor; /** * This constructs a EditorMenuHandler instance who handles the events of the * particular Editor instance. * */ protected EditorMenuHandler(Editor editor){ this.editor = editor; } /** * This here is where all the events of interest get handled. It will be here * that you will have to ask the editor to do the appropriate things. * @see java.awt.event.ActionListener */ @SuppressWarnings("deprecation") public void actionPerformed(ActionEvent ae){ FileDialog filedialog; final SearchDialog searchDialog; String arg = (String)ae.getActionCommand(); //()); } } //the Save ... case if(arg.equals(Editor.fileLabels[1])){ if(Editor.VERBOSE) System.err.println(Editor.fileLabels[1] + " has been selected"); filedialog = new FileDialog(editor, "Save File Dialog", FileDialog.SAVE); filedialog.show(); if(Editor.VERBOSE){ System.err.println("Exited filedialog.setVisible(true);"); System.err.println("Save file = " + filedialog.getFile()); System.err.println("Save directory = " + filedialog.getDirectory()); } } //the Search ... case if(arg.equals(Editor.fileLabels[2])){ if(Editor.VERBOSE) System.err.println(Editor.fileLabels[2] + " has been selected"); searchDialog = new SearchDialog(editor); searchDialog.show(); if(Editor.VERBOSE) System.err.println("searchDialog.show(); has exited"); } //the Quit ... case if(arg.equals(Editor.fileLabels[3])){ if(Editor.VERBOSE) System.err.println(Editor.fileLabels[3] + " has been selected"); System.exit(0); } //the Cut case if(arg.equals(Editor.editLabels[0])){ if(Editor.VERBOSE) System.err.println(Editor.editLabels[0] + " has been selected"); } //the Copy case if(arg.equals(Editor.editLabels[1])){ if(Editor.VERBOSE) System.err.println(Editor.editLabels[1] + " has been selected"); } //the Paste case if(arg.equals(Editor.editLabels[2])){ if(Editor.VERBOSE) System.err.println(Editor.editLabels[2] + " has been selected"); } } /** * This needs to be here since we need to implement the ItemListener * interface * @see java.awt.event.ItemListener */ public void itemStateChanged(ItemEvent ie){ //shouldn't need to do anything here. } } With the problem at: //()); } But that assumes that my Open method even works Editor.java /* * comp285 Editor class */ import java.awt.*; import java.awt.event.*; /** * * @author Ian A Mason. * @see CenteredFrame * @see java.awt.Frame * @version 1.0 beta * @date 7/02/01 */ class Editor extends CenteredFrame { /** * A static flag, accessed via the class, not an instance!! * A boolean flag used to turn on/off error messaging to System.err. * This protected constant can be used by the other classes in this * application. You can turn it off once you think your program * is ready to ship! */ protected static final boolean VERBOSE = true; /** * Static data, accessed via the class, not an instance!! * The labels for the items in the file pulldown menu. * This protected constant can be used by the other classes in this * application. These are used by the EditorMenuHandler object to * decide which item has been selected. */ protected static final String[] fileLabels = { "Open ...", "Save ...", "Search ...", "Quit ..." }; /** * Static data, accessed via the class, not an instance!! * The labels for the items in the edit pulldown menu. * This protected constant can be used by the other classes in this * application. These are used by the EditorMenuHandler object to * decide which item has been selected. */ protected static final String[] editLabels = { "Cut", "Copy", "Paste"}; /** * The TextArea instance textArea is the little workhorse of the editor. * <em>Note that it is private, and must remain so!</em> Only the editor object * is permitted to talk to this object. * @see java.awt.TextArea * @see java.awt.TextComponent */ private final TextArea textArea = new TextArea("", 40, 80, TextArea.SCROLLBARS_BOTH); /** * The MenuBar instance menuBar is the toplevel widget at the top of the editor * that contains the pull down menus. <em>Note that it is private, and must * remain so! Only the editor object is permitted to talk to this object.</em> * @see java.awt.MenuBar */ private final MenuBar menuBar = new MenuBar(); /** * The file menu is the thing that one clicks on to pull down the menu items. * @see java.awt.Menu */ private final Menu fileMenu = new Menu("File"); /** * The items in the pull down file menu belong to this array. Its length is determined * by the static final array of file item labels. * @see java.awt.MenuItem */ private final MenuItem[] fileItem = new MenuItem[fileLabels.length]; /** * The edit menu is the thing that one clicks on to pull down the menu items. * @see java.awt.Menu */ private final Menu editMenu = new Menu("Edit"); /** * The items in the pull down edit menu belong to this array. Its length is determined * by the static final array of edit item labels. * @see java.awt.MenuItem */ private final MenuItem[] editItem = new MenuItem[editLabels.length]; /** * This is the name we use to refer to the object that handles the editors * events. Though we will not actually ever send it any messages, just merely * register it with Java as a listener to the appropriate events. * * @see EditorMenuHandler */ private EditorMenuHandler menuHandler; /** * An auxiliary procedure for initializing the pull down menus. It eliminates * a small amount of code duplication. */ private void initMenu(MenuItem[] menuItems, String[] menuLabels, Menu menu, EditorMenuHandler menuHandler, MenuBar menuBar){ for(int i = 0; i < menuItems.length; i++){ menuItems[i] = new MenuItem(menuLabels[i]); menu.add(menuItems[i]); menuItems[i].addActionListener(menuHandler); } menuBar.add(menu); } /** * The private Editor object constructor is where most of the work gets done. * Making the CenteredFrame part using the super construct (i.e by calling the * CenteredFrame constructor. It also makes the other * important toplevel object, the menuHandler. * It also must make * all the awt components that are part of the editor: the text area, the * pull down menus, and register the menuHandler with the widgets that it * needs to listen to (the events that they generate). */ private Editor(){ super("Text Editor"); menuHandler = new EditorMenuHandler(this); textArea.setFont(new Font("SansSerif", Font.PLAIN, 15)); setMenuBar(menuBar); // make the pull down file menu initMenu(fileItem,fileLabels,fileMenu,menuHandler,menuBar); // make the pull down edit menu initMenu(editItem,editLabels,editMenu,menuHandler,menuBar); //set the layout manager to be a BorderLayout object setLayout(new BorderLayout()); //put the textArea in the center add(textArea, BorderLayout.CENTER); //validate the layout validate(); //make the editor visible setVisible(true); } public void Open(SimpleFileReader read){ textArea.replaceRange(read.readLine(), 0, 3200); } /** * The main method that creates an Editor instance, and * thus starts the whole kit and kaboodle. */ public static void main(String[] args){ Editor editor = new Editor(); //the reason this doesn't exit immediately is because //this is actually a multithreaded application. The other //thread sitting in the background is the <em>event handler thread</em> } } With the Open Method: public void Open(SimpleFileReader read){ textArea.replaceRange(read.readLine(), 0, 3200); } And the SimpleFileReader.java /* comp285 SimpleFileReader.java */ import java.io.*; /** * SimpleFileReader is a small class to wrap around the usual FileReader * to shield you from the exception handling which we haven't yet gotten * to in class. * <P>It has just three methods of note: one to open a new file for reading, * one to read line from an open file, and one to close the file when done. * <P>Here is a simple example that shows using the SimpleFileReader to * to display the contents of a file on the console: * <PRE> * SimpleFileReader reader = SimpleFileReader.openFileForReading("letter.txt"); * if (reader == null) { * System.out.println("Couldn't open file!"); * return; * } * String line; * while ((line = reader.readLine()) != null) * System.out.println(line); * reader.close(); * </PRE> * <P>You don't need to make any changes. * * * @see java.io.FileReader * @see java.io.BufferedReader * @version 1.1 10/01/99 * @author Julie Zelenski */ public class SimpleFileReader { /** * Opens a new file for reading. The filename can either be a relative * path, which will be relative to the working directory of the program * when started, or an absolute path. If the file exists and can be * opened, a new SimpleFileReader is returned. If the file cannot be * opened (for any reason: wrong name, wrong path, lack of permissions, etc.) * null is returned. */ public static SimpleFileReader openFileForReading(String filename) { try { return new SimpleFileReader(new BufferedReader(new FileReader(filename))); } catch(IOException e) { return null; } } /** * Reads the next line from the open file. Returns the entire contents * of the line as one string, excluding the newline at the end. * If at EOF and no more lines to read, null is returned. null is also * returned on any I/O error. */ public String readLine() { try { return reader.readLine(); } catch (IOException e) { return null; } } /** * Closes the file when done reading. You should close a reader when * you are finished to release the OS resources for use by others. */ public void close() { try { reader.close(); } catch (IOException e) {} } /** * Constructor is private so that only means to create a new reader * is through the static method which does error checking. */ private SimpleFileReader(BufferedReader reader) { this.reader = reader; } private BufferedReader reader; } Thank you in advance for your help! If you have any questions about my questions, please let me know. ---------- * To quote from the Prompt: "There are essentially two top level objects in the design of this widget: the editor object (an instance of the Editor class); and the menuHandler object (which is an instance of the EditMenuHandler class. These are the two classes you will have to elaborate upon. There are a few other classes hanging around, but you should not have to tinker with them at all."
http://www.dreamincode.net/forums/topic/161985-text-editor-open/
CC-MAIN-2017-09
refinedweb
1,734
50.43
One of the goals for writing unit tests is to ensure that code does what it is supposed to do. When we write and compile the code, we know it gets through perfectly without any errors. However not having any errors do not necessarily mean that it does what it’s supposed to do. We need to have some mechanism to know that the code produces the results we require and we also have other means to validate the code output. Your test case for Unit test should test for results or code output validity. Consider the below simple program add 2 numbers (I know this example is too easy and not practical one ,however this is best example coming to my mind now while writing this post,sorry I do have some great unit tests for my piece of code, I will share those as well later on) public class AddTwoNumbers { public double add (double number1, double number2) { Return number1 + number2; } } The Intended purpose of AddTwoNumbers is to take 2 double values and do the addition. We need some mechanism to know that when this program gets executed we are indeed doing addition and program is also not giving us back any runtime exception. Probably we can write the test for this program something like below, public class AddTwoNumbersTest { public static void main(String[] args) { AddTwoNumbers addtwonum = new AddTwoNumbers(); double output = addtwonum.add(40,50); if (output != 90) { System.out.println("Bad result: " + result); } } } One of the other ways to test this program is with Junit and use its assertEquals Method. import static org.junit.Assert.assertEquals; import org.junit.Test; public class AddTwoNumbersTest { @Test public void testAddTwoNumbers() { AddTwoNumbers addtwonum = new AddTwoNumbers(); double output = addtwonum.add(40,50); assertEquals(60, result, 0); } } Junit probably is one of the best library for unit testing the java code. Probably sometimes later I will write more on Junit. In case while writing the code ,the requirements are not clear, then probably making some assumptions surely helps. However we need to ensure that our assumptions are repeatedly clarified with users or relevant stakeholders. So the first unit test case for your piece of code should be to verify that your code does what it is supposed to do. Tags: Java, Junit, Testcases, Unit test cases, Unit Testing
http://vasanti.org/blog/?cat=43
CC-MAIN-2018-09
refinedweb
384
51.89
GUI: searching technique searching technique Hi, i need any searching technique in java to search the data and give the all possible data by links Borders Java NotesBorders You can add a border to any component (JComponent), including JPanel, using the component's setBorder(...) method. To create borders.... Borders can be grouped into these types: Empty border -- Empty space around searching problem searching problem how we can make a code in core java for searching in hard disk? i have to make an antivirus as my minor project , so i have need this type code to search the virus in hard disk searching for strings in a file searching for strings in a file how can i search of a person and display the other details associated with the name using java gui window?  ...:// Sorting and Searching Sorting and Searching Hi i would really be thankful if someone could help me with this A program is required to ask users to rate the Java...) { Scanner input = new Scanner(System.in); System.out.print("Rate Java(0-10 Java String searching. Java String searching. How to search a string in given String array... and for searching we used userCity.equalsIgnoreCase(city[i... in list: "); userCity = scanner.next(); int i = 0; int Java... date. I want to refine my search. Can anybody plz tell me how can I perform Gui plz help would do better next time if the ratio is smaller than 70%. this is what i got so far. so basically what i did is i used the java palletes to make a application...Gui plz help Create a Java application that would allow a person Gui Interface - Java Beginners Gui Interface hi I have two seperate interfaces in the same projects . my question is how can I access this interface using a jbutton (i.e jbutton = next where next points to another interface addCourse.java) What would Java GUI - Applet Java GUI HELLO, i am working on java chat server, i add JFrame and make GUI structure by draging buttons and labels, now i want to insert...(); frame.setVisible(true); } } Thanks sir, i got your answer JButton Appearance Java: JButton Appearance You don't have to do anything special with a button, but there are many methods for changing the appearance... and borders, change the color, etc Normally, you don't need to use the ActionEvent GUI 2 - Java Beginners GUI 2 How can I modify this code? Please give me a GUI... world and like it alot. I was wondering where can I go to learn more about java...;GUI Example");pack();show();}public void actionPerformed(ActionEvent event Interview Tips - Java Interview Questions Interview Tips Hi, I am looking for a job in java/j2ee.plz give me interview tips. i mean topics which i should be strong and how to prepare. Looking for a job 3.5yrs experience Free Java Books Yourself Java 2 in 24 Hours As the author of computer books, I spend a lot... understand what makes the Java technology work. Introduction... using the Java programming language, but I had not found a textbook I was happy Searching with alphabetical order - Java Beginners Searching with alphabetical order Hi, I want to this please help me Steps:- 1:-I have a one form of name text box with two... help me its very urgent Thanks i think question is not much Searching with alphabetical order - Java Beginners Searching with alphabetical order Hi, please understood my problem and send write code its very urgent I a write once again. Steps:- 1:-I have a one form single name text box and two button delete and search GUI Alternatives , it isn't difficult to build a Graphical User Interface (GUI) in Java, but it is hard... to use the Java GUI libraries to build your GUI. There are alternatives... your interface be in Java? You can use existing GUI technologies like Flash Writing a GUI program - Java Beginners where and what i should put into the overall code. Also I can't quite figure out how...Writing a GUI program Hello everyone! I'm trying to write a program... has to calculate the prime factors of the given number. I figure out the whole GUI problem - Java Beginners GUI problem how to write java program that use JTextField to input... this, outputButton.setText(inputButton.getText()); hope u got it!!! ... this, outputField.setText(inputField.getText()); hope u got java gui - Java Beginners java gui i have to create dynamically databse,table, and number of field..inside that field dynamically data can be entered with type of variable..after entering all the dat in different form field label,i should have a button Java Programming Books , and as far as I know I was one of the first to do what I did - publish the book as I..., to just really understand what makes the Java technology work.  ...; A Java GUI Programmer's Primer Rationale for GUI tutorial decisions Table of Contents Rationale for GUI tutorial decisions Java offers many... that some Java textbooks are written without any GUI coverage, and others cover... of programs that have no GUI interface. For example, Java is very popular java gui-with jscroll pane java gui-with jscroll pane Dear friends.. I have a doubt in my gui application. I developed 1 application. In this application is 1 Jscrollpane... the window manually.....but i need this through my program...How can i show that text Fill-in: Rainfall GUI Java NotesFill-in: Rainfall GUI Name ______________________________ (5 points) Make a drawing of approximately what the window that this generates looks... 79 80 81 82 83 84 // RainfallGUI2.java - Provides a GUI interface java gui database - Java Beginners java gui database I have eight files. Each file has exactly same... record. It means there are 100 records(each of eight items). I can display the data on command line but I do not know how to display the same using java Tips & Tricks Tips & Tricks Splash Screen in Java 6.0 Splash screens are standard part of many GUI applications to let the user know about starting GUI Interface - Java Beginners GUI Interface Respected sir, please send me the codimg of basic... and multiplication. But use classes javax swing java awt java awt.event no other...)); for (int i = 0; i < buttonOrder.length(); i++) { String keyTop GUI - Java Beginners GUI How do i make these buttons work? Update, Delete, Save, Submit... links: Insertion, sorting and searching in array to perform searching and sorting in array. In the java code given below we have...; } Insertion, sorting and searching in array  ... arr[]) { System.out.println(msg + " : "); for (int i = 0; i < This is what i need - Java Beginners This is what i need Implement a standalone procedure to read in a file containing words and white space and produce a compressed version of the file.... for this question i need just : one function can read string like (I like Java: Basic GUI Java NotesBasic GUI Next - Big Blob This first example just shows what... 16 17 18 // structure/CalcV1.java // Fred Swartz - December 2004 // GUI Organization: All work is in the GUI constructor. // // (1) Main creates Java GUI Java GUI 1) Using Java GUI, create a rectangular box that changes color each time a user click a change color button. 2) Modify Question 1 to include a new button named insert image, that allow user to insert a bitmap image Java GUI IndexOf - Java Beginners Java GUI IndexOf Hello and thank you for having this great site. Here is my problem. Write a Java GUI application called Index.java that inputs...) return 0; int cnt = 0; for (int i = 0;; cnt++) { if ((i Gui - Java Beginners Gui How can i set a background color in my code and also put the Gender panel in the middle or center of the Personal details and The Buttons the adding an image on the label Inpatients maintainance module and also increasing Java GUI Program - Java Beginners Java GUI Program How is the following program supposed to be coded... created by the application. Hi friend, I am sending running code. I hope, This code will help you. import java.io.*; public class Java GUI Java GUI difference between swing and applet Magic Matrix in GUI Magic Matrix in GUI I want program in java GUI contain magic matrix for numbers What is Web Designing What is Web Designing The Internet has redefined the borders of our modern... exactly what they are looking for when they visit the site. A clearly defined purpose or goal of the site helps in understanding of what visitors want Java GUI - Java Beginners Java GUI HOW TO ADD ICONS IN JAVA GUI PROGRAMMES Searching an element - JSP-Servlet Searching an element Dear sir, sir i have an employee table ,in that i have attributes like empId name ,salary,loc etc.I have one jsp in that i am doing a searching an element by empId and displaying a all the employee table Rental Code GUI - Java Beginners Rental Code GUI dear sir... i would like to ask some code of java GUI form that ask the user will choose the menu to input Disk #: type... thank you and i will appreciate your kindness Serializing GUI Components Across Network - tutorial Serializing GUI Components Across Network 2001-03-14 The Java Specialists... and that you don't assign my to a Java loony bin, especially with the things I do... to as many people as you know who might be interested in Java. Serializing GUI GUI Interface .Reply me with in hour..Its Urgent - Java Beginners GUI Interface .Reply me with in hour..Its Urgent Hi ... Now i am... have to create GUI Interace ..How should i create the Interface. In Existing project - contains , encryption & Decryption..what i have to do is...To create Selecting elements of 2D array with GUI Selecting elements of 2D array with GUI Hello! I am building a Java application with GUI (JFrame form) that is supposed to display all... for each row or column. What I am struggling with is how to write a code...(); StudentMarks data[] = new StudentMarks[num]; for (int i = 0; i < data.length; i++) { System.out.println("Enter marks Tips & Tricks Tips & Tricks Here are some basic implementations of java language, which you would...?? You got it right! The program below runs without the main method. Here we have how to save a gui form in core java how to save a gui form in core java please help me i am java beginner how to save a jframe containing jtable and panels in java thank you What is Java - Java Beginners What is Java What is Java and how a fresher can learn it fast? Can any one share the fastest learning tips for Java Programming language? Thanks! Hi,Java is one of the most popular programming language. You can learn searching a text string in file - Java Beginners searching a text string in file code to match a string in a file that is already mentioned in java code.if the string matches any part of a string that whole string is printed Java gui program for drawing rectangle and circle Java gui program for drawing rectangle and circle how to write java gui program for drawing rectangle and circle? there shoud be circle...", "this is a green rectangle" etc. help me please.. i have to submit it this thursday Introduction to Dojo and Tips Introduction to Dojo and Tips This tips is light towards people with some JavaScript... need to use some of the features found in dojo. In this tips, learn about Java Gui - Java Beginners Java Gui HOW TO ADD LINK LABELS IN JAVA PROGRAMMES bank account gui ; Transaction>(); I already done with the GUI i just need the code to make the button...("Deposit Amount"); l[3]=new Label("Withdraw Amount"); for(int i=0;i<4;i++){ t[i]=new TextField(10); p.add(l[i]); p.add(t[i]); } p.add(but); p.add(but1 Java GUI - Java3D...:// If I open .class file with notepad what is displayed? If I open .class file with notepad what is displayed? What is displayed when we open java .class files with notepad file searching file searching i need a prog for searching inside a text file after evry 1 min to find does it hav any new entry Convert the code to GUI Java and GUI application Example Java and GUI application Example Convert the code to GUI Java GUI Class Example Java GUI Class Example Convert the code to GUI GUI Java JSP application GUI Java JSP application GUI Tutorial I - FIRST DRAFT Table of Contents GUI Tutorial I - FIRST DRAFT Table of contents... your first GUI programs, I suggest you imitate the examples. Eventually you... 26 27 28 // File : gui-tutorial/tw2/TinyWindow2.java // Purpose searching the data searching the data respected sir , i am making the desktop application , so how can i search the data which are stored in the mysql databses through click the button and display in jtable through netbeans dynamically Java GUI to build a Student Registration Program Java GUI to build a Student Registration Program Write a program..., the grader can request the report for a student or for a course I built an input... undergrad courses). I also made a list of 10 students. I'm a little hesitant Java GUI code Java GUI code Write a GUI program to compute the amount of a certificate of deposit on maturity. The sample data follows: Amount deposited: 80000.00 Years: 15 Interest rate: 7.75 Total Amount: Hint** to solve this problem GUI - Java Beginners GUI testing GUI testing in software testing HiNow, use the code and get the answer.import javax.swing.*;public class DemoTryCatchDialog...;GUI Example");pack();show();}public void actionPerformed(ActionEvent event Java I/O Java I/O What value does readLine() return when it has reached the end of a file Java I/O Java I/O What is the difference between the Reader/Writer class hierarchy and the InputStream/OutputStream class hierarchy Java I/O stream Java I/O stream What class allows you to read objects directly from a stream Java I\O file Java I\O file What is the difference between the File and RandomAccessFile classes urgent help needed in JDBC AND JAVA GUI - JDBC . the student can withdraw ,deposit and perform balance enquiries with the account, but i want any one to help me convert from scanner to java GUI for this code...urgent help needed in JDBC AND JAVA GUI my application allows Convert the code to GUI How to create GUI application in Java How to create GUI application in Java Component gui - Java Beginners Component gui Can you give me an example of Dialog in java Graphical user interface? Hi friend, import javax.swing.*; public...:// Thanks i got an error while compile this program manually. i got an error while compile this program manually. import... mapping.findForward("errors.jsp"); } } i set both servlet,struts jar files and i got an error in saveErrors() error Heading cannot find java about JRdio button and give exaple. how do you add a number to a GUI using swing? Briefly describe about JTable with exaple program. what do you mean by pluggable look and feel appearance what technique - Java Beginners what technique what technique or algorithm i need to use to develop a system a scheduling time table in java Netbeans GUI Ribbon Netbeans GUI Ribbon how to create ribbon task in java GUI using netbeans Ask Questions? If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for. Ask your questions, our development team will try to give answers to your questions.
http://www.roseindia.net/tutorialhelp/comment/82190
CC-MAIN-2013-20
refinedweb
2,648
63.29
Upgd nt4 pdc to w2kad It is possible to get DNS running on a non-Windows machine to service your AD structure. You will just not be able to do everything you could with a fully realized AD rollout (which includes DNS on the Domain Controllers). No Dynamic DHCP entries inDNS. No AD-intergrated DNS stuff. Personally, I am not that brave to run it like this. I have a similar situation in that I am rolling out AD on Saturday (wish me luck!), but my company currently has a global DNS solution built on Solaris machines. Now, I have decided to not try and fight with DNS on Solaris and AD. Instead, I am setting up a new Win2K server (\\NEWDC) as a member server. After that, I will promote my current NT4 PDC (\\PDC) to Win2k, which will auto-run DCPROMO and set upAD AND install DNS. AFter that, I am taking my new Win2K server \\NEWDC and promoting it to be another Domain Controller in my now-existing AD forest (and installing DNS at that time). After that, I am transferring all FSMO roles from \\PDC to \\NEWDC. Once that is done, I am demoting \\PDC so I will only have 1 Domain Controller, \\NEWDC Ok? Good. Now, once \\NEWDC is the only AD server, I am going to go into its DNS Management MMC Snap-in, and I am going to enable DNS Forwarders for itsDNS server. I am going to point the Forwarders to the primary Solaris DNS servers we already have. I am doing that because the DNS setup for AD will be DIFFERENT from my company's current DNS domain namespace running on the Solaris boxes. And thatway, my office clients (who will be part of the AD domain OFFICE.DOMAIN) will be able to resolve DOMAIN.COM (which is hosted by the Solaris DNS servers) by the DNS on \\NEWDC. Sure, \\NEWDC is just gonna forward name resolution requests for DOMAIN.COM to the Solaris DNS machines, but to the clients it will be transparent. Hope this all makes sense. It took a couple of weeks planning to get this to work. Upgd nt4 pdc to w2kad Ok, if you are just not comfortable rolling out AD with its DNS requirements, then yeah, set up a new NT4 box. Make it a BDC in your existing NT domain. Let it synchronize up with your PDC. Then promote this new BDC to be the PDC. You can then take the old PDC offline and scrap it. Doing it this way will keep all of your Windows accounts, and the new machine is the PDC. This is, admitedly, a lot easier than the AD rollout. Yes, Win2K with AD is better than NT4 flat domain, but if you don't have a need to go to AD, then don't. And if you really don't want to interface with DNS on Linux at all, then go the NT4 route. Good luck! Upgd nt4 pdc to w2kad Sounds spot-on. Check out the DNS requirements for 2000 AD though. Microsoft recommends their 2000 DNS server naturally, but yours may be ok if it supports dynamic updates and SRV resource records. As far as whether to, or not. 2000 is much better for lots of reasons, more efficient, more stable, and nicer to manage. AD adds more complexity and with it more granular control. It is a steep learning curve if you really want to use it to it's full potential, and if you have a small relatively simple network then you won't gain much. Your decision. Upgd nt4 pdc to w2kad Answer #1 looks kinda like the line of thought I was looking at. Very Detailed, very complex, Many points of failure (Things I could do wrong) The server is at a hosting center and only needs to authenticate a few VPN logins from developers, The IWAM and IUSER accounts for a couple of IIS servers, DB and a few file servers. My main concern is prior to me coming to this company, they installed all the customers dynamically updating (Customer.mycompany.com) DNS on a Linux DNS box. If I tank this, thousands of customers will be in screwed (I will be screwed). I will not be using any groups, OU's or policys with AD. From both of your answers so far it is looking like i should just replace the Pile Of PDC (needs reboot 3-4 times a day now)with a new fresh server with nt4 pdc on it. What do you think, either of you guys? Upgd nt4 pdc to w2kad This conversation is currently closed to new comments.
https://www.techrepublic.com/forums/discussions/upgd-nt4-pdc-to-w2kad/
CC-MAIN-2021-10
refinedweb
783
80.72
Pre-trained Models with Keras in TensorFlow Tuesday May 2, 2017 With TensorFlow 1.1, Keras is now at tf.contrib.keras. With TensorFlow 1.3, it should be at tf.keras. This is great for making new models, but we also get the pre-trained models of keras.applications (also seen elsewhere). It's so easy to classify images! import tensorflow as tf model = tf.contrib.keras.applications.ResNet50() This will automatically download trained weights for a model based on Deep Residual Learning for Image Recognition. The weights are cached below your home directory, in ~/.keras/models/. Convenient image tools are also included. Let's use an image of a koala from the imagen ImageNet subset. filename = 'n01882714_4157_koala_bear.jpg' image = tf.contrib.keras.preprocessing.image.load_img( filename, target_size=(224, 224)) This model can take input images that are 224 pixels on a side, so we have to make our image that size. We're just doing it by squishing, in this case. We'll make that into an array that the model can take as input. import numpy as np array = tf.contrib.keras.preprocessing.image.img_to_array(image) array = np.expand_dims(array, axis=0) Now we can classify the image! probabilities = model.predict(array) We have one thousand probabilities, one for each class the model knows about. To interpret the result, we can use another helpful function. tf.contrib.keras.applications.resnet50.decode_predictions(probabilities) ## [[(u'n01882714', u'koala', 0.99466419), ## (u'n02497673', u'Madagascar_cat', 0.0013330306), ## (u'n01877812', u'wallaby', 0.00085774728), ## (u'n02137549', u'mongoose', 0.00063530984), ## (u'n02123045', u'tabby', 0.00056512095)]] Great success! The model is highly confident that it's looking at a koala. Not bad. It's pretty fun that this kind of super-easy access to quite good pre-trained models is now available all within the TensorFlow package. Just pip install and go! The thousand ImageNet categories this model knows about include some things that are commonly associated with people, but not a "person" class. Still, just for fun, what will ResNet50 say about me? ## [[(u'n02883205', u'bow_tie', 0.3144455), ## (u'n03787032', u'mortarboard', 0.059674311), ## (u'n02992529', u'cellular_telephone', 0.049916871), ## (u'n04357314', u'sunscreen', 0.048197504), ## (u'n04350905', u'suit', 0.03481029)]] I guess I'll take it? Notes: The model may have been trained on the very koala picture we're testing it with. I'm okay with that. Feel free to test your own koala pictures! There's also another function, resnet50.preprocess_input, which in theory should help the model work better, but my tests gave seemingly worse results when using that pre-processing. It would be used like this: array = tf.contrib.keras.applications.resnet50.preprocess_input(array) Keras in TensorFlow also contains vgg16, vgg19, inception_v3, and xception models as well, along the same lines as resnet50. I'm working on Building TensorFlow systems from components, a workshop at OSCON 2017.
https://planspace.org/20170502-canned_models_with_keras_in_tensorflow/
CC-MAIN-2020-29
refinedweb
484
62.75
Hi and welcome to our site!If none of the profits were distributed and was not required to be distributed - the form K1 is not required.NOL will stay with the estate and unused deductions will be passed to beneficiaries on the final tax return (final K1) when the estate is closed.If anything were distributed previously should not affect the distribution on the final tax return. Another loss in 2012 - The answer is what I expected, but since this estate is being fought out in court, I wanted to be certain that I was correct. Thanks, Joan So, if the property is distrusted in 2012,, can I show the property distribution on the 2013 k-1.? If I wait for the final return to file any K"1's I don't know the proper way to show the property distrustions of the corpus from a prior year. Perfect - I did see that the K-1 on the 1041 has no place for property distributions, but I knew the beneficiaries needed something to show basis of the rental property. Your understanding is correct. Only items that affect income tax return of beneficiaries are reported on K1. The distribution of the corpus is not required to be reported. You may however report the distribution of the corpus on line 14 as Other information. If the only item to report is the corpus distribution - you still MAY issue K1, but it is not required. Some additional comments are passed by MequonCPA: Any distribution of assets by the trust is assumed to be income first. The fact that the trustee chose to distribute real estate rather than cash doesn't change the sequence.
http://www.justanswer.com/tax/811nn-question-k-1-s-1041-estate-return-estate.html
CC-MAIN-2015-48
refinedweb
281
61.56
I've been reading more of the tutorials. Could someone please explain to me what this line of code is for:Could someone please explain to me what this line of code is for:Code:#include <iostream> //For cout #include <cstring> //For the string functions using namespace std; int main() { char name[50]; char lastname[50]; char fullname[100]; // Big enough to hold both name and lastname cout<<"Please enter your name: "; cin.getline ( name, 50 ); if ( strcmp ( name, "Julienne" ) == 0 ) // Equal strings cout<<"That's my name too.\n"; else // Not equal cout<<"That's not my name.\n"; // Find the length of your name cout<<"Your name is "<< strlen ( name ) <<" letters long\n"; cout<<"Enter your last name: "; cin.getline ( lastname, 50 ); fullname[0] = '\0'; // strcat searches for '\0' to cat after strcat ( fullname, name ); // Copy name into full name strcat ( fullname, " " ); // We want to separate the names by a space strcat ( fullname, lastname ); // Copy lastname onto the end of fullname cout<<"Your full name is "<< fullname <<"\n"; cin.get(); } Code:fullname[0] = '\0';
http://cboard.cprogramming.com/cplusplus-programming/61757-strings.html
CC-MAIN-2013-48
refinedweb
176
74.83
Hi everyone! I finished up my C programming book back in December, then took a break. I'm back and studying C++ now, and this is my first question. I completed the exercise successfully, in terms of using "new" for a structure pointer, and all data displayed as it should after user input. What I'm wondering is, just for my own edification, I placed identical display code after I used "delete" to free the memory, and while the string member seems to be emptied out, both of the float members still retain the input data. Is this okay, or am I not using the delete keyword properly with a structure? Thanks! Code: // Do programming exercise 4, but use new to allocate a structure // instead of declaring a structure variable. Also, have the program // request the pizza diameter before it requests the pizza company name. #include <iostream> using namespace std; struct Pizza { char company[30]; float diameter; float weight; }; int main() { const int arraysize = 30; Pizza * pie = new Pizza; cout << "\nWhat is the diameter of your pizza in inches? _\b"; cin >> pie->diameter; cin.get(); cout << "\nWhat restaurant did your pizza come from? _\b"; cin.getline(pie->company, arraysize); cout << "\nWhat is the weight of your pizza in ounces? _\b"; cin >> pie->weight; cout << "\nYour pizza came from " << pie->company << ", it's " << pie->diameter << " inches in diameter, and\n" << "it weighs " << pie->weight << " ounces." << endl; delete pie; cout << "\nAfter freeing up used memory:\n"; cout << "\nYour pizza came from " << pie->company << ", it's " << pie->diameter << " inches in diameter, and\n" << "it weighs " << pie->weight << " ounces." << endl; return 0; }
http://cboard.cprogramming.com/cplusplus-programming/139362-using-delete-structure-pointer-printable-thread.html
CC-MAIN-2015-32
refinedweb
271
61.97
Install the iOS API client Install - Add a dependency on AlgoliaSearch-Client-Swift: CocoaPods: add pod 'AlgoliaSearch-Client-Swift'to your Podfilefor Swift 4 CocoaPods: add pod 'AlgoliaSearch-Client-Swift', '~> 4.0'to your Podfilefor Swift 3 Carthage: add github "algolia/algoliasearch-client-swift"to your Cartfile - Add import AlgoliaSearchto your source files Supported platforms Our Swift client is supported on iOS, macOS, tvOS and watchOS, and is usable from both Swift and Objective-C. Language-specific notes You can browse the automatically generated reference documentation. (See also the offline-enabled version.) Upgrading If you were using version 2.x of our Swift client, read the migration guide to version 3.x. Init Index To begin, you will need to initialize the client. In order to do this you will need your Application ID and API Key. You can find both on your Algolia account. let client = Client(appID: "YourApplicationID", apiKey: "YourAPIKey") let index = client.index(withName: . If you are building a native app on mobile, be sure to not include the search API key directly in the source code. You should instead consider fetching the key from your servers during the app’s startup. Did you find this page helpful? We're always looking for advice to help improve our documentation! Please let us know what's working (or what's not!). We're constantly iterating thanks to the feedback we receive.
https://www.algolia.com/doc/api-client/swift/getting-started/
CC-MAIN-2018-34
refinedweb
233
58.38
Search: Search took 0.03 seconds. - 16 Dec 2009 4:10 PM Was using EXTjs 3.0. Have upgraded to 3.0.3 and it's still not playing ball (i.e. "namespace":"myNs" is not being appended to the extdirect_api.js file). I can confirm that the same files work... - 15 Dec 2009 1:54 PM Hi Dan, I'm assuming that if i set 'action_namespace', I should then call the direct functions using the namespace? Specifically, if I use your multiply example as an action in an a module called... - 9 Dec 2009 3:42 PM Cool. I'll have a play and let you know. W :-) - 9 Dec 2009 2:30 PM Thanks for this Dan, It's great! I'm staring a new project, and wondered if anyone has this working with 1.3/4, or should I stick to 1.2? I cant see anything in the source that would stop it... - 16 Nov 2009 11:22 AM - Replies - 2 - Views - 1,352 Thank you for taking the time to reply :-) - 13 Nov 2009 11:36 AM - Replies - 2 - Views - 1,352 I have a n00bish question.. I'm trying to follow Saki's big app method, but have got stuck. I'm not sure how you add a handler for a button bar to it's parent viewport onRender function. Example code... - 3 Jul 2009 9:55 AM I'm such a wally. the plugin parses the actions files, not the model files. puting the commneted function in the actions.class.php file fixed everything. - 2 Jul 2009 11:37 AM I'm still learning symfony, and am keen to use this plugin. I cant seem to get it to work though. Could you tell me where i went wrong here? Follwing the instructions in the readme, and using the... Results 1 to 8 of 8
https://www.sencha.com/forum/search.php?s=79f50cbfb646fc9ae40d38649a6e3036&searchid=12492388
CC-MAIN-2015-35
refinedweb
312
85.99
This is the initial layout of the grid. The value must be an Array of Object items. Each item must have i, x, y, w and h proprties. Please refer to GridItem documentation below for more informations. That's it! Vue Slicksort does not come with any styles by default, since it's meant to enhance your existing components.drag grid drop vue-slicksort mixin-components sortable-helper sort animated dependency free vue vuejs vue-component vue-mixin sortable sortable-list list smooth mixin component react-sortable-hoc vue-sort vue-sortable drag-and-drop A grid-based drag/drop/resize directive plugin for Angular 2grid angular angular2-grid angular2 web-components angular-component Makes your elements draggable in Vue. group is unique key of dragable list.vue vue-dragging vue-drag vue-dnd draggable drag drop html5 droppable drag-and-drop dnd Example of a two column, responsive, centered grid. All grid layout classes and responsive width classes are modifiers. $av-namespace Global prefix for layout and cell class names. Default: grid.css sass scss bem grid-layout grid oocss. A directive for providing drag and drop capabilities to elements and data. Available through npm install vue-drag-and-drop or include as an inline script, like in example.html.drag drop vuejs Modular Grid System. MUELLER is a modular grid system for responsive/adaptive and non-responsive layouts, based on Compass. You have full control over column width, gutter width, baseline grid and media-queries.layout grid sass compass responsive adaptive rwd Vue component (Vue.js 2.0) or directive (Vue.js 1.0) allowing drag-and-drop and synchronization with view model array.vue vuejs drag and drop list sortable.js web-components Plugin does NOT modify the source data array. Cell template is used to get access to list data, indexing and sorting params generated by plugin.vuejs grid-system plugin vue We have large collection of open source products. Follow the tags from Tag Cloud >> Open source products are scattered around the web. Please provide information about the open source projects you own / you use. Add Projects.
https://www.findbestopensource.com/product/jbaysolutions-vue-grid-layout
CC-MAIN-2020-10
refinedweb
352
50.73
Decimal. You can assign either a reference type or a value type to a variable of the Object data type. An Object variable always holds a pointer to the data, never the data itself. However, if you assign a value type to an Object variable, it behaves as if it holds its own data. For more information, see Object Data Type. You can find out whether an Object variable is acting as a reference type or a value type by passing it to the IsReference method in the Information class of the Microsoft.VisualBasic namespace. Information.IsReference returns True if the content of the Object variable represents a reference type.
http://msdn.microsoft.com/en-us/library/t63sy5hs(v=vs.120).aspx
CC-MAIN-2014-15
refinedweb
110
53.21
On Fri, Nov 25, 2011 at 01:43:28PM +1100, Erik de Castro Lopo wrote: > Well, colour me surprised. > > The existing bluetile compiles with version 0.10 of xmonad and > xmonad-contrib and also installs, without any changes being > needed. The magic of Haskell! ;-) That's good to hear! When backporting Bluetile to XMonad 0.9, I copied a lot of needed modules from xmonad-contrib (from what was then just in darcs). But I put them into a different namespace to avoid conflicts. Now that XMonad 0.10 is available, I am planning to release a cleaned-up version of Bluetile where all that code duplication is removed. I'll post on the list once that is done. Regards! Jan
http://lists.debian.org/debian-haskell/2011/11/msg00046.html
CC-MAIN-2013-48
refinedweb
121
78.14
Follow-up Comment #7, patch #8377 (project octave): Got a answer from Sandeep (Sunny): "Yes. convert_to_cartesian() is geodetic2ecef" (BTW Please follow up in the patch tracker, not through (private) email.) I found out that convert_to_cartesian.m might be a wrapper around geodetic2ecef.m as in the tests the input & output of convert_to_cartesian.m more or less wrap up several input/output arguments of geodetic2ecef.m. In addition, myassert() is missing. In short, the code seems too incomplete to incorporate in the next mapping package release :-( For me it is simply undoable to fix all such changes in the test suite; I lack time for that. I also found a bug in geodetic2ecef.m (that could be due to my changes): there needs to be another "else" clause in the code testing for the "ell" variable: if ((nargin < 4) || isempty (ellipsoid)) ell = get_ellipsoid(); elseif (! isstruct (ellipsoid)) ell = get_ellipsoid (ellipsoid); else ## Missing else clause ell = ellipsoid; ## New stanza endif ..without that change the first test breaks. I haven't had time to check the rest of the functions. I hope you can do that yourself. Could you please start from my patch on top of your two patches? I've already checked in the contributions of Pooja (see patch #8372) yesterday; AFAICS your patches and mine still apply cleanly upon the new repo state as of yesterday April 3. It would be very nice if your contributions could make it for the next mapping package release. Do not worry about style, I can fix that; my concern is that the code and all tests works in Octave-4.0.0-rc2. Thanks _______________________________________________________ Reply to this item at: <> _______________________________________________ Message sent via/by Savannah
https://lists.gnu.org/archive/html/octave-patch-tracker/2015-04/msg00010.html
CC-MAIN-2019-35
refinedweb
282
74.08
I'm doing an assignment for school which is to simulate the grep command in C++. We are to take in a word to search, an input file to search through, and output file to output the results. The only text that should be in the output file is the contents of each line that had the search word in it, with a line number of where it was in the input file. We are supposed to use the functions of <fstream>. I'm a beginner to c++ and am having trouble wrapping my head around this problem. I don't know how to output just the line which has the word nor how to input a way of tracking line numbers. What I have so far: #include <iostream> #include <fstream> #include <string> using namespace std; int main() { string keyword, inputFile, outputFile, line; unsigned keywordCount = 0; cout << "Enter word to search for: " << endl; cin >> keyword; cout << "Enter file to search through: " << endl; cin >> inputFile; cout << "Enter file to output results to: " << endl; cin >> outputFile; ifstream in( inputFile.c_str() ); if( !in ) { cout << "Could not open: " << inputFile << endl; return EXIT_FAILURE; } ofstream out; out.open( outputFile.c_str() ); if( !out ) { cout << "Could not open: " << outputFile << endl; return EXIT_FAILURE; } while( getline( in,line ) ) { if( line.find( keyword ) ){ out << line; ++keywordCount; } } cout << keywordCount; } Any help is appreciated.
https://www.daniweb.com/programming/software-development/threads/417186/trouble-finding-a-specifc-word-from-a-file
CC-MAIN-2017-17
refinedweb
221
66.78
How to Use Class Libraries in Visual StudioSee Visual Studio: Tips and Tricks for similar articles. The steps below describe how to utilize class libraries in Visual Studio. - A class library is a collection of class definitions contained in a .dll or .exe file. - In order to use the class library, you must first add a reference to the library (see "How to add references to your Visual Studio Project"). - Once the library has been referenced, the classes in the library can be instantiated and exercised. In order to instantiate the class, you must either fully qualify the class name or bring it into scope with a using statement (C#) or Import statement (VB). To fully qualify the class name, you reference the library name and class name using dot syntax. If, for example, the library is named 'MyLib' and the class is named "MyClass", you would use the following syntax:C#VB MyLib.MyClass = new MyLib.MyClass(); Dim newObject as MyLib.MyClass() - If you prefer, you can bring the namespace into scope with a 'using' or 'import' statement and then reference the class directly. For example,C# using MyLib; class NewClass; { static void Main(string[] args) { MyClass = new MyClass(); } }VB imports MyLib Sub Main() Dim newObject as MyClass() End Sub - After instantiating the class, you can then use it as you would any object (exercise the properties, methods, etc.). Related Articles - How to Add References to Your Visual Studio Project - How to Use Class Libraries in Visual Studio (this article)
https://www.webucator.com/article/how-to-use-class-libraries-in-visual-studio/
CC-MAIN-2022-21
refinedweb
251
60.85
SYNOPSIS #define _XOPEN_SOURCE 500 #include <stdlib.h> int getsubopt(char **optionp, char * const *tokens, char **valuep); DESCRIPTION gets list- option. The value extends to the next comma, or (for the last subop- tion) character at the end of the string if the last suboption was just processed.(). CONFORMING TO POSIX.1-2001. NOTES Since getsubopt() overwrites any commas it finds in the string *optionp, that string must be writable; it cannot be a string constant. " fprintf(stderr, "suboptions are 'ro', 'rw', " "and 'name=<value>'\n"); exit(EXIT_FAILURE); } /* Remainder of program... */ exit(EXIT_SUCCESS); } SEE ALSO getopt(3), feature_test_macros(7) COLOPHON This page is part of release 3.23 of the Linux man-pages project. A description of the project, and information about reporting bugs, can be found at.
http://www.linux-directory.com/man3/getsubopt.shtml
crawl-003
refinedweb
127
58.58
Holy cow, I wrote a book! Today's Little Program asks you to type something, but gives you only two seconds to do it. This is not interesting in and of itself, but it shows you how to cancel console I/O. There is no motivation for this exercise because Little Programs come with little to no motivation. Okay, fine, here's the motivation. We have a GUI application that has a debug console. When the user exits the application, we cannot shut down cleanly because the debug console is stuck on a read from stdin. We want to unstick the thread gently. We don't want to use GenerateConsoleCtrlEvent with CTRL_C_EVENT because that will send the event to all processes using the same console, but we don't want other processes to be affected. stdin GenerateConsoleCtrlEvent CTRL_C_EVENT Okay, now our Little Program. #include <windows.h> #include <stdio.h> // horrors! mixing C and C++! DWORD CALLBACK ThreadProc(void *) { Sleep(2000); CancelIoEx(GetStdHandle(STD_INPUT_HANDLE), nullptr); return 0; } int __cdecl wmain(int, wchar_t **) { DWORD scratch; HANDLE h = CreateThread(nullptr, 0, ThreadProc, nullptr, 0, &scratch); if (h) { printf("type something\n"); char buffer[80]; if (fgets(buffer, 80, stdin) != nullptr) { printf("you typed %s", buffer); } else if (feof(stdin)) { printf("end-of-file reached\n"); } else if (ferror(stdin)) { printf("error occurred\n"); } } return 0; } If you type something within two seconds, it is reported back to you, but if you take too long, then the CancelIoEx cancels the console read, and you get an error back. CancelIoEx If you want to continue, you'll have to clearerr(stdin), but if you just want to unstick the code that is performing the read (so that you can get the program to exit cleanly), then leaving stdin in an error state is probably better. clearerr(stdin) (If you had used ReadFile instead of fgets, the read would have failed with error code ERROR_OPERATION_ABORTED, as documented by CancelIoEx.) ReadFile fgets ERROR_OPERATION_ABORTED In Looking for leaked objects by their vtable, we used the object's constructor to locate the vtable, and then scanned the heap for the vtable to find the leaked object. But you can run this technique in reverse, too. Suppose you found an object and you want to find its constructor. This is not a problem if you have the source code, but if you are doing some reverse-engineering for application compatibility purposes, you don't have the luxury of the application source code. You may have figured out that the application fails because the byte at offset 0x50 is zero, but on the previous version of Windows, it was nonzero. You want to find out who sets the byte at offset 0x50, so that you can see why it is setting it to zero instead of a nonzero value. If the object has a vtable, you can scan the code segments for a copy of the vtable. It will show up in an instruction like mov dword ptr [reg], vtable_address This is almost certainly the object's constructor, setting up the object vtable as part of construction. You can set a breakpoint here to break when the object is constructed, and then you can set a write breakpoint on offset 0x50 to see where its value is seto. The RegisterWindowMessage function lets you create your own custom messages that are globally unique. But how do you free the message format when you're done, so that the number can be reused for another message? (Similarly, RegisterClipboardFormat and clipboard formats.) RegisterWindowMessage RegisterClipboardFormat You don't. There is no DeregisterWindowMessage function or DeregisterClipboardFormat function. Once allocated, a registered window message and registered clipboard format hangs around until you log off. DeregisterWindowMessage DeregisterClipboardFormat There is room for around 16,000 registered window messages and registered clipboard formats, and in practice exhaustion of these pools of numbers is not an issue. Even if every program registers 100 custom messages, you can run 160 unique programs before running into a problem. And most people don't even have 160 different programs installed in the first place. (And if you do, you almost certainly don't run all of them!) In practice, the number of registered window messages is well under 1000. A customer had a problem with exhaustion of registered window messages. "We are using a component that uses the RegisterWindowMessage function to register a large number of unique messages which are constantly changing. Since there is no way to unregister them, the registered window message table eventually fills up and things start failing. Should we use GlobalAddAtom and GlobalDeleteAtom instead of RegisterWindowMessage? Or can we use GlobalDeleteAtom to delete the message registered by RegisterWindowMessage?" GlobalAddAtom GlobalDeleteAtom No, you should not use GlobalAddAtom to create window messages. The atom that comes back from GlobalAddAtom comes from the global atom table, which is different from the registered window message table. The only way to get registered window messages is to call RegisterWindowMessage. Say you call GlobalAddAtom("X") and you get atom 49443 from the global atom table. Somebody else calls RegisterWindowMessage("Y") and they get registered window message number 49443. You then post message 49443 to a window, and it thinks that it is message Y, and bad things happen. GlobalAddAtom("X") RegisterWindowMessage("Y") And you definitely should not use GlobalDeleteAtom in a misguided attempt to deregister a window message. You're going to end up deleting some unrelated atom, and things will start going downhill. What you need to do is fix the component so it does not register a lot of window messages with constantly-changing names. Instead, encode the uniqueness in some other way. For example, instead of registering a hundred messages of the form Contoso user N logged on, just register a single Contoso user logged on message and encode the user number in the wParam and lParam payloads. Most likely, one or the other parameter is already being used to carry nontrivial payload information, so you can just add the user number to that payload. (And this also means that your program won't have to keep a huge table of users and corresponding window messages.) Contoso user N logged on Contoso user logged on wParam lParam Bonus chatter: It is the case that properties added to a window via SetProp use global atoms, as indicated by the documentation. This is an implementation detail that got exposed, so now it's contractual. And it was a bad idea, as I discussed earlier. SetProp Sometimes, people try to get clever and manually manage the atoms used for storing properties. They manually add the atom, then access the property by atom, then remove the properties, then delete the atom. This is a high-risk maneuver because there are so many things that can go wrong. For example, you might delete the atom prematurely (unaware that it was still being used by some other window), then the atom gets reused, and now you have a property conflict. Or you may have a bug that calls GlobalDeleteAtom for an atom that was not obtained via GlobalAddAtom. (Maybe you got it via GlobalFindAtom or EnumProps.) GlobalFindAtom EnumProps I've even seen code that does this: atom = GlobalAddAtom(name); // Some apps are delete-happy and run around deleting atoms they shouldn't. // If they happen to delete ours by accident, things go bad really fast. // Prevent this from happening by bumping the atom refcount a few extra // times so accidental deletes won't destroy it. GlobalAddAtom(name); GlobalAddAtom(name); So we've come full circle. There is a way to delete an unused atom, but people end up deleting them incorrectly, so this code tries to make the atom undeletable. Le Chatelier's Principle strikes again. One.) For. Some_MULTITHREADED is used. CoInitializeEx COINIT_MULTITHREADED FinalizerThreadStart. KickOffThread And the flags passed to this call to CoInitializeEx are 0, which once again means that it defaults to MTA. There, we have confirmed experimentally that, at least in this case, the implementation matches the documentation. That the implementation behaves this way is not surprising. After all, the CLR does not have insight into the GetTickCount function. It does not know a priori whether that function will create any COM objects. After all, we could have been p/invoking to SHGetDesktopFolder, which does use COM. Given that the CLR cannot tell whether a native function is going to use COM or not, it has to initialize COM just in case. GetTickCount SHGetDesktopFolder ¹ Or somebody who is trying to mislead us into thinking that it is the finalizer thread. I tend to discount this theory because as a general rule, code is not intentionally written to be impossible to understand. A. call. GetMessageW But look more closely at the overwritten bytes. The first byte is cc, which is a breakpoint instruction. Hm... cc Since Windows functions begin with a MOV EDI, EDI instruction for hot patching purposes, the first two bytes are always 8b ff. If we unpatch the cc to 8b, we see that the rest of the code bytes are intact. MOV EDI, EDI 8b ff 8b." CONTOSO user32!GetMessageW int.) A customer was debugging their application and discovered that for one of the objects they were using, the IUnknown::AddRef method returns 0. How is that possible? That would imply that the object's reference count was originally negative one? IUnknown::AddRef The return value from IUnknown::AddRef::AddRef will count only one reference per proxy, even if the proxies themselves have reference counts greater than one. The object the customer was using came from MSHTML.DLL, and it so happens that the implementation of IUnknown::AddRef used by that component always returns zero. It is technically within their rights to do so. MSHTML.DLL::AddRef that betrays no information about the object's true reference count may have been a defensive step to prevent applications from making any such dubious dependency. IUnknown:Release If you install the debugging version of MSHTML.DLL, then the IUnknown::AddRef method will return the reference count. Which makes sense in its own way because the value is intended to be used only when debugging. This." XYZ.EXE XYX. pwnz0rd.exe Renaming or copying a file requires FILE_ADD_FILE permission in the destination directory, and if you have permission to add files to a directory, why stop at just adding files that are copies of existing files? You can add entirely new files! FILE_ADD_FILE In other words, instead of copy XYZ.EXE XYX.EXE, just do copy pwnz0rd.exe XYX.EXE. copy XYZ.EXE XYX.EXE. XYX.EXE CreateProcess I was helping somebody look up how to enable frobbing for widgets, and I found one set of instructions on a blog somewhere. To be honest, this happened long enough ago that I forgot what it was exactly, but here's something that captures the general spirit:.) The changes will take effect at the next reboot. To make them take effect immediately, simply run the command episkey GANDALF.color=black DRADIS=pikachu. voodoo.) abc frob="1" frob="0" The changes will take effect at the next reboot. To make them take effect immediately, simply run the command epis.
http://blogs.msdn.com/b/oldnewthing/default.aspx?Redirected=true&PageIndex=3
CC-MAIN-2015-18
refinedweb
1,862
62.88
Update to Code Template add-in for Visual C++ WEBINAR: On-Demand Full Text Search: The Key to Better Natural Language Queries for NoSQL in Node.js Darren Richard's code template add-in for Visual C++ is great. It provides a way to insert commonly used code fragments into a file merely by clicking a menu item. Furthermore, code fragments can be modified by simply editing a simple text file. After I used it for a while I found some features lacking that I really needed in order to use the add-in fully. So I modified it. I have added three new features to the add-in : submenus, keywords, and format specifiers. This article does not describe how to use the original features of the add-in. Refer to Darren's article Code Template add-in for Visual C++ 5.0 for information on how to use the original add-in. The add-in now supports submenus. The submenus may be nested arbitrarily deep although I have not tested more than 2 levels. To 'declare' a submenu within the code fragment file, use the delimiter '#[' followed by the name of the submenu. You may then proceed to declare code fragments as you normally would using the '#{' delimiter. To close the submenu, use the ']#' delimiter. For example : #[Comments #{Header Files ... #} #{Source Files ... #} ]#The preceding example will create a submenu off the main menu of the add-in. The submenu will be called 'Comments'. The submenu will contain 2 menu items, 'Header Files' and 'Source Files'. You can use separators within the submenus as well. I have not tested the submenus beyond 3 levels. Keywords Whenever I write the comment header for my files, I like to specify the filename, date, and the project name. In order to support this, the add-in has been modified to support keywords. Keywords are substituted for their actual value when the add-in is copying the code fragment from the template file to the target file. Keywords may appear anywhere that code can appear. Keywords are delimited by '#%' and '%#'. The following keywords are supported : DATE - The current date. EXT_ONLY - The current file's extension. FILE - The current file, including extension but not path. FILENAME_ONLY - The current filename, without extension. PATH - The path to the current file. PROJECT - The current project. TIME - The current time. For example : #{Header File /*********************************** * File : #%FILE%# * Project : #%PROJECT%# ***********************************/ #}The preceding example, when inserted into the target file, will expand to a comment block with the filename of the target file and the project it is contained in. Format Specifiers The final enhancement that has been made is format specifiers. Format specifiers work similar to those in 'C'. They modify the formatting of the enclosed text. Format specifiers are delimited by '#<' and '#>'. Each beginning delimiter must be followed by the format specifier, without any spaces. After the format specifier, and before the ending delimiter, should be the text to format. The following format specifiers are supported : U - Uppercases the text. L - Lowercases the text. W - Forces the text to be a given width. The width should be specified after the 'W' specifier, separated by a space. The following example should help clear things up : #{Header File /*************************************** * #<W 40 This string will be padded to 40 characters># * #<U This string will be uppercased># * #<L This string will be lowercased># ***************************************/ }# Format specifiers are processed after the keywords have been expanded. Therefore, format specifiers can be applied to the results of a keyword expansion. For example : #{ #if !defined(#<U #%FILENAME_ONLY%#>#_H_INCLUDED) #define #<U #%FILENAME_ONLY%#>#_H_INCLUDED #endif // Sentry #}The preceding example will take the filename of the current file and uppercase it and then insert it. If the file is called Addin.h, for example, the code will expand to #if !defined(ADDIN_H_INCLUDED) #define ADDIN_H_INCLUDED #endif // Sentry Future Work One feature that is still missing, but that I would like to add when time permits is the ability to be prompted for information when the code fragment is being inserted. Then, based on my response, the code fragment will be modified. One immediate use I see for this is when defining a class. One of the things I put in my class comment header is the name of the base class. Currently there is no mechanism to detect this. It would be nice if, instead, the add-in prompted me for the base class when it was inserting the code fragment. Perhaps I'll get around to it soon... Installation To install the add-in, do the following : 1. Copy codetempl these extensions prove helpful to those of you using the add-in already. Any feedback is appreciated. If you want to add your own keywords or format specifiers then you will need to modify the source code. Look in Format.h and Format.cpp for the approriate code. Keywords are far easier to add then format specifiers. If you do add any neat new keywords or format specifiers then please pass them along. I have provided a sample template file. It uses most of the keywords and specifiers. It also uses multiple submenus. You can use the template file as an example to help you create your own. Download source and add-in - 45 KB Date Last Updated: March 6, 1999 There are no comments yet. Be the first to comment!
https://www.codeguru.com/cpp/v-s/devstudio_macros/codetemplateadd-in/article.php/c3083/Update-to-Code-Template-addin-for-Visual-C.htm
CC-MAIN-2018-13
refinedweb
888
67.86
Issues Link to tip version of source files From Christos Τrochalakis (ctrochalakis): It would make sense if we could use urls that always point to the tip version of the source files. something like: It'd be nice if we could also do this with other tag names and with branch names. It's a great feature of hgweb that I miss when using Bitbucket. For example: I suspect that if you added support for arbitrary tag and branch names, support for the “tip” name would come for free; I base this on the fact that `hg tags` includes “tip” in its output. Shouldn't be too difficult, I'll get on this later. I was thinking about this issue, I believe there are two, kind of different things, that need to addressed: But when viewing the file links should probably be /src/2e567e30060b/myfile We don't have a translation map yet, i.e. if you view a rev that's actually tip, it will stills how the rev hash, but I think there are certain dangers to doing that, like if you are viewing a file and a newer version gets committed, it will change the file once you reload the page. If you really want this behavior, feel free to replace the rev hash with 'tip' in the url yourself, should yield the same results. I'm keeping it resolved for now. Re-open if further discussion is needed. like if you are viewing a file and a newer version gets committed, it will change the file once you reload the page. Yes, you are correct, but I suspect that this behavior would be perfectly normal. You are viewing the tip version of a file, tip can change anytime. What I am saying is that semantics are correct. But that's probably a matter of taste :) Thanks for resolving this Jesper :) Yes, you are correct, but I suspect that this behavior would be perfectly normal. You are viewing the tip version of a file, tip can change anytime. What I am saying is that semantics are correct. Yes, I agree that it's expected behavior, but I think one should "choose" this behavior by manually updating the URL. More often than not, someone will click on a file that just so happened to be updated in tip, and expect the page he's on to be retained. It's a perfectly valid case that you want to "follow" a file by having 'tip' in the URL, but as I said, it should be chosen, not default behavior. I have a problem with the current behavior. User Scenario Problem With that user scenario, they will never get the latest files unless I bother them with annoying, frequent announcements. I know a way to get the tip. It is to substitute 'changeset' with 'tip' in the url. They, or most of them, however, do not know about it. There is a similar problem with Internet search engines. User Scenario Proposal FYI, for any Git users, use the branch name (i.e. "master") instead of "tip". "tip" is for Mercurial only. This doesn't seem to work with namespaced branch names in Git, either by substituting 'namespace/branch' or 'namespace%2Fbranch' for the commit ID. This thread is the first hit on Google when trying to achieve this, so here's an explanation of the URL pattern I found to work. The URL for a particular version of a resource follows the pattern: For a Git repository, replace <sha1>with the branch name (i.e. master) to see the version at that branch. For Mercurial, do the same, but use tip(apparently -- I haven't tested this.) Removing component: repository (automated comment) Or, to get a full blown HTML page (with links to the history and all): replace rawwith srcin Drew's comment above. (Nice find, Drew!) You can also use a relative URL to link between your wiki pages and the source with just where tree-ish can be a commit_id, branch, etc (Thanks Arjan & Drew) Drew Noakes I have, does not work. Haven't found a workaround, that's a pity.
https://bitbucket.org/site/master/issues/202/link-to-tip-version-of-source-files
CC-MAIN-2016-36
refinedweb
693
79.09
* 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 » Certification » Programmer Certification (SCJP/OCPJP) Author Forward Referencing, Initializers Dirk Hudson Greenhorn Joined: Oct 14, 2004 Posts: 1 posted Oct 14, 2004 08:17:00 0 public class Initializers{ int length = 10; { System.out.println("values are: " + length + " , " + width); //line 5 } double area = length*this.width; // line 7 int width = 2; public static void main(String[] args){ System.out.println("This is a test"); Initializers init = new Initializers(); } } when i compile the above code I get a illegal forward reference error on line 5. so i changed the reference to this.width which seems to work with 0 as default value of width. what is going on here ? isn't width and this.width the same thing ? i have a guess that all instance variables are assigned their default values when a class is loaded (ie when static vars are initialized) and are then "explicitly" initilized when an instance is created using new. this theory seems to be accurate as when I did the following: { System.out.println("values are: " + length + " , " + width); //line 5 int width = 2; } i get a "cannot resolve symbol" error. Edited by Corey McGlone: Added CODE Tags [ October 14, 2004: Message edited by: Corey McGlone ] Colin Fletcher Ranch Hand Joined: Sep 10, 2004 Posts: 200 posted Oct 14, 2004 08:34:00 0 Dirk, The problem with the below code is this... length is defined as 10 - ok System.out.println ... On this line you are trying to use the width variable, but the width variable is not declared BEFORE you use it. The compiler complains and says there is a forward reference which means you use the variable before defining the type / value for it. Moving the declartion to before the "System.out.println..." will correct this. Another way to think of it is this: (be the compiler) How can I print the value of the width variable when I don't even know what type it is ? public class Initializers{ int length = 10; { System.out.println("values are: " + length + " , " + width); //line 5 } double area = length*this.width; // line 7 int width = 2; public static void main(String[] args){ System.out.println("This is a test"); Initializers init = new Initializers(); } } SCJP 1.4 SCWCD 1.4 Corey McGlone Ranch Hand Joined: Dec 20, 2001 Posts: 3271 posted Oct 14, 2004 08:42:00 0 In general, the compiler will prevent you from reading a variable that has not yet been initialized. However, there are ways to "trick" the compiler into allowing you to do so. The trick I use most often is this: public class Test { int a = 5; { System.out.println(a + ", " + getB()); } int b = 2; private int getB() { return b; } } By invoking a method that gets me the value of b, the compiler doesn't realize that we're referencing a variable that hasn't yet been initialized. Basically, the compiler just isn't that smart. By using the keyword "this", you're accomplishing the same thing - you're tricking the compiler into allowing you to do something you should not be doing. SCJP Tipline, etc. I agree. Here's the link: subject: Forward Referencing, Initializers Similar Threads Static Blocks and Instance Initializers (on certification exam?) Instantiation/Forward referencing when static variables are initialized help with blank final variables Instantiation/Forward referencing All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter JForum | Paul Wheaton
http://www.coderanch.com/t/246615/java-programmer-SCJP/certification/Referencing-Initializers
CC-MAIN-2014-35
refinedweb
591
63.8
I have installed blender package on Ubuntu 10.04. I thought it would install python support for blender. Now i'm trying to import Blender modules from python interpreter but it can not find blender module. This is the command i gave and the output is: Code: Select all import Blender The same for 'import bpy'. Code: Select all ImportError: No module named Blender Using python2.6 and the output of is Code: Select all blender -v I have also downloaded blender-2.49b release and compiled with cmake. It created lots of *.o files in 'source/blender/python/api2_2x' folder but there are not any python modules in subfolders of build folder. Code: Select all Blender 2.49 (sub 2) Build Now what should i do? A solution without any compilation process, only by using apt-get tools would be best. But an explanation of the way of compiling blender also to create python modules is good too. Thank you!
https://www.blender.org/forum/viewtopic.php?t=22116
CC-MAIN-2017-22
refinedweb
161
76.62
Welcome to the Parallax Discussion Forums, sign-up to participate. #include "simpletools.h" #include "dht22.h" int DO = 22, CLK = 23, DI = 24, CS = 25; // SD card pins on Propeller BOE int NUM = 0; // ------ Main Program ------ int main() { int n; sd_mount(DO, CLK, DI, CS); // Mount SD card FILE* fp = fopen("TempHumData.txt", "w"); // Open a file for writing while (NUM < 3) { int n = dht22_read(5); fwrite(&n, 400,15,fp); print("%s%03.2f%s\r", "The temperature is ", ((float) dht22_getTemp(FAHRENHEIT)) / 10.0, " degrees F"); print("%s%03.2f%s\r", "Humidity is ", ((float) dht22_getHumidity()) / 10.0, "%"); pause(2000); NUM = NUM + 1; } fclose(fp); fp = fopen("TempHumData.txt", "w"); fread(&n, 400, 15, fp); print(".2f%", n); fclose(fp); } Figured out what I need for now, perhaps my phrasing was too ambiguous. Creating an array of the values myself and using fprintf to write them as decimal integers solved my problem. I still have some random bits of code in here I was using for debugging purposes, but it works! I attached pictures of both the terminal log and data file I wrote too. Hope this helps someone in the future. Cheers! first of all welcome to the forum. Second, it is sort of funny that one finds a solution shortly after writing a post, happens quite often to me. Just describing the problem leads to a solution. Enjoy! Mike Yea it's weird how it works like that. It helps to get the problem out of your head and onto something you can look at. I just realized I need a time stamp too, I'm wondering what my options are there. The safest way is to have a file of sufficient length already written with zeros or some other known value, and then open and re-write the file with records as needed. This way, all your data is there (perhaps excluding the last) when a power fail or reset for some other reason happens. If you know your file is contiguous, you can just do a low level sector write. I'm only writing 2 floats to the text file everytime I run, I've changed the fp = fopen("TempHumData.txt", "w") to fp = fopen("TempHumData.txt", "a") so that the data appends rather than overwrites it and closes. Right now I'm working on how to get the propeller to take a sample every 30 minutes, append the data file and then close. I know sleep would be easy but, I think this poses power consumption problems as I plan on running this with a battery pack outside for a few days in a row at least. I think using waitcnt and clkfreq is what I'm looking for, here's a really brief pseudo code idea: -Place gauge outside and run, manually record real time. (Not programming -Create 10 minute delay using waitcnt and clkfreq, reset clock and add 1 to a variable -If variable == 2; run data collection loop, reset clock and reset variable to 0 I'm not concerned with hyper accurate time readings (like it's fine if I take the temperature and humidity at 12:02 rather than at 12), just with accidentally creating an overflow problem with my timer and not actually getting the reading done. I think the waitcnt register maxes out at around 50 seconds real time before resetting. Perhaps I could just make my program count higher... EDIT: Lowering the clock speed though! Hmmmm.. source: This seems like a tasty fix, gotta investigate lowering the clock speed. My assembly is weak and I can't find a good example to change up the clock frequency using inline assembly that I can wrap my head around. Just using sleep it is! For now... Essentially I just sleep for 30 minutes, and though this is an increased power draw compared to waitcnt it should still last days powered from 4 AA batteries. I wrapped everything up in a while loop and reset the count after 30 minutes. Seems simple and effective so far, I was wondering if anyone has any knowledge of long term clock issues with sleep. Like does the clock get messed up over time. I tested it over 30 minutes and it executed just fine as written below, I just worry if this will continue to function properly over multiple days. Also, should I repost the finished project with pictures and complete code when I'm done with it in a new thread? You will need to keep the xtal oscillator running for accuracy, but you can lower the run frequency to 5MHz (xtal * 1) and use waitcnt to lower again. IIRC overflow is ~53s at 80MHz, so 16 x 53s gives around 14min, so try using 10mins and perform every third count. You dont think sleep will work if I'm not concerned with power management. I have a 4 AA battery pack, should last a few days I think. I'm not hyper concerned with the clock accuracy either. If the weather is taken at 12:01 rather than 12 its not a huge deal. I think this should work. I timed an hour and a half and got three measurements and it stored correctly. Would I need inline assembly to get that clock frequency down? I looked at the propeller manual but didn't really understand the code I was seeing. Also not sure what sleep translates to. You will need help from someone with C experience. Good luck! Awesome, I'm looking to redo some of the project to make it more robust over the summer and will definitely check out that thread. A great project IMHO!
https://forums.parallax.com/discussion/comment/1486175/
CC-MAIN-2021-04
refinedweb
947
72.16
A Sample Information Engine Project Info: 1952 words (8 pages) Essay Published: 13th Apr 2021 in Information Systems Coiza – Making sense of information 1. Introduction I more or less run my life directed by information from the Internet. I check the weather, check the traffic, look for places to go, look for reviews for the places, get updates from my friends and work – and browse lots of information from many other sources. The information I am interested in depends on many factors including the time of the day, my location, whether it is a work day or a weekend, whether I am at home or on vacation. Indeed many times the information I am interested is prompted by information I have already discovered. For example, on a work day I might check the weather and, if it looks like rain, check the availability of trains to get me home (well I wouldn’t want to get wet!). If you need assistance with writing your essay, our professional essay writing service is here to help!Find out more Technology like Google Now do a great job of automating information assimilation by guessing what information relevant is relevant to me. The challenge of this type of technology is that assimilation, particularly across many information sources, can be complex and not easy to guess. An alternative approach is to explicitly define the rules by which information is assimilated in a way that can then be automatically processed by what I call “Information Engines”. In this article I want to talk about an Information Engine that I have constructed called Coiza. Coiza is built around information channels that can be subscribed to and which display information as feeds like those used by Facebook and Twitter. Channels may display raw information, for example a news channel (like the BBC), or may display information resulting from combining information, for example location and Wikipedia summaries for that location. Channels can produce any information including context information like location and time of day. The most interesting feature of Coiza is that it allows the definition of new channels based on existing channels and rules on how the information from the existing channels gets used to produce information from a new channel. 2. Viewing Channels Channels can be subscribed to within Coiza. Depending on the channel it may be necessary to supply parameter values and/or authorisations for Coiza to access private information (e.g. Google Calendar) using the OAuth protocol. Once channels have been subscribed to then information is displayed from that channel in a feed like format where the feed is hidden if there is no information to display. 3. Creating Channels Viewing channels is where most users will spend the majority of the time, but the richness of channels available to view is enabled by ability to build new channels with relative ease. Any user within Coiza can create and publish channels by writing CoizaLang code. CoizaLang code consists of two primary constructs: - Info – A model of a piece of information that is either consumed or produced by a channel and can be rendered within feeds. - Channel – Consumes zero or more info flows, emits a single info flow, and defines rules for producing the output flow. Channels may be nested within each other. 3.1 Building Infos Here is an example of a CoizaLang info for Message illustrating the key features of infos. Firstly like all constructs, infos live within a namespace, or package, in this case coiza since it is supplied as part of the coiza platform. All infos (and for that matter channels) must live in a namespace beginning with the username of the coiza user that created it – which in my case is “jwillans”. Infos can subtype, or extend, other infos which, as we shall see a bit later, allows the same instance of a type to play different roles depending on the channel using it. In this example Message subtypes TitledContent and, in addition to having the link and author fields defined locally, title and content fields are inherited through the sub type relationship. Fields can be typed using primitive values or other info types. A further important feature of infos is the optional render block which defines how infos are turned into html for display within a feed. When a subscribed channel is displayed (see the screenshot in Section 2) the supplied feed is a result of turning infos into html using the render block. Render blocks support a subset of html along with the ability to reference and navigate info fields using a small expression language. 3.2 Building Channels Channels are the bread and butter of coiza. A CoizaLang channel has zero or more input ports, a single output port, all of which are typed by infos. The job of a channel is to produce output infos – often as a result of processing input infos. The resulting infos can then either be displayed as feeds, assuming the channel has being subscribed to, and/or used as the input to a further channel. In this way networks of channels can be created building on one another. 3.2.1 Getting the news Here is a simple example of a channel which does not do any processing directly but wraps the existing channel RSSFeedProvider to define a BBC news channel. I sometimes call these types of channels assembly channels. RSSFeedProvider is one of a number of channels that hook in to externally supplied data, in this case getting information from an RSS feed. Other example of external data channels in coiza includes Google Calendar, IMAP email, LinkedIn, current location, Wikipedia, currency converters … and the list is growing all the time. From a coiza point of view these behave exactly like any other (user defined) channel. Like infos, channels are named and live within a package namespace. A channel can have zero or more parameters which are declared in the parenthesis after the channel name (line 5). In the case of the BBC News channel no parameters are required. However RSSFeedProvider does have a single string parameter defining the RSS feed location, and the URL of the BBC news feed is supplied as an argument to the RSS feed (line 7). This BBC News channel has no input ports but defines a single output port (line 9) which simply takes the output of RSSFeedProvider. By the way, although it cannot be seen from the above code, RSSFeedProvider produces infos of type Message which we covered in the previous section. 3.2.2 Filtering the news Let’s get more adventurous and explore some of the other features of CoizaLang. Suppose we wanted to filter the news by title, we could define a further channel as follows: FilteredTitle demonstrates a parameterised channel, requiring a filter string, with both input (+) and output (-) ports and a body that does some processing. Note how the ports are typed as Titled infoswhich is the base type Message subtypes thereby enabling this channel to filter titles on any type that extends Titled including Messages. The body of the channel iterates over all the incoming infos from feed and filters them using a pattern (line 11) which essentially says that an info must be of type Titled and the title field must contain the value of filter. Any matching infos are emitted to the output port. Now that we have a filter channel we can create a new assembly channel to filter the BBC news leveraging the two channels we have created. Most of the features of this channel has been illustrated previously, the one new feature is the wire declaration (line 14) which, as you may guess, defines how output ports are connected to input ports. In this case how the output of the BBC news channel is the input of the filter title channel. The output of this channel is then the output of the assembly channel (line 12). 3.2.3 Publishing the news During developing a channel it is possible to test the channel in order to ensure it works as designed as shown below. For a user channel to be subscribable, and used outside of testing, then it is important to guarantee that it is not going to change. To do this, a channel must be published which then prevents change. Before publication can happen, all infos or channels that are referenced by the channel must also be published and the channel must not have any type checking issues (there is no sense in publishing a channel that won’t work). Unpublishing can only take place if the construct being unpublished has no dependents either in the form of other constructs or user subscriptions. If a change is required to a published channel with dependents then the only approach is to create a new version of that channel (or indeed info). Our academic experts are ready and waiting to assist with any writing project you may have. From simple essay plans, through to full dissertations, you can guarantee we have a service perfectly matched to your needs.View our services We have created a couple of channels – BBC News and Filtered BBC News – that once published can be subscribed to by any user. Rather than the user having to search for the CoizaLang channel name (i.e. BBCNews or FilteredBBCNews) it is possible to give the channel a user friendly name along with a description which are both used as part of the search for subscribable channels mechanism. 3.2.4 Tell me in the morning You’ve probably got a handle now on how coiza works and how anyone can build channels and those channels once published can either be subscribed to or used as a basis of further channels. By way of a final example, if Bob Brown publishes a channel to filter based on the time of day, then we can create another BBC News channel which filters both on the title and the time of day. 4. Summary I have talked about how Information Engines can help bring information together into a form that is more appropriate to what the users is interested in knowing, and I have walked through an example of an Information Engine I have constructed called Coiza. Hopefully Coiza looks useful and you will consider becoming a subscriber to the rich array of channels that are beginning to be defined – or indeed define one or more channel for yourself. Finally in case you were wondering – why is Coiza called ‘Coiza’ – it comes from the Portuguese word coisa meaning ‘:
https://www.ukessays.com/essays/information-systems/sample-information-engine-coiza-2229.php
CC-MAIN-2021-21
refinedweb
1,763
55.98
Learn Java in a day Learn Java in a day  ..., "Learn java in a day" tutorial will definitely create your... are the list of topics that you can learn easily in a day: Download and install project project i have to do my final year project project topic:Weekly Automatic College Timetable Generation System BRIEF EXPLANATION ABOUT PROJECT This project takes various inputs from the user such as Teacher List, Course List Where to learn java programming language fast and easily. New to programming Learn Java In A Day Master Java Tutorials...Where to learn java programming language I am beginner in Java and want to learn Java and become master of the Java programming language? Where Day for the given Date in Java Day for the given Date in Java How can i get the day for the user input data ? Hello Friend, You can use the following code: import..."); String day=f.format(date); System.out.println(day index - Java Beginners index Hi could you pls help me with this two programs they go hand in hand. Write a Java GUI application called Index.java that inputs several... the number of occurrences of the character in the text. Write a Java GUI learn learn i need info about where i type the java's applet and awt programs,and how to compile and run them.please give me answer Java arraylist index() Function Java arrayList has index for each added element. This index starts from 0. arrayList values can be retrieved by the get(index) method. Example of Java Arraylist Index() Function import Get first day of week Get first day of week In this section, we will learn how to get the first day of ..._package>java FirstDayOfWeek Day of week: 7 Sunday project project suggest a network security project based on core java with explanation project project i need a project in java backend sql project project sir i want a java major project in railway reservation plz help me and give a project source code with entire validation thank Video Tutorial: How to learn Java? . Java Programming Tutorial Index page Learn Java in a day...Java Video tutorial for beginners - Provides learn first information about... as programmer. This video explains you how beginner can learn the Java programming Java project ideas Java project ideas Hi, Can anyone tell me the java project ideas? I want to develop the project to learn java programming concepts in depth. Thanks Hi, You can develop following types of applications: a) Hotel hi , we r working on one project related to our results. we using java and for back end sqlserver 2005. In dis we are trying to retrieve result from some site and store it in our data base so that we can perform project project how to create core java code for trend analysis calculator including index in java regular expression including index in java regular expression Hi, I am using java regular expression to merge using underscore consecutive capatalized words e.g., "New York" (after merging "New_York") or words that has accented characters Java Project Java Project Java project using with collection and generic with observer design pattern project project how to make blinking eyes using arc, applet in core java project project write a program in java to develop a port scanner for common devices(HTTP,FTP,Telnet get Next Day Java get Next Day In this section, you will study how to get the next day in java...() provide the string of days of week. To get the current day, we have used   java project java project how many tables are required in backend for online examination system project in jsp If backend is SQL project - JSP-Servlet java project i am going to do a mini-project on computerization... in the college they will be having photo session for one day and they need to enter... mini-project... where all the students can enter into the application java project java project i would like to get an idea of how to do a project by doing a project(hospital management) in java.so could you please provide me with tips,UML,source code,or links of already completed project with documentation project should write Java code, so as to: 1. Compute Gross Monthly Salary for all JAVA project JAVA project How to extract tags and their corresponding properties of a "cascading style sheet" file using JAVA Help With My Java Project? Help With My Java Project? Write a console program that repeatedly... these steps: display: As Entered for each entry in the array, display the index... a bubble sort, for each entry in the array, display the original index java project java project Connecting to MySQL database and retrieving and displaying data in JSP page by using netbeans Marvellous chance to learn java from the Java Experts Marvellous chance to learn java from the Java Experts A foundation course on Java technology which... for Software Development on Java Platform. Learn to implement Java Project Java Project how to write a program for competitive exams(for student practice purpose)? for example: first student have to login after login then he has to select the particular exam what he want to write i.e the exam may applications, mobile applications, batch processing applications. Java is used... | Linux Tutorial | Java Script Tutorial | PHP Tutorial | Java Servlet Tutorial | Java Swing Tutorial | JEE 5 Tutorial | JDBC java project - Java Beginners java project how can i download the source code for the project college admission system Project - Java Beginners Java Project Hello Sir I want Mini Student Admission System project in java with Source Code and Back end Database is MS Access. plz Give That Sir its Very Very Urgent project - Java Beginners project in Java Need example project in Java Java Project - Java Beginners Java Project Hey, thanks for everything your doing to make us better. Am trying to work on a project in java am in my first year doing software Engineering and the project is m end of year project. Am really believing Where can I learn Java Programming Learn Java in a Day Master Java in a Week More links for Java... and time to learn Java in a right way. This article is discussing the most asked question which is "Where can I learn Java Programming?". We have Java Project - Java Beginners Java Project Dear Sir, Right now i am working in java image processing project. In that i have to split in one image like Texture, color..., Please visit the following links: How we learn java How we learn java what is class in java? what is object in java? what is interface in java and use? what is inheritence and its type JAVA PROJECT - Java Beginners JAVA PROJECT Dear Sir, I going to do project in java " IT in HR, recruitment, Leave management, Appriasal, Payroll" Kindly guide me about... etc. I am doing project first time. waiting for your reply, Prashant java project - Java Beginners java project hi this amol i wish to do a project on banking software in java can u help how can i help u .. and what the kind... adam certified java programmer certified websphere ya sure!! Hi Friends, Can somebody please tell me a website from where I can download java live projects along with the source code java project - Java Beginners java project Sir, how can i download the source for for the proect college admission Find the Day of the Week Find the Day of the Week This example finds the specified date of an year and a day... time zone, locale and current time. The fields used: DAY_OF_WEEK How to learn programming free? , Here are the tutorials: Beginners Java Tutorial Learn Java in a day Master Java...How to learn programming free? Is there any tutorial for learning Java absolutely free? Thanks Hi, There are many tutorials project - Java Beginners java project HAVE START A J2ME PROJECT WITH NO CLEAR IDEA .. ANY ONE... project titled, as ?M-News Application? is basically a mobile news application Project. In our project we are going to develop a Mobile Application which project detail - Java Beginners project detail Dear roseindia, i wnat to the idea for doing project in the java JAVA AWT BASE PROJECT JAVA AWT BASE PROJECT suggest meaningful java AWT-base project Java Project - Java Beginners question in my java project. But this program is shoing error on the 50th line...Java Project Create a class Computer that stores information about... of java too much hepl plz regarding project and come up with combined solution quickly. PROJECT NAME: DID I WRITE A GOOD JAVA PROGRAM?(JAVA/MVC/UI) BRIEF DESCRIPTION OF A PROJECT: The program helps.... PROJECT DETAILS: Any engineer writing a good program should learn the best regarding project solution quickly. PROJECT NAME: DID I WRITE A GOOD JAVA PROGRAM?(JAVA/MVC/UI) BRIEF DESCRIPTION OF A PROJECT: The program helps engineers in checking whether...regarding project OBJECTIVES OF THIS PROJECT: -Ability to test regarding project JAVA PROGRAM?(JAVA/MVC/UI) BRIEF DESCRIPTION OF A PROJECT: The program helps... to the programmer. PROJECT DETAILS: Any engineer writing a good program should learn...regarding project sir we need help about project. we have idea Project - Java Beginners Project Give me a sample project idea done using code minor project in core java minor project in core java I am a student of BE IT branch 6sem ,i have to prepare a minor project in core java please sujest some topics other then management topics topics java project topics Hello everyone, Can you please give me ideas on new projects in java(belonging to any part of java ), read the topics related to it and then i will make it. Please give me inventory ideas small java project - Java Beginners small java project i've just started using java at work and i need to get my self up to speed with it, can you give me a small java for beginners project to work on. your concern will be highly appreciated project in java - JDBC friend, i am sending java project link, visit following link http...project in java hi, i should do a project that enables a local cable operator to manage his customers. this should be done in java plz send me Java project in Servlet Java project in Servlet Hi, I have one java (Servlet) project... have private network (LAN). So i want to run that project from any pc. Access to project should be from any syatem. Means can i access post 2 problems Java Project - Development process Java Project Hello Sir I want Java Project for Time Table of Buses.that helps to search specific Bus Time and also add ,Update,Delete the Bus Routes. Back End MS Access Plz Give Me Learn Java - Learn Java Quickly Learn Java - Learn Java Quickly Java is an object oriented programming language... and universities. The most important feature of Java is that it can run JAVA Web project deployment JAVA Web project deployment Hi friends, I have created a website using servlet and JSP with SQL server on the backend. Now I have to deploy the project so that I can open the project and someone can work on it without installing index a given paragraph in alphabetical order How to index a given paragraph in alphabetical order Write a java program to index a given paragraph. Paragraph should be obtained during runtime... paragraph : This is a technical round. Please index the given paragraph. Output Looking for sample project in java using netbeans Looking for sample project in java using netbeans Hi all, i am novice in developing desktop application in java using netbeans. can anyone pls help... learn something from it by refering that project. pls its urgent   Getting Previous, Current and Next Day Date Getting Previous, Current and Next Day Date In this section, you will learn how to get previous, current and next date in java. The java util package provides Advertisements If you enjoyed this post then why not add us on Google+? Add us to your Circles
http://www.roseindia.net/tutorialhelp/comment/84424
CC-MAIN-2015-40
refinedweb
2,028
60.04
From Nick Sutterer, A Computer Science Undergraduate at Albert-Ludwigs University (Freiburg, Germany) When writing an article about Apotomo I had to make a decision: either introduce it as a simple widget plugin for rails or - as the name Apotomo (”all power to the model”) implies - end up in monologues about model-driven component-oriented enterprize concepts. Today I will simply introduce Apotomo as a widget library for rails. Introduction Apotomo is a widget library for rails. The concept is familiar to everyone who’s already worked with a GUI library: Take a window, draw some frames in it and throw in some buttons. Attach some logic to the buttons, hook a method to the frame and you’re done. In Apotomo (that’s a widget library), the central place - where all this drawing and attaching happens - is the modeling tree. For your convenience I prepared a meaningful model which is the foundation of an imaginary drinking application: people can track their drinks in a database, can list what they drank and can view their current blood alcohol value. Useful? Not very. Example def drinking_model_tree top_page = page("Top Page!", 'top_page') track_page = section("Tracking Page", 'tracking_page') tracking_notebook = notebook('tracking_tabs') track_tab = tab("Track a Drink", 'track_tab') list_tab = tab("List tracked", 'list_tab') level_page = section("Permille Page", 'permille_page') top_page << cell(:drinker, :pages_menu, 'pages_menu') top_page << track_page track_page << tracking_notebook tracking_notebook << track_tab track_tab << cell(:drinker, :track_form, 'track_cell', :states => [:track_drink]) tracking_notebook << list_tab list_tab << cell(:drinker, :list_drinks, 'list_cell') top_page << level_page level_page << cell(:drinker, :show_level, 'show_level') return top_page end And a controller method: def apotomo act_as_widget('top_page', drinking_model_tree) end It may look a bit weird at first, but it is very simple: I nest widget objects to model my application. For example, I create a notebook widget which has two tab children, that again have children. Using the #act_as_widget method in a Controller action I can command Apotomo to render my top page. Have a look at the rendered states of the application! Can you see the cool tabs? This is all done by Apotomo since it provides some handy and ready-to-use widgets. We will now look at some of those widgets. Widgets? Apotomo (did I mention that this is a widget library for rails?) is based on another rails plugin called “rails cells”. A typical cell looks like a controller, with methods and respective views, but is not bound to a specific controller and thus can be called throughout the application. Every widget in Apotomo is a derived cell and can be fully adjusted to the developers needs - behaviour as well as the templates used for rendering can be overwritten. This is an important principle in Apotomo. Pages, sections, notebooks, and tabs are all structural widgets used for grouping parts of the application. They have predefined (but customizable!) views and behaviour. Notebooks and pages are very similar, they render themself and their current sub page/tab. Apotomo’s state- and addressing system provides information about which pages or tabs are presently focused by the user. The crucial parts of every application - the business logic - is packed into logic cells. Looking at our example app, the line list_tab << cell(:drinker, :list_drinks ...) attaches the #list_drinks method of the drinker cell class to the "Tracking Page" widget. This cell method could look like def list_drinks id = param(:user_id) @drinks = drinks_for_user_id(id) end This really looks common to us - it’s somehow identical to a controller method. But wait, what is this param() call? It’s more than a widget library! In conventional Rails parameter values are accessed using the #params method. Apotomo (Hey! Did you know that this is a widg… ok, I’ll be quiet) provides a more progressive approach to parameter accessing. Instead of looking directly in the global request parameter hash, a parameter request through the param method travels up the widget hierarchy asking every ascendent widget if it knows the value. This opens the way for a completely new parameter management and some innovative concepts which are already implemented in so called domain widgets in Apotomo. I’ll discuss this in the next article, promised! Another feature is the cell addressing in Apotomo. Normally in Rails you have to know the respective controller/method combination to address a specific function, e.g. when linking to another page, or in a form. We rather address widgets in Apotomo. Let’s take the line top_page << cell(:drinker, :pages_menu ...) that attaches the cell method pages_menu to the Top Page to render a clickable navigation menu. The view template for this method might look like <ul> <li><%= link_to_cell("Tracking Page", 'tracking_page') %></li> <li><%= link_to_cell("What's my level?", 'permille_page') %></li> </ul> That’s cool - we refer to cells (or, widgets) - and this brings some great advantage: the addressing mechanism travels - similar to the parameter thing - up the hierarchy and to the target cell, asking every cell on its way if they want add something to the address. This is extremely helpful for saving state-relevant information in urls. We’ll stick to this in the next article as well. Apotomo integration Basically Apotomo could control a complete application. However people will be sceptical with this new concept. The #act_as_widget method provides a way to render only parts of the modeling tree within views or controllers of an existing application. For example I could integrate only the tracking-notebook widget and its tabs in some view of my app - leaving it open to the developer how much “Apotomo” he wants. And now? This was a very brief overview about Apotomo, it has more features that will (hopefully) be discussed in another article. I’d love to see some discussion going on at . If you have any issues with Apotomo feel free to mail me at nick@tesbo.com. Props go out to Google for sponsoring Apotomo during Summer of Code 2007 and my mentor Patrick Hurley for his help and support! More about cells and Apotomo can be found at. The example app can be downloaded as standalone rails environment at, but please notice that the API may change in the near future. i know this guy. alcoholic, but a friggin genius. Interesting stuff, reminds me of Wicket (java thing). very nice stuff. I know this nerd too. let's drinkandtrack - Rock 'n' Roll !
http://www.oreillynet.com/ruby/blog/2007/07/post_2.html
crawl-002
refinedweb
1,043
55.13
Overview - Methods in Python are a crucial concept to understand as a programmer and a data science professional - Here, we’ll talk about these different types of Methods in Python and how to implement the Introduction Python is a wonderful language but it can be daunting for a newcomer to master. Like any spoken language, Python requires us to first understand the basics before we can jump to building more diverse and broader applications in the data science field. Here’s the thing – if you cover your basics well, you’ll find Python to be a breeze. But it’s crucial to spend the initial learning time familiarizing yourself with the features Python offers. It’ll really pay off in the long run! Python is of course an Object-Oriented Programming (OOP) language. This is a wide concept and is not quite possible to grasp all at once. In fact, mastering OOP can take several months or even years. It totally depends upon your understanding capability. I highly recommend going through my previous article on the ‘Basic concepts of Object-Oriented Programming‘ first. So in this particular article, I’ll expand the concept of methods in Object-Oriented Programming further. We’ll talk about the different types of Methods in Python. Since python Methods can be confusing sometimes if you are new to OOP, I’ll cover methods in Python and their types in detail in this article. And then we’ll see the use cases of these methods. But wait – what are Python methods? Well, let’s begin and find out! If you’re completely new to Python, you should check out this free Python course that’ll teach you everything you need to get started in the data science world. Table of Contents - What are Methods in Python? - Types of Methods in Python - Instance methods - Class methods - Static methods - When to use Which type of Python Method? What are Methods in Python? The big question! In Object-Oriented Programming, we have (drum roll please) objects. These objects consist of properties and behavior. Furthermore, properties of the object are defined by the attributes and the behavior is defined using methods. These methods are defined inside a class. These methods are the reusable piece of code that can be invoked/called at any point in the program. Python offers various types of these methods. These are crucial to becoming an efficient programmer and consequently are useful for a data science professional. Types of Methods in Python There are basically three types of methods in Python: - Instance Method - Class Method - Static Method Let’s talk about each method in detail. Instance Methods The purpose of instance methods is to set or get details about instances (objects), and that is why they’re known as instance methods. They are the most common type of methods used in a Python class. They have one default parameter- self, which points to an instance of the class. Although you don’t have to pass that every time. You can change the name of this parameter but it is better to stick to the convention i.e self. Any method you create inside a class is an instance method unless you specially specify Python otherwise. Let’s see how to create an instance method: class My_class: def instance_method(self): return "This is an instance method." It’s as simple as that! In order to call an instance method, you’ve to create an object/instance of the class. With the help of this object, you can access any method of the class. obj = My_class() obj.instance_method() When the instance method is called, Python replaces the self argument with the instance object, obj. That is why we should add one default parameter while defining the instance methods. Notice that when instance_method() is called, you don’t have to pass self. Python does this for you. Along with the default parameter self, you can add other parameters of your choice as well: class My_class: def instance_method(self, a): return f"This is an instance method with a parameter a = {a}." We have an additional parameter “a” here. Now let’s create the object of the class and call this instance method: obj = My_class() obj.instance_method(10) Again you can see we have not passed ‘self’ as an argument, Python does that for us. But have to mention other arguments, in this case, it is just one. So we have passed 10 as the value of “a”. You can use “self” inside an instance method for accessing the other attributes and methods of the same class: class My_class: def __init__(self, a, b): self.a = a self.b = b def instance_method(self): return f"This is the instance method and it can access the variables a = {self.a} and\ b = {self.b} with the help of self." Note that the __init__() method is a special type of method known as a constructor. This method is called when an object is created from the class and it allows the class to initialize the attributes of a class. obj = My_class(2,4) obj.instance_method() Let’s try this code in the live coding window below. With the help of the “self” keyword- self.a and self.b, we have accessed the variables present in the __init__() method of the same class. Along with the objects of a class, an instance method can access the class itself with the help of self.__class__ attribute. Let’s see how: class My_class(): def instance_method(self): print("Hello! from %s" % self.__class__.__name__) obj = My_class() obj.instance_method() The self.__class__.__name__ attribute returns the name of the class to which class instance(self) is related. 2. Class Methods The purpose of the class methods is to set or get the details (status) of the class. That is why they are known as class methods. They can’t access or modify specific instance data. They are bound to the class instead of their objects. Two important things about class methods: - In order to define a class method, you have to specify that it is a class method with the help of the @classmethod decorator - Class methods also take one default parameter- cls, which points to the class. Again, this not mandatory to name the default parameter “cls”. But it is always better to go with the conventions Now let’s look at how to create class methods: class My_class: @classmethod def class_method(cls): return "This is a class method." As simple as that! obj = My_class() obj.class_method() This works too! We can access the class methods with the help of a class instance/object. But we can access the class methods directly without creating an instance or object of the class. Let’s see how: My_class.class_method() Without creating an instance of the class, you can call the class method with – Class_name.Method_name(). But this is not possible with instance methods where we have to create an instance of the class in order to call instance methods. Let’s see what happens when we try to call the instance method directly: My_class.instance_method() We got an error stating missing one positional argument – “self”. And it is obvious because instance methods accept an instance of the class as the default parameter. And you are not providing any instance as an argument. Though this can be bypassing the object name as the argument: My_class.instance_method(obj) Awesome! 3. Static Methods Static methods cannot access the class data. In other words, they do not need to access the class data. They are self-sufficient and can work on their own. Since they are not attached to any class attribute, they cannot get or set the instance state or class state. In order to define a static method, we can use the @staticmethod decorator (in a similar way we used @classmethod decorator). Unlike instance methods and class methods, we do not need to pass any special or default parameters. Let’s look at the implementation: class My_class: @staticmethod def static_method(): return "This is a static method." And done! Notice that we do not have any default parameter in this case. Now how do we call static methods? Again, we can call them using object/instance of the class as: obj = My_class() obj.static_method() And we can call static methods directly, without creating an object/instance of the class: My_class.static_method() You can notice the output is the same using both ways of calling static methods. Here’s a summary of the explanation we’ve seen: - An instance method knows its instance (and from that, it’s class) - A class method knows its class - A static method doesn’t know its class or instance When to Use Which Python Method? The instance methods are the most commonly used methods. Even then there is difficulty in knowing when you can use class methods or static methods. The following explanation will satiate your curiosity: Class Method – The most common use of the class methods is for creating factory methods. Factory methods are those methods that return a class object (like a constructor) for different use cases. Let’s understand this using the given example: from datetime import date class Dog: def __init__(self, name, age): self.name = name self.age = age # a class method to create a Dog object with birth year. @classmethod def Year(cls, name, year): return cls(name, date.today().year - year) Here as you can see, the class method is modifying the status of the class. If we have the year of birth of any dog instead of the age, then with the help of this method we can modify the attributes of the class. Let’s check this: Dog1 = Dog('Bruno', 1) Dog1.name , Dog1.age Dog2 = Dog.Year('Dobby', 2017) Dog2.name , Dog2.age class Calculator: @staticmethod def add(x, y): return x + y print('The sum is:', Calculator.add(15, 10)) You can see that the use-case of this static method is very clear, adding the two numbers given as parameters. Whenever you have to add two numbers, you can call this method directly without worrying about object construction. End Notes In this article, we learned about Python methods, types of methods and saw how to implement each method. I recommend you go through these resources on Object-Oriented Programming- - Basic Concepts of Object-Oriented Programming in Python - Inheritance in Object-Oriented Programming for Python – An In-Depth Guide for Everyone Let me know in the comments section below if you have any queries or feedback. Happy learning!You can also read this article on our Mobile APP 20 Comments Excellent article. It was great help for me. Thousands thanks. Glad to help! Great. Thanks for your article. Please, are you able to write on Iterators, Iterables and Generators in Python. Hi Olu! I’m glad you liked my blog. You can read about Iterables and Generators from here, we already have a blog on this topic – Thanks for sharing this Article. Thank you! Happy to help. Read all your three blogs with respect to OOPS. They are very interesting and helpful. Thanks for reading! Happy to help. Great article, well explained. Thanks for sharing! Happy to help! Thnaks good blog Happy to help! Great Article! Thank you! Thank you, as an advanced beginner, so to say, I found the article to be a nice refresher. Just the way you (don’t) explain how an instance is passed from the call reference to a method as a first argument is a bit misleading. I’d suggest a little edit. Thanks for the suggestion, I’ll look into it! Well explained article. Thanks Thanks Pallavi, happy to help:) Thank You. The content is very clean and simple and it makes me to understand very easily. Thanks a lot:) Happy to help!
https://www.analyticsvidhya.com/blog/2020/11/basic-concepts-object-oriented-programming-types-methods-python/
CC-MAIN-2021-31
refinedweb
1,975
75.1
import java.util.Scanner; public class LuckySevens { private int diceLength; private int rolls; private int sides; private int numRolls = 0; public static void main (String [] args) { Scanner reader = new Scanner(System.in); int diel, die2, dollars, count, maxDollars, countAtMax; System.out.print("How many dollars do you have? "); dollars = reader.nextInt(); maxDollars = dollars; countAtMax = 0; count = 0 ; while (dollars > 0) { count++; diel = (int)(Math.random() * 40 )+ 1 ; die2 = (int)(Math.random() * 40 )+ 1 ; if (diel + die2 == 7) dollars +=4; else dollars -=1; if (dollars > maxDollars) { maxDollars = dollars; countAtMax = count; } } System.out.println ("You are broke after " + count + " rolls.\n" + "You should have quit after " + countAtMax + " rolls when you had $" + maxDollars + "."); } } I need help with my dice class and putting objects to modify the LuckySevens class: Project Description: Redo the Lucky Sevens dice-playing program from the last unit so that it uses two dice objects. That is, design and implement a Dice class. Each instance of this class should contain the die's current side. There should be an accessor method for the die's current value. The method roll is the only mutator method. Then within your LuckySevens class, instantiate two Dice objects, and just roll them whenever you need a new value for each turn. Don't create two new Dice objects every time you need to roll the dice (would you go to the store every time to get a brand new pair of dice whenever you needed to roll them?). Just roll the ones you already have. Note that much of the code that you need is already in the original LuckySevens class. You are just breaking out the dice rolling function into its own standalone class, which could be used by other objects if needed. When you are finished with this project, show me your new LuckySevens class that uses a separate Dice object. public class Dice { private int dice ; private int side; private int numRolls = 0; public int Roll() { return (int)(Math.random() * 6 )+ 1 ; } public int getside() { return side ; } }
https://www.daniweb.com/programming/software-development/threads/510159/luckysevens
CC-MAIN-2017-47
refinedweb
336
64.71
The primitive render hook which creates GR_PrimTetra objects. More... #include <GR_PrimTetra.h> The primitive render hook which creates GR_PrimTetra objects. Definition at line 28 of file GR_PrimTetra.h. Definition at line 34 of file GR_PrimTetra.C. Definition at line 39 of file GR_PrimTetra.C. This is called when a new GR_Primitive is required for a tetra. gt_prim or geo_prim contains the GT or GEO primitive this object is being created for, depending on whether this hook is registered to capture GT or GEO primitives. info and cache_name should be passed down to the GR_Primitive constructor. processed should return GR_PROCESSED or GR_PROCESSED_NON_EXCLUSIVE if a primitive is created. Non-exclusive allows other render hooks or the native Houdini primitives to be created for the same primitive, which is useful for support hooks (drawing decorations, bounding boxes, etc). Reimplemented from GUI_PrimitiveHook. Definition at line 44 of file GR_PrimTetra.C.
http://www.sidefx.com/docs/hdk/class_h_d_k___sample_1_1_g_r___prim_tetra_hook.html
CC-MAIN-2018-51
refinedweb
146
51.14
- Advertisement hknowledgeMember Content Count19 Joined Last visited Community Reputation113 Neutral About hknowledge - RankMember c++ byte arrays how to output hknowledge replied to hknowledge's topic in For Beginners's ForumAll I know about the data is that it is stored as binary data. A MSFT told me the data would contain /device/harddiskvolume2/something/something.exe He never specified wether it was a null terminated string or char array or anything like that. So does anyone have any assumptions? In the MSDN documentation it is listed as FWP_BYTE_BLOB as the data type. The byte blob is storing an AppId from the FWPM_NET_EVENT0 header. If that helps. How would I even output it with cout? for(int a = 0; a < size; ++a) { cout << data + a; } ? c++ byte arrays how to output hknowledge posted a topic in For Beginners's ForumI have kind of a problem. This is the first time I have encountered a binary byte array and I need to output it to the screen. typedef structure binary_byte_array{ UINT32 size; UINT8 *data } Size is how many bytes are in the array. *data is a pointer to the start of the data. In the data is a file location. For example it will contain something like c:/something/somefilename.exe. I need to be able to output the file location stored in the data. I know how to read binary data from files, but I am kind of stuck on how to read it stored in this kind of array. I am also confused how I would output it to the screen, do I need to convert it from binary to ascii char's? The data is written in 4 byte blocks right? (The size of a UINT8) Or is that just the size of the pointer? Thank you for any help. Microsoft uses this data type for some of their internal workings, How to explain Programming? hknowledge replied to dimitri.adamou's topic in GDNet LoungeIts like learning a foreign language. You know what you want to say to someone but you have to learn their language first so they understand. Except the machine is the foreigner you are trying to communicate with. That is how I would describe it to someone. People are going to be potentially confused by a technical explanation. who else started out wanting to create a MMO game? hknowledge replied to scrap's topic in GDNet LoungeI wanted to take USGS datasets to render the world terrain to real scale and then be able to walk around in my own virtual world with just randomly generated trees, and textures that matched its region. Then I wanted to make a war game out of it like you got a handful of spy drones and a few satellites and you had to use them to find another person playing. Then when you found them you had to hit them with cruise missiles. Modern games are so unimaginative and I really wish I had the skill alot of game developers have. I am still years away from being able to do it. I know how to code (albeit slowly), and I know how to use DirectX, it would still take me awhile. Nowadays I have more interest in making tools and science. Like making things to secure my computer or carry out chemical reactions. I also would like to learn more about making servers and databases. And making my own operating system even. And things like parallel computing, hardware design, etc. Basically just stuff that interests me in a hobby type of way. - I am not sure that is a complete answer because the button in the dialog won't work when you use wm_create. Neither does moving it. And it does not receive messages. Basically the program freezes. - [source lang="cpp"]#include "windows.h" #include "resource.h" HWND wfpMainWnd = 0; HINSTANCE wfpAppInst = 0; BOOL CALLBACK MainDlgProc(HWND hDlg, UINT msg, WPARAM wParam, LPARAM lParam) { switch(msg) { case WM_INITDIALOG: return true; case WM_COMMAND: switch(LOWORD(wParam)) { case IDOK: EndDialog(hDlg, 0); return true; } break; } return false; } LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch(msg) { case WM_CREATE: DialogBox(wfpAppInst, MAKEINTRESOURCE(IDD_DIALOG), wfpMainWnd, MainDlgProc); return 0; case WM_DESTROY: PostQuitMessage(0); return 0; } return DefWindowProc(hWnd, msg, wParam, lParam); } int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR cmdLine, int showCmd) { wfpAppInst = hInstance; WNDCLASS wc; wc.style = CS_HREDRAW | CS_VREDRAW; wc.lpfnWndProc = WndProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = wfpAppInst;"wTest"; RegisterClass(&wc); wfpMainWnd = ::CreateWindow(L"wTest", L"GameDev Win32 Test", WS_OVERLAPPEDWINDOW, 0, 0, 800, 600, 0, 0, wfpAppInst, 0); ShowWindow(wfpMainWnd, showCmd); UpdateWindow(wfpMainWnd); MSG msg; ZeroMemory(&msg, sizeof(MSG)); while(GetMessage(&msg, 0, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } return (int)msg.wParam; }[/source] - I am solving the problem by calling dialogbox() from in the winmain() main function. The dialog and window behave like normal when I don't use wm_create in the windows procedure. Also why are people rating me down whenever I post? - Here is a basic skeleton of what I tried. Bool callback maindialog() lresult callback wndproc() { Case wm_create: Dialogbox(); } int winapi winmain() { } I am on my phone so can't post the source but that was the general idea on what I tried. The main window never displayed until the dialog was destroyed. I will post the source when I get a chance. Thank you for all the reply's. "Must-Learn" Languages hknowledge replied to KittyPlaysViolin's topic in For Beginners's ForumC, C++, Assembly In that order. With C and C++ you can create whatever you can imagine. With assembly added you will be a god instead of an angel - I never thought it might be locking the thread. Thank you. I might just try using regular child windows instead of dialogs then. The only bad part is there is no control resource editor/designer for regular windows, only dialogs. I will have to hand code all the controls in myself. - I answered my own question. Its because wm_create is called before the window is drawn. Thank you anyways gamedev! I still wonder why the window wouldn't be drawn after the dialog, I guess you would need to set it as focus somehow so it's procedure is called for a second time. win32 dialog question hknowledge posted a topic in General and Gameplay ProgrammingIn the wm_create of my window callback procedure I am calling createdialog() to open a dialog window. When the function is called my main window dissappears and the dialog takes its place.I have my main window set as the parent. Why? I want my dialog and the main window open at the same time. When I close the dialog with enddlg() the main window comes back. I can open the dialog through a menu and they both appear but if I use wm_create it doesn't. visual studio intellisense/warning upgrade for 2005 to bring closer to 2010? hknowledge replied to hknowledge's topic in General and Gameplay ProgrammingDoes anyone know if the 2008 version has that feature? visual studio intellisense/warning upgrade for 2005 to bring closer to 2010? hknowledge posted a topic in General and Gameplay ProgrammingVisual studio 2010 has a neat feature that when you pass a argument into a function it tells you with a red squiggly line that you haven't passed the right type. Very useful. The problem is that I only have visual studio 2005 that has intellisense and warnings from the stone age in comparison. Does anyone know any addin's that upgrades 2005 to have this specific functionality? I can't use visual studio express because I need the resource editor, among a few other things. c++ initiliazation what do you call it hknowledge replied to hknowledge's topic in General and Gameplay ProgrammingYes thank you I know I was just posing a question I already knew the answer to. I wanted to expose how the syntax does not hold up. Seems like it was tacked on as an afterthought. Yes of course always use 0.0f for floats i was just making a quick example my apology. thank you again for the reply. there is probably a reason this syntax is not recognized in the bjarne stroustrop official reference book. - Advertisement
https://www.gamedev.net/profile/184840-jtw/
CC-MAIN-2019-22
refinedweb
1,379
65.32
By: Charlie Calvert Abstract: A discussion of benefits to be derived from using testing tools such as JUnit, DUnit, NUnit or CppUnit. The heart of the argument is that such tools encourage programmers to create highly modular, reusable classes that are easy to maintain. This programming tip describes an infrequently mentioned set of benefits derived from using testing tools such as JUnit for Java or DUnit for Delphi. More particularly, this article shows how to use testing tools to help you create small, robust, reusable modules out of which complete programs can be created. Metaphorically, the image to keep in mind mirrors the process you go through to create a model out of LEGOs. In the ideal architectural model championed in this article, each class you create should be small and robust, just like a LEGO piece. Using these classes should be just as simple and reliable a process as building a model with LEGOs. Of course, in the real world things won't be quite that simple, but that is the ideal put forward in this article. Before starting the main body of this article, let me say a few words for those who have not yet started writing test code. My favorite tools for testing are JUnit for Java and DUnit for Delphi. I use Ant for Java or Want for Delphi to tie my test suites together so that I can run large numbers of test at one time. C# developers use NUnit and some C++ programmers use CppUnit. For further information on the basics of creating test suites, follow the links found in this paragraph, or see my Java article on using JUnit. Please remember that this article is not a broad description of testing in general, but rather a discussion of one particular benefit I believe that testing can produce. The main benefit to be derived from testing your code is increased robustness and reliability. I'm taking that much for granted, and instead going after a related subject which I hope some readers will find useful or informative. The code and theory shown in this tip applies equally to the C++, C#, Delphi and Java languages. I have striven to keep the text found here as short as possible, so that you can read this tip in just a few minutes. The controversial formulation used by the most "extreme" advocates of testing suites runs as follows: "Before you write a new class or method, first create one or more routines for testing it." I'll confess that I rarely follow this recommendation to the letter, but nevertheless I like the spirit it fosters. Suppose you are given an assignment to write code that will open a file, parse its contents, and then return certain pieces of information from that file. According to the radical proposition listed in the previous paragraph, the first thing you should do is write one or more tests. That is, you first write code for testing your real code, then you write your real code and run the test suite to see if it works. Such a proposition goes against the grain of most programmer's instincts. If we have a job to do, we want to first write code that accomplishes the task before us. We want to go away to that quiet place, pound out the code that will dazzle our peers and impress our superiors, and return in a matter of hours covered with glory. But our radical formulation of the testing theory says that we should first write code that will test the code that we are about to create. To most of us, this seems like an impediment, like a step backwards rather than a step forward. But let's take a moment to consider why testing of this kind might be useful. The argument in this tip is simply that writing lots of tests can help you create appropriately granular, easy to understand, robust classes that tend to be easily reusable. There is no room in this tip to explain in detail why I think such classes are worth creating. Furthermore, there is nothing in creating test suites that forces you to produce classes of this type. Nevertheless, if you agree that such classes are indeed useful, I will try to show how writing test suites can help you create code that adheres to this often praised architecture. We all know what it is like to have a huge body of code, and to suspect that a problem is in a particular part of it, and to find that the only way to test the suspect portions of the code is to initialize the entire program so that you can correctly call the code you want to test. After launching this monolithic program, you can no longer be sure that the problem is indeed isolated in the suspect portion of the code. For instance, the error might be an artifact of memory corruption problems encountered elsewhere in your code. It is my contention that writing test suites can help you avoid the problem described in the previous paragraph. Once again, test suites don't force you to avoid monolithic architectures. It is my contention, however, that they can help you avoid creating such programs. The first thing you discover when you start writing test routines is that you must create a second program, much smaller than your main program. This second program will hold your test suite. When writing this smaller test suite, it is only natural that will want it to be capable of testing just one small portion of your program. It is very difficult, and not particularly useful, to try to test an entire program all at one time. Instead, you want to be able to test small, easy to understand subsections of your main program. This simple fact can have some fairly interesting ramifications. In particular, your desire to create simple test suites can strongly encourage you to break your program up into small, well designed classes. The end result is a program that is relatively easy to understand, and relatively easy to maintain. It is precisely at this point that you can see the wisdom of writing your test suite first, and then writing your actual code second. If your first priority is writing a test suite, then you will naturally want to craft classes that are easy to test. In short, you will want to create small, modular, classes with few dependencies. If you write the code for your main program first, then you won't feel quite so strongly compelled to write small, modular classes. Instead, your priority will be to write code that adds a new feature to your program as quickly as possible. Such code is often monolithic in nature. It is simpler to stuff your new feature into the current class you are working on, rather than creating a new class that is more modular. In short, thinking about testing your code helps you think in a modular mode that leads to robustness and reuse. Conversely, thinking in terms of adding features to your current program can encourage you to write large, monolithic programs that are hard to maintain. Therefore, it is arguable that writing test suites encourages you to pursue good programming practices such as writing small, modular, easy to reuse classes. Suppose you are creating a class that is designed to calculate the time the Voyager spacecraft will take to travel between various planets in our solar system. Suppose further that the data about the distances between planets needed for making those calculations is stored in an XML file that you have been asked to parse. More particularly, suppose you are working with a class that looks something like this: public class MyPlanetTravelTimeCalculator { private: Double CalculateDistance(String PlanetA, String PlanetB) public: Double CalculateTravelTime(String PlanetA, String PanetB, int Speed) Double CalculateTravelTime(String PlanetA, String PanetB, String Planet C, int Speed) Double CalculateTravelTime(String PlanetA, String PanetB, String Planet C, String Planet D, int Speed) } Your test class, on the other hand, is located in a different module, and looks like this: public class MyTestSuite { public: void TestCalculateDistance() } As hinted at earlier in this article, your job is not to calculate the time for traveling between the two planets, but instead to write the single private routine called CalculateDistance in the class called MyPlanetTravelTimeCalculator. The CalculateDistance routine will need to open up an XML file, and retrieve data about the distance between two planets. Such a routine is not difficult to write or test. But it does have several points of failure, such as locating the file, getting the rights to use the file, properly parsing the file, and properly retrieving the correct data from the file. Writing a test suite encourages you to careful check each of these features to ensure they are working properly. As mentioned above, you want to create a small, simple test suite that deals with a small, and relatively isolated portion of your code. By thinking this way, it should be obvious that you will be better off if you create a separate class designed to parse the XML file and retrieve the sought after data. In short, instead of working with two classes, you want to be working with the following three classes: public class MyPlanetTravelTimeCalculator; // Shown above public class MyPlanetDistanceCalculator; // Contains your code public class MyTestSuite; // Contains test code As you can see, the very idea of creating a test suite has encouraged us to adopt good programming practices. Creating a separate class for each task in your program is the right thing to do, and the very act of creating a test suite has encouraged you to engage in this practice. If you did not create the test suite, you might tend to stuff the new functionality you are creating into the MyPlanetTravelTimeCalculator class. This would indeed be the easiest way to proceed, but not necessarily the wisest. Of course, there will be those who think it is a waste of time to create a separate class for opening an XML file and parsing out the data defining the distances between planets. In programming, however, things are rarely as simple as they seem. For instance, calculating the time for traveling between two planets is a non trivial task. Both planets are moving around the Sun at different rates, and both planets will be in different positions at different times of the year. When looked at from that perspective, suddenly the calculations made in the MyPlanetTravelTimeCalculator no longer seem so trivial. Furthermore, you don't want to burden that class with having to worry about the validity of the data it is using. Instead, you will most sincerely want to create a separate class for calculating the distance between planets, and you will be glad for a test suite that ensures that this secondary class that you depend on is absolutely foolproof. You have enough troubles without having to worry about being fed invalid data. Savvy readers might note that the MyPlanetTravelTimeCalculator class described in the previous section is more "monolithic" than the MyPlanetDistanceCalculator class. In particular, the former class depends on the latter class and can't be tested on its own. Having a dependency one level deep is not a serious problem in terms of initializing or testing a class. However, experienced programmers know that these dependencies can grow over time, until finally one is working with a class that has dependencies six or seven levels deep. In such cases, it is hard to see how testing suites can help you keep your program modular. The danger of deeply nested hierarchies is discussed very well in Item 14 of Johsua Bloch's excellent book entitled "Effective Java." Test suites can help you recognize such deeply nested dependencies, and can encourage you to refactor your program so that it is not quite so monolithic. In particular, if you are creating a test suite, and find that your deep nesting of dependencies is making it hard to create a test program for your classes, then you can see a problem emerging and attempt to fix it. In particular, it is best to strive to keep dependencies shallow, that is, to never create hierarchies more than three classes deep. However, in the real world, despite our best efforts, there will be times when deep hierarchies must be created. In such cases, the right thing to do is to break out your code into "layers." Then you should write test suites that "prove" the correctness of a particular layer. Once that layer is shown to be valid, you can build on top of it with confidence. All programmers have experience working with such "layers" of code. For instance, Delphi programmers build on top of a "layer" of code called the VCL, which is in turn built on top of a layer of code comprising the core features of the Pascal language as it is defined by the compiler and the System unit. Java programmers typically build on top of J2SE. In fact, Java programmers typically build on top of multiple layers. For instance, J2EE is dependent on J2SE, and tools like JaxB or SOAP are built on top of the core Java classes. If you have a well tested layer of code, then you need not even think of it as a dependency that needs testing. For instance, C++ programmers that write a class which uses the STL don't usually need to think of their code as being nested several layers deep. That programmer can "assume" that the STL is solid, just as Delphi programmers "trust" the VCL and Java programmers "trust" the core classes in J2SE. Just how well founded our trust and assumptions may be is fortunately not a question I have room to consider in this article! The lesson to learn from reading this section is simple. Try to create simple, modular classes that are easy to test. Do everything you can to create simple architectures of this type whenever possible. However, if you must create deeply layered hierarchies, then try to find ways to break your code up into layers that can be throughly tested on their own. For instance, if the IO operations to retrieve data from a set of XML files ends up being quite complex, then separate all those operations off into their own "layer" and test them thoroughly. Then you can write code that uses that layer without having to worry about its validity. The Java language with its built in support for packages and jar files is particularly conducive to this kind of architecture. C++ and Delphi programmers can achieve similar functionality by creating components or DLLs. NOTE: A word needs to be added here about different kinds of dependencies. Consider, for instance, the hierarchy found in the Java ArrayList class: java.lang.Object | +--java.util.AbstractCollection | +--java.util.AbstractList | +--java.util.ArrayList Here we can see that the ArrayList class is "dependent" on three other classes, in that it has a fairly deep hierarchy. However, if you are familiar with Java and with this particular class, then you know that from the point of view of a test suite, the ArrayList class is very straightforward. It is easy to initialize, and easy to test. There is little need to worry about the validity of simple classes such as AbstractList of AbstractCollection. Problems with those classes could be solved either by the tests written for those classes, or in the tests you write for the ArrayList class. In fact, this example helps to illustrate why I think writing test suites helps you create modular, properly designed classes. The fact that the ArrayList class is so easy to test is in a sense a "proof" that it is properly designed. This class is modular, reusable, and easy to maintain. In this sense, it is a "layer" on which you can safely construct other classes. My point here is that you don't need to worry that the hierarchy of this class is four layers deep. The "proof" that this hierarchical depth is not a problem is demonstrated by how easily you can test it with JUnit. In other words, it is not always the depth of the hierarchy with which you need be concerned, but rather the ease with which you can test a particular class. As you recall, this article is an examination of the following controversial statement: "Before you write any new routine, first create a routine for testing it." When I first heard that statement it sounded a bit too fussy, a bit too compulsive. But after considering the problem for awhile, I saw that there might be more to the proposition than I at first supposed. I still don't follow the rule to the letter, but I think it helps point us toward a very valuable set of programming practices. In particular, we have seen that writing test routines can help us achieve some worth while goals: Besides these benefits, I should add that the act of creating a test suite can get our creative juices flowing. It forces us to think about the kinds of problems we are likely to encounter. When testing a class, we tend to think about what can go wrong for a user of a class. Instead of looking for an expedient solution to the problem that we can plug into a bigger program, we instead think about what could go wrong with a simple, easy to understand class. This kind of thinking can help us find ways to write robust code. After considering these benefits of creating test suites, it is perhaps easy to see why some people endorse this technology. Of course, there are many other reasons to write test suites than those discussed in this article. But I believe the benefits discussed here are important in and of themselves. Server Response from: SC3
http://edn.embarcadero.com/article/30049
crawl-002
refinedweb
2,998
57.61
"Luke Dunstan" <coder_infidel@...> wrote in news:BAY16-DAV13DD093859D4DF8668069D8A3E0@...: > >. > Ok, first of all, I'm using Windows XP SP1. Now, I found that the program runs fine with -O1, or with no optimizations at all, but fails with -O2 or greater. Are you saying you used -O3 and it still worked?? What would make a difference between our machines?? Dan > >> //***************************************************************** > > Attachment decoded: untitled-2.txt > ------=_NextPart_000_0039_01C53B57.290564A0 > > Attachment decoded: rainbow2.png > ------=_NextPart_000_0039_01C53B57.290564A0-- Luke Dunstan: > > No you don't have to - look at the following, $ gcc -v -g -o hallo hallo.c Using built-in specs. Target: mingw32 Configured with: ../configure --with-gcc --with-gnu-ld --with-gnu-as --host=mingw32 --target=mingw32 --prefix=g:/mingw4 --enable-threads --disable-nls --enable-languages=c,c++ --disable-win32-registry --disable-shared --enable-sjlj-exceptions --enable-hash-synchronization --enable-libstdcxx-debug --oldincludedir=/mingw/include Thread model: win32 gcc version 4.0.0 20050222 (experimental) g:/mingw4/bin/../libexec/gcc/mingw32/4.0.0/cc1.exe -quiet -v -iprefix g:\mingw4\bin\../lib/gcc/mingw32/4.0.0/ hallo.c -quiet -dumpbase hallo.c -auxbase hallo -g -version -o C:/DOKUME~1/Michael/LOKALE~1/Temp/ccs9aaaa.s ignoring nonexistent directory "g:/mingw4/bin/../lib/gcc/mingw32/4.0.0/../../../../mingw32/include" ignoring nonexistent directory "g:/mingw4/lib/gcc/mingw32/4.0.0/../../../../mingw32/include" #include "..." search starts here: #include <...> search starts here: g:/mingw4/bin/../lib/gcc/mingw32/4.0.0/../../../../include g:/mingw4/bin/../lib/gcc/mingw32/4.0.0/include g:/mingw4/lib/gcc/mingw32/4.0.0/../../../../include g:/mingw4/include g:/mingw4/lib/gcc/mingw32/4.0.0/include /mingw/include End of search list. GNU C version 4.0.0 20050222 (experimental) (mingw32) compiled by GNU C version 4.0.0 20050222 (experimental). GGC heuristics: --param ggc-min-expand=30 --param ggc-min-heapsize=4096 as -o C:/DOKUME~1/Michael/LOKALE~1/Temp/ccK8baaa.o C:/DOKUME~1/Michael/LOKALE~1/Temp/ccs9aaaa.s ld -Bdynamic -o hallo.exe /mingw/lib/crt2.o -Lg:/mingw4/bin/../lib/gcc/mingw32/4.0.0 -Lg:/mingw4/bin/../lib/gcc -Lg:/mingw4/lib/gcc/mingw32/4.0.0 -Lg:/mingw4/bin/../lib/gcc/mingw32/4.0.0/../../.. -Lg:/mingw4/lib/gcc/mingw32/4.0.0/../../.. -L/mingw/lib C:/DOKUME~1/Michael/LOKALE~1/Temp/ccK8ba Maybe someone can tell us what exactly the search algorithm for gcc was adopted for Mingw on win32 ? Read and respond to this message at: By: sjoerd I have tried searching the archives, but I couldn't find anything, so here goes. We have a project where we have quite a few dll's that we load dynamically (i.e. under program control) using the LoadLibrary function. When attempting to load some of the dll's, we get an error: Invalid access to memory location. This error occurs because there is an access violation in the dll startup code (my guess, DllMainCRTStartup. but none of the debuggers I tried could actually give me a name of the function where it failed). We create the dll's using dllwrap and let it figure out the --image-base argument to the linker (it does this based on a hash of the name of the dll). This means that all dll's get their own image base value (I checked, all dll's get different values). When I add an --image-base argument to the call to produce one of the failing dll's, it loads without problems--well, some values that I tried didn't work, but I found a value that did. This means it's not necessarily the code that is wrong. I have also tried generating my own image base values. One attempt was to use the same algorithm that dllwrap uses, except with a different string hash function. This resulted in all dll's getting different image base values, but the first dll I tried to load failed in the same way. The second attempt was to generate non-random, but all different image base values at intervals that are plenty large enough. With this I couldn't even start the program, giving Microsoft's cryptic code that means: access violation. Presumably (although I didn't test) during the loading of one of the dll's that is part of the application. The third attempt was to set the image base for all dll's to 0x10000000, the value used by Visual Studio (I use the .NET 2003 version). This also failed to start the application. My guess is that LoadLibrary tries to relocate the library and that it fails to do it correctly. However, this is conjecture. Has anybody seen this? Does anybody have a solution? Is this a bug in the compiler or linker? I am using the compiler and linker from MinGW-3.2.0-rc-3.exe. The project compiles and runs fine on Linux, and also on Windows when compiled with Visual Studio. It also works on Cygwin, however we don't use dll's there, so we can't really compare. Also heopfully needless to say, we don't mix compilers (except for the system libraries). ______________________________________________________________________ You are receiving this email because you elected to monitor this forum. To stop monitoring this forum, login to SourceForge.net and visit: Found the appropriate message eventually at - " Both "man" and "groff", with appropriate patches, can be built from source, using MinGW -- both install into MSYS' /local/bin, *not* /bin" Is it possible to obtain binaries and/or the appropriate patches for this? Dave Murphy wrote: > > > Read and respond to this message at: By: figuinho Dear Luke, thanks for your. Actually it helped me indirectly. From your link, I found this one: I renamed my nsp.lib in libnsp.a and used the following command line %CC% -shared -o coslib.dll coslib.o %INCDIRS% -L. -lnsp. It produces my dll file with no errors. Thanks a lot! Alex ______________________________________________________________________ You are receiving this email because you elected to monitor this forum. To stop monitoring this forum, login to SourceForge.net and visit: Hello, thanks Luke, Hartmut. After I read Luke`s answer I did another google search and found this Guess what!!! Hartmut, one of the functions there, is made as you said. Thanks everyone!!! -- Juan Pablo <xjuan_gq_nu@...>: > g:/mingw4/bin/../lib/gcc/mingw32/4.0.0/../../../crt2.o So crt2.o must be in the directory ../lib relative to gcc.exe. Luke
https://sourceforge.net/p/mingw/mailman/mingw-users/?viewmonth=200504&viewday=7
CC-MAIN-2018-17
refinedweb
1,074
60.41
>>." IBM to the rescue (Score:5, Informative) IBM provides free access to the Olson database updates: Was this post even necessary? there's always Joda Time... (Score:5, Informative):Any day now (Score:2, Informative) Re:ORACLE = One Raging Asshole Called Larry Elliso (Score:0, Informative) ...or I could just use one of the other two dozen high level languages that has a far better implementation. For a new project, why would anyone use Python over Go? They have basically the same semantics except Go has far better performance and has decent threading model. Re:Java lost me years ago those because I disabled the plugin in my browsers years ago. Don't folks understand that 99.99% of Java users are unaffected by the plugin exploits??? When programming Java, you sure don't have to wrap everything in an object. Everything is in a class, but so what? Classes provide a namespace for your code, which is useful. They also give you lazy loading so you don't have to wait for an entire app to load. There are a lot of bad Java programmers though. It seems too few of them have really learned CS and don't understand the internals or runtime well. That's a mistake when using any language..
http://developers.slashdot.org/story/13/06/08/051235/oracle-discontinues-free-java-time-zone-updates/informative-comments
CC-MAIN-2014-41
refinedweb
214
67.25
W3C SWAD Recent (Feb2002) development: See the Makefile for details. Next steps: See also Internet mail message header format by D. J. Bernstein for lots of practical info about parsing email. I implemented some of it in a perl script. Other mail-messages-in-the-web thingies:'t very useful for finding out about it. Sigh. @@compare/contrast with earlier stuff, e.g. foaf:mbox , foaf:name, rdfs:label. See RDF and the RDF interest group archives for more context. This is/was a schema based on RFC 822. Please refer to it by the namespace name. I maintain it as HTML, but I make it availble as RDF using a transformation. See the Makefile or an XSLT service for details on how to invoke it. the addr-spec part of a mailbox, e.g. mailto:foo@example.org the phrase part of a mailbox, e.g. Dan Connolly @@say that this is a subproperty of rdfs:label? (as are foaf:name and dc:title?) this comes from berkeley mail, no?@@ date(mid:222, "Mon, 22 Jun 1999 12:33:23 CDT") ::= mid:222 bears date 'xyz'. see RFC822, section @@ note that case matters in XML and RDF, while it doesn't in RFC822 header field names. So this one property corresponds to all case variants (Date, date, DATE) of the field name. note: sometimes it's just mid:foo--to-->mailto:bar, but sometimes it's mid:foo--to-->[recipient]--addr-spec-->mailto:bar . Same applies to From/CC as well. @Hmm... maybe I should use different properties, related by a rule. Hmm... maybe the object of the to property should be a list so that we can record that these were the (stated) recipients, and there were no others. I say stated because there could be blind copies.
http://www.w3.org/2000/04/maillog2rdf/email
crawl-001
refinedweb
300
77.84
What development environment do you guys use?on 1) windows 2) linux? How can I download the entire winapi reference to my computer?meaning I can access the API reference even when I am offline Creating an installer for my programnot sure where to post this but I'm using visual studio 2010 and I'm trying to create an installer f... What's wrong with this code?Problem 1: Error messages: service.c(474): error C2061: syntax error : identifier 'main' service.c(... code contest[code] #include <iostream> using std::cout; using std::endl; int main() { cout << "Hello Wo... This user does not accept Private Messages
http://www.cplusplus.com/user/unregistered/
CC-MAIN-2016-22
refinedweb
106
60.92
I’ve been playing with an idea of how to extend the traditional unix shell pipeline. Historically shell pipelines worked by passing free-form text around. This is very flexible and easy to work with. For instance, its easy to debug or incrementally construct such a pipeline as each individual step is easily readable. However, the pure textual format is problematic in many cases as you need to interpret the data to work on it. Even something as basic as numerical sorting on a column gets quite complicated. There has been a few projects trying to generalize the shell pipeline to solve these issues by streaming Objects in the pipeline. For instance the HotWire shell and Microsoft PowerShell. Although these are cool projects I think they step too far away from the traditional interactive shell pipelines, getting closer to “real” programming, with more strict interfaces (rather than freeform) and not being very compatible with existing unix shell tools. My approach is a kind of middle ground between free-form text and objects. Instead of passing free-form text in the pipeline it uses typed data, in the form of glib GVariants. GVariant is a size-efficient binary data format with a powerful recursive type system and a textual form that is pretty nice. Additionally the type system it is a superset of DBus which is pretty nice as it makes it easier to integrate DBus calls with the shell. Additionally I created a format negotiation system for pipes such that for “normal” pipes or other types of output we output textual data, one variant per line. But, if the destination process specifies that it supports it we pass the data in raw binary form. Then I wrote some standard tools to work on this format, so you can sort, filter, limit, and display variant streams. For example, to get some sample data I wrote a “dps” tool similar to ps that gives typed output. Running it prints something like: $ dps <{'pid': <uint32 1>, 'ppid': <uint32 0>, 'euid': <uint32 0>, 'egid': <uint32 0>, 'user': <'root'>, 'cmd': <'systemd'>, 'cmdline': <'/usr/lib/systemd/systemd'>, 'cmdvec': <['/usr/lib/systemd/systemd']>, 'state': <'S'>, 'utime': <uint64 38>, 'stime': <uint64 138>, 'cutime': <uint64 3867>, 'cstime': <uint64 1273>, 'time': <uint64 1344635046>, 44635046>, 'start': <uint64 1>, 'vsize': <uint64 0>, 'rss': <uint64 0>}> ... Not super-readable, but its a textual format that you could combine with traditional tools like grep and awk. But, with the type information we can do more interesting things. For instance, we could filter using a numeric comparison, say finding all system uids: $ dps | dfilter euid \< 1000 <{266>, 44635266>, 'start': <uint64 1>, 'vsize': <uint64 0>, 'rss': <uint64 0>}> ... Then we can add numerical sorting: $ dps | dfilter euid \< 1000 | dsort rss <{365>, 'start': <uint64 1>, 'vsize': <uint64 61488>, 'rss': <uint64 24408>}> <{'pid': <uint32 769>, 'ppid': <uint32 745>, 'euid': <uint32 0>, 'egid': <uint32 0>, 'user': <'root'>, 'cmd': <'Xorg'>, 'cmdline': <'/usr/bin/Xorg :0 -background none -logverbose 7 -seat seat0 -nolisten tcp vt1'>, 'cmdvec': <['/usr/bin/Xorg', ':0', '-background', 'none', '-logverbose', '7', '-seat', 'seat0', '-nolisten', 'tcp', 'vt1']>, 'state': <'S'>, 'utime': <uint64 1602>, 'stime': <uint64 3145>, 'cutime': <uint64 22>, 'cstime': <uint64 9>, 'time': <uint64 1344634285>, 'start': <uint64 1081>, 'vsize': <uint64 108000>, 'rss': <uint64 16028>}> ... And, nice display: $ dps | dfilter euid \< 1000 | dsort rss | dhead 4 | dtable pid user rss vsize cmdline pid user rss vsize cmdline 1 'root' 24408 61488 '/usr/lib/systemd/systemd' 769 'root' 16028 108000 '/usr/bin/Xorg :0 -background none -logverbose 7 -seat seat0 -nolisten tcp vt1' 608 'root' 15076 255312 '/usr/bin/python /usr/sbin/firewalld --nofork' 747 'root' 8276 452604 '/usr/sbin/libvirtd' Note how we do two type-sensitive operations (filter by numerical comparison and numerical sort) without problems, and that we can do the “head” operation to limit output length without affecting the table header. We also filter on a column (euid) which is not displayed. And, all the data that flows in the pipeline is in binary form (since all targets support that), so we don’t waste a time re-parsing it. Additionally I think this is a pretty nice example of the Unix idea of “do one thing well”. Rather than having the “ps” app have lots of ways to specify how the output should be sorted/limited/displayed we have separate reusable apps for those parts. Of course, its a lot more typing than “ps aux”, which makes it less practical in real life. I’ve got some code, which while quite rudimentary, does show that this could work. However, it needs a lot of fleshing out to be actually useful. I’m interested in what people think about this. Does it seem useful? 51 thoughts on “Rethinking the shell pipeline” Awesome idea. I would like to see coreutils2 and other popular tools following this approach. Interesting. I wanted to do something like this myself, except using something like YAML as the output/interchange. YAML is implicitly (but strongly) typed and can represent data in a couple different structures (have not looked at GVariants though). Bonus points for defining some sort of iteration syntax, or making a shell which shares the language (vs stringly-typed bash). I just want to rewrite all of linux userland actually this is why I had to stop, I don’t know where to stop. The big problem with this is always the “isn’t ps aux easier” question. I think you realize that with your last comment. Currently shell users have to deal with complexity in the tools they use to manipulate the data (sed/awk/grep/echo/tail). What you propose may remove the complexity of those tools and replace it instead with a more complex pipeline. I’m not sure thats better, and its also really hard to get off the ground because if you can’t support all the utilities that I use from day to day, then I still have to learn all the previous tools to deal with the 1% you can’t deal with. Once I’ve learned those tools, I’m going to ask “why should I use your tools if the pipeline is longer, and I still have to use BASH” IMHO (and I hate to rain on your parade), but it always made more sense to me to try and replace BASH entirely. If you had a way to replace BASH with something like python that was a bit more interactive friendly, then you might be able to make a really compelling case. Things you would want to do: 1) Be able to recall that output of a previous command without rerunning it. Imagine running something like “ps” and getting a list of processes that you could then examine without having to constantly refine the pipe. Something like “ps; filter($LAST,pid<1000); grep($LAST,command=/*init*/);" Realize thats not what you want so "grep($LAST[1],command=/*dbus*/);" etc… 1.1) Have some way to convert that final accumulation of filters into a single useful line of code. 2) No more dealing with BASH's odd escaping or quoting issues, because everything is just a python function. 3) Ability to load libraries to deal with the proliferation of non-text files like Word or Excel documents. 4) Perhaps a sane way to handle the complex hierarchical files like XML since PERL6 seems to be far far away. I would be looking at things that have been successful in interactive data manipulation (like R) and trying to identify what made them successful and how that might be applied to build a modern shell which is not going to be constrained by all the limitations in memory and CPU that lead to BASH in the first place. Unfortunately I think trying to make the CLI tools simpler is actually the opposite of what is really desirable, because it doesn't address the limitations of BASH. What makes R so great is that the core language supports these very powerful filtering and splicing mechanisms (dps[dps$euid<1000,c("pid","user","rss","vsize","cmdline")] would cover everything in yours but the sorting and dhead), but you can't do that because BASH would go nuts and be completely unable to parse properly with any whitespace. You _obviously_ want dgit. Yes and no. It is easy to see the benefits of your system. However, what is preventing the existing system from doing these things? Why couldn’t we have a `ps` that outputs that as CSV? GNU `sort` can sort by an arbitrary column of CSV, a `dfilter` like program would be simple, and cut+column would fill the roll of dtable. That said, I can look at any one line of output in your format, and know what each “column” does. It reminds me of a similar proposal to use lisp instead of XML or plain text. I think it was on the one programming blog with a picture of a boat, but I can’t think of the name at the moment. I’d also be interested in your negotiation system, you seem to have glossed over it. That is awesome! Best solution I’ve ever seen to this sort of thing. Incidentally, there is a conversation going on at Hacker News Very interesting and it definitely seems useful. A suggestion is to make the commands start with the same name, for example when you write “dps” and “dsort” I would personally prefer “psd” and “sortd” so the commands alphabetize together, stem together, and can be read faster IMHO. (the “d” may not be the best choice of letter because it typically means daemon… maybe some other suffix?). Good luck with your project! Brilliant!!! You just re-invented dynamic typing and data serialisation. This changes everything!! [WORDPRESS HASHCASH] The poster sent us ‘0 which is not a hashcash value. Like the idea. My coworker and I wrote jgrep.org as a similar sart but around json Have built on this and some of my other tools have powershell like object passing over the shell pipes using json which combines well with jgrep “Mathematicians stand on each other’s shoulders while computer scientists stand on each other’s toes.” [WORDPRESS HASHCASH] The poster sent us ‘0 which is not a hashcash value. So the advantage is that commands output typed fields so you can choose to use other commands to sort, filter, etc with all the advantages that having types provide i.e. easy to sort numerical data. The disadvantage seems to be the long commands. Maybe the use case for this is to make the internals of these commands more maintainable? As you say, instead of “ps” having many ways to format the output, it makes calls to the sort/limit/etc commands internally whilst still offering the control through the command line options. That could be a candidate for internal refactoring so you get cleaner code but still have the ability to get typed output as a user. JSON? Have you considered using JSON / e4x-ish type stuff instead of a gratuitious new serialization format? ps -json | json-grep foo=bar | json-table foo=Foo bar=”Some Bar” baz=Other Foo Some Bar Other 1 2 3 4 5 6 –Robert For the record, I vote for a format that doesn’t include explicit integer-size annotations – they’re almost certainly more harm than good in an interactive pipeline. ” Even something as basic as numerical sorting on a column gets quite complicated.” What about “sort -k” ? Please read the man-pages, and buy yourself a good book about shell scripts programming and stop wasting your time trying to reinvent the wheel. The traditional shell pipes are just perfect. We don’t want (neither we need) anything different. Indeed, I think the unix philosophy is not something that unix itself has followed. Just look at any modern variant of the old unix commands and count the number of options and special operators they have. Basically because of the limits imposed by human readable text output. Adding type and structure to command output is really the way it should be, the pretty-printing should be left to specialized formatting commands, just as you have done. This looks interesting. There are several questions, though: the format: difficult to read. Difficult to type – for that reason alone it won’t be something people will want to use. Don’t forget, the shell is for typing. People will end up cursing you out for inflicting this on them. The guy who came up with the Web, Tim Berners-Lee, said he was sorry about wasting the huge amount of ink for printouts that include “http://” since it is superfluous. Type annotations should be completely eliminated except in situations of ambiguity, and actually – if things are ambiguous maybe they just should be eliminated. It should be possible to implement the literals in sh, Bash, and ZSH, at the very least. That’ll give you enough to specify the format in itself. dbus: Who cares about dbus? I understand you’re a desktop programmer and everything you do is in dbus. However, in the “hardcore” shell world, no one ever hears of DBus. Unless they want to interface with Gnome, and then only briefly, because using it from the command line is a pain. Is that really what people want? I do not know and I can’t answer. However the idea of using C-ish things could be useful. However, let’s be honest with eachother: the people using dbus don’t care about the shell for the work they use dbus in; and people using the shell for their work don’t care about using dbus. This is forced. I understand you have a hammer in your hand which you know and like, but not everything is a nail, and I’m sure you know all this but just feel the need to remind you. The format being passed around: ideally, the shell should be able to tell if one of the programs has to produce or some other has to receive objects (and don’t fool yourself, your GVariants are still objects). At the point of initial execution the shell should be able to check which applications can support this. If the pipeline cannot be set up intelligently, it should exit with “Broken pipe” or something like that (there are people better with shells than I, who could say more about this). You could do this by requiring every program that supports object i/o to only do it if it’s passed –object. What more, you should have the shell typecheck the object schemata or whatever we want to call it. In normal pipes, you use text and that’s all. There’s no way to have “bad text”. You can, however, have “bad objects”, or incompatible objects. For example, ask for fields that don’t exist. I am not sure what should be happening at this point. A part of me says “use exceptions and go freeform”, another says “have contracts for greater security and robustness”. Going freeform is often annoying in that it messes up in very unpredictable ways. However, if this should lift off, then there should be a way to extend the standard posix toolkit – by this i mean awk, bash, maybe sed – to report the types required by their programs. I am not sure if that is easy. Utilities: you want the standard utilities to start supporting some object format in the end. Having “dps” and “dbash” and “dawk” and “dsed” and “deverything” will annoy people to no end, so should be transitional. “Do one thing well” wasn’t about input/output formats, man: it’s about having a single logical concept in the program, as opposed to many different ways in which a program can *process data*. Doesn’t talk about ways in which a program can *access data*. Look at the recent trend in nul-separated lists (e.g. look at find, xargs) Input/output: why are we streaming around text? For actual usability, speed, and as little mangling as possible, you want to stream around shared memory addresses in hex. Then, if someone wants, he can print out what’s in those addresses with the use of some tool. Do you really want to pump so much text through our prototypical object-enabled awk? Think about it, you can have objects in programs that are self-referrent. That’d never fly. And even if you disable this (how? you can’t *really* predict cycles!) then you will not be able to work with huge objects, which is the point at which you actually want to start using objects and text. Furthermore: what if the data I want to expose isn’t actual data – what if it’s generative? What if I want to expose a search algorithm, which displays fields that can be accessed, but it only does so in a generative manner as they get accessed? What if Google had to pre-generate all of its search results before displaying the first page – that would never fly. Not everything is a non-dynamic dictionary like what your GVariants I understand are. Most things can however be made to display themselves in the form of a dynamic dictionary. Methods: static objects are fairly fucking boring. I would like to condemn them at this point and remind you that you yourself use a lot of different, dynamic abilities every day, and that not being able to call methods isn’t a large enough step. The shell is for programming just like any other language you use, so I don’t see why it should be archaically reduced to the capabilities of cobol. Other languages: not everything is C. Of course, Python, Java, Qt, JavaScript, what have you are just C. But the future seems to be bright for very different languages. Ask people who program in Erlang, Haskell, Clojure, Scheme, even Prolog, see what they think. Ask them how they would string their programs together, and ask what strengths their language could use to make this process of pipelining better and more powerful. I’m sure things like C, Python or JS can follow suit through sophisticated libraries. What I’m trying to say is, don’t use the least common denominator to get your ideas. This is important. Look at the best points of each language you can come up with, come up with an idea, and then the ones who don’t support it will work towards supporting it. Methods again: If you don’t allow methods you disable an important form of discovery, that is, make sure programmers can’t learn what they do by doing. If you have methods, you can ask an object to return its type, schema, or documentation. More and more languages that support this in their shells show how crucial this is and what a great way of facilitating development you would be using if you didn’t do it. Regarding standard utils: There’s definitely potential for the standards being extended. Example with made-up syntax below. I use a dot, it might already mean something in awk, I don’t know. This one prints processes of uid less than 1000 in the form of cmd, pid sorted by pid. ps | awk ‘/$0.uid < 1000/{yield {$0.cmd, $0.pid} }' | sort -n1 -F 'pid' | awk '{print}' Notice we use "yield" to stay in the hex-address representation world, then use print to print the actual content out. This one finds flash instances by searching for Firefoxes plugin-container program: ps | grep 'plugin-container' -F 'cmd' | awk '{print $0.pid}' | xargs kill -15 This one finds flash instances too: ps | grep 'plugin-container' -rF | awk '{print $0.pid}' | xargs kill -15 Maybe awk could even do something like $pid instead of $0.pid. Not sure that's necessary, though. Notice I haven't specified –object in either of those. awk or grep can report that it needs object input, so the shell can make the other programs follow suit. Front page on hacker news: This looks great. I’ve been meaning to do something similar myself, but never got the time. A few related things I’d been thinking about: – What if applications could specify a stylesheet (e.g. XSLT) in the output? Then ps could suggest a suitable rendering and the shell could display it in table form by default (or a GUI could render it as a GTK table, etc). grep and sort would just pass the stylesheet hint through. – It would be super useful if “filename” was a separate type (not just “string”). The shell could render files and directories in the right colours, adjust paths if you cd, let you double-click to open them, etc. – If applications could specify the content-type of the output, we wouldn’t need to have binary data dumped to the terminal. The shell could splice binary output data to a temporary file, or select a suitable viewer application. – Would be nice if applications could output progress reports. e.g. find could say which file it was looking at, du how far it had got. The shell could display these temporarily if things were taking a long time. Basically, how extensible is the format? Thomas: I’d like to avoid any form of header describing the data, as that doesn’t work well with record-level filtering which seems to be a very common operation in shell. Filenames in dbus/gvariant are typically bytestrings to avoid non-utf8 problems, but they have no specific type other than that. The format is just GVariant, but the negotiations could be extended to support more formats or format details. For certain types of unix pipeing, I have found it useful to pipe from tool to CSV, and then let sqlite process the data, using SQL statements. SQL solves many of the sorting, filtering, joining things that you can do with unix pipes too, but with a syntax that is broadly known. Especially the joining I have found hard to do well with shell/piping. I think a sqlite-aware shell would be awesone, especially if common tools had a common output format (like csv with header) where that also included the schema / data format. @unix lover: “sort -k” is nice as long as you don’t end up with a first column containing strings which can contain spaces themselves… then you fall in the nightmare of having to format the output of the various commands to use another separator, and tell the various commands to parse their input with that separator too. There is definitely room for a better shell pipeline ; I’m not sure that blog post proposition is the best solution, but I find it nice to see some discussion of that problem. Seriously after 3 years of PowerShell, it’s a really bad idea. It’s more complicated and slow. Making the output of the tools we have to use more parseable with cut/awk is a better option. I did some experimenting with the SQL approach a few years ago, you can see an example of my idea here: but without better integration with the shell it would not be convenient. However, I think it would be very convenient if at the shell prompt you could do something like select * from $processes where pid < 1000 sort by rss limit 4 Have you considered “sniffing” for the output stream and doing the right thing (ie apply a full dtable treatment) when the output is in a terminal ? (quite similar to ls colouring or git’s EDITOR usage) If you add back some of the “field selection” parameters to dps, then it means $ dps | dfilter euid \< 1000 | dsort rss | dhead 4 | dtable pid user rss vsize cmdline could be shortened to $ dps aux | dfilter euid \< 1000 | dsort rss | dhead 4 Commands would then just do the right thing if outputted in a terminal and have more flexible behaviour while outputting in another pipe. 1. Pipes is byte orientated not text 2. everything you think is wrong with them is a feature 3. gnu is not unix I found your idea close to TermKit: am I right? Hell yes. Ignore the nay-sayers. They’re idiots. We need something like this. PowerShell has proven it is a good idea and we should have done this eons ago. My recommendation is to make sure there is no way to accidentally guess wrong about what kind of pipe. Maybe if the program is in /usr/dbin assume the program is aware of the new pipe format. That way dsort becomes sort, etc. You might consider making the language compatible with PowerShell. Yes, that sucks for political reasons but they have spent a LOT of time thinking out how to do it thru trial and error. You won’t have to repeat their trials. Tom I left a comment on HN [1] so I’m not gonna repeat it here, but I’ve been working on exactly the same thing as a side project. We have very similar ideas (typed streams, a couple of basic tools that do one thing well) and I think this is an awesome way of exploring how the unix interface can be improved in the future. One thing I’m not sure about is the binary format and the “output format depending on pipe consumer” feature – in my eyes, a textual representation like json + json schema for the types is a more consumable and wide spread structured data format; regarding the actual tool output, isn’t a single configurable tool like dtable enough? Also, by outputting plain json, one could leverage a number of available filtering / sorting json cli tools available [2] – even if untyped, they are still useful. [1] [2] That is a great idea! It’s easy to either create wrapper programs like dls for ls to output this data, or for the program authors to add –dout or something switch to allow both backwards and forward compatibility. It would be even better if multiple message formats could be used. The shell could then handle translating from one format to another or automatically adding the –dout switch/calling enabled stub program between pipes. There are many formats and many scripting languages out there. It’s only natural that the shell has support to for them to easily talk to one another. Ruby has YAML, JavaScript/CoffeeScript have JSON, Java has XML, Flash has AMF, there’s also the interesting MsgPack and others. The added benefit is that unix shell programs could then easily become extensible as web services The idea of passing more structured data or objects in a pipeline comes up every so often. On the surface, it looks like a great idea, but it inevitably fails in the end because it limits flexibility and adds complexity. (I recently gave a presentation on the topic of simplicity, citing precisely this example:) In order to use the new pipeline, *all* your tools need to understand the new data model; otherwise you break the very important “filter” function of unix command-line tools. Imposing a requirement of structure on the tools that consume the data implies that you anticipate (correctly!) all possible uses of the data; anything your data model assumes about the use or hides from the user is thus written in stone. But common unix tools are so successful and useful precisely because they do not pretend to be able to anticipate all possible uses. The data is as flexible as possible, allowing any user to come up with any possible use case and manipulate it as they deem fit. The unix philosophy is not only “do one thing well”, it’s: ‘Write programs that do one thing and do it well. Write programs to work together. Write programs to handle text streams, because that is a universal interface.’ (Douglas McIlory, inventor of the pipe) The second and third sentences are equally important. Why reinvent the textual representation? How about something a bit more compact like JSON? . How is this restricting the possible use cases of anything? If in the future ls needs an additional field for something, it wouldn’t break existing tools. Even if the output format changes, it wouldn’t break anything, at most people would have to adapt their filter / sorting / etc scripts. However, this would equal to the actual current unix ls command changing its output and I don’t see that happening – and if it did, go and adapt your awk and sed scripts that have to parse some arbitrary text. Current plain text output is the most “non-composable”, rigid way of doing things – sure we make do by painfully parsing columns and rows, but it can be much, much easier. Eh, half of the benefit of textual data representation is ease of reading and manipulation by human operators. If you want something more amenable to machine parsing and manipulation, it would be better to just use a database or at least some standard format such as JSON. If you intend to send large amounts (GBs) of data between programs, command line piping will be much too slow anyway. Better to use a well tested system of exchanging data, such as a database, or for real time exchange, perhaps a queriable server. I made LoseThos without pipes or streams. Yeah, I support pictures at the command-line. Those could be serialized. I have a neat feature where you can put call-backs for text — my help, command-line source editor, forms all can have text call backs and you can do text indirection for form letters. Viva la difference. i decided nothjing in losethos is for printers. Documents are for the screen with scrolling markees and stuff. I think a variant of this has been thoroughly implemented in the Scheme shell, scsh. It should still be around. Their ambition was also to have sane programming language for the shell. Take a look, I never got into it, but remenber it was well documented. Hi, I love the bash also I didn’t code many scripts yet, but the output == return principle is awesome. To make your structured pipe more usable I think it would be really helpfull to have a convert program which does the reverse of dtable, so that you could import the output of the normal ps aux into the GVariants format. Also if this might not be too easy I think it would unleash the power of this tool. x @philip: > . What about the human consumer? Many tools have as a primary (or one of the main) use case that of an actual human reading and understanding the results. I don’t think I’d like “ls” to spit out json, and I also don’t think I’d want to have to invoke a “turn json into human friendly format” filter (which would have to differ for about every command invoked). Secondly, sometimes you do not _want_ all possible output. In your example of ls, this means that it will always look up all additional attributes of a file. If your NIS server is down, it will hang because it can’t resolve UID->username (which you can work around with ‘-n’). > How is this restricting the possible use cases of anything? If in the future ls > needs an additional field for something, it wouldn’t break existing tools. No, but any possible tool I wish to write will have to be able to read your format (say, json). If the format passes objects, then the filter cannot continue processing until the entire object is received and the entire json input is interpreted. If my initial tool generates a few million lines of output, this isn’t going to make the filter very happy. > Even if the output format changes, it wouldn’t break anything, at most > people would have to adapt their filter / sorting / etc scripts. Off-loading this task to the people writing a filter is a pretty good example of what I mean. Suppose you have ‘dls’ and I wrote two filters ‘dsort’ and ‘dhead’. ‘dls’ adds new fields in the output, but ‘dsort’ and ‘dhead’ are not aware of these fields. They will simply ignore them. Now in order for me to use ‘dls’, I need to go and update these filters (and whatever other tools I might wish to use to post-process ‘ls’). Compare that to the current situtation: even if somebody decided to change the output of ‘ls’, this would not require an update to any other binary to be able to post-process the output. > However, this would equal to the actual current unix ls command changing > its output and I don’t see that happening – and if it did, go and adapt your > awk and sed scripts that have to parse some arbitrary text. That is not quite the analogy. The correct analogy would be that if you update ‘ls’ to add/change output, you also would have to build a new ‘awk’ and a new ‘sed’. I’m quite convinced that the current stream interface is a good example of ‘Worse is Better’; yes, conceptually the idea of passing objects is appealing, and it may be more “correct”, but it’s not actually “better”. Simplicity always wins. the beauty and the power of the pipe is its simplicity. Got this comment by mail from Alex Elsayed (blog issues): One thing I think is important and many of the commenters are missing is that this is more a ‘structured data’ shell pipeline as opposed to an ‘object’ pipeline, and that is a VERY GOOD THING. Objects encapsulate what operations you can do on them as well as the data, whereas structured data simply adds context. To those commenting about how this ‘limits’ what can be done with the data, your comments are completely true and insightful… for object pipelines. As this is a structured data pipeline, they really don’t quite match reality. Note how the examples are all about running a filter that looks for values, rather than calling methods on what is passing through. This is not dependent on what the creator ‘anticipated’ – it’s more akin to having all data producers be set to ‘verbose’ (ps -eo $everything) and using a key/value output format (avoiding field termination issues and such, no more bugs due to running find -print instead of -print0) as opposed to calling the ‘getpid’ method on ‘process’ objects. One thing I would suggest: Have a ‘dformat’ (or ‘dfmt’ for lazy people like me) command, that takes a normal shell commandline (like [ls, /tmp]) as its ARGV, looks up a formatter plugin corresponding to the executable in /usr/share/dpipeline or similar, and uses that to format the output. That removes the need to define large numbers of commands like dps and such, and avoids namespace pollution. At that point, all you need are dfmt and the filter/display commands. It also makes it easier to ship formatters with the applications they belong to, modulo friendly upstreams. I would recommend using a different data format, though. Using GVariant ties it to glib, and for something like this being tied to a specific library may not be the best idea. I’d second the suggestion to use JSON – perhaps have the first entry be a ‘schema’ that defines the fields and their datatypes, and then all subsequent entries are just the fields and their values. I’m not sure you would really gain all that much by using a binary representation anyway, mainly just because of use cases, but that would be something that requires empirical verification before I’d put money on either side. For the “JSON is not compact enough” concern, there’s also BSON (binary JSON): Yes, it does. Look usefull, I mean. I’m not so sure about the serialization format (it looks rather awkward to write and parse) but /any kind/ of common serialization/structured data format would be a big step forward if we could just make all command line tools understand it. More from Alex Elsayed: @Jan Schaumann, there are a few ways around the issues you bring up. First of all, regarding the human consumer, see my earlier comment about ‘dfmt’ and embedding a simple schema – using the same architecture, a ‘dunfmt’ that uses a similar system (or even the same plugins) to reformat in a type- specific way would be trivial, and could even be plugged into a d* command automagically if the output is a TTY. With regard to not wanting all possible output, you have a point. However,). This would, however, probably be better implemented in a dedicated shell mechanism of some sort rather than by abusing pipes. Third, yes, any tool you write will have to be able to parse it… Except that you could always use dtable or the like, and turn it into NULL-separated values or whatever. And JSON isn’t particularly difficult, either, since essentially every language has tools to parse it. Even Bash has such a library in the form of ‘JSHON’. In addition, most JSON parsers I’ve encountered support reading and writing “objects” (the JS term for hashes/dictionaries) simply concatenated with each other in addition to having them be encapsulated in an array. If you make each ‘line’ a single object (as would usually make sense for CLI programs like ps or ls) then they can in fact be parsed incrementally, and dealt with as they come rather than as a big dump all at once. An example would be Perl’s JSON module and the “incremental parsing” functions therein. Fourth, if the system does as I suggest in my third point and uses one entry per line, ‘dhead’ never needs to know what is inside – it just reads N objects and then terminates. Similarly, ‘dsort’ has no need to understand the object – it merely needs the ability to take some sort of identifier as an argument to tell it what field to sort by. If an entry has a value named ‘foofoobar’ that I want to sort by, I just run ‘dsort -k foofoobar’. It then looks up the ‘foofoobar’ key in each element and sorts by the result. No intrinsic knowledge ever needs to be included into dsort itself. Your example about alterations to the output of ‘ls’ not breaking clients is also factually untrue – there are distros which default to different ways of formatting times in ls. This breaks scripts that parse the output. With this, it can simply be stored as a Unix timestamp and formatted at the display end. That entire class of problem comes from mixing mechanism (provide a time) and policy (But how do we format it?). This system allows separating them. And the fact that dsort merely taking a key name, looking it up, and sorting by the result removes any intrinsic knowledge of the data structures means that it really *is* a good parallel with changing your awk script, and not rebuilding the awk binary. @alexl >). That sounds like adding significant complexity. Adding flags to select a subset of things to output then sounds like it would negate the benefits of allowing other tools to operate on the object output and do their filtering. At the very least, it duplicates capabilities. > This would, however, probably be better implemented in a dedicated shell > mechanism of some sort rather than by abusing pipes. I can see that. Of course that means that in order to take advantage of these new pipes, users have to start using a new shell (which for many people is a significant hurdle). Some people prefer one shell over another, have extensive customizations and scripts, functions etc. they rely on. Building a new shell for this object model will raise the barrier to entry significantly, I think. > Your example about alterations to the output of ‘ls’ not breaking clients is >also factually untrue – there are distros which default to different ways of > formatting times in ls. This breaks scripts that parse the output. Yes, but it does not break the tools invoked in the script. Changing output format willy nilly is a very bad idea, I very much agree on that. But even if my various scripts break, I do not have to update or rebuild sed(1), awk(1), grep(1) etc. Oh, talking about grep(1)… how would grep(1) work in this model? It seems to me that grep(1) needs to be able to parse regular plain text streams for its most common use case. But it’s also a filter, so it would need to understand the new object format, too and decide when to use which? Ie, “grep <file" needs to work — would the new shell implement "<" to read a file and turn each line into an object "{ line: text, linenum: N }" or something like that? How would regular expression matching work? Ie, in a text stream, I can create regexes that match multiple fields; if I'm operating on objects with unordered fields, how do I match "^[a-z123]+ .*(foo|bar).*" across fields? From Alex Elsayed: @Jan Schaumann (fyi, alexl is posting these comments for me because I can’t submit comments due to a weird 403 forbidden error; I’m “Alex Elsayed” or “eternaleye”) You wouldn’t *need* a new shell to make use of bidirectional communication – as I said, I seem to remember their being some sort of ‘accept() on a pipe’ trick that basically turns it into a socket for all intents and purposes other than namespace. I just said that it would probably be *better* to do it that way, and have the shell set up bidirectional file descriptors alongside the standard streams vaguely similar to the TermKit design so that control is out- of-band from bulk data. Regarding grep, I think it would still work. For one thing, JSON ‘objects’ are iterable – you can walk the keys. Sure, they can contain other objects, but some sort of depth-first search isn’t out of the picture. By default, maybe have grep do a regex match on the values of every field that way; the user could use -k to restrict which fields to search, or even use –keys or similar to search keys instead of values. If all else fails, you can still reformat it into text anyway for a more traditional grep. That said, I do think that grep may be the wrong conceptual model for such a filter, though. I think something that behaves more like ‘test’/[[ ]] might fit better, since it’s checking values rather than parsing strings. That doesn’t even exclude regexes – IIRC, Bash supports regexes in [[ ]], and I know Zsh does. Therefore, perhaps some sort of ‘dvalfilter’ that either takes a comparator string (“/foo/bar/0/qux >= 72”) or if that interface is icky something more like -k /foo/bar/0/qux -ge -v 72. (here /foo/bar/0/qux is equivalent to the perl $obj->{foo}->{bar}->[0]->{qux}) To match across multiple fields, just specify more than one using ‘and’ & ‘or’ operations – think of it like passing -e to grep multiple times. I had an idea like this years ago that I never did anything with. Except, instead of having alternate versions of commands that output xml/json/gvariant/whatever, I was going to modify the existing commands, having them still output the same stuff to stdout as they do now, and output something like your format to a separate “stdmetaout” fd (which would also include information about which columns of the textual output correspond to which fields in the structured output. Maybe in some cases it wouldn’t fully duplicate the data, but would just say, eg “the PID field can be parsed out of columns 10-15 of stdout”). So as long as the data was being piped between metadata-aware processes, all the metadata would stick around, but once it got passed to a non-metadata-aware process (or reached the shell’s stdout), the metadata would be dropped and you’d be left with just the text. So, you could do stuff like ps aux | awk ‘$RSS > 1024’ | sort -k START which would print all the processes using more than 1M, sorted by start time (and would also print the “ps” header at the top still, because the metadata would indicate that that was header information, so it shouldn’t be moved by “sort”). That is about the extent of how far I got in thinking about it… what would be great would be a wrapper for common unix utilities to convert from the standard formatting to object formatting. That way you could do something like $ dwrap ps and that would interpret the results of the standard ps call and convert it to an object notation. I’ve long wanted to make one of these that would convert to JSON, but never really got around to starting a project that immense. Perhaps, a better idea is to resurrect some functional shell. The idea is quite old, see e.g. Nowadays, the best option is to use Haskell, or, better yet, a language based on it, but with slightly different syntax adapted for shell needs. This way, we’ll have both strong typing and laziness. The latter will solve problem of ‘not wanting all possible output’, and also will allow for loop fusions, eliminating unnecessary copying/serialization/deserialization. Something of that sort exists already:
https://blogs.gnome.org/alexl/2012/08/10/rethinking-the-shell-pipeline/comment-page-1/
CC-MAIN-2019-09
refinedweb
7,606
68.3
In this short post I will show the syntax for writing data to a SQL database with the Python library, sqlite3. We will be using Python 3+. A SQLite database is exactly what it sounds like – a lightweight implementation of the popular SQL relational database management system, making it perfect for browsers, embedded systems, or small scale data storage/analysis (Wikipedia). On to the code, let’s do it in less than 20 lines. For sake of example, let’s say you scraped some linguistic data like this (but chose to output it in .csv format instead). Then you have three columns: context, response, and score. Each of these will be entered as text fields (though we may want to change score to “real” type later on). Here’s the data I tested this code with: context, response, score "Raj: I don't like bugs, okay. They freak me out.", Sheldon: Interesting. You're afraid of insects and women. Ladybugs must render you catatonic., 5 "Sheldon: (3 knocks) Penny! (3 knocks) Penny! (3 knocks) Penny!Bernadette: What happens if I say come in?Penny: Well, find out.Bernadette: Come in!Sheldon: (silence)(3 knocks) Bernadette! (3 knocks) Bernadette! (3 knocks) Bernadette!Penny: Come in! Sheldon: Keep it up. I've got nowhere else to be.Bernadette: Just come in.","Sheldon: For future reference, if I want to watch Mean Girls, I'll just stream it on Netflix.", 5 Sheldon: Why are you crying? Penny: Because I'm stupid. ,"Sheldon: That's no reason to cry. One cries because one is sad. For example, I cry because others are stupid, and that makes me sad.", 5 And here’s the script that will populate a table “utterances” with the data in the CSV file and save it as “example.db”. import sqlite3 import csv f=open('sheldon_quotes.csv','r') # open the csv data file next(f, None) # skip the header row reader = csv.reader(f) sql = sqlite3.connect('example.db') cur = sql.cursor() cur.execute('''CREATE TABLE IF NOT EXISTS utterances (context text, response text, score real)''') # create the table if it doesn't already exist for row in reader: cur.execute("INSERT INTO utterances VALUES (?, ?, ?)", row) f.close() sql.commit() sql.close() Simple example. “sqlite3.connect()” creates a new database or connects to an existing one of the same name. “sql.cursor” creates the cursor object that you use to execute the actual database commands (values are substituted in wherever “?” exists. It takes care of figuring out that index 0 of the row goes where the first question mark is placed, index 1 goes where the second question mark is, and so on. You can take a look at the data by adding two lines like this: for row in cur.execute('SELECT * FROM utterances'): print(row) There’s also some good documentation on the docs page. I recommend taking a look at commands like .fetchone(), .fetchall(), .keys(), create_function, and the example shell here which is a short script that lets you interactively experiment with commands.
http://www.adamantine.me/2017/05/22/how-to-write-data-to-a-sqlite-database-in-python/
CC-MAIN-2018-39
refinedweb
506
69.79
WSDL Connectors The Axis and CXF transports provide WSDL connectors that can be used for invoking remote web services by obtaining the service WSDL. Mule creates a dynamic proxy for the service and then invokes it. The easiest tool for doing this, however, is the Web Service Consumer. Generic WSDL Endpoints A WSDL endpoint enables you to easily invoke web services without generating a client. At startup, it reads the WSDL to determine how to invoke the remote web service during runtime. When a message is sent through the WSDL endpoint, it is able to construct a SOAP message using the message payload and its knowledge of the expected payload format from the WSDL. You must provide the full URL to the WSDL of the service to invoke, and you must supply a method parameter that tells Mule which operation to invoke on the service: wsdl: The WSDL URL is prepended with the wsdl: prefix. Mule checks your class path to see if there is a WSDL provider that it can use to create a client proxy from the WSDL. Mule supports both Axis and CXF as WSDL providers. If you want to use a specific one, you can specify it on the URL as follows: wsdl-cxf: Or: wsdl-axis: In general, you should use the CXF WSDL endpoint. The one limitation of the CXF WSDL provider is that it does not allow you to use non-Java primitives (objects that are not a String, int, double, and so on). Sometimes the Axis WSDL generation does not work (incorrect namespaces are used), so you can experiment with each one to see which works best. Note that there are no specific transformers to set on WSDL endpoints. Specifying an Alternate WSDL Location By default, the WSDL provider looks for your WSDL by taking the endpoint address and appending ?wsdl to it. With the CXF transport, you have the option of specifying a location for the WSDL that is different from that specified with the ?wsdl parameter. This may be useful in cases where the WSDL isn’t available the normal way, either because the SOAP engine doesn’t provide it or the provider does not want to expose the WSDL publicly. In these cases, you can specify the wsdlLocation property of the CXF endpoint as follows: In this case, the WSDL CXF endpoint works as it normally does, except that it reads the WSDL from the local drive. Example of the CXF WSDL Endpoint This example demonstrates how to take multiple arguments from the console, invoke a web service, and print the output to the screen. It uses the Currency Converter web service on. This service requires two arguments: the "from" currency code and the "to" currency code. When the CXF dispatcher prepares arguments for the invocation of the service, it expects to find a message payload of Object[] – that is, an Object array. In the case of the Currency Converter, this should be an array of two Objects - the "from" currency and the "to" currency. There are several ways to construct this object array, but the easiest way is to use the custom transformer StringToObjectArrayTransformer, which translates a delimited String into an Object array. In the example below, you simply type in a String in the format of <fromCurrency>,<toCurrency>. For example, type "EUR,USD" to get the conversion rate for Euros to US Dollars, and you get something like this:
https://docs.mulesoft.com/mule-user-guide/v/3.9/wsdl-connectors
CC-MAIN-2018-13
refinedweb
572
57.91
The macros STORE_(NUMBER|INT|UINT) from jsinterp.c do not call SAVE_SP_AND_PC before calling potentially GC-triggering js_NewDoubleValue. This leads to a GC hazard as demonstrated with the following example: ~/m/ff/mozilla/js/src $ cat ~/m/y.js var expect = f(); gczeal(2); var actual = f(); if (expect !== actual) throw "Hazard: actual="+actual+" expect="+expect; function f() { var a = 1e10; var b = 2e10; var c = 3e10; return (a*2) * ((b*2) * c); } ~/m/ff/mozilla/js/src $ ./Linux_All_DBG.OBJ/js ~/m/y.js uncaught exception: Hazard: actual=1.44e+42 expect=2.4e+31 Note that so far I was not able to discover a way to get a crash with that. But it can be used to read a memory image of allocated structs. Created attachment 300249 [details] [diff] [review] v1 The patch just adds the missing calls to SAVE_SP_AND_PC. I checked in the patch from comment 1 to the trunk: Comment on attachment 300249 [details] [diff] [review] v1 The patch applies to the 181 branch as is. Comment on attachment 300249 [details] [diff] [review] v1 approved for 1.8.1.13, a=dveditz for release-drivers Created attachment 304953 [details] js1_5/extensions/regress-414755.js v I checked in the patch from comment 1 to MOZILLA_1_8_BRANCH: Checking in jsinterp.c; /cvsroot/mozilla/js/src/jsinterp.c,v <-- jsinterp.c new revision: 3.181.2.95; previous revision: 3.181.2.94 done v 1.8.1 linux|mac /cvsroot/mozilla/js/tests/js1_5/extensions/regress-414755.js,v <-- regress-414755.js initial revision: 1.1
https://bugzilla.mozilla.org/show_bug.cgi?id=414755
CC-MAIN-2016-30
refinedweb
259
52.26
I’ll be honest with you, when I came upon Svelte, I thought to myself: “Oh come on, not another JavaScript framework. I’m just about to get proficient with React. I can’t take another one of these.” But I jumped in and used Svelte for a while, and I’m happy that I did. Of course, if you use Svelte, you already know that it’s a compiler, not a framework that ships with your production code. This makes your apps smaller and faster than “traditional” JavaScript frameworks and libraries like React, Angular, and Vue. But that’s just the tip of the iceberg. Svelte has learned from its predecessors and provides an exceptionally elegant development experience. It’s telling that the entire Svelte API documentation is effectively one page: the framework is as minimal in its design as its output, and that’s a good thing. But if you’re here, you probably already know that. So what about internationalizing our Svelte apps? Other JS frameworks have a slew of i18n library options to choose from. What do we have to use for Svelte? Well, one option is svelte-i18n by Christian Kaisermann. It’s a light wrapper around FormatJS that uses Svelte stores to provide a no-frills i18n solution with ICU message support. That’s a good start, and we can build on top of that. In fact, in this article we’ll do just that, internationalizing a small demo Svelte app with svelte-i18n. Note » If you’re not familiar with FormatJS or ICU messages, don’t worry. It’s not necessary to know about them to follow along here. Our Demo app Alright, enough with the chit-chat. Let’s get to the code. We have a starter project so that we can get right to the i18n work. Here’s what it looks like so far: Our demo app, Flimic, is a list of films You can download all the code for our demo on Github. If you want to work along with us here, just download the repo and checkout the startbranch. Our app, Filmic, is a curated list of eighties Hollywood movies. Our goal is to make the app’s UI available both in English, our source locale, and Arabic. You can use any locales here, of course. By the time we’re done, we will have accomplished the following: - Walkthrough of the starter project code - Installing and setting up the svelte-i18n library - Dynamic, per-locale translation file loading - Handling locale direction: left-to-right VS right-to-left - Using basic translation messages, interpolation, plurals, and date formatting - Building a simple locale switching UI for our users When we’re done, our app will look like this: Our completed app will be localizable to any locale of our choosing Btw who else owned both the Ghostbusters II and Batman soundtracks? No? No one? Ok, awkward. Let’s start. The Starter Project Code Our starter project isn’t terribly complex. However, let’s quickly go over how it’s put together so that we’re comfortable with our starting point. The starter project’s component hierarchy looks like the following. Header and Footer are just bread-and-butter layout components that contain text. MovieGrid is a bit more interesting: it’s a stateful component that loads movie data from a JSON file. Each movie item is passed to a presentational Movie component that displays the item. Here’s a sample of our data from movies.json: At the moment, our UI text is all hard-coded, and our data is only presented in English. Let’s address this and internationalize our app with svelte-i18n. Installation & Setup We’ll start by pulling svelte-i18n into our project through NPM. ✋🏽 Heads up » After installing svelte-i18n and running your development server, you may get warnings that say, “(!) thishas been rewritten to undefined“. This is a known problem when using Rollup with some modules. The code the warnings are refering to seems to work just fine in our case, and Rollup is probably being a bit overzealous with its warnings. However, if you want to address the issue and get rid of the warnings, you can modify the project’s Rollup configuration to pass the modules the value of thisthat they expect. We’ve done the work for you already in our Github repo, so check it out there. That’s all we need to install the library. Now let’s use it to internationalize our app. We’ll cut our teeth with the Header component since it’s nice and simple. Here’s the current code for Header: We’ll want to update our .title and .subtitle so that they display dynamic, translated messages. Let’s head over to our root App component and set up those messages. svelte-i18n provides regular Svelte stores for setting its messages dictionary, and the active locale. ✋🏽 Heads up » We need to set our messages dictionarybefore we set our active localeor svelte-i18n will throw an error. The Messages Dictionary The library uses a simple key-value map for its messages. Top-level keys are locale codes like ar, or fr-CA. Underneath each locale code is the locale’s translated messages. The messages themselves are keyed by IDs that we can use elsewhere in our app. Let’s use these messages in our Header component now. Another store, _() (underscore), is provided by svelte-i18n for retrieving our messages for the current locale. We just need to provide a message’s ID to the function, like _('app.title'). 🔗 Resource » You can use format()instead of _() if you want, as the latter is just an alias of the former. Check out the svelte-i18n documentation for more info. Notice that we can nest our messages in our dictionary, and retrieve deeply nested messages with dot notation. Here, we’ve nested both our title and subtitle messages under app, and we can access them with something like "app.title". This isn’t a requirement, of course, and we can use a flat list of messages under each locale, or mix and match flat and nested messages. Also notice that we’re using the $ shortcut notation that Svelte provides us. The $ tells Svelte to subscribe to the _ store for us, and to unsubscribe when the current component is destroyed. This avoids memory leaks while keeping our component reactive to the store: when either the current locale or dictionary change, our Header component will re-render with updated message values. Refactoring to a Custom i18n Adapter We probably don’t want to leave our setup code in App.svelte, as that can get messy as our app grows. Let’s clean things up and create a little /src/services/i18n.js wrapper module that houses our custom i18n logic. We wrap our initialization logic in a setupI18n function, which we expose along with svelte-i18n’s _() . Our App component can now be a lot cleaner. We can now import our forwarded _() from our custom wrapper whenever we want to display translated messages in our components. All we had to change in our Header component was our import statement. This refactor makes our code more flexible. We can potentially swap another library in place of svelte-i18n in the future. The new code design also allows us to add custom i18n logic without dramatically affecting the rest of our app. A Note on Advanced Locale Detection According to the svelte-i18n documentation, the library provides locale detection through the browser’s window.navigator.language, a URL query param, or the URL hash/anchor. This is provided via a getClientLocale() function. I havent’s used getClientLocale() myself, but you can find out more in the docs. If you do give the library’s locale detection a try, please let us know how that worked out for you in the comments below. Explore why app translation can be key to your global business expansion and follow our best practices. Explore why app translation can be key to your global business expansion and follow our best practices.Check out the guide Dynamic Loading of Translation Files via HTTP We’re currently hard-coding our translation messages in our i18n setup code. While this might be OK for very small projects, we often want to break out our translations into one file per locale. Let’s do that now. First, we’ll move our current messages to files under /public/lang. This allows these files to be served directly by the web server we’re working with. /public/lang/en.json /public/lang/ar.json We’ll have a /public/lang/{locale-code}.json file for each locale our app supports. With those files in place, we can update our setup logic to load them in when needed. ✋🏽 Heads up » When moving our messages to our new files, we need to make sure that we’re always using double quotes around string values, and avoiding trailing commas, to adhere to JSON syntax. We use the standard fetch API to load the message file for the given _locale. We also return the result of the fetch promise chain, itself a promise. This allows calling code to be notified when our i18n setup is complete: the message file has been loaded, its contents placed in the dictionary store, and the current locale is set. Rendering Only After Our Locale Has Loaded If we were to refresh our app in the browser right now, we’d get an error and our app wouldn’t load. This is because our current app logic doesn’t wait for our translation messages to load from the network. Our $_() calls in Header, for example, won’t have any messages to work with on first render. Let’s correct this. We’ll add a helper store, isLocaleLoaded, which will let us know whether translation messages are ready. isLocaleLoaded is just a derived store: whenever the active locale is updated, so is isLocaleLoaded. Before any locale is set, svelte-i18n will give locale an object type. Once it is correctly set, the libray will set locale to the code of the active locale, e.g. "en", a string type. We check for this in our devired store, and make sure that isLocaleLoaded‘s value is true only after i18n initialization is successful. We can now use this derived store in our App component to fix our error. With the new $isLocaleLoaded store state, we show a loading indicator while our message file is coming down the pipe. Once the file is loaded and svelte-i18n has been set up, $isLocaleLoaded becomes true, which causes the app UI to render. Bye bye, error. 🔗 Resource » In case you’re wondering, the $:syntax above makes a statement reactive in Svelte components. These reactive statements can make for very consice code, and pair really well with Svelte stores, so check them out in the Svelte documentation if you haven’t come across them before. Handling Locale Direction: Right-to-Left VS Left-to-Right Currently, when we select Arabic, our layout direction remains left-to-right. Arabic is a right-to-left language, and the UI just looks awkward in that locale now. Let’s fix this by adding another derived store to our i18n library. The dir store’s value is "rtl" if the active locale is Arabic, and "ltr" otherwise. This works fine for our little demo app with two locales. Of course, in a bigger app we would need some more complex logic and perhaps a map of locales to directions. Let’s update our App component to use our new store. We simply react to any changes in $dir, which itself is updated when the underlying active locale is updated, and manually set the direction of the document DOM element. This makes the browser show our app’s page in a right-to-left orientation when we set our locale to Arabic, and left-to-right otherwise. Working with Translation Messages At this point we’ve seen how to work with basic translation messages. We have keyed messages in our translation files that we access via the $_('myMessageId') store function in our components. Let’s take a look at more complex examples of translation messages as we explore interpolation, plurals, and date formatting. Interpolation Under the hood, svelte-i18n uses the FormatJS library collection, which itself uses the ICU message defacto standard. ICU messages use {curly braces} for interpolated values. Let’s update the Footer of our demo to get a taste of ICU interpolation. The current footer is a presentational component that has a simple implementation. The end of all things: our footer While the text of our footer paragraph will change per locale, the URLs of the links within the paragraph won’t. We can pass those URLs to our translated messages as named variables. We use {curly braces} to denote those variables in our translation files. The svelte-i18n $_() function takes a second parameter after the message ID: a map of keyed values to swap into our messages dynamically. So our updated Footer component code can look like this: ✋🏽 Heads up » Note that we’re using the potentially unsafe @htmlmodifier in our Svelte template here. @htmlwill tell Svelte not escape any HTML code before outputting our dynamic values. This works for us here, since we want to output the <a>tags in our translations messages as unescaped HTML. However, we should always make sure that we trust the source of any data we output with @html, since Svelte won’t sanitize the data for potential XSS injection attacks. When passing our map to $_() we just make sure to match the keys in our object map to the keys in our messages. svelte-i18n and its underlying plumbing will take care of the rest. Working with Tags & Style Scope in Our Messages By embedding the <a> tag in our translation messages, we don’t have Svelte applying its component-scoped styles to our link text anymore. This is due to the extra, hashed CSS class that Svelte adds to our component HTML when it renders it, or the lack of it in our case. Our component’s parent footer tag, for example, is rendered to the browser as something like <footer class="footer svelte-vwdjom">. The svelte-{hash} CSS class allows the footer‘s corresponding styles to be scoped to our component, and not leak out to other components, when they’re rendered out to our /public/bundle.css: This often helps us work with styles in a nice, modular way. However, Svelte needs our HTML to be directly in our .svelte files to be able to add its hashed CSS classes to it. When we moved our <a> tags outside to our message .json files, Svelte lost sight of them. We can work around this issue by using the special :global() syntax that Svelte provides. Here’s the updated Footer.svelte code using :global(). The .footer :global(a) selector will scope its style rules to any <a> element under this component’s .footer, whether that <a> is explicitly defined in the component’s template or not. This effectively fixes our styling problem, and returns our link styles to where they were before we moved them to our JSON files. Plurals Right now our movies’ stats are being displayed without regard for plurality. “1 awards” is just wrong, isn’t it? – Also GB won 6 awards and was nominated for 8 Alright let’s correct this by using the ICU plural messages that come with svelte-i18n. We’ll move our relevant messages to our language files while we’re at it. The {key, plural, matches} syntax is standard ICU stuff. If it looks weird to you, check out the FormatJS documentation for a nice, short intro. Also worth noting is that Arabic has more plural forms than English. ICU messages accommodate this and allow us to specify different plural forms/categories for each locale. Now let’s use our new messages in our Movie component. We use the $_() function as normal to access our plural messages. We also pass in a variable that gives svelte-i18n the number it uses to select the appropriate plural form from the ones we defined in our message files. We call this variable n here as a matter of convention. Its name doesn’t matter, however, as long as it matches the name in our plural messages. And that’s our plurals taken care of. Now this adds up: we’re presenting proper plurals Date Formatting We’re currently displaying the release date of each movie as it is in our JSON data. How do we format our dates while respecting locales? We’d like to show the date in a natural way for the active locale. This is easy enough to accomplish with svelte-i18n. Let’s first move our whole “Released 1984-06-08” string to our language files so that we can translate it. Nothing new here. In fact, our updated code won’t handle localized date formatting yet. We can use svelte-i18n’s $_.date() function to localize our date. $_date() requires a Date object as its first parameter, so we convert our released string to a Date before we pass it to the function. An optional second parameter can be "short" | "medium" | "long" and is used to display dates in preset formats. 🔗 Resource » See the svelte-i18n documentation for more info about date formatting, number formatting, and more. Localized dates with very little code While the svelte-i18n options work fine for us if we want predefined short, medium, or long dates, they don’t give us exactly what we want here. We only want to show each movie’s release year, and we want that localized. Unfortunately, at the time of writing this is not possible with svelte-i18n. The infrastructure looks to be there: svelte-i81n is built on top of FormatJS, which itself uses the standard Intl.DateTimeFormat for its date formatting. Intl.DateTimeFormat has extensive options for date formatting. But since svelte-i18n doesn’t expose these options to us, we have to use Intl.DateFormat directly. We can add a little function to our custom i18n library that does what we want. We cache a copy of the active locale in cachedLocale whenever we set the locale in setupI8n. This cachedLocale is used in our custom function, formatDate, which is a simple convenience function that wraps Intl.DateTimeFormat. We can now call formatDate from our Movie component to get exactly the localized formatting we want. The options object we pass to formatDate gets forwarded to the Intl.DateTimeFormat constructor, so we can use any formatting option the standard constructor accepts. By passing { year: 'numeric' } to Intl.DateTimeFormat we tell it to produce date strings that only contain the given date’s four-digit year. Done and dusted. Our dates are custom-formatted to our exact specs A Quick Locale Switcher Let’s round out our app with a locale switcher so that our user can consume our app’s content in the language of their choosing. LocaleSwitcher is a plain old Svelte component that is meant to be controlled by its parent. It wraps an HTML <select> element and exposes its set value and a custom locale-changed event. locale-changed is fired when the user selects an option from the <select> dropdown and the event provides the newly selected value to its listeners. 🔗 Resource » Read more about Svelte’s custom component events in the documentation. We can now wire up our LocaleSwicther in our App root component to allow locale switching. That’s it, really. Now, whenever our user selects a new locale from our switcher we load that locale’s message file and switch svelte-i18n’s locale behind the scenes. This causes our app to re-render with the new locale’s messages. And that about does it for our demo. Here’s what the final form of our app looks like. Our completed demo app in all its glory 🔗 Resource » You can get all the code for the completed demo on Github. Related Articles If you want to go deeper into JavaScript i18n/l10n, check out these juicy reads: - A Step-by-Step Guide to JavaScript Localization - Beginning JavaScript I18n with i18next and Moment.js - The Best JavaScript I18n Libraries - A Human-friendly Way to Display Dates in TypeScript/JavaScript - Roll Your Own JavaScript i18n Library with TypeScript – Part 1 - Roll Your Own JavaScript i18n Library with TypeScript – Part 2 We hope you enjoyed this tumble into localizing Svelte apps with svelte-i18n. Would you like us to provide more content dealing with i18n and Svelte, perhaps some more advanced topics like i18n with Sapper and SSR or other Svelte + i18n topics? Let us know in the comments below. And if you’re looking to scale your localized app, look no further than Phrase for a professional, robust localization platform. Phrase helps you automate your i18n tasks as a developer, and provides a powerful translation UI for your translators. Translations sync to your development environment(s) and work with your app seamlessly. Phrase also provides a flexible API, powerful web console, and many advanced i18n features: OTA translations, branching, machine translations, and more. Take a look at all of Phrase’s features, and sign up for a free 14-day trial.
https://phrase.com/blog/posts/how-to-localize-a-svelte-app-with-svelte-i18n/
CC-MAIN-2020-16
refinedweb
3,593
64.2
With #5361 ready for review, this page provides a basic rundown of what changed, in case the code doesn't easily expose all the improvements. New features - All file handling is now done through storage classes, which handle basic interactions with an underlying storage system. Django will ship with just one, which deals with the filesystem just like everything works now, but users can create whatever other backends they like. Examples could be storing files on S3 (a common request), customizing file naming behavior, encrypting/decrypting files transparently, etc. The docs on the ticket do a good job of explaining how to use them, so I won't bore you with that here. The default storage system is FileSystemStorage, and is specified by the new DEFAULT_FILE_STORAGEsetting. FileFieldnow provides a FieldFileobject instead just a filename, so that file operations can take place on it directly. This was needed on one hand to move people away from the open(instance.get_avatar_filename()), since that won't work once other backends enter the picture. Instead, instance.avatarcan be used as a file-like object directly. Also, it has path, sizeand urlproperties instead of get_foo_*. - The open()method of storage objects also accepts a mixinargument, which allows the returned Fileto have overrides and extra methods for specific file types. FileSystemBackendwon't allow access to any file that's not beneath the path it was instantiated with. This is primarily useful for security, but also as a deterrent against accidentally putting a leading slash in upload_to. - Speaking of upload_to, it now accepts a callable as well as a string. If a callable is provided, it's called with the model instance and the filename, so user code has much greater control over how files are named. - The current default storage system will always be available, both as a class and as an object, from django.core.files.storage. The class is DefaultStorageand the instance of it is default_storage. This way, subclasses can override just some behavior, such as file naming, without worrying about how the files are really being stored, or views can save/retrieve files manually, with the same flexibility. FileFieldalso accepts a storageargument, where a custom storage object can be passed in, to be used as an override of DEFAULT_FILE_STORAGE. Differences from previous patches django.core.filestoragefrom older patches is gone, and everything has been moved into django.core.files, in keeping with the trend set by [7814]. The basic File object is at django.core.files.base, while all storage-related classes and functions are at django.core.files.storage. This means that, by default, all new storage systems would start as third-party apps, since there's no longer a "dedicated" place for them. - There's now a single base django.core.files.base.Fileclass for all file types, regardless of whether they come from a storage system, an upload, or whatever. This means, for instance, that all storage-related operations are now capable of chunking, while all uploaded files also have __nonzero__based on file.name. Both UploadedFileand FieldFilehave customizations on top of it though, so it's not like Fileis built to be all things to all people. - Other image-related functionality has also been moved to django.utils.images, in the form of ImageFile, a mixin that provides width and height options. - The API for getting meta-information about a file (such as its size, filesystem path, URL, width and height) has changed from methods to read-only properties. Those that would have to access the content (size, width and height) cache the results so they don't have to do so more than necessary. Backwards-incompatibile changes I've tried very hard to maintain backwards-compatibility wherever reasonable, but there are still a few places where API improvements merit some changes. In addition, there's one (hopefully) rare case where backwards-compatbility is impossible to retain. Deprecated get_FOO_* methods Most of the Model._get_FIELD_* methods have been deprecated, pointing to the appropriate attributes on the new FieldFile instance. Given a model like this: class FileContent(models.Model): content = models.FileField(upload_to='content') Here's how the changes map out: FileField and ImageField have moved Because of all the new code in an already-crowded django.db.models.fields, FileField and ImageField have been moved into their own module: django.db.models.fields.files. They're still imported directly into django.db.models, so the vast majority of existing code will continue to work without modification, but if anyone's importing them directly, they'll need to update the import path. django.utils.images has moved The new location is django.core.files.images, where it's far more appropriate. An import and a DeprecationWarning have been left at the old location. Use File to save raw content Passing raw file content as strings to save() has been deprecated, in favor of using a File subclass. In addition to a DeprecationWarning and an automatic conversion, there's now a django.core.files.base.ContentFile, which is a simpler class than SimpleUploadedFile, as it doesn't deal with content-type, charset or even a filename. It's basically just a light wrapper around StringIO that adds chunking behavior, since most of the internals expect to be able to use that. Empty FileField values are no longer None FileField will always provide an object to model instances, regardless of whether there's actually a file associated with it, which is necessary for the instance.content.save() behavior. Previously, if there was no file attached, instance.content would be None, which is no longer true, so the following will no longer work: if instance.content is not None: # Process the file's content here. Instead, File objects evaluate to True or False on their own, so the following is functionally identical: if instance.content: # Process the file's content here. FileField can't be unique, primary_key or core The exact behavior of these with a FileField was undefined, and was causing problems in many cases, so they now raise a TypeError if supplied. Tickets involved There are a number of tickets marked fs-rf, indicating that they're impacted by this patch. First, the issues that are truly fixed, and can be marked as fixed in the commit: - #5361 - The main file storage ticket, where the patch itself resides. - #3621 - If upload_tostarts with a slash, FileSystemStorage's increased security will now raise a SuspiciousOperationwhen saving a file, long before it hits the database. - #5655 - The supplied patch was adapted and included, resolving the issue. Tests have been included to verify this. - #7415 - Saved files are now always stored in the database using forward slashes, and retrieving using os.path.normpath() And there are also a few that will be made possible, but not provided in core directly (probably mark as wontfix): - #2983 - Since saving and deleting behavior has been moved into FileFieldinstead of Model, a subclass can provide this behavior. If not that way, a custom storage object can do the rest, passing it into the FileFieldas its storageargument. - #4339 - By providing a custom storage class, it's easy to change this type of file naming behavior. The patch's tests include a Trac-style example, using numbers instead of underscores. - #4948 - If this is even still an issue (see this comment), more fine-grained locking can be provided by a custom storage class. - #5485 - Like #4339 above, custom file naming across the board is easy with a custom storage class. - #5966 - Custom storage can create or delete directories however is necessary for a given environment. - #6390 - Custom backends will be quite possible, but are best suited as third-party apps. And a couple where the problem was resolved by removing the feature that was causing problems (I'm not sure if these should be fixed or wontfix):
https://code.djangoproject.com/wiki/FileStorageRefactor?version=4
CC-MAIN-2017-09
refinedweb
1,305
54.73
Implementing the Actual Watcher At this point, we're able to configure a watcher, but it won't do anything useful because the implementation of that class is still open on the to-do list. This class is really the meat of this DSL; everything else around it is to enable the syntax, but without the implementation, it's just another way of building hashes of a certain structure. We left off at the builder initializing the watcher class. All this does is move the data structures from the builder into the watcher implementation. This watcher has a public interface but most of its work is implemented in private methods. Again, the behavior of the Watcher implementation has been captured in a minimal amount of specs as shown in Listing 5. In addition to the syntax, this Watcher class also has the ability to be started, to be stopped, and to handle registered events. Watcher # Syntax specs removed for brevity handling events - should handle events without guards - should handle events with passing guards - should not raise events with failing guards - should trigger events with passing guards - should not trigger events with failing guards engine - should start the watcher - should stop the watcher - should dispose the watcher Because the FileSystemWatcher uses unmanaged resources, it is probably a good idea to wait with creating that instance to the last possible moment. This also gives us the opportunity to manipulate the configuration before we actually start the watcher. There are two main jobs for the watcher class: the first job is to handle the events when they pass the guards and the second main job is to start/stop/dispose the FileSystemWatcher. Let's start with handling events and work our way up from there. This handle method is about the most complex method from this article; the code for this method is shown in Listing 6. def handle(action, args) @handled ||= {} path = args_path(action, args) #1 hand = @handlers[action.to_sym] #2 hand.each_pair do |filter, handlers| handlers.each do |h| if not handled?(h, path) #4 h.call(args) #5 @handled[path] ||= [] @handled[path] << h #6 end end if passes_guard?(filter, path) #3 end nil end private def passes_guard?(guard, path) return true if guard == :default guard.to_watcher_guard.match(path.gsub(/\\/, "/")) #7 end def handled?(handler, path) (@handled[path]||[]).include?(handler) end def args_path(action, args) (action == :rename ? args.old_full_path : args.full_path) end #1 Getting the path for the trigger #2 Getting the handler registrations #3 Checking guards #4 Skipping already handled handlers #5 Handling the event #6 Registering event as handled #7 Calling monkey patched method As you can see in the listing, the handle method actually does a bunch of things. The first notable item is the call to args_path (#1), which will return the path that originally triggered the event because a rename has different event arguments as the rest of the events. Then, we grab the registered handlers for this action (#2). They are the direct result of the configuration we did earlier with the builder. After getting the registered handlers, we iterate over them so we can try calling the handlers. The first thing we do in the loop is work out if this particular handler passes the guards for this path (#3). If this handler passes the guards, we're going to check if this instance has already been handled (#4). When this last check also succeeds, we can finally call the handler (#5) and register this handler as one of the handled events (#6). We did glance over the private methods that have been defined in the code listing. There is one thing there I'd like to draw your attention to. In the passes_guard? method, there is a call to the method to_watcher_guard (#7). The code for that method is shown in Listing 7 and the method is supposed to take care of converting glob-like patterns (spec/**/*.rb?) to regular expressions so they can be used as watcher guards. class String alias :old_gsub :gsub def gsub(pattern, replacement=nil, &b) if pattern.is_a? Hash #1 pattern.inject(self.dup) { |memo, k| memo.old_gsub(k.first, k.last) } else self.old_gsub(pattern, replacement, &b) end end def to_watcher_guard re_str = self.gsub /(\/)/ => '\/', #2 /\./ => '\.', /\?/ => '.?', /\*/ => ".*", /\.\*\.\*\\\// => "(.*\\/)?" /#{re_str}/ end end class Regexp def to_watcher_guard self end end #1 Augmenting behavior of gsub #2 Very basic glob pattern parser We want to augment the behavior of the String class so we're going to take advantage of the fact that classes are open in Ruby. I want to get to the point that I can provide a hash of gsub replacement instructions so that I can avoid writing something like my_string.gsub(/a/, '1').gsub(/b/, '2')…gsub(/z/, '26'). To do that, I first created an alias for the gsub method with the name old_gsub. This allows me to create a new gsub method and call that aliased method to get the old behavior back. Our gsub method checks if the first parameter is a hash (#1) and, if it is, it iterates the pairs and execute the old gsub method passing the result to the next iteration. We've also got a second method called to_watcher_guard defined on both the String and the Regexp class. People can define guards as either a glob pattern or a regular expression. And the passes_guard? method from Listing 6 calls this to_watcher_guard #2 method on the registered guards for a particular event. This method takes care of converting a string value to a regular expression by: - Normalizing \ paths to / paths - Escaping '.' characters - Replacing the single character wildcard '?' with a regular expression for an optional character '.?' - Replacing the multicharacter wildcard * with a regular expression for optional multiple characters '.*' - Replacing the recurse in subdirectories wildcard ** with a regular expression for optional folders So far, our DSL execution engine checks the guards on the individual handlers, but we also have to get in front of those and check global guards first. The code for that functionality is shown in Listing 8. def trigger(action, args) @handled = {} return nil unless guards_pass_for action, args #A handle action, args end private def guards_pass_for(action, args) return true if filters.empty? filters.all? { |g| passes_guard?(g, args_path(action, args)) } end #A Checking global guards There isn't that much interesting happening in Listing 8. We check the guards by iterating over the filters collection and, if they pass, we invoke the handle method from Listing 6. This brings us to the last chunk of functionality that's open for discussion: starting and stopping the watcher. Listing 9 holds the last bit of code to complete the watcher implementation. ACTION_MAP = { #1 :changed => :change, :created => :create, :deleted => :delete, :renamed => :rename, :error => :error } def start @watcher ||= init_watcher unless @watcher.enable_raising_events @watcher.enable_raising_events = true end end def stop if @watcher and @watcher.enable_raising_events @watcher.enable_raising_events = false #4 end end def dispose self.stop @watcher.dispose if @watcher #5 @watcher = nil end private def init_watcher watcher = System::IO::FileSystemWatcher.new @path #2 watcher.include_subdirectories = @subdirs setup_internal_handlers watcher @watcher = watcher end def setup_internal_handlers(watcher) ACTION_MAP.each_pair do |event, action| #3 nothing_registered = (@handlers[action]||{}).empty? unless nothing_registered watcher.send("#{event}") { |_, args| trigger action, args } end end end #1 Defining action name map #2 Creating FileSystemWatcher object #3 Setting up handlers on the watcher #4 Stopping the FileSystemWatcher #5 Disposing the FileSystemWatcher This code first defines a constant value that holds a Hash of the .NET event name and the action name we create when the user of the DSL defines an event handler (#1). The start method first sets up an instance of the CLR object System.IO.FileSystemWatcher (#2) and then configures this instance with the include subdirectories value we get from the DSL. Next, it sets up the configured event handlers. So, if there is a handler defined for create, it will attach a block to the Created event on the FileSystemWatcher instance (#3). This event handler invokes the trigger method, which we discussed in Listing 8. The start method then sets the enabling_raising_events property to rue, which starts the watcher. The stop method doesn't do anything else except set the enable_raising_events property to False (#4). The dispose method takes care of cleaning up the resources for the watcher. It first stops the FileSystemWatcher instance, then we dispose the FileSystemWatcher instance (#5) and set its instance variable to nil so it's hopefully completely gone.
http://www.drdobbs.com/web-development/sweetening-the-plain-vanilla-net-filesys/225200551?pgno=3
CC-MAIN-2015-18
refinedweb
1,403
63.59
Use Visual C# to improve string concatenation performance This article provides information about how to improve string concatenation performance in Visual C#. Original product version: Visual C# Original KB number: 306822 Summary This article shows the benefits of using the StringBuilder class over traditional concatenation techniques. Strings in the Microsoft .NET Framework are invariant (that is, the referenced text is read-only after the initial allocation). It provides many performance benefits and poses some challenges to the developer who is accustomed to C/C++ string manipulation techniques. This article refers to the .NET Framework Class Library namespace System.Text. Description of strings in the .NET Framework One technique to improve string concatenation over strcat() in Visual C/C++ is to allocate a large character array as a buffer and copy string data into the buffer. In the .NET Framework, a string is immutable, it can't be modified in place. The C# + concatenation operator builds a new string and causes reduced performance when it concatenates large amounts of text. However, the .NET Framework includes a StringBuilder class that is optimized for string concatenation. It provides the same benefits as using a character array in C/C++, and automatically growing the buffer size (if needed) and tracking the length for you. The sample application in this article demonstrates the use of the StringBuilder class and compares the performance to concatenation. Build and run a demonstration application Start Visual Studio, and then create a new Visual C# Console application. The following code uses the +=concatenation operators and the StringBuilderclass to time 5,000 concatenations of 30 characters each. Add this code to the main procedure. const int sLen=30, Loops=5000; DateTime sTime, eTime; int i; string sSource = new String('X', sLen); string sDest = ""; // Time string concatenation. sTime = DateTime.Now; for(i=0;i<Loops;i++) sDest += sSource; eTime = DateTime.Now; Console.WriteLine("Concatenation took " + (eTime - sTime).TotalSeconds + " seconds."); // Time StringBuilder. sTime = DateTime.Now; System.Text.StringBuilder sb = new System.Text.StringBuilder((int)(sLen * Loops * 1.1)); for(i=0;i<Loops;i++) sb.Append(sSource); sDest = sb.ToString(); eTime = DateTime.Now; Console.WriteLine("String Builder took " + (eTime - sTime).TotalSeconds + " seconds."); // Make the console window stay open // so that you can see the results when running from the IDE. Console.WriteLine(); Console.Write("Press Enter to finish ... "); Console.Read(); Save the application. Press F5 to compile and then run the application. The console windows should display output similar to the examples: Concatenation took 6.208928 seconds. String Builder took 0 seconds. Press ENTER to finish... Press ENTER to stop running the application and to close the console window. Troubleshooting If you are in an environment that supports streaming the data, such as in an ASPX Web Form or your application is writing the data to disk, consider avoiding the buffer overhead of concatenation or the StringBuilder, and write the data directly to the stream through the Response.Writemethod or the appropriate method for the stream in question. Try to reuse the existing StringBuilder classrather than reallocate each time you need one. Which limits the growth of the heap and reduces garbage collection. In either case, using the StringBuilderclass makes more efficient use of the heap than using the +operator. References The StringBuilder class contains many other methods for in-place string manipulation that aren't described in this article. For more information, search for StringBuilder in the Online Help.
https://docs.microsoft.com/en-US/troubleshoot/dotnet/csharp/string-concatenation
CC-MAIN-2021-31
refinedweb
567
50.12
16 October 2012 By clicking Submit, you accept the Adobe Terms of Use. A good understanding of jQuery, general knowledge of JavaScript, and some knowledge of PhoneGap will help you make the most of this article. Required Adobe products PhoneGap (Cordova) Kendo UI Mobile Intermediate Unless you have been living under a rock or hunkered down in an underground bunker like Brendan Fraser in Blast From The Past, you have probably heard of PhoneGap. It's that magic thing that enables you to write mobile applications the same way that you would build a web application. However, there is still a gap (no pun intended, I swear) here. While PhoneGap might make it easy for you to create an application that runs on a mobile device, how do you make it look like a mobile application? In this tutorial you will see how Kendo UI Mobile, a brand new framework for building HTML5 native applications, can help you do just that. It works great with PhoneGap and it gives you the native looking controls you need, like TabStrips, ListViews, NavBars, and so much more. Additionally, you will learn how to use PhoneGap Build along with Kendo UI Mobile's unique Adaptive Rendering Framework to write your application one time, and deploy it on multiple platforms. Kendo UI Mobile is the hot new HTML5 mobile framework that enables you to build phone and tablet applications that actually look like they are using native UI controls. You can download a fully functional trial of Kendo UI Mobile that even comes with support. Please note, your name and email address are required to obtain the trial download. The mobile framework contains a complete collection of feature rich widgets that are targeted at both phone and tablet form factors. You can browse the demos and see familiar mobile UI controls like the TabStrip, the NavBar, and even the ubiquitous iPad SplitView. You can think of Kendo UI Mobile of being made up of two pieces: the framework and the widgets. The mobile framework includes core functionality of Kendo UI Mobile (see Figure 1). This includes the core Application object that is created when you create an application with Kendo UI Mobile, as well as things like Views, which contain the rendered content between the header and footer of the application. The widgets are the UI components that you would expect to find in a mobile application (see Figure 2). Because mobile devices have touch interfaces, the UI components are very different than what you would find in a normal web application. Widgets include the TabStrip and the ListView. The ListView features kinetic scrolling, pull to refresh, and everything that you have come to expect from a quality mobile application. Adaptive rendering Kendo UI Mobile will automatically adjust the UI to the current device's native look and feel (see Figure 3). The same application will look different on iOS and Android. On iOS, for example, the TabStrip is at the bottom where you would expect it to be, while on Android it's moved to the top. Currently Kendo UI Mobile supports iOS, Android, BlackBerry, and Meego (see Figure 4). Note: Looking for Windows Phone support? See this article for why it's missing from our list of supported platforms. PhoneGap Build is a project that is currently in Beta. Once you upload an application's source to it, PhoneGap Build can build the application for every supported PhoneGap platform and then give you a link or QR code to download the application. You can upload your application to PhoneGap as a single index.html page or as a ZIP file containing your project assets. Alternatively, you can have PhoneGap Build pull your code from an existing Git repository, or have it create a new one for you. Note: To build for iOS, you will need to register your device with the iOS Developer Center and upload your corresponding certificate so that you can deploy your app straight to the device without having to go through Xcode. Check out this article for more information on setting that up. You will need to create an account at build.phonegap.com. You can use your Adobe account, or you can login with your GitHub account. Once you sign in, you will be prompted to create an application by providing a name and specifying if you want to upload the source or use Git (see Figure 5). You can even use GitHub and pull from there. I named the new application Reddits. You can use any name for your application. For this tutorial, I strongly recommend pushing the code to a GitHub repository and then pulling it in for PhoneGap Build. If you do, select the Pull From A Git/Svn Repo Url option and type your existing GitHub repository URL. I prefer this approach, as having to zip up an application over and over and upload it over and over to refresh it is tedious. You will need some specific files to get started with PhoneGap Build, so I have created a bootstrap project that you can download here. The Kendo UI Mobile bootstrap project contains all of the files that you need to get rolling with a new Kendo UI Mobile application using PhoneGap Build (see Figure 6). Specifically, it includes the following files: Kendo UI Mobile framework is easy to use, relying mostly on the HTML markup to define the application. Using HTML5 data attributes, you specify the structure of your application in the HTML, so you need to write only a minimal amount of JavaScript. This enables you to layout your mobile application with markup instead of trying to do it all with convoluted JavaScript code consisting of a thousand selectors. You will need to include the kendo.mobile.all.min.css file in your page. This file has all the styles in it for the different mobile devices. You will also need to include jQuery, and the kendo.mobile.min.js file: <link rel="stylesheet" href=""> <script src="assets/js/jquery.min.js"></script> <script src=""></script> In the bootstrap project I have included a basic Kendo UI Mobile Layout (see Figure 7). Kendo UI Mobile applications generally include two main components, Layouts and Views. Your application may consist of any number of these components in virtually any combination. However, it is most common to have a single Layout that has multiple Views. Open index.html to see how a Kendo UI Mobile application is structured. A Kendo UI Mobile Layout is a shared container for multiple views. It usually has a NavBar widget as well as a TabStrip widget, but this depends on how you want to design your application. The Layout in the bootstrap application has the following markup: <div data- <div data- <div data- <span data-</span> </div> </div> <div data- <div data- <a data-Home</a> <a data-Settings</a> </div> </div> </div> The top level div has a data-role of layout. This tells Kendo UI Mobile that this is a Layout container. It's also possible to create Kendo UI Mobile controls from HTML elements by selecting them with a jQuery selector and then calling the appropriate widget. For instance, for a ListView you might use the following: $(“#itemsList”).kendoMobileListView(); However, it is far more common and cleaner to specify the widget you want to use with the data-role attribute and configure the widget using additional data attributes. Within the top level layout element, there are two div elements, one with data-role="header" and the other with data-role="footer". You will want to define headers and footers for your layout before you start using widgets like the NavBar or TabStrip. This will let Kendo UI Mobile know where you want to position them in the application. Inside the header element there is a NavBar widget. It, in turn, has a simple span with data-role="view-title". This will display the title of the currently loaded view in the NavBar. This way when you switch views (via a TabStrip for example), the current view title will be displayed. The footer contains the popular TabStrip. It's declared by using a div and setting data-role="tabstrip". Each TabStrip item can have an icon by setting the data-icon property. For a complete list of icons that you can use, check out the TabStrip documentation. Each TabStrip button is pointed at a corresponding View with its href set to a # plus the View id. As previously mentioned, Views represent the content inside of Layout. Technically, they don't have to be in a Layout, but they commonly reside there. While it may seem logical that they would be placed inside of their Layout div, this is not the case. They are placed on the same level as the Layout div. <div data- <p>Home View</p> </div> <div data- <p>Settings View</p> </div> By now you have caught on to the use of data attributes for configuration. In the case of views, they are used to define which Layout the view should use (if any) and the title that should be displayed in the NavBar when the view is loaded. If you want to preview the application in your browser, simply open your browser's developer tools and type MYAPP.run(); in the console. This function is called by the PhoneGap deviceready event when your application is running natively. Now that you have the bootstrap project and you understand how to lay out elements with Kendo UI Mobile, you are ready to build a simple application and then upload it to PhoneGap Build. This simple application will use the home screen of the bootstrap and add the hot programming topics from Reddit. To do this you will need to add a ListView to the application as well as use a DataSource. Add a ul element to the home view and set its data-role to listview. This will specify that it is a Kendo UI Mobile ListView. The ListView can either take up the whole screen, or it can be inset. For this example, set the ListView style to inset using the data-style attribute. <ul data-</ul> ListViews can have static items or they can be bound to a source of data (either remote or local data). For this example, you are going to bind the ListView to the Reddit remote JSON API. Add the following code to app.js // this function returns a Kendo UI DataSource // which reads the top threads off of the programming.reddit // datasource MYAPP.reddit = kendo.data.DataSource.create({ // set the data to a local array of object transport: { read: "" }, schema: { data: "data.children", fields: { title: "data.title" } } }); This is a Kendo UI DataSource. It reads the remote endpoint (using a jQuery .ajax call under the covers) and then parses the returned result according to the specified schema object. Now that the DataSource has been defined, you will need to specify it on your ListView. Note: You may be wondering why I've given the DataSource a rather odd variable name ( MYAPP.reddit ). In JavaScript you want to put all your variables in a single object, which will then go into the global namespace. This keeps you from cluttering the global namespace with a bunch of custom variables that could step all over each other. The data attribute for defining a data source on a ListView is straightforward: data-source="MYAPP.reddit". Now, the only thing left is to define a template for the ListView. Kendo UI Mobile Templates are lightweight and engineered to be exceptionally fast. You can declare a template by creating a script block and giving it a type of "text/x-kendo-templ" and an ID so you can specify the template in the ListView. Kendo UI Mobile templates support several syntaxes. The example below uses is the "#: <value> #" format, where <value> is the field from the DataSource that you want displayed. <script type="text/x-kendo-templ" id="reddit-template"> #: title # </script> Add this to index.html. This will display the title field in li elements inside the ListView. Notice that you don't need to wrap each element in an li. To inform the ListView that you want it to use this template when it renders items, set the data-template attribute: <ul data-</ul> If you didn't create a project in PhoneGap Build earlier, now is the time. Before you can actually upload your file, or pull it from Git, you need to modify the config.xml file. This file tells PhoneGap Build some very important information. For example, here is mine. <?xml version="1.0" encoding="UTF-8"?> <widget xmlns = xmlns: <name>Reddits</name> <description> A super simple application for testing Phonegap Build With Kendo UI Mobile </description> <author href="" email="burkeholland@gmail.com"> Burke Holland </author> <icon src="icon.png" gap: <feature name=""/> <preference name="orientation" value="portrait" /> </widget> This specifies the title of the application, the description, the version of PhoneGap you are using, and the permissions the application is going to need. For instance, if you were going to use the camera, you would need to specify an additional feature. <feature name=""/> Once you upload or specify your Git repository to pull from, PhoneGap Build will begin building your project for all platforms (for iOS you need to upload your certificate and provisioning profile file). My build process completed in around 10 minutes. As each build process finishes you are presented with a download button and a QR code (see Figure 8). You might notice that there is a script reference for a phonegap.js file that doesn't exist in the project. <script src="phonegap.js" type="text/javascript" charset="utf-8"></script> This is because PhoneGap Build provides that file for you to make sure it's specific for the platform that is being built. You can change the version of PhoneGap that you want to target at any time by going to the PhoneGap Build admin panel and updating the version. You can scan the QR codes you receive with your devices or you can navigate to build.phonegap.com on your device and tap the Download button. This will install the application on your device. I installed the application from PhoneGap Build on my iPhone 4 and Galaxy Nexus. The same app runs on two different devices (see Figure 9). Now you should be able to put all of the pieces together. PhoneGap gives you a native shell and device access. PhoneGap Build packages your application for every platform. Kendo UI Mobile gives you native UI controls on every device with the familiarity of jQuery and a simple markup-driven architecture. Download Kendo UI today and get started building native mobile apps with HTML5. Continue your learning on Kendo UI Mobile by checking out the mobile demos. Also make sure to visit our comprehensive documentation site and explore the API, widgets, and various tutorial articles. Here are some links to help you keep going:
https://www.adobe.com/devnet/phonegap/articles/getting-started-kendo-ui-mobile-phonegap-build.html
CC-MAIN-2016-30
refinedweb
2,513
62.98
ATTR(1) XFS Compatibility API ATTR(1) attr - extended attributes on XFS filesystem objects attr [ -LRSq ] -s attrname [ -V attrvalue ] pathname attr [ -LRSq ] -g attrname pathname attr [ -LRSq ] -r attrname pathname attr [ -LRSq ] -l -g attrname option tells attr to search the named object and print (to stdout) the value associated with that attribute name. With the -q flag, stdout will be exactly and only the value of the attribute, suitable for storage directly into a file or processing via a piped command. LIST The -l option tells attr to list the names of all the attributes that are associated with the object, and the number of bytes in the value of each of those attributes. With the -q flag, stdout will be a simple list of only the attribute names, one per line, suitable for input into a script. REMOVE The -r attrname option tells attr to remove an attribute with the given name from the object if the attribute exists. There is no output on successful completion. SET/CREATE The -s attrname option tells attr to set the named attribute of the object to the value read from stdin. stdin will not be read. With the -q flag, stdout. The -S option is similar, except it specifies use of the security attribute namespace. When the -q.), setfattr(1), attr_get(3), attr_set(3), attr_multi(3), attr_remove(3), attr(5), xfsdump(8) ATTR(1) Pages that refer to this page: attr_get(3), attr_getf(3), attr_list(3), attr_listf(3), attr_multi(3), attr_multif(3), attr_remove(3), attr_removef(3), attr_set(3), attr_setf(3), xattr(7), mount(8), xfsdump(8)
https://man7.org/linux/man-pages/man1/attr.1.html
CC-MAIN-2020-40
refinedweb
266
50.97
On Mon, Jul 22, 2013 at 05:56:43AM -0700, Kyle J. McKay wrote: > In order to perform sane URL matching for http.<url>.* options, > http.c normalizes URLs before performing matches. > > A new test-url-normalize test program is introduced along with > a new t5200-url-normalize.sh script to run the tests. Advertising While looking at test-url-normalize (and wanting to experiment some with your series to see how it handled a few behaviors), I wondered if we shouldn't be exposing this selection process to the user somehow via git-config. That is, would a shell script ever want to say "what is the value of this config variable for url $X"? Certainly our test scripts want to, and having a test-* program covers that, but might user scripts want to do the same? Or even to introduce its own URL-matched config options? How hard would it be to convert the "-c" option of test-url-normalize into something like: git config --file=foo --url http noepsv $URL which would look for http.$URL.noepsv matches. If we want to go that route, we don't have to do it now (the test-* interface is unpublished, and the git-config interface can simply come later than the internal feature). But it may be worth thinking about now while it is in your head. > diff --git a/test-url-normalize.c b/test-url-normalize.c > new file mode 100644 > index 0000000..f18bd88 > --- /dev/null > +++ b/test-url-normalize.c > [...] > + if (!strcmp("sslverify", opt_lc.buf)) > + printf("%s\n", curl_ssl_verify ? "true" : "false"); > + else if (!strcmp("sslcert", opt_lc.buf)) > + printf("%s\n", ssl_cert); > +#if LIBCURL_VERSION_NUM >= 0x070903 > + else if (!strcmp("sslkey", opt_lc.buf)) > + printf("%s\n", ssl_key); > +#endif > +#if LIBCURL_VERSION_NUM >= 0x070908 > + else if (!strcmp("sslcapath", opt_lc.buf)) > + printf("%s\n", ssl_capath); > +#endif > [...] Do we need to have the complete list of options here, including curl version limitations? It seems like this will eventually get out of date with the list of options. Would it be sufficient to test just one (or even just handle a fake "http.$URL.foo" variable)? > +#define url_normalize(u) http_options_url_normalize(u) Does this macro do anything besides shorten the name? Is the extra level of indirection to the reader worth it? -Peff -- To unsubscribe from this list: send the line "unsubscribe git" in the body of a message to majord...@vger.kernel.org More majordomo info at
https://www.mail-archive.com/git@vger.kernel.org/msg32824.html
CC-MAIN-2016-50
refinedweb
402
67.04
- Find Largest of Three Numbers This article is created to cover multiple programs in Java that find and prints the largest of three numbers, entered by user at run-time of the program. Here are the list of programs covered by this article: - Find largest of three numbers using if ... else - Find largest of three numbers using nested if ... else - Find largest of three numbers using conditional operator (?:) Find Largest of Three Numbers using if else The question is, write a Java program to find the largest of three given numbers. The program given below is its answer: import java.util.Scanner; public class CodesCracker { public static void main(String[] args) { int a, b, c, large; Scanner scan = new Scanner(System.in); System.out.print("Enter the First Number: "); a = scan.nextInt(); System.out.print("Enter the Second Number: "); b = scan.nextInt(); System.out.print("Enter the Third Number: "); c = scan.nextInt(); if(a>b && a>c) large = a; else if(b>a && b>c) large = b; else large = c; System.out.println("\nLargest = " +large); } } The snapshot given below shows the sample run of above program, with user input 1, 2, and 3 as first, second, and third number to find and print the largest among these three numbers: Here is another sample run with user input 1, 3, and 2 as three numbers: Find Largest of Three Numbers using Nested if else This program is created by implementing the actual logic behind finding the largest number among three given numbers, using nested if...else import java.util.Scanner; public class CodesCracker { public static void main(String[] args) { int a, b, c, large; Scanner scan = new Scanner(System.in); System.out.print("Enter Three Numbers: "); a = scan.nextInt(); b = scan.nextInt(); c = scan.nextInt(); if(a>b) { if(b>c) large = a; else { if(c>a) large = c; else large = a; } } else { if(b>c) large = b; else large = c; } System.out.println("\nLargest = " +large); } } Here is its sample run with user input 20, 10, and 30 as three numbers: Find Largest of Three Numbers using Conditional Operator This is the last program of this article, created using conditional operator or ternary operator, that is ?:. I've used the previous program, to wrap the if...else into conditional operator: import java.util.Scanner; public class CodesCracker { public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.print("Enter Three Numbers: "); int a = scan.nextInt(); int b = scan.nextInt(); int c = scan.nextInt(); int large = (a>b) ? ((b>c)?a:(c>a)?c:a) : (b>c)?b:c; System.out.println("\nLargest = " +large); } } In the following statement, from above program: int large = (a>b) ? ((b>c)?a:(c>a)?c:a) : (b>c)?b:c; First the code (condition) a>b gets evaluated. If this code evaluates to be True, then the following code: ((b>c)?a:(c>a)?c:a) will get evaluated, otherwise the following code: (b>c)?b:c will get evaluated. Let's suppose the condition a>b evaluates to be True. Therefore, the following code: ((b>c)?a:(c>a)?c:a) will get evaluated in a way that the condition b>c gets evaluated. If this condition evaluates to be True, then a gets evaluated, otherwise: (c>a)?c:a) gets evaluated. This process continues until the whole expression lefts a single variable i.e., a, b, or c. Let's demonstrates the statement using the example given below. How the Largest of Three Numbers gets Calculated using Conditional Operator For example, if a=20, b=10, and c=30. Then the statement: int large = (a>b) ? ((b>c)?a:(c>a)?c:a) : (b>c)?b:c; gets evaluated as, first the code a>b or 20>10 evaluates to be True, therefore the code ((b>c)?a:(c>a)?c:a) gets evaluated. That is, the code (b>c) or (10>30) evaluates to be False, therefore the code (c>a)?c:a gets evaluated. That is, the code c>a or 30>20 evaluates to be True, therefore the code c gets evaluated. That is, no more code to execute, as the final variable is c, therefore the value of c, that is 30 will get initialized to large. That's it. Same Program in Other Languages - C Find Largest of three Numbers - C++ Find Largest of three Numbers - Python Find Largest of three Numbers « Previous Program Next Program »
https://codescracker.com/java/program/java-program-find-largest-of-three-numbers.htm
CC-MAIN-2022-21
refinedweb
741
58.79
Pretty sure this is a basic question, however I was not able to find a solution so far. After removing some columns, I ended up with rows that have an empty value in each column (tooltip shows "null"), which I want to remove now. I tried the following processor ("filter rows/cells on value"): However, the empty rows are not removed. A counter-check with "Action: Only keep matching rows" removes all rows. The "Remove rows where cell is empty-processor" in combination with selecting "all" columns removes each row with at least one empty column (which is not what I want) as described in. Am I missing something? Thanks! Hello, In the meantime, you can use the following trick: 1. Add a Python function step in "cell" mode to output an "all_empty" column, with the following code def process(row): all_empty = all( [str(v).strip() == '' or v is None for k,v in row.items() if k != 'all_empty'] ) return(all_empty) 2. Add a filter on value step to remove the rows where the "all_empty" indicator column is True Hope it helps, Alex ©Dataiku 2012-2018 - Privacy Policy
https://answers.dataiku.com/5031/how-to-remove-rows-with-all-emptly-values-across-all-columns?show=5033
CC-MAIN-2019-39
refinedweb
188
64.91
import "github.com/mholt/caddy" Package caddy implements the Caddy server manager. To use this package: 1. Set the AppName and AppVersion variables. 2. Call LoadCaddyfile() to get the Caddyfile. Pass in the name of the server type (like "http"). Make sure the server type's package is imported (import _ "github.com/mholt/caddy/caddyhttp"). 3. Call caddy.Start() to start Caddy. You get back an Instance, on which you can call Restart() to restart it or Stop() to stop it. You should call Wait() on your instance to wait for all servers to quit before your process exits. assets.go caddy.go commands.go controller.go plugins.go rlimit_posix.go sigtrap.go sigtrap_posix.go upgrade.go" ) AssetsPath returns the path to the folder where the application may store data. If CADDYPATH env variable is set, that value is used. Otherwise, the path is the result of evaluating "$HOME/.caddy". DescribePlugins returns a string describing the registered plugins. EmitEvent executes the different hooks passing the EventType as an argument. This is a blocking function. Hook developers should use 'go' keyword if they don't want to block Caddy. HasListenerWithAddress returns whether this package is tracking a server using a listener with the address addr. IsInternal returns true if the IP of addr belongs to a private network IP range. addr must only be an IP or an IP:port combination. Loopback addresses are considered false. IsLoopback returns true if the hostname of addr looks explicitly like a common local hostname. addr must only be a host or a host:port combination. IsUpgrade returns true if this process is part of an upgrade where a parent caddy process spawned this one to upgrade the binary. RegisterCaddyfileLoader registers loader named name. RegisterEventHook plugs in hook. All the hooks should register themselves and they must have a name. func RegisterParsingCallback(serverType, afterDir string, callback ParsingCallback) RegisterParsingCallback registers callback to be called after executing the directive afterDir for server type serverType.(typeName string, srv ServerType) RegisterServerType registers a server type srv by its name, typeName.. SplitCommandAndArgs takes a command string and parses it shell-style into the command and its separate arguments. Code:] Started returns true if at least one instance has been started by this package. It never gets reset to false once it is set to true. Stop stops ALL servers. It blocks until they are all stopped. It does NOT execute shutdown callbacks, and it deletes all instances after stopping is completed. Do not re-use any references to old instances after calling Stop.. Upgrade re-launches the process, preserving the listeners for a graceful upgrade. It does NOT load new configuration; it only starts the process anew with the current config. This makes it possible to perform zero-downtime binary upgrades. TODO: For more information when debugging, see: ValidDirectives returns the list of all directives that are recognized for the server type serverType. However, not all directives may be installed. This makes it possible to give more helpful error messages, like "did you mean ..." or "maybe you need to plug in ...".. AfterStartup is an interface that can be implemented by a server type that wants to run some code after all servers for the same Instance have started. CaddyfileInput represents a Caddyfile as input and is simply a convenient way to implement the Input interface. func (c CaddyfileInput) Body() []byte Body returns c.Contents. func (c CaddyfileInput) Path() string Path returns c.Filepath. func (c CaddyfileInput) ServerType() string ServerType returns c.ServerType. (c *Controller) Context() Context Context gets the context associated with the instance associated with c. func (c *Controller) OnFinalShutdown(fn func() error) OnFinalShutdown adds fn to the list of callback functions to execute when the server is about to be shut down NOT as part of a restart. func (c *Controller) OnFirstStartup(fn func() error) OnFirstStartup adds fn to the list of callback functions to execute when the server is about to be started NOT as part of a restart. func (c *Controller) OnRestart(fn func() error) OnRestart adds fn to the list of callback functions to execute when the server is about to be restarted. func (c *Controller) OnShutdown(fn func() error) OnShutdown adds fn to the list of callback functions to execute when the server is about to be shut down (including restarts). func (c *Controller) OnStartup(fn func() error) OnStartup adds fn to the list of callback functions to execute when the server is about to be started (including restarts). func (c *Controller) ServerType() string ServerType gets the name of the server type that is being set up. CtxKey is a value type for use with context.WithValue. EventHook is a type which holds information about a startup hook plugin. EventName represents the name of an event used with event hooks. Define the event names for the startup and shutdown events. DefaultInput returns the default Caddyfile input to use when it is otherwise empty or missing. It uses the default host and port (depends on host, e.g. localhost is 2015, otherwise 443) and root.. Instance contains the state of servers created as a result of calling Start and can be used to access or control those servers. Start starts Caddy with the given Caddyfile. This function blocks until all the servers are listening. Caddyfile returns the Caddyfile used to create i. Restart replaces the servers in i with new servers created from executing the newCaddyfile. Upon success, it returns the new instance to replace i. Upon failure, i will not be replaced. SaveServer adds s and its associated listener ln to the internally-kept list of servers that is running. For saved servers, graceful restarts will be provided. func (i *Instance) Servers() []ServerListener Servers returns the ServerListeners in i. ShutdownCallbacks executes all the shutdown callbacks of i, including ones that are scheduled only for the final shutdown of i. An error returned from one does not stop execution of the rest. All the non-nil errors will be returned. Stop stops all servers contained in i. It does NOT execute shutdown callbacks. Wait blocks until all of i's servers have stopped. Listener is a net.Listener with an underlying file descriptor. A server's listener should implement this interface if it is to support zero-downtime reloads.. LoaderFunc is a convenience type similar to http.HandlerFunc that allows you to use a plain function as a Load() method. func (lf LoaderFunc) Load(serverType string) (Input, error) Load loads a Caddyfile. PacketConn is a net.PacketConn with an underlying file descriptor. A server's packetconn should implement this interface if it is to support zero-downtime reloads (in sofar this holds true for datagram connections). ParsingCallback is a function that is called after a directive's setup functions have been executed for all the server blocks.. ServerListener pairs a server to its listener and/or packetconn. func (s ServerListener) Addr() net.Addr Addr returns the listener's network address. It returns nil when it is not set. func (s ServerListener) LocalAddr() net.Addr LocalAddr returns the local network address of the packetconn. It returns nil when it is not set.() Context } ServerType contains information about a server type. type SetupFunc func(c *Controller) error SetupFunc is used to set up a plugin, or in other words, execute a directive. It will be called once per key for each server block it appears in. DirectiveAction gets the action for directive dir of server type serverType. type Stopper interface { // Stop stops the server. It blocks until the // server is completely stopped. Stop() error } Stopper is a type that can stop serving. The stop does not necessarily have to be graceful.. Package caddy imports 22 packages (graph) and is imported by 557 packages. Updated 2017-09-16. Refresh now. Tools for package owners.
https://godoc.org/github.com/mholt/caddy
CC-MAIN-2017-39
refinedweb
1,297
59.4
SpeakProgressEventArgs.Text Property .NET Framework (current version) Namespace: System.Speech.Synthesis The text that was just spoken when the event was raised. Assembly: System.Speech (in System.Speech.dll) The SpeechSynthesizer normalizes numbers to the words that correspond to how the number will be spoken. For example, the synthesizer speaks the number “4003” as “four thousand three”. It raises a SpeakProgress event for each of the spoken words. However, the Text property for each of the three words is the same. It is the text “4003” from the prompt. The following example illustrates the how the SpeakProgress event reports the CharacterPosition and Text properties for strings that contain numbers. using System; using System.Xml; using System.IO;(); // Create an XML Reader from the file, create a PromptBuilder and // append the XmlReader. PromptBuilder builder = new PromptBuilder(); builder.AppendText("4003"); // Add a handler for the SpeakProgress event. synth.SpeakProgress += new EventHandler<SpeakProgressEventArgs>(synth_SpeakProgress); // Speak the prompt and play back the output file. synth.Speak(builder); } Console.WriteLine(); Console.WriteLine("Press any key to exit..."); Console.ReadKey(); } // Write each word and its character position to the console. static void synth_SpeakProgress(object sender, SpeakProgressEventArgs e) { Console.WriteLine("Speak progress - Character position: {0} Text: {1}", e.CharacterPosition, e.Text); } } } Return to top .NET Framework Available since 3.0 Available since 3.0 Show:
https://msdn.microsoft.com/en-us/library/system.speech.synthesis.speakprogresseventargs.text.aspx
CC-MAIN-2018-05
refinedweb
218
54.18
A quick summary of the issue:I'm testing a QT desktop application and some of the Tree control methods require a Qt object as a parameter to use the method (object of QPoint type). QPoint is not built into TestComplete as far as I can tell, so I'm trying to use PyQt5 site-package libraries (same version of python as my Test Complete isntall - Python 3.6 X64) to generate the appropriate object. I've tried a couple of different methods of importing external libraries and I'm using the recommended suggestion of putting the site packages in the Test Complete python libraries folder. I created a python test script to see if I can create the required QPoint object before using in my test scripts.Result:1) It works the first time I run the script2) On subsequent runs of the script it doesn't' seem to load the libraries correctly but it generates a different error each time. If I then shut test complete and reopen, it will again work the first time but not subsequent times3) The same code works perfectly fine in a local system interpreter. It seems that Test Complete is doing something strange with the library import and is possibly not correctly unloading the library after the test script has finished. Any suggestions on either A) how to select QTreeView nodes (I've been advised that the indexAt method is required) or B) how to get the system to process the PyQt5 import would be greatly appreaciated. Longer explanation with more information: I'm testing a QT desktop application and I'm getting stuck when trying to navigate the QTTreeView widgets. I can't select or open any of the tree nodes with the available methods. When I looked into the QT documentation for this QT object (QtreeView class) and after speaking to our developers, apparently I need to use the indexAt () method to select the node by grid coordinates because the tree is an abstracted view of another object somewhere else. In order to use the QTreeView_indexAt() method that the tree view returns in Testcomplete’s object browser I need to submit the coorindates as a QPoint object into the parameter. TestComplete does not have the QPoint function built in that I can find. So initially I pulled down PyQt5 into my system python installation (which I matched to the python 3.6 version in test complete) and tried to reference it from the site packages there as described by a number of posts in this forum.e.g. in a script I added the following code to test if it would work, then I just ran the main function. Import os from os import sys sys.path.insert(0, 'C:\\Python\\Python36\\Lib\\site-packages') import PyQt5.QtCore def main(): qpoint_obj = PyQt5.QtCore.QPoint(3,5) This didn’t seem to work because it was complaining about being unable to locate PyQt5.sip when importing QtCore, even though it’s in the path.Also the same code works fine if I run the same code from the IDLE interpreter that comes with system installation.(I also tried different import combinations with the same effect) import osfrom os import syssys.path.insert(0, 'C:\\Python\\Python36\\Lib\\site-packages') from PyQt5.QtCore import QPoint Next, I tried the other suggestion when using external packages and copying the entire PyQt5 package to the Test complete installation directory C:\Program Files (x86)\SmartBear\TestComplete 14\x64\Bin\Extensions\Python\Python36\Lib So now the PyQt5 should be within the TestComplete python path. Interestingly this seems to work on the first run of the main function, but then subsequently fails when I try to run it again. After until I close and reopen Test Complete, it again works for the first run but not again after, until I close again. I updated my script to the following to try diagnose if it was a problem with the loading of the imported PyQt5 modules. I created function to check if PyQt5 was being imported and to log it if it was not import os from os import sys # sys.path.insert(0, 'C:\\Python\\Python36\\Lib\\site-packages') #import importlib #importlib.invalidate_caches() import PyQt5.QtCore def main(): #importlib.invalidate_caches() #import PyQt5.QtCore Log.Message("Python version: " + str(sys.version)) Log.Message(str(sys.path)) Log.Message(os.environ['PYTHONPATH'].split(os.pathsep)) check_if_module_imported("PyQt5.QtCore") qpoint_obj = PyQt5.QtCore.QPoint(3,5) def check_if_module_imported(module_name_str): if module_name_str not in sys.modules: Log.Message(module_name_str + " Module not imported") else: Log.Message(module_name_str + " Module imported") On the first attempt after re-opening Test Complete it works. On each subsequent attempt after that I get an error to do with the PyQt5 import, but the error changes each time I run it. Attempt run 2 and 3:Attempt 4:Attempt5:Attempt 6: I also tried placing Runner.Stop() at the end of my main function, but this did not resolve the issue for subsequent runs eitherAny ideas on how to resolve this? Solved! Go to Solution. There was no solution available: Response from support: The developers have provided an update. Unfortunately, they are unable to say exactly what is causing the problem. We are unable to guarantee that third party libraries will work properly, because of this they are unable to provide any fix for this issue. View solution in original post I'd contact Support directly. Here's the link: I see that the investigation is ongoing in case 00447869. It would be great if you shared the final results of the investigation in this thread, as well @nhucker ! This info could help people solve a similar issue in the future🙂 I got a similar problem when trying to use the library LXML. The first run of my test worked fine, but each others run where throwing the following error: ImportError: Interpreter change detected - this module can only be loaded into one interpreter per process. You might have a similar problem, even though the error returned is not the same.
https://community.smartbear.com/t5/TestComplete-Desktop-Testing/PyQt5-import-for-testing-QT-only-works-on-the-first-test-run-and/td-p/205828
CC-MAIN-2021-10
refinedweb
1,012
62.17
The warning in the problem statement hints that naively trying to remove every cow and directly evaluating the area of the resulting fence may be too slow. Consider the fence with the original configuration of cows. If we remove a cow that is not on the fence itself, then the fence will not change. The only time when the fence could change is if we remove a cow that is on the fence itself. Let us consider the bottom section of the fence. If there is exactly one cow on that section, and we remove it, the bottom section of the fence will shift up to the cow that has the second-smallest y-coordinate. If there are at least two cows on that section though, then the fence will not change. By similar logic, this is true for each part of the fence. Therefore, it suffices to keep track of the two smallest and two largest x and y coordinates. Here is my Java code. import java.io.*; import java.util.*; public class reduceB { // x1 and x2 are the smallest x-coordinates seen // x3 and x4 are the largest x-coordinates seen static int x1, x2, x3, x4; // y1 and y2 are the smallest y-coordinates seen // y3 and y4 are the largest y-coordinates seen static int y1, y2, y3, y4; public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new FileReader("reduce.in")); PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter("reduce.out"))); int n = Integer.parseInt(br.readLine()); x1 = Integer.MAX_VALUE; x2 = Integer.MAX_VALUE; x3 = 0; x4 = 0; y1 = Integer.MAX_VALUE; y2 = Integer.MAX_VALUE; y3 = 0; y4 = 0; int[] x = new int[n]; int[] y = new int[n]; // read in all the locations for(int i = 0; i < n; i++) { StringTokenizer st = new StringTokenizer(br.readLine()); x[i] = Integer.parseInt(st.nextToken()); y[i] = Integer.parseInt(st.nextToken()); update(x[i], y[i]); } // the original fence has this area int ans = (x4-x1) * (y4-y1); for(int i = 0; i < n; i++) { // check for each point if we use the smallest/largest coordinate // or the second-smallest/second-largest coordinate int xMin = x1; if(x[i] == xMin) { xMin = x2; } int xMax = x4; if(x[i] == xMax) { xMax = x3; } int yMin = y1; if(y[i] == yMin) { yMin = y2; } int yMax = y4; if(y[i] == yMax) { yMax = y3; } // check if the new area is smaller ans = Math.min(ans, (xMax - xMin) * (yMax - yMin)); } // print the answer pw.println(ans); pw.close(); } // This function takes in a point and updates the // two smallest and two largest x and y coordinates. public static void update(int x, int y) { if(x < x1) { x2 = x1; x1 = x; } else if(x < x2) { x2 = x; } if(x > x4) { x3 = x4; x4 = x; } else if(x > x3) { x3 = x; } if(y < y1) { y2 = y1; y1 = y; } else if(y < y2) { y2 = y; } if(y > y4) { y3 = y4; y4 = y; } else if(y > y3) { y3 = y; } } }
http://usaco.org/current/data/sol_reduce_bronze_open16.html
CC-MAIN-2018-17
refinedweb
494
70.33
FPRINTF(P) POSIX Programmer s Manual FPRINTF(P) PROLOG This manual page is part of the POSIX Programmer s Manual. The Linux implementation of this interface may differ (consult the corresponding Linux manual page for details of Linux behavior), or the interface may not be implemented on Linux. NAME fprintf, printf, snprintf, sprintf - print formatted output SYNOPSIS #include <stdio.h> int fprintf(FILE *restrict stream, const char *restrict format, ...); int printf(const char *restrict format, ...); int snprintf(char *restrict s, size_t n, const char *restrict format, ...); int sprintf(char *restrict s, const char *restrict format, ...); DESCRIPTION, begin- ning and ending in its initial shift state, if any. The format is com- posed of zero or more directives: ordinary characters, which are simply copied to the output stream, and conversion specifications, each of which shall result in the fetching of zero or more arguments. The results are undefined if there are insufficient arguments for the for- mat. specifica- tions specifica- tion, lan- guage-dependent radix character in the output string. The radix charac- ter: * Zero or more flags (in any order), which modify the meaning of the conversion specification. * An optional minimum field width. If the converted value has fewer bytes than the field width, it shall be padded with spaces by default on the left; it shall be padded on the right if the left- adjustment flag (-), described below, is given to the field width. The field width takes the form of an asterisk (*), described below, or a decimal integer. * An optional precision that gives the minimum number of digits to appear for the d , i , o , u , x , and X conversion specifiers; the number of digits to appear after the radix character for the a , A , e , E , f , and F conversion specifiers; the maximum number of sig- nificant digits for the g and G conversion specifiers; or the maxi- mum number of bytes to be printed from a string in the s and S conversion specifiers. The precision takes the form of a period ( .) followed either by an asterisk (*), described below, or an optional decimal digit string, where a null digit string is treated as zero. If a precision appears with any other conversion specifier, the behavior is undefined. * An optional length modifier that specifies the size of the argument. * A conversion specifier character that indicates the type of conver- sion to be applied.$n", hour, min, precision, sec); The flag characters and their meanings are: The integer portion of the result of a decimal conversion ( %i , %d , %u , %f , %F , %g , or %G ) shall be formatted with thou- sands grouping characters. For other conversions the behavior is undefined. The non-monetary grouping character is used. - The result of the conversion shall be left-justified within the field. The conversion is right-justified if this flag is not specified. + The result of a signed conversion shall always begin with a sign (+or-). The conversion shall begin with a sign only when a negative value is converted if this flag is not specified. <space> If the first character of a signed conversion is not a sign or if a signed conversion results in no characters, a <space> shall be prefixed to the result. This means that if the <space> and +flags both appear, the <space> flag shall be ignored. # Specifies that the value is to be converted to an alternative form. For o conversion, it increases the precision (if neces- sary) to force the first digit of the result to be zero. For x or X conversion specifiers, a non-zero result shall have 0x (or 0X) prefixed to it. For a , A , e , E , f , F , g , and G con- version specifiers, the result shall always contain a radix character, even if no digits follow the radix character. Without this flag, a radix character appears in the result of these con- versions only if a digit follows it. For g and G conversion specifiers, trailing zeros shall not be removed from the result as they normally are. For other conversion specifiers, the behavior is undefined. 0 For d , i , o , u , x , X , a , A , e , E , f , F , g , and G conversion specifiers, leading zeros (following any indication of sign or base) are used to pad to the field width; no space padding is performed. If the0and-flags both appear, the 0 flag is ignored. For d , i , o , u , x , and X conversion specifiers, if a precision is specified, the 0 flag is ignored. If the 0and" flags both appear, the grouping characters are inserted before zero padding. For other conver- sions, the behavior is undefined. The length modifiers and their meanings are: hh Specifies that a following d , i , o , u , x , or X conversion specifier applies to a signed char or unsigned char argument (the argument will have been promoted according to the integer promotions, but its value shall be converted to signed char or unsigned char before printing); or that a following n conversion specifier applies to a pointer to a signed char argument. h Specifies that a following d , i , o , u , x , or X conversion specifier applies to a short or unsigned short argument (the argument will have been promoted according to the integer promo- tions, but its value shall be converted to short or unsigned short before printing); or that a following n conversion speci- fier applies to a pointer to a short argument. l (ell) Specifies that a following d , i , o , u , x , or X conversion specifier applies to a long or unsigned long argument; that a following n conversion specifier applies to a pointer to a long argument; that a following c conversion specifier applies to a wint_t argument; that a following s conversion specifier applies to a pointer to a wchar_t argument; or has no effect on a fol- lowing a , A , e , E , f , F , g , or G conversion specifier. ll (ell-ell) Specifies that a following d , i , o , u , x , or X conversion specifier applies to a long long or unsigned long long argument; or that a following n conversion specifier applies to a pointer to a long long argument. j Specifies that a following d , i , o , u , x , or X conversion specifier applies to an intmax_t or uintmax_t argument; or that a following n conversion specifier applies to a pointer to an intmax_t argument. z Specifies that a following d , i , o , u , x , or X conversion specifier applies to a size_t or the corresponding signed inte- ger type argument; or that a following n conversion specifier applies to a pointer to a signed integer type corresponding to a size_t argument. t Specifies that a following d , i , o , u , x , or X conversion specifier applies to a ptrdiff_t or the corresponding unsigned type argument; or that a following n conversion specifier applies to a pointer to a ptrdiff_t argument. L Specifies that a following a , A , e , E , f , F , g , or G con- version specifier applies to a long double argument. If a length modifier appears with any conversion specifier other than as specified above, the behavior is undefined. The conversion specifiers and their meanings are: d, i The int argument shall be converted to a signed decimal in the style "[-]dddd". The precision specifies the minimum number of digits to appear; if the value being converted can be repre- sented in fewer digits, it shall be expanded with leading zeros. The default precision is 1. The result of converting zero with an explicit precision of zero shall be no characters. o The unsigned argument shall be converted to unsigned octal for- mat. u The unsigned argument shall be converted to unsigned decimal format The unsigned argument shall be converted to unsigned hexadecimal format in the style "dddd"; the letters "abcdef" are used. Equivalent to the x conversion specifier, except that letters "ABCDEF" are used instead of "abcdef" . f, charac- ter shall appear. If a radix character appears, at least one digit appears before it. The low-order digit shall be rounded in an implementation-defined manner. A double argument representing an infinity shall be converted in one of the styles "[-]inf" or "[-]infinity" ; which style is implementation- defined. A double argument representing a NaN shall be converted in one of the styles "[-]nan(n-char-sequence)" or "[-]nan" ; which style, and the meaning of any n-char-sequence, is implementation-defined. The F conversion specifier produces "INF" , "INFINITY" , or "NAN" instead of "inf" , "infinity" , or "nan" , respectively. e, E The double argument shall be converted in the style "[-]d.ddde±dd", where there is one digit before the radix char- acter (which is non-zero if the argument is non-zero) and the number of digits after it is equal to the precision; if the pre- cision is missing, it shall be taken as 6; if the precision is zero and no # flag is present, no radix character shall appear. The low-order digit shall be rounded in an implementa- tion-defined manner. The E conversion specifier shall produce a number with E instead of e introducing the exponent. The exponent shall always contain at least two digits. If the value is zero, the exponent shall be zero. A double argument representing an infinity or NaN shall be converted in the style of an f or F conversion specifier. g, G The double argument shall be converted in the style f or e (or in the style F or E in the case of a G conversion specifier), with the precision specifying the number of significant digits. If an explicit precision is zero, it shall be taken as 1. The style used depends on the value converted; style e (or E ) shall be used only if the exponent resulting from such a conversion is less than -4 or greater than or equal to the precision. Trailing zeros shall be removed from the fractional portion of the result; a radix character shall appear only if it is followed by a digit or a#flag is present. A double argument representing an infinity or NaN shall be converted in the style of an f or F conversion specifier. a, A A double argument representing a floating-point number shall be converted in the style "[-]0xh.hhhhp±d", where there is one hex- adecimal digit (which shall be non-zero if the argument is a normalized floating-point number and is otherwise unspecified) before the decimal-point character and the number of hexadecimal digits after it is equal to the precision; if the precision is missing and FLT_RADIX is a power of 2, then the precision shall be sufficient for an exact representation of the value; if the precision is missing and FLT_RADIX is not a power of 2, then the precision shall be sufficient to distinguish values of type dou- ble, except that trailing zeros may be omitted; if the precision is zero and the # flag is not specified, no decimal-point character shall appear. The letters "abcdef" shall be used for a conversion and the letters "ABCDEF" for A conversion. The A con- version specifier produces a number with XandP instead of x and p . The exponent shall always contain at least one digit, and only as many more digits as necessary to represent the decimal exponent of 2. If the value is zero, the exponent shall be zero. A double argument representing an infinity or NaN shall be converted in the style of an f or F conversion specifier. c The int argument shall be converted to an unsigned char, and the resulting byte shall be written. If an l (ell) qualifier is present, the wint_t argument shall be con- verted. s The argument shall be a pointer to an array of char. Bytes from the array shall be written up to (but not including) any termi- nating null byte. If the precision is specified, no more than that many bytes shall be written. If the precision is not speci- fied or is greater than the size of the array, the application shall ensure that the array contains a null byte. If an l (ell) qualifier is present, the argument shall be a pointer to an array of type wchar_t. Wide characters from the array shall be con- verted to characters (each as if by a call to the wcrtomb() function, with the conversion state described by an mbstate_t object initialized to zero before the first wide character is converted) up to and includ- ing a terminating null wide character. The resulting characters shall be written up to (but not including) the terminating null character (byte). If no precision is specified, the application shall ensure that the array contains a null wide character. If a precision is specified, no more than that many characters (bytes) shall be written (including shift sequences, if any), and the array shall contain a null wide char- acter if, to equal the character sequence length given by the preci- sion, the function would need to access a wide character one past the end of the array. In no case shall a partial character be written. p The argument shall be a pointer to void. The value of the pointer is converted to a sequence of printable characters, in an implementation-defined manner. n The argument shall be a pointer to an integer into which is written the number of bytes written to the output so far by this call to one of the fprintf() functions. No argument is con- verted. C Equivalent to lc . S Equivalent to ls . % Print a % character; no argument is converted. The complete conversion specification shall. Charac- ters dig- its is more than DECIMAL_DIG but the source value is exactly repre- sent(). RETURN VALUE neg- ative value. If the value of n is zero on a call to snprintf(), nothing shall be written, the number of bytes that would have been written had n been sufficiently large excluding the terminating null shall be returned, and s may be a null pointer. ERRORS For the conditions under which fprintf() and printf() fail and may fail, refer to fputc() or fputwc() . In addition, all forms of fprintf() may fail if: EILSEQ A wide-character code that does not correspond to a valid char- acter has been detected. EINVAL There are insufficient arguments. The printf() and fprintf() functions may fail if: ENOMEM Insufficient storage space is available. The snprintf() function shall fail if: EOVERFLOW The value of n is greater than {INT_MAX} or the number of bytes needed to hold the output excluding the terminating null is greater than {INT_MAX}. The following sections are informative. EXAMPLES Printing Language-Independent Date and Time The following statement can be used to print date and time using a lan- guage-independent format: printf(format, weekday, month, day, hour, min); For American usage, format could be a pointer to the following string: "%s, %s %d, %d:%.2n" This example would produce the following message: Sunday, July 3, 10:02 For German usage, format could be a pointer to the following string: "%1$s, %3$d. %2$s, %4$d:%5$.2n" This definition of format would produce the following message: Sonntag, 3. Juli, 10:02 Printing File Information The following example prints information about the type, permissions, and number of links of a specific file in a directory. The first two calls to printf() use data decoded from a previous stat() call. The user-defined strperm() function shall return a string simi- lar to the one at the beginning of the output for the following com- mand:- gr); ... Printing a Localized Date String The following example gets a localized date string. The nl_langinfo() function shall return the localized date string, which specifies the order and layout of the date. The strftime() function takes this infor- mation and, using the tm structure for values, places the date and time information into datestring. The printf() function then outputs dat- est %n", datestring, dp->d_name); ... Printing Error pass- wordn"); exit(1); } ... if (link(LOCKFILE,PASSWDFILE) == -1) { fprintf(stderr, "Link error: %n", strerror(errno)); exit(1); } ... Printing Usage Information <filn", argv[0], Options); exit(1); } ... Formatting a Decimal String The following example prints a key and data pair on stdout. Note use of the * (asterisk) in the format string; this ensures the correct number of decimal places for the element based on the number of ele- ments requested. #include <stdio.h> ... long i; char *keystr; int elementlen, len; ... while (len < elementlen) { ... printf("%s Element%0*ln", keystr, elementlen, i); ... } Creating a Filename The following example creates a filename using information from a pre- vious getpwnam() function that returned the HOME directory of the user. #include <stdio.h> #include <sys/types.h> #include <unistd.h> ... char filename[PATH_MAX+1]; struct passwd *pw; ... sprintf(filename, "%s/%d.out", pw->pw_dir, getpid()); ... Reporting an Event: %n", strerror(errno)); } ... Printing Monetary Information %n", table[i].format, convbuf, table[i].description); } else { printf(" %n", convbuf); } ... Printing Wide Characters The following example prints a series of wide characters. Suppose. APPLICATION USAGE If the application calling fprintf() has any objects of type wint_t or wchar_t, it must also include the <wchar.h> header to have these objects defined. RATIONALE None. FUTURE DIRECTIONS None. SEE ALSO fputc() , fscanf() , setlocale() , strfmon() , wcrtomb() , the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 7, Locale, <stdio.h>, <wPRINTF(P)
http://man.linuxtool.net/centos5/u11/man/3p_fprintf.html
CC-MAIN-2021-43
refinedweb
2,900
51.78
if I using custom modules in my plugins with something like the follow: from helper.configuration_files import generate I find that once I change the module it doesn't refresh or reload the module until I reload sublimetext. Is it possible to get it to reload everything automatically? You have to write some python to get the (sub)modules to reload properly. I do this with Package Control (python3 branch): github.com/wbond/sublime_packag ... Control.pygithub.com/wbond/sublime_packag ... eloader.py Thanks, that got me on the right track! I change any file in Package Control/package_control but sublime not reloading this file. Why? Sublime Text only automatically reloads .py files in the root of a package. Thus if you save Package Control.py, it will reload all of the other files inside of the package_control/ folder.
https://forum.sublimetext.com/t/reloading-external-modules-st3/8990/3
CC-MAIN-2016-44
refinedweb
137
60.01
Simple Arduino Temperature, Moisture and Light Monitor Recently I planted some succulent seeds indoors, and had to put them in a miniature greenhouse so that they could sprout. I wanted a way to keep an eye on the temperature, moisture and ambient light in the greenhouse, so I whipped this up. It outputs realtime measurements to an LCD. If you’ve seen my ProGrow project, this is a simplified version without any data storage or relays. Parts I used an old scrap 3D print for the frame; it’s just a block of plastic that I screwed everything to. The electronic parts used are: - Arduino Nano – AliExpress Link - Arduino Nano expansion board ( optional ) – AliExpress Link - FC113 + LCD Module – AliExpress Link - DHT11 Temperature/Humidity Sensor – Aliexpress Link - Photoresistor Module – Aliexpress Link A quick overview of each component and why I’m using it: - Arduino Nano - Extremely low cost (<$3) - Ready to go ATMega328p board with voltage regulators and USB - Lots of expansion opportunities - Arduino Expansion Board - Makes life easier for prototyping/wiring with the Nano - FC-113 + 16×2 LCD - Cheap and easy to use LCD combo - Only requires two analog pins for communication - Photoresistor module - Works just like a photoresistor with an analog signal, but it also has a digital output - Has an indicator LED and potentiometer for the digital output - DHT11 Temperature/Humidity Module - Cheap, easy to use and fairly accurate. - DHT22 is a better version, but is more expensive Connecting everything to the Arduino The DHT11 module has 4 pins, but only three are used: - Vcc to +5V - Signal to Digital Pin 5 - Gnd to Gnd The photoresistor module I am using also has 4 pins, and only three are used. The analog output of the module is used over the digital output. You can get the same functionality with just a resistor and a photoresistor. - Vcc to +5V - Aout to Analog pin 1 - Gnd to Gnd The LCD module is connected to the FC 113. The FC 113 is connected in the following manner: - Vcc to +5V - SCL to Analog pin 5 - SDA to Analog pin 4 - Gnd to Gnd The arduino nano can be powered through USB with 5V, or through the Vin pin with 7V-12V. Programming Programming the Arduino for this is pretty straightforward. All the Arduino has to do is take a measurement from the DHT11 and photoresistor, and then output them to the display. There are libraries available for the DHT sensor, and the FC 113 module, so the whole process is straightforward. Before starting You need two libraries to make things easier, one for the DHT11 and one for the FC 113. You can download the DHT library I used at: You can download the FC 113 library I used at: How to install libraries: Before Setup //Temp/Humidity/Light Monitor V0.1 #include <LiquidCrystal_I2C.h> //Import LcrystalI2C for FC 113 + LCD module #include <dht.h> //Import DHT for DHT11 temperature/humidity sensor int tempSensor = 5; //Digital pin 5 for temperature sensor int lightSensor = A1; //Analog pin 1 for light sensor dht DHT; //Sets up dht11 as DHT First I include the required libraries. Then, I establish pin 5 for the temperature sensor and analog pin 1 for the light sensor. Finally, I set up an object called DHT to handle data from the DHT11 sensor. Setup void setup(){ Serial.begin(9600); //Establishes serial at 9600 lcd.init(); //Initialize the lcd lcd.backlight(); //Initialize LCD backlight lcd.clear(); //Clear LCD Serial.print(analogRead(lightSensor)); //Print currently photoresistor value to serial; for troubleshooting purposes } The setup just consists of initializing the LCD module, and printing a simple message to the serial monitor as an optional self-check. Loop void loop(){ DHT.read11(tempSensor); //Reads information from tempSensor(pin 5), stores in DHT lcd.setCursor(0,0); //Sets cursor of LCD to very first position lcd.print("H: "); //Prints H: , for humidity lcd.print(DHT.humidity); //Outputs humidity lcd.setCursor(0,1); //Sets cursor of LCD to first position, second line lcd.print("T: "); //Prints T: , for temperature lcd.print(DHT.temperature); //Outputs temperature lcd.print(" C"); //Prints C for celcius delay(4000); //Delays for approximately 4 seconds lcd.clear(); //Clears the LCD lcd.setCursor(0,0); //Resets cursor to first position lcd.print("Lux: "); //Prints Lux, for light level lcd.print(analogRead(lightSensor)); //Outputs lux value delay(4000); //Delays for 4 seconds before looping } The loop starts by reading the DHT11 sensor, and storing the values in the DHT object. Then, it outputs the information to the LCD. It delays for a few seconds, and then it reads the light sensor. It continues in a loop like this, reading and then outputting.
https://adamslab.ca/category/circuits/
CC-MAIN-2019-18
refinedweb
780
54.32
Much of the functionality that is exposed through the RESTful HTTP API is also available using an HTML user interface interpreted by your favorite web browser. Whether your request for particular HTTP API endpoints results in an HTML UI or more machine-readable formats is based on content negotiation headers. This tour walks you through the major user interface components when accessing the HTTP API through a web browser. When you access the root path of the RESTful HTTP API you are presented with a rendering of the root level of your Fedora repository. From here you can: - Create new Resources (Containers or Binaries) - Inspect the properties of Resources. - Update the properties of Resources. - Navigate the Repository Hierarchy of Resources. - Import/Export Resources. - Start Transactions. The user interface is divided into regions. - Navigation bar (top) - Resource information and navigation (center left) - Optional resource actions (center right) Navigation Bar The navigation bar, which appears at the top of each page, includes links to the following: - Transactions Resource Information Information about the resource requested is displayed below the navigation bar, filling the left two thirds of interface. 1 Object Title If a title (either or) is available, it is displayed here. If no title has been assigned, the resource URI is displayed in this location. 2 Object Path Fedora 4 is different from Fedora 3 in that there is an innate tree hierarchy to the repository rather than a flat structure. The path (list of ancestors) for the viewed resource is presented below the object title. Performance is expected to be better with a deeper hierarchy with fewer items per level as opposed to a shallow hierarchy where each level has a larger number of siblings. The automatic ID (and path) generated is meant to optimize performance, but you may use your own organizational strategy when creating resources. In this particular example, the container was created with a fully qualified name including a namespace and local name (separated by a colon). Fedora 4 does not require (nor recommend) that identifiers have namespaces. 3 Featured Properties Very basic metadata such as the UUID and modification/creation times and users are presented below the resource path. 4 Children Any children that the container has will be listed and linked here. Like the parent containter, if a child resource has recognized title metadata, the title will be presented here rather than its URI. 5 All Resource Properties All properties of the resource are presented here. Hover your mouse over the namespace prefix to see the full namespace. 6 Other Resources A subset of properties from the parent resource. Click on the gray box to expand the list of properties or the label text to view that resource directly. Actions These may include: Create New Child Resource From the homepage or any container page a form exists that lets you create a new container or binary that will be the child of the current container. Download/Update Content When viewing a NonRdfSourceDescription with binary content, click the large green button to download that content. You can also update the description of the binary using the form. Update Properties When viewing a resource, you can add or delete properties using the "Update Properties" form. Delete Resource You can delete the resource you are currently viewing by clicking the red "Delete" button. Import/Export When viewing a resource, you can export it using the "Export as..." button. In the case of containers, you can also import a resource using the "Import" form.
https://wiki.duraspace.org/display/FEDORA471/Feature+Tour
CC-MAIN-2019-39
refinedweb
584
52.49
Red Hat Bugzilla – Bug 182095 Incorrect BuildRequires for kernel-hugemem Last modified: 2009-04-16 16:02:42 EDT While trying the depsolver code from mock on cman-kernel, a problem with the BuildRequires manifested itself. Solving BuildDependencies on x86_64 fails, as the cman-kernel depends on kernel-hugemem = %{kernel_version} and kernel-hugemem-devel = %{kernel_version}. These packages are only built on i686 and thus do not exist in a x86_64 buildroot. Enclosing the hugemem-requirements into %if %{buildhugemem} %endif should take care of this problem. Assign to chris, as I think he's the buildmeister. Unfortunately to get cman-kernel to build properly with our build system we are unable to use %if statements to exclude kernel-hugemem for non i686 builds. It's best to either setup a dummy package which provides kernel-hugemem on non i686 builds or to remove the line from your builds.
https://bugzilla.redhat.com/show_bug.cgi?id=182095
CC-MAIN-2017-17
refinedweb
147
52.49
Sometimes when you work on large projects, you can end up with code that looks like this: if num_values < 15: do_thing() Now, what does the 15 mean? Well, I’m sure you would have known when you first wrote the code, but what happens in 3 months when you try to modify it or pass it on to someone else in your team? Also, what happens if you determine that the number should actually be 16? Now you have to go through all your files and swap numbers in all the right places (and if you miss any you can introduce subtle bugs). So what’s the solution? Well, what you really need is a single source of truth for your clearly defined constants, which you can: - Easily look up - Modify/update - Import into other code Python makes this really easy – all you have to do is create a “constants.py” file in your project directory (I suppose you could call it whatever you like, but that’s beside the point). From here, you can import your variables as if you were importing a library: from constants import NOM_FREQ_HZ, VALUES_IN_MIN A screenshot of this file from a recent project looks a little like this: This approach helped me write much more readable code, when working with an extremely complicated dataset where numbers were used to represent different value categories. Obviously for smaller scripts it might not be worth setting up a dedicated file, but for this project, my constants file ended up being a couple of hundred lines long, and is far easier to maintain than if they were defined multiple times across all the files in the project.
https://jacksimpson.co/category/content/data-science/
CC-MAIN-2021-31
refinedweb
279
66
UNAME(2) Linux Programmer's Manual UNAME(2) uname - get name and information about current kernel #include <sys/utsname.h> int uname(struct utsname *buf);'). On success, zero is returned. On error, -1 is returned, and errno is set to indicate the error. EFAULT buf is not valid. POSIX.1-2001, POSIX.1-2008, SVr4. There is no uname() call in 4.3BSD. The domainname member (the NIS or YP domain name) is a GNU extension.. uname(1), getdomainname(2), gethostname(2), uts_namespaces(7) This page is part of release 5.11 of the Linux man-pages project. A description of the project, information about reporting bugs, and the latest version of this page, can be found at. Linux 2021-03-22 UNAME(2) Pages that refer to this page: arch(1), systemd-nspawn(1), uname(1), getdomainname(2), gethostname(2), personality(2), syscalls(2), core(5), org.freedesktop.hostname1(5), systemd.exec(5), systemd.unit(5), lvmsystemid(7), signal-safety(7), uts_namespaces(7), modprobe(8), sm-notify(8)
https://man7.org/linux/man-pages/man2/uname.2.html
CC-MAIN-2021-17
refinedweb
169
52.36
remove - remove a file or directory Current Version: Linux Kernel - 3.80 Synopsis #include <stdio.h> int remove(const char *pathname); Description. Conforming To C89, C99, 4.3BSD, POSIX.1-2001. Bugs Infelicities in the protocol underlying NFS can cause the unexpected disappearance of files which are still being used. See Also Colophon This page is part of release 3.80 of the Linux man-pages project. A description of the project, information about reporting bugs, and the latest version of this page, can be found at. License & Copyright This file is derived from unlink.2, which has the following copyright: This manpage is Copyright (C) 1992 Drew Eckhardt; and Copyright (C) 1993 Ian Jackson. Edited into remove.3 shape by: Graeme W. Wilford (G.Wilford@ee.surrey.ac.uk) on 13th July 1994 %%
https://community.spiceworks.com/linux/man/3/remove
CC-MAIN-2018-34
refinedweb
134
62.14
Have you ever seen them? The cute little #defines and consts that have weird looking values like 0x81772012 or 0x49122035, used allover the code... the purpose which is known to only to their author ??? If you ever had interest in encrypting you're probably acquainted with them (Berkely DB has a full load of them! ) i was wondering how people invent them! is it like "hmm let see ... square of 0x1231 minus 0x121909 plus 0x93abde XOR 0x132958 add one more AND VOILA !! thats the number that solves my problems!!! " and also if you have some interesting and working code loaded with them share it ! heres some : Code://Berkely DB hashing algorithms (one of the best i've ever seen) #define DCHARHASH(h, c) ((h) = 0x63c63cd9*(h) + 0x9c39c33d + (c)) #define UINT8 unsigned char UINT Hashfunc1(const void *key,UINT len) { const UINT8 *e, *k; UINT h; UINT8 c; k = key; e = k + len; for (h = 0; k != e;) { c = *k++; if (!c && k > e) break; DCHARHASH(h, c); } return h; } //////Better unsigned int Hashfunc2(const void *key,UINT len) { const unsgined char *e, *k; unsigned int h; k = key; e = k + len; for (h = 0; k < e; ++k) { h *= 16777619; //what is that MAGIC ?!?!?! h ^= *k; } return h; }Code://author :Praveena <pvncad@krec.ernet.in> //descr: some encrypting scheme i found //the folowing code is used for generating // key seeds #define cypher 8 #define CYPHER_SZ (8*sizeof(int32_t)) typedef char int8_t; typedef short int16_t; typedef int int32_t; typedef __int64 int64_t; typedef unsigned char uint8_t; typedef unsigned short uint16_t; typedef unsigned int uint32_t; typedef unsigned __int64 uint64_t; void modseed(int32_t seed[cypher]) { int x; for(x=1;x<cypher;x++) seed[x]=seed[x]*0x81772012+seed[x]+0x49122035+seed[x+1]; for(x=1;x<cypher;x++) seed[0] ^= seed[x]; } int seedsum(int32_t seed[cypher]) { int n,x; n=0x80379251; for(x=0;x<cypher;x++) n=n^seed[x]; return ((n>>24)^((n>>16)&255)^((n>>8)&255)^(n&255)); } void seed_gen(char *pwd,int32_t seed[cypher]) { char *pp = pwd; memset((void*)seed,0,CYPHER_SZ); modseed(seed); while((*pp)){ modseed(seed); seed[0]=seed[0]+(*pp); modseed(seed); pp++; } } // and encoding int encode(char *buf,char *password) { int ret = 0; char *pstr = buf; int seed[cypher]; seed_gen(password,seed); while(*pstr) { modseed(seed); *pstr ^= (char)(seedsum(seed)); pstr++; } *pstr = '\0'; return 1; }
http://cboard.cprogramming.com/brief-history-cprogramming-com/20427-magic-magic-numbers.html
CC-MAIN-2014-52
refinedweb
392
66.17
The Schema Registration and Schema Location Hint Threadmdrake-Oracle Sep 1, 2006 6:04 AM The purpose of this thread is to two fold. The first is to address issues related to the process of registering an XML Schema with Oracle XML DB. The second is to explain how Oracle XML DB determines whether or not a particular XML document is associated with a particular XML Schema. An XML Schema decribes a class of XML. An XML document that is associated with a particular XML Schema is considered to be an instance of that class, and is often referred to as an instance document. An XML Schema decribes a class of XML. An XML document that is associated with a particular XML Schema is considered to be an instance of that class, and is often referred to as an instance document. This content has been marked as final. Show 6 replies 1. What is the purpose of the SchemaURL parameter ?mdrake-Oracle Sep 1, 2006 5:44 AM (in response to mdrake-Oracle)The SchemaURL parameter simply provides a unique identifier for each XML Schema registered in a particular database schema. By convention the schemaURL is typically given in the form of a URL, but this is not mandatory, In the cases where the schemaURL is a valid URL XML DB does not need to be able to access the URL in order to register the XML Schema. The schemaURL supplied to registerSchema must be an exact match for the "Schema Location Hint" in any instance documents that are going to be loaded into the database using protocols or DBMS_XDB.createResource(). 2. What privliges are required to register an XML Schema ?mdrake-Oracle Sep 1, 2006 5:45 AM (in response to mdrake-Oracle)In order to register an XML Schema a database user must have ALTER SESSION and CREATE VIEW. In addition, to register a global XML Schema, as distinct from a LOCAL XML Schema, the user must have been granted XDBADMIN. 3. Why can't I describe the table or types created by Schema Registration ?mdrake-Oracle Sep 1, 2006 5:46 AM (in response to mdrake-Oracle)The names of objects (Tables, Types, Type attributes) created by the schema registration processes are derived from the names of the objects in the XML Schema. Since XML Schema uses mixed case naming, the names of the Tables, Types and Type Attibtues are also created with mixed case names. This means that you must enclose the names of these objects in quotes when accessing them in SQL as the following example demonstates. You can also force explicit uppercase names for these items by annotating the XML Schema. Use xdb:SQLName to specify the name of Type Attributes, xdb:defaultTable to specify the name of Tables and xdb:SQLType to specify the name of SQLTypes. SQL> select table_name from user_xml_tables 2 where xmlschema = :schemaUrl 3 / TABLE_NAME ------------------------------ PurchaseOrder348_TAB SQL> desc PurchaseOrder348_TAB ERROR: ORA-04043: object PurchaseOrder348_TAB does not exist SQL> desc "PurchaseOrder348_TAB" Name Null? Type ----------------------------------------- -------- ---------------------------- TABLE of SYS.XMLTYPE(XMLSchema "PurchaseOrder.xsd" Element "PurchaseOrder") STORAGE Object-relational TYPE "PurchaseOrderType347_T" SQL> desc PurchaseOrderType347_T ERROR: ORA-04043: object PurchaseOrderType347_T does not exist SQL> desc "PurchaseOrderType347_T" "PurchaseOrderType347_T" is NOT FINAL Name Null? Type ----------------------------------------- -------- ---------------------------- SYS_XDBPD$ XDB.XDB$RAW_LIST_T Reference VARCHAR2(30 CHAR) Actions ActionsType340_T Reject RejectionType339_T Requestor VARCHAR2(128 CHAR) User VARCHAR2(10 CHAR) CostCenter VARCHAR2(4 CHAR) ShippingInstructions ShippingInstructionsTyp338_T SpecialInstructions VARCHAR2(2048 CHAR) LineItems LineItemsType345_T SQL> 4. Where does XML DB store the content of my XML documents ?mdrake-Oracle Sep 1, 2006 6:16 AM (in response to mdrake-Oracle)When a Schema-based XML document is loaded in the Oracle XML DB repository the content of the document can be stored in one of two places. If the document is correctly associated with an XML Schema then the content of the document will stored in the default table defined by the XML Schema. If the document is not associated with an XML schema then the content of the document will stored in the database schema owned by the XDB user. You can tell whether or not a document has been recognized as being associated with an XML schema by looking at the size of the document using WebDAV or FTP. If the size of the document is reported as 0 bytes then the content of the document has been stored in the default table. If the size of the document is reported as non-zero then the document has not been associated with an XML Schema. Note that when using WebDAV to view the size of the file the a newly loaded file may appear with a non-zero size until the contents of the folder are refreshed. When a file is loaded into the repository via the FTP, HTTP or WebDAV protcols of a resource is created using DBMS_XDB.createResource() XML DB peeks into the content of the document. If the content of the file is not recognized as XML the document is stored in the database schema owned by the XDB user. If the file contains XML, XML DB looks at the root tag of the document to see if includes either a schemaLocation attribute or a noNamespaceSchemaLocation attribute in the W3C XMLSchema-Instance namespace. If the root tag does not contain these attributes then the document is stored as non schema based XML. The content will stored in the database schema owned by the XDB user. If the XML document contains a schemaLocation attribute or a noNamespaceSchemaLocation attribute XML DB attempts to match the document against the list of registered XML Schemas available to the user uploading the document. If a match is found XML DB next matches the root element of the document againt the set of global elements defined by the XML schema and and uses the value of the xdb:defaultTable and xdb:defaultTableSchema attributes to determine which table the content should be stored in. If XML DB is unable to match the document against the list of known XML schemas the content of the document is stored in the database schema owned by the XDB user. 5. Why is my document not accessable via the default table ?mdrake-Oracle Sep 1, 2006 6:30 AM (in response to mdrake-Oracle)There are two reasons why the content of a Schema Based XML document is not accessable via deafult table. The first is that the document is protected with an ACL that forbids the user searching for the document from seeing it. The second is that the document was not recognized as being a member of the class defined by the XML Schema and so was stored as non-schema-based in the XML DB repository rather than as schema based XML in the default table. 6. Why was the XML document not recognized as an instance of the XML Schema ?mdrake-Oracle Sep 27, 2006 7:18 PM (in response to mdrake-Oracle)The methodolgy used by XML DB to match instance documents to XML schemas is based on a mechansim defined by the W3C XML schema standard. The W3C standard uses the XMLSchema-instance namespace to add schema specific information to instance documents. The XMLSchema-instance namespace defines two attibutes that can be used to identify which XML Schema a document is associated with. These attributes are the noNamespaceSchemaLocation attribute and the schemaLocation attribute. The noNamespaceSchemaLocation attribute is used in conjunction with XML Schemas that do not include a targetNamespace declaration. The schemaLocation attribute is used in conjunction with XML Schemas that declare a targetNamespace The noNamspaceSchemaLocation attribute is used to supply the Schema Location Hint of the XML schema the document is associated with. For XML DB to recognize that the document is a member of the class defined the XML schema the Schema Location Hint must be an exact for the schemaURL that was used tor register the XML schema with XML DB. The schemaLocation attribute is used to supply a Schema Location Hint for each namespace used by the instance document. The attribute consists of a set of namespace location mappings. A namespace location mapping consists of a namespace and the Schema Location Hint for the XML Schema that declares that namespace. An XML Document is considered to be instance of the XML schema if the Schema Location Hint matches the URL of a registered XML Schema that declares the namespace associated with the Schema Location Hint as it's targetNamespace. For example First, the instance document must declare the XMLSchema-instance namespace eg The XMLSchema-instance namespace is used to associated the XML document with an XML schema. It does by supplying a "Schema Location Hint" for the target XML schema. The Schema Location Hint is typically the authoritive location for the XML Schema. When using XML DB the Schema Location Hint must match the URL used to register the XML schema with XML DB when working with XML DB. xmlns:xsi="" The manner is which the schema location hint is supplied depends on hether or not the xml schema contains a targetNamespace declaration If a targetNamespace is defined then it the instance must include the schemaLocation attribute. The schemaLocation attribute must contain a mapping between the targetNamespace and the Schema Location Hint in the form "namespace schemaLocationHint". If the XML schema declares a target namespace such as targetNamespace="" and the Schema Location Hint is "gmlpacket.xsd" then you use the schemaLocation attribute. It will look like this. If the XML schema does not declare a target namespace then you the noNamespaceSchemaLocation attribute. It will look like this.. xsi:schemaLocation=" gmlpacket.xsd" xsi:noNamespaceSchemaLocation="gmlpacket.xsd"
https://community.oracle.com/thread/421093?tstart=0
CC-MAIN-2016-44
refinedweb
1,605
57.91
Hi All, I’m designing a time-series data analysis application using Dash+Plotly. Here’s my setup version(s) : dash - 1.14.0 plotly - 4.9.0 dash_html_components - 1.0.3 dash_core_components - 1.10.2 I have a column which has nearly 40-70 unique categories. I want to create a scatter plot where I need a trace for each category. I tried sub-dividing the data based on category, and tried adding trace for each of them. Basically, a single figure with 40-70 traces. But, the application gets crashed if I do this. I know there is a way by which we can color map the markers, but I don’t know how. Plus, the no of entries in this column changes dynamically, depending on the input data. Can someone help me how I could achieve this? Here is a small snippet of my code: import pandas as pd import numpy as np import plotly.graph_objects as go fig = go.Figure() df = pd.read_csv(r'data.csv') colors = df.Colors.unique().tolist() # Categorical column which has 40-70 unique values for c in colors: temp = df[df.TCID.isin([c])] fig.add_trace( go.Scatter( x = df['X'], y = df['Y'], mode = 'markers', name = thread, marker = dict( size=7, line = dict( width = 1, color = 'DarkSlateGrey') ) ) ) fig.update_layout(title_text = 'Sample Plot') fig.write_html('plot.html', auto_open=True)
https://community.plotly.com/t/application-hangs-when-adding-40-traces/43614
CC-MAIN-2021-49
refinedweb
228
62.04
Agenda See also: IRC log Richard: respond on our behalf to CSS on ruby issue <scribe> in progress Dan: update draft to support option C for specifying preferences in ws-i18n Richard: while awaiting comments, port the document to W3C WG Note format and prepare for publication as a First Public Working Draft. <r12a> basically done, some tweaks remain link to follow all, to review and comment on public-i18n-core mailing list, with a view to agreeing to move forward with publication as FPWD on 22nd during telecon david: doing a review of MS WebExpressions3 ... actually generates stds compliant richard: above is the link to the note-ified bidi document ... Najib joined via IRC from Rabat (note to other attendees)... Welcome Najib richard: discussion on html list ... hixie wants to change <meta ... content-language> to have only one language ... not how it works now ... hixie thinks they use it differently ... summary of various events as in email addison: was surprised by hixie's latest reaction andrew: he believes that older docs should be able to pass at html5 ... change to <meta> would go against that richard: this is meta information as opposed to attribute based information ... introduces more confusion, since the syntax changes ... and blurs the meta data usage ... will WG support comments andrew: supports it david: think the inconsistency argument belongs also addison: I support it <scribe> ACTION: richard: send WG response on Issue-88 based on your email to Hixie and HTML-WG [recorded in] richard: proposed edited rec through process ... domain leader: they reference RFC 3066 (or its successor) <r12a> [BCP47] <r12a> Tags for Identifying Languages, A. Phillips and M. Davis, Editors, September 2006. <r12a> Available at richard: would make sense as PER to change to BCP 47 addison: that's the old date ... point to 5646 <r12a> note format of document, link above today... start moving to FPWD scribe: we gave WG a week to review ... after FPWD, wide announcement and receive comments addison: separate comments list or winter? richard: discussing with Aharon ... need to move to w3c list to support process ... thinking of using winter ... should there be separate IG list, now or later? <Aharon> About 40 people on my list. andrew: ask the 40 people what they prefer? <Aharon> Good idea - will ask. addison: it is proposed that we publish as FPWD ... are there any objections? anything we need to do first? andrew: may need to do some things first ... trying to work out which part are initiated by consistency/bugs in browsers ... which are just good ideas ... and which are bad design workarounds ... and then some things where I think "should it work that way?" ... useful to publish wide to get more comments richard: not necessary to be polished andrew: yes, publish, but personally wondering if we'd be better off filing bugs; some things more developer stuff ... rahter than things to fix in html ... but some things need fixing in html5 ... need to be more distinct about which things go where richard: think its all good stuff ... and good to get into html5 spec ... tell implementers what they ought to do but trying to ensure they actually do it via html5 ... otherwise vendors may not take action or may "innovate" andrew: parts for developers should be more explicitly written for that audience addison: useful to send explicit comment fantasai: sent most of comments in via email ... one about algorithm and conformance implementations ... and the general confusion about having more than one ... and bdi not neutral <scribe> chair: anyone against publishing as FPWD fantasai: support publication andrew: support moving forward addison: +1 aharon: safely assume I do too david: +1 <najib> +1 RESOLVED: publish bidi document as FPWD richard: bring up idea about a second document more squarely targetted at CSS aharon: interested in collaborating on it addison: information for authors, perhaps tutorials? or what? aharon: meant to help browser vendors implement better ... some things missing are ... control over kind of numerals to use <fantasai> that would be a text-transform value (such as using language to do numeric shaping) aharon: left-right commonly used instead of start-end <najib> There is a Bidi problem with CSS, display <najib> Sorry <najib> There is a Bidi problem with CSS, display inline. aharon: just adding start-end doesn't solve problem, since ancestor may affect it ... float start or end depends on context, padding, etc. ... some tools exist to mirror a CSS file offline ... should not require an offline tool to do it ... explicit control over scroll bar location fantasai: css wg has carefully avoided scroll bar positioning ... selectors based on direction of element ... would have to do that at selectors matching time ... performance impact could be large ... start/end properties has been discussed but not considered urgent ... no objection for stuff like float ... but significant cascading complications for stuff like padding (and vast number thereof) ... problems (rather than features) should be done sooner rather than later ... as CSS2.1 wants to be done ... do in next month or so r12a: sounds like a lot to be done, but needs more thought ... a discuss right now on CSS WG list on start-end ... @ f2f about 18months ago floated to CSS FTF WG mtg ... css folks felt people might not need that? ... describe what you want to be able to do and make case for that it would help a lot ... CSS needs to hear from field users <Zakim> najib, you wanted to ask if scroll bar is matter of GUI, rather than style fantasai: kind of affects both ... if author knows more content will appear, want to force scroll bars (or hide them) ... to prevent layout jumping r12a: default behavior part of GUI ... but maybe override that?? ... text transform is like that too? fantasai: send any problems to CSS 2.1 right away ... and then do feature requests <Aharon> Would it be possible for fantasai to provide links to existing work and discussions on relevant topics? r12a: real showstoppers ... so that css can close down fantasai: be sure that all 2.1 issues get to them in next month or two <fantasai> Issues that impact HTML may also impact CSS <Aharon> Thank you! <fantasai> CSS can't be inconsistent with HTML <fantasai> so, e.g., if white space behavior is changed for HTML it has to be changed for CSS too fantasai: think a document like the html focused document would be very useful Aharon: can fantasai help me identify what should be directed to CSS? fantasai: whitespace, bullets, ... anything that doesn't pertain to markup rather than html aharon: will make first pass to identify CSS issues ... so if you can proofread, that would be really great <fantasai> IRC comments from Najib, moved from time period during previous topic, but related to this one <najib> About the bidi proposal. <najib> Happy to see it as WG proposal. <najib> At a first reading, I have some remarks about the examples given in section 2.1 <najib> I think we can summarize them into more simple problem statement. <najib> I'm going to send an email about it. <najib> I'll send other feedbacks later on. <najib> That's all. addison: great! thank you. look forward to the email. addison to attend too? it's at 6AM richard: discussed with ITS ... could drop namespace as long as behavior is there ... e.g. span and dir rather than its:span ... showed me example with both dir and its:dir <scribe> ACTION: richard: publish FPWD of Bidi WG-Note and complete all transreq requirements pertaining thereto [recorded in]
http://www.w3.org/2010/02/24-core-minutes.html
CC-MAIN-2015-11
refinedweb
1,261
66.84
Please meet Maarten Balliauw, JetBrains Technology Evangelist for PHP and .Net products. 1. Hi Maarten, we would like to welcome you to JetBrains and thank you for taking the time to speak with us. We know you drink lots of coffee every day and Visual Basic 4 was the first programming language for you, but for those who don’t already know you, can you tell us a bit more about yourself? Now that I think about it, my first programming language probably was AMOS Basic on the Amiga 1200. Apart from that, I’ve been doing web development for a while, started with PHP when I was 16 and moved over to ASP.NET and later ASP.NET MVC but kept doing PHP as well. Both languages and stacks have their disadvantages but also their merits. And it’s fun to combine! I’ve been doing all of that, first freelance and then with RealDolmen where I’ve had a lot of opportunities to work in this area with customers. Lately I’m really interested in the Windows Azure cloud platform and everything that has to do with HTTP APIs. On the personal side, I live together with my wife near Antwerp, Belgium. A great place to live and work! 2. Why did you decide to join JetBrains, and what will you be working on? To be honest, I was quite happy at my previous company, RealDolmen. Talking with Hadi Hariri gave me a very positive impression of JetBrains and when an opportunity to become an evangelist came by, I decided to jump the bandwagon. My main focus areas are going to be .NET and PHP. I’ll be working on spreading the word about all JetBrains products available in those languages such as ReSharper, dotTrace, dotPeek and PhpStorm. I’ll also be bugging JetBrains developers with feature requests as well, originating from community feedback and from working with those products myself. Expect blog posts, screencasts and such on all these products! And if you have feedback, bug me so I can bug others 3. What areas of PHP and .NET are you most interested in? My history with PHP covers a number of things. I’ve started as a script kiddie developing simple web applications, then I enjoyed building things with Zend Framework. When I started at RealDolmen, my world was mostly Microsoft based, sometimes with a layer of PHP on top. That’s where my interest in interoperability came to life. I’ve started building PHPExcel (). Then came PHPLinq (), my take on having .NET’s language integrated queries in PHP, PHPMEF and the official Windows Azure SDK for PHP. On the .NET side, the web stack and the cloud stack are my favorites. ASP.NET MVC and ASP.NET Web API, Windows Azure, and all combinations possible. Check GitHub and CodePlex and you’ll find some projects I either started working on or am contributing to. 4. What do you like most in JetBrains tools for .NET developers? The fact that those tools provide functionality that does not exist out of the box, like disassembling some assembly to find out why it’s behaving in a way you didn’t expect. dotPeek is great at doing that! These tools also make existing functionality better. Yes, there’s IntelliSense in Visual Studio, but ReSharper does a great job at improving it with things like autocompletion of properties on dynamic types, for example. Tools like YouTrack are great as well. Over the past year I find that my development is becoming more and more keyboard-oriented. The fact that I can assign a work item to myself, estimate it at one hour and move it to an “in progress” state by simply typing “assignee me estimation 1h in progress” is astonishingly fast and makes the issue tracker not come in my way of working on a problem. 5. What trends do you see in PHP as a language? Where is it heading? PHP has come a long way. I recall myself thinking “why are there no namespaces?” in a not-too-distant past. The past 2 minor versions though have brought tons of new language features, like namespaces and traits. The garbage collector has improved and now handles circular references way better than before (something that bit me a lot when building PHPExcel). The language has grown more mature, more people are contributing to it. Whether in the form of code or ideas, but it’s getting a lot more attention. I really like the direction it is going! 6. Some PHP developers don’t believe they need an IDE for PHP, i.e. you can be just as productive with a text editor. What is your opinion about it? Well… That’s a difficult one. I understand some people when they say they can do their job in VIM, and they are right. If you see them work, all I can say is they are fast and good at what they do. But even though they use all kinds of automation and macros, I see them doing a lot of things manually or by running additional bits and pieces on their code that come out of the box in an IDE. Why is that? Because IDEs tend to be built around “knowing” the language. They analyze your project and dependencies and try to figure out how everything fits together. Things like refactoring become a lot easier that way. 7. What are your hobbies and what do you like to do in your free time? I love working on open source projects and on some side projects in my spare time. Next to that, I’ve started brewing my own beer. It’s a fun thing to do as it’s different from my day-to-day activities. And if you do it right, you’re rewarded with a nice beer to drink with family and friends. Which brings me to the next thing I love to do: being with family. You don’t get to choose them but I’m lucky to have a great wife, great parents and a great brother who I like being with. They all like beer, so that combines with my new brewing hobby. I also ski and love to do a hike in the woods as well. 8. Thank you for your time and we look forward to the positive and productive work as a Technical Evangelist at JetBrains. Are there any upcoming events, books or topics that you would like to mention? The next event I’ll be speaking at is the Warm Crocodile Conference in Denmark. Organized by a great guy and a lot of good speakers so I’m really looking forward to going there. The last book I’ve worked on was Pro NuGet which I wrote with a friend. We’re considering writing a vNext of that one. Apart from that, keep an eye on my Blog, my Twitter and of course everything that comes out of JetBrains. Pingback: JetBrains is Going to the “City of Light” for TechDays France | JetBrains Company Blog Pingback: JetBrains .NET Tools Blog » JetBrains is Going to the “City of Light” for TechDays France Thank you for sharing your thoughts. I really appreciate your efforts and I am waiting for your next write ups thank you once again. Do you write/have any other blogs or have any plans for another blog?
http://blog.jetbrains.com/blog/2013/01/03/interview-with-jetbrains-evangelist-maarten-balliauw/
CC-MAIN-2015-27
refinedweb
1,240
73.88
The most powerful way to customize the user-facing content of your helpdesk is to use Deskpro’s Email templates system. You can edit templates to change: You can also add custom email templates. Templates can include phrases: short, re-usable pieces of text, used to store something like the user greeting at the beginning of an email, or the name of a section of the portal. A major advantage of storing text using phrases is that you can include the same phrase in many templates. Deskpro’s multi-language support is also based around phrases. You can access Useful template variables from a template, enabling you to retrieve information about the user who is logged in, the ticket they’re currently viewing, etc., and display that back to the user. You’ll need a basic understanding of HTML to edit templates. If you want to customize the portal design, you’ll need a more advanced knowledge of HTML/CSS. Here’s an example of how to customize helpdesk content by editing a template and using phrases and variables. Suppose you decide you want to edit the content of the automatic email users receive when they register an account. By default the email looks something like this: As you’d expect, “Example User” is automatically replaced with the name of the user who’s receiving the email. We’ll see how this happens later. Go to Tickets > Email Templates to find the corresponding template. Look under User Email Templates and you will see the Welcome Email template. Click on the template to open the template editor window. You’ll see that the template contains code for the Email Subject and Email Body. Let’s look at the Email Body: {{ phrase('user.emails.greeting') }} <br /><br /> {{ phrase('user.emails.register-welcome') }}<br/> <a href="{{ url_full('user') }}">{{ url_full('user') }}</a> {% if not person.is_agent_confirmed %} <br /><br /> {{ phrase('user.emails.register-agent-validation') }} {% endif %} You probably recognize that some of this is HTML markup: <br /> for line breaks and <a href> to make a link. The other parts, such as {{ phrase('user.emails.greeting') }} and {% if not person.is_agent_confirmed %} ... {% endif %}, are the template syntax. {{ phrase('X') }} is the syntax to include a phrase in the email. You can look up phrases by going to Settings > Languages. Under Installed Languages, click on your default language, then Edit Phrases. Under User Interface Phrases, click on Emails to see email phrases. The default content for user.emails.greeting is: Dear {{to_name}}, When the email is sent, the content of the phrase is inserted into the email. Since the phrase contains the {{to_name}} variable, when the email is sent, the template system replaces this with the variable content, which is the name of the user. If the email is being sent in another language, the translated version of user.emails.greeting from the corresponding language pack gets inserted instead. For example, here’s the Spanish translation: Let’s suppose your marketing department has decided that user emails should start with “Hello ...” rather than “Dear ...” You could replace {{ phrase('user.emails.greeting') }} with Hello {{to_name}}, but that would only change the greeting for this email type, and it wouldn’t be translated into other languages. A better solution is to go to Setup > Languages and use Edit Phrases to enter and save a custom version of the phrase. All the other email templates which use the phrase will now use the custom version. You can also use Edit Phrases to enter a custom translation for any other languages you have installed. Sometimes, instead of changing the existing phrases on your helpdesk, you may need to create a new phrase. To do this, go to Setup > Languages and click on All Custom Phrases then click Add Custom Phrase button. You will be prompted to choose a name for the phrase (custom phrase names are always prefixed with custom.). Note that the Default and Translation sections for a custom phrase are non-functional. If your helpdesk has multiple languages installed, to translate your custom phrase, you must create it in each language you have, making sure to use the same name for each version. See How do I translate a custom phrase? for details. Warning You can’t include variables directly in custom phrases. You must use the method described in Variables in custom phrases.
https://support.deskpro.com/en/guides/admin-guide/editing-templates/introducing-templates
CC-MAIN-2019-22
refinedweb
725
65.93
The Bible is the world’s best-selling and most widely distributed book. Its name comes from the Koine Greek “Ta Biblia”, which means “the books”. It’s a collection of 66 books written by around 40 authors over approximately 1,500 years. Originally there was no division of chapters and verses. But in order to facilitate studying and referencing specific parts of the text, these divisions were developed. In around 1227, Stephen Langton, an Archbishop of Canterbury, divided the Bible in chapters. In 1553, Robert Estienne published the first Bible with his verse system, which is the one used until today. Cross references… In order to have a better visualization of your data, you may want to gather everything in one place, creating a dashboard. Plotly Express is a tool that will let you to create awesome interactive graphs easily and, with Plotly Dash, you can use them to compose a dashboard. In this article, I’ll show you how to create two graphs and put them together in a simple dashboard. We’ll be using COVID-19 data around the world as an example. The first graph we’ll create is a scatter plot on a world map showing the evolution of cases through the weeks… WhatsApp is a messaging app created by Brian Acton and Jan Koum in 2009. Currently, it’s owned by Facebook, that acquired the app in 2014. In Brazil, WhatsApp is almost ubiquitous, installed on 99% of Brazilian smartphones. Last month, Mark Zuckerberg announced that WhatsApp is delivering roughly 100 billion messages a day. With this huge amount of data being created everyday, how can we structure everything in order to extract insights from it? There’s a interesting GitHub repository by kurasaiteja that shows a path on how to achieve this objective. In this article, I’ll be presenting what you can find… How much and how to tax is a subject that divides opinions. In a world where many starve to death, wealth tax seems to be a viable option to decrease social inequality and distribute the income for many people. In this article, we’ll visualize how taxes on goods and services correlates with social inequality. Let’s start gathering the data, we’ll get them from Global Revenue Statistics Database and Standardized World Income Inequality Database. The first step is to create a dataframe with data from both databases. import pandas as pd import numpy as np import matplotlib.pyplot as pltglobal_revenue =… An important way to prevent the spread of COVID-19 is social distancing. This strategy was followed all around the world, Brazil included. However, the distancing is being weakened over time, which made me think: do states with better education follow the distancing longer? At first, this question may look nonsense, but having in mind that the poor knowledge of how viruses work and the spread of fake news make people care less about preventive measures, maybe states that offer a better education will have more aware people. Of course things aren’t so simple, there are many other aspects that influence… IT Student & Software Developer | LinkedIn:
https://edusrmt.medium.com/?source=post_internal_links---------6----------------------------
CC-MAIN-2021-21
refinedweb
520
61.67
Dagger Actions Actions are the basic building block of the Dagger platform. An action encapsulates an arbitrarily complex automation into a simple software component that can be safely shared, and repeatably executed by any Dagger engine. Actions can be executed directly with dagger do, or integrated as a component of a more complex action. There are two types of actions: core actions and composite actions. Core Actions Core Actions are primitives implemented by the Dagger Engine itself. They can be combined into higher-level composite actions. Their definitions can be imported in the dagger.io/dagger/core package. To learn more about core actions, see the core action reference. Composite Actions Composite Actions are actions made of other actions. Dagger supports arbitrary nesting of actions, so a composite action can be assembled from any combination of core and composite actions. One consequence of arbitrary nesting is that Dagger doesn't need to distinguish between "pipelines" and "steps": everything is an action. Some actions are just more complex and powerful than others. This is a defining feature of Dagger. Lifecycle of an Action A composite action's lifecycle has 4 stages: - Definition - Integration - Discovery - Execution Definition A new action is defined in a declarative template called a CUE definition. This definition describes the action's inputs, outputs, sub-actions, and the wiring between them. Here is an example of a simple action definition: package main import ( "dagger.io/dagger" "dagger.io/dagger/core" ) // Write a greeting to a file, and add it to a directory #AddHello: { // The input directory dir: dagger.#FS // The name of the person to greet name: string | *"world" write: core.#WriteFile & { input: dir path: "hello-\(name).txt" contents: "hello, \(name)!" } // The directory with greeting message added result: write.output } Note that this action includes one sub-action: core.#WriteFile. An action can incorporate any number of sub-actions. Also note the free-form structure: an action definition is not structured by a rigid schema. It is simply a CUE struct with fields of various types. - "inputs" are simply fields which are not complete, and therefore can receive an external value at integration. For example, dirand nameare inputs. - "outputs" are simply fields which produce a value that can be referenced externally at integration. For example, resultis an output. - "sub-actions" are simply fields which contain another action definition. For example, writeis a sub-action. There are no constraints to an action's field names or types. Integration Action definitions cannot be executed directly: they must be integrated into a plan. A plan is an execution context for actions. It specifies: - What actions to present to the end user - Dependencies between those tasks, if any - Interactions between the tasks and the client system, if any Actions are integrated into a plan by merging their CUE definition into the plan's CUE definition. Here is an example of a plan: package main import ( "dagger.io/dagger" ) dagger.#Plan & { // Say hello by writing to a file actions: hello: #AddHello & { dir: client.filesystem.".".read.contents } client: filesystem: ".": { read: contents: dagger.#FS write: contents: actions.hello.result } } Note that #AddHello was integrated directly into the plan, whereas core.#WriteFile was integrated indirectly, by virtue of being a sub-action of #AddHello. To learn more about the structure of a plan, see it all begins with a plan. Discovery Once integrated into a plan, actions can be discovered by end users, by using the familiar convention of usage messages: $ dagger do --help Execute a dagger action. Available Actions: hello Say hello by writing to a file Usage: dagger do [OPTIONS] ACTION [SUBACTION...] [flags] Flags: [...] Execution Once the end user has discovered the action that they need, they can execute it with dagger do. For example: dagger do hello
https://docs.dagger.io/1221/action/
CC-MAIN-2022-27
refinedweb
624
50.33
Overview Atlassian Sourcetree is a free Git and Mercurial client for Windows. Atlassian Sourcetree is a free Git and Mercurial client for Mac. LESS for Fantom LESS for Fantom wraps the LESS CSS language for easier integration into Fantom projects. The Fantom pod supports an programmer API, a command line interface, and a build::Task for integration into build pipelines. Installing fanr install -r less API If you simply want to compile LESS to CSS from Fantom, just use the API, which takes a LESS source string, and returns the output CSS string: css := Less { str=less }.toCss If you wish to use @import with the API method, you must use file references, so Less can resolve the imported files: css := Less { file=`example.less`.toFile }.toCss Command Line The CLI takes a source .less file and writes a target .css file: $ fan less foo.less bar.css Build Task To integrate LESS into a build script, simply add a new build target to invoke LessTask. If you'd like the LESS task to be part of the default target, simply override the existing BuildPod.compile target: class Build : BuildPod { new make() { podName = "example" summary = "Example Pod" version = Version("1.0") depends = ["sys 1.0", "less 1.1.5"] srcDirs = [`fan/`, `test/`] resDirs = [`res/css/`] } @Target { help = "Compile to pod file and associated natives" } override Void compile() { less super.compile } @Target { help = "Compile less to css" } virtual Void less() { LessTask(this).run } } By default the LessTask will look for .less source files under {scriptDir}/less/, and will write output CSS into {scriptDir}/res/css. The task will recursively find and write files with the matching directory structures. If you want to use a different source and/or output directory, just configure those fields on your LessTask: @Target { help = "Compile less to css" } virtual Void less() { LessTask(this) { srcDir = scriptDir + `some/dir/` outDir = scriptDir + `some/other/dir` }.run } Build Task and @HILLARY ATKINS When using LessTask, note that any file that is used as an @import in another file will be excluded from the CSS output. Which means if you wish to use a LESS file as both an import and an output CSS file, you will need to break the import content out into a separate file, and use a simple shell LESS file: import "base.less";
https://bitbucket.org/afrankvt/less
CC-MAIN-2018-51
refinedweb
387
71.75
#include <common/common.hh> A 3D mesh. Constructor. Destructor. Add a material to the mesh. Move the center of the mesh to the given coordinate. This will move all the vertices in all submeshes. Put all the data into flat arrays. Generate texture coordinates using spherical projection from center. Get AABB coordinate. Return the number of indices. Get a material. Get the number of materials. Get the index of material. Get the name of this mesh. Return the number of normals. Get the path which contains the mesh resource. Get the skeleton to which this mesh is attached. Get a child mesh. Get a child mesh by name. Get the number of children. Return the number of texture coordinates. Return the number of vertices. Return true if mesh is attached to a skeleton. Get the maximun X, Y, Z values. Get the minimum X, Y, Z values. Recalculate all the normals of each face defined by three indices. Scale all vertices by _factor. Set the name of this mesh. Set the path which contains the mesh resource. Scale all vertices by the _factor vector. Set the mesh skeleton. Move all vertices in all submeshes by _vec.
http://gazebosim.org/api/8.0.0/classgazebo_1_1common_1_1Mesh.html
CC-MAIN-2017-51
refinedweb
196
73.34
gatsby-recipe-storybook-js If you haven't tried Gatsby Recipes yet you really should! You can read a bit more about them here which will give you a better overview of how they work, but to summarize here's a quote from Gatsby founder Kyle Mathews Gatsby Recipes, a new tool to automate common site building tasks. To use recipes you must upgrade to the latest version of the Gatsby CLI npm install -g gatsby-cli@latest You can then use a recipe by running something similar to the below in your CLI gatsby recipes url-to-recipe/name-of-recipe.mdx The Storybook Problem The problem in a nutshell is that Gatsby does a few things when you run either gatsby develop or gatsby build that Storybook by default does not. To get the two playing nicely together we need a custom webpack config and it's precisely tasks like this where Gatsby Recipes can do the lions share of the work so you don't have to! 🦁 For instance, if you have any components that contain either a <Link /> imported from gatsby or any GraphQL queries you'll likely see an error not to dissimilar to this 👇 ERROR in ../node_modules/gatsby/cache-dir/gatsby-browser-entry.js 25:4Module parse failed: Unexpected token (25:4)You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See return (> <React.Fragment>| {finalData && render(finalData)}| {!finalData && <div>Loading (StaticQuery)</div>} - The first reason we get this error is because Gatsby exports as ES6 and Storybook by default expects all code to be ES5 / CommonJs. - The second reason is that the gatsby developand gatsby buildsteps remove GraphQL queries, Storybook by default does not. So that's the issue, but what can we do about fixing it? The solution Storybook allows us to write our own webpack config and there's some docs on that here but in short we need to push a new rule to the Storybook webpack config that will mimic the Gatsby build steps. This new rule will do the following things. - Match all js|jsxfile extensions - Transpile all ES6 code found within them to ES5 / CommonJs - Strip out any GraphQL queries - Add the react-docgenplugin (not essential but i like prop documentation) This doesn't sound like a huge job but if you're scared of Webpack like i am it's nice to be able to automate this step so you can just get on and develop your UI. So that's why i created this recipe. The recipe The complete steps of my recipe are as follows: - Install babel plugins and presets - Install babel-plugin-react-docgen - Install Storybook React NPM packages and addons - Create custom Storybook webpack config (main.js) for js|jsx - Configure Storybook / Gatsby Link settings (preview.js) - Create example Link stories - Add Storybook npm scripts to package.json You can test out my recipe gatsby-recipe-storybook-js-js.mdx The repo can be found here on GitHub and if you're interested in the Webpack config you can find that here in main.js Oh and before i forget, make sure you've run gatsby develop or gatsby build before you start Storybook, because we need the relevant GraphQL data to exist before we run Storybook. There's also a TypeScript flavor of this recipe, you can read about that here gatsby-recipe-storybook-ts Lemme know how you get on! @pauliescanlon
https://paulie.dev/posts/2020/04/gatsby-recipe-storybook-js/
CC-MAIN-2020-29
refinedweb
582
56.79
WRITE (ObjectScript) Synopsis WRITE:pc writeargument,... W:pc writeargument,... where writeargument can be: expression f *integer *-integer Arguments Description The WRITE command displays the specified output on the current I/O device. (To set the current I/O device, use the USE command, which sets the value of the $IO special variable.) WRITE has two forms: WRITE without an argument WRITE with arguments Argumentless WRITE Argumentless WRITE lists the names and values of all defined local variables. It does not list process-private globals, global variables, or special variables. It lists defined local variables one variable per line in the following format: varname1=value1 varname2=value2 Argumentless WRITE displays local variable values of all types as quoted strings. The exceptions are canonical numbers and object references. A canonical number is displayed without enclosing quotes. An object reference (OREF) is displayed as follows: myoref=<OBJECT REFERENCE>[1@%SQL.Statement]; a JSON array or JSON object is displayed as an object reference (OREF). Bit string values and List values are displayed as quoted strings with the data value displayed in encoded form. The display of numbers and numeric strings is shown in the following example: SET str="fred" SET num=+123.40 SET canonstr="456.7" SET noncanon1="789.0" SET noncanon2="+999" WRITE canonstr=456.7 noncanon1="789.0" noncanon2="+999" num=123.4 str="fred" Argumentless WRITE displays local variables in case-sensitive string collation order, as shown in the following WRITE output example: A="Apple" B="Banana" a="apple varieties" a1="macintosh" a10="winesap" a19="northern spy" a2="golden delicious" aa="crabapple varieties" Argumentless WRITE displays the subscripts of a local variable in subscript tree order, using numeric collation, as shown in the following WRITE output example: a(1)="United States" a(1,1)="Northeastern Region" a(1,1,1)="Maine" a(1,1,2)="New Hampshire" a(1,2)="Southeastern Region" a(1,2,1)="Florida" a(2)="Canada" a(2,1)="Maritime Provinces" a(10)="Argentina" Argumentless WRITE executes control characters, such as Formfeed ($CHAR(12)) and Backspace ($CHAR(8)). Therefore, local variables that define control characters would display as shown in the following example: SET name="fred" SET number=123 SET bell=$CHAR(7) SET formfeed=$CHAR(10) SET backspace=$CHAR(8) WRITE backspace=" bell="" formfeed=" " name="fred" number=123 Multiple backspaces display as follows, given a local variable named back: 1 backspace: back="; 2 backspaces: back""; 3 backspaces: bac"="; 4 backspaces: ba"k="; 5 backspaces: b"ck="; 6 backspaces: "ack="; 7 or more backspaces: "ack=". An argumentless WRITE must be separated by at least two blank spaces from a command following it on the same line. If the command that follows it is a WRITE with arguments, you must provide the WRITE with arguments with the appropriate line return f format control arguments. This is shown in the following example: SET myvar="fred" WRITE WRITE ; note two spaces following argumentless WRITE WRITE WRITE myvar ; formatting needed WRITE WRITE !,myvar ; formatting provided Argumentless WRITE listing can be interrupted by issuing a CTRL-C, generating an <INTERRUPT> error. You can use argumentless WRITE to display all defined local variables. You can use the $ORDER function to return a limited subset of the defined local variables. WRITE with Arguments WRITE can take a single writeargument or a comma-separated list of writearguments. A WRITE command can take any combination of expression, f, *integer, and *-integer arguments. WRITE expression displays the data value corresponding to the expression argument. An expression can be the name of a variable, a literal, or any expression that evaluates to a literal value. WRITE f provides any desired output formatting. Because the argumented form of WRITE provides no automatic formatting to separate argument values or indicate strings, expression values will display as a single string unless separated by f formatting. WRITE *integer displays the character represented by the integer code. WRITE *-integer provides device control operations. WRITE arguments are separated by commas. For example: WRITE "numbers",1,2,3 WRITE "letters","ABC" displays as: numbers123lettersABC Note that WRITE does not append a line return to the end of its output string. In order to separate WRITE outputs, you must explicitly specify f argument formatting characters, such as the line return (!) character. WRITE "numbers ",1,2,3,! WRITE "letters ","ABC" displays as: numbers 123 letters ABC Arguments pc An optional postconditional expression. InterSystems IRIS executes the command if the postconditional expression is true (evaluates to a nonzero numeric value). InterSystems IRIS does not execute the command if the postconditional expression is false (evaluates to zero). You can specify a postconditional expression for an argumentless WRITE or a WRITE with arguments. For further details, refer to Command Postconditional Expressions in Using ObjectScript. expression The value you wish to display. Most commonly this is either a literal (a quoted string or a numeric) or a variable. However, expression can be any valid ObjectScript expression, including literals, variables, arithmetic expressions, object methods, and object properties. For more information on expressions, see Using ObjectScript. An expression can be a variable of any type, including local variables, process-private globals, global variables, and special variables. Variables can be subscripted; WRITE only displays the value of the specified subscript node. Data values, whether specified as a literal or a variable, are displayed as follows: Character strings display without enclosing quotes. Some non-printing characters do not display: $CHAR 0, 1, 2, 14, 15, 28, 127. Other non-printing characters display as a placeholder character: $CHAR 3, 16–26. Control characters are executed: $CHAR 7–13, 27. For example, $CHAR(8) performs a backspace, $CHAR(11) performs a vertical tab. Numbers display in canonical form. Arithmetic operations are performed. Extended global references display as the value of the global, without indicating the namespace in which the global variable is defined. If you specify a nonexistent namespace, InterSystems IRIS issues a <NAMESPACE> error. If you specify a namespace for which you do not have privileges, InterSystems IRIS issues a <PROTECT> error, followed by the global name and database path, such as the following: <PROTECT> ^myglobal,c:\intersystems\IRIS\mgr\. ObjectScript List structured data displays in encoded form. InterSystems IRIS bitstrings display in encoded form. Object References display as the OREF value. For example, ##class(%SQL.Statement).%New() displays as the OREF 2@%SQL.Statement. A JSON dynamic object or a JSON dynamic array displays as an OREF value. For information on OREFs, see “OREF Basics” in Defining and Using Classes. Object methods and properties display the value of the property or the value returned by the method. The value returned by a Get method is the current value of the argument; the value returned by a Set method is the prior value of the argument. You can specify a multidimensional property with subscripts; specifying a non-multidimensional property with a subscript (or empty parentheses) results in an <OBJECT DISPATCH> error. %Status displays as either 1 (success), or a complex encoded failure status, the first character of which is 0. f A format control to position the output on the target device. You can specify any combination of format control characters without intervening commas, but you must use a comma to separate a format control from an expression. For example, when you issue the following WRITE to a terminal: WRITE #!!!?6,"Hello",!,"world!" The format controls position to the top of a new screen (#), then issue three line returns (!!!), then indent six columns (?6). The WRITE then displays the string Hello, performs a format control line return (!), then displays the string world!. Note that the line return repositions to column 1; thus in this example, Hello is displayed indented, but world! is not. Format control characters cannot be used with an argumentless WRITE. For further details, see Using Format Controls with WRITE . *integer The *integer argument allows you to use a positive integer code to write a character to the current device. It consists of an asterisk followed by any valid ObjectScript expression that evaluates to a positive integer that corresponds to a character. The *integer argument may correspond to a printable character or a control character. An integer in the range of 0 through 255 evaluates to the corresponding 8-bit ASCII character. An integer in the range of 256 through 65534 evaluates to the corresponding 16-bit Unicode character. As shown in the following example, *integer can specify an integer code, or specify an expression that resolves to an integer code. The following examples all return the word “touché”: WRITE !,"touch",*233 WRITE !,*67,*97,*99,*104,*233 SET accent=233 WRITE !,"touch",*accent ; variables are evaluated WRITE !,"touch",*232+1 ; arithmetic operations are evaluated WRITE !,"touch",*00233.999 ; fractional numbers are truncated to integers To write the name of the composer Anton Dvorak with the proper Czech accent marks, use: WRITE "Anton Dvo",*345,*225,"k" The integer resulting from the expression evaluation may correspond to a control character. Such characters are interpreted according to the target device. A *integer argument can be used to insert control characters (such as the form feed: *12) which govern the appearance of the display, or special characters such as *7, which rings the bell on a terminal. For example, if the current device is a terminal, the integers 0 through 30 are interpreted as ASCII control characters. The following commands send ASCII codes 7 and 12 to the terminal. WRITE *7 ; Sounds the bell WRITE *12 ; Form feed (blank line) Here’s an example combining expression arguments with *integer specifying the form feed character: WRITE "stepping",*12,"down",*12,"the",*12,"stairs" *integer and $X, $Y An integer expression does not change the $X and $Y special variables when writing to a terminal. Thus, WRITE "a" and WRITE $CHAR(97) both increment the column number value contained in $X, but WRITE *97 does not increment $X. You can issue a backspace (ASCII 8), a line feed (ASCII 10), or other control character without changing the $X and $Y values by using *integer. The following Terminal examples demonstrate this use of integer expressions. Backspace: WRITE $X,"/",$CHAR(8),$X ; displays: 01 WRITE $X,"/",*8,$X ; displays: 02 Linefeed: WRITE $Y,$CHAR(10),$Y /* displays: 1 2 */ WRITE $Y,*10,$Y /* displays: 4 4 */ For further details, see the $X and $Y special variables, and “Terminal I/O” in I/O Device Guide. *-integer An asterisk followed by a negative integer is a device control code. WRITE supports the following general device control codes: Input Buffer Controls The *-1 and *-10 controls are used for input from a terminal device. These controls clear the input buffer of any characters that have not yet been accepted by a READ command. The *-1 control clears the input buffer upon the next READ. The *-10 control clears the input buffer immediately. If there is a pending CTRL-C interrupt when WRITE *-1 or WRITE *-10 is invoked, WRITE dismisses this interrupt before clearing the input buffer. An input buffer holds characters as they arrive from the keyboard, even those the user types before the routine executes a READ command. In this way, the user can type-ahead the answers to questions even before the prompts appear on the screen. When the READ command takes characters from the buffer, InterSystems IRIS echoes them to the terminal so that questions and answers appear together. When a routine detects errors it may use the *-1 or *-10 control to delete these type-ahead answers. For further details, see Terminal I/O in the I/O Device Guide. For use of *-1 in TCP Client/Server Communication refer to the I/O Device Guide. Output Buffer Controls The *-3 control is used to flush data from an output buffer, forcing a write operation on the physical device. Thus it first flushes data from the device buffer to the operating system I/O buffer, then forces the operating system to flush its I/O buffer to the physical device. This control is commonly used when forcing an immediate write to a sequential file on disk. *-3 is supported on Windows and UNIX platforms. On other operating system platforms it is a no-op. For use of *-3 in TCP Client/Server Communication refer to the I/O Device Guide. Examples In the following example, the WRITE command sends the current value in variable var1 to the current output device. SET var1="hello world" WRITE var1 In the following example, both WRITE commands display the Unicode character for pi. The first uses the $CHAR function, the second a *integer argument: WRITE !,$CHAR(960) WRITE !,*960 The following example writes first name and last name values along with an identifying text for each. The WRITE command combines multiple arguments on the same line. It is equivalent to the two WRITE commands in the example that follows it. The ! character is a format control that produces a line break. (Note that the ! line break character is still needed when the text is output by two different WRITE commands.) SET fname="Bertie" SET lname="Wooster" WRITE "First name: ",fname,!,"Last name: ",lname is equivalent to: SET fname="Bertie" SET lname="Wooster" WRITE "First name: ",fname,! WRITE "Last name: ",lname In the following example, assume that the current device is the user’s terminal. The READ command prompts the user for first name and last name and stores the input values in variables fname and lname, respectively. The WRITE command displays the values in fname and lname for the user’s confirmation. The string containing a space character (" ") is included to separate the output names. Test READ !,"First name: ",fname READ !,"Last name: ",lname WRITE !,fname," ",lname READ !,"Is this correct? (Y or N) ",check#1 IF "Nn"[check { GOTO Test } The following example writes the current values in the client(1,n) nodes. SetElementValues SET client(1,1)="Betty Smith" SET client(1,2)="123 Primrose Path" SET client(1,3)="Johnson City" SET client(1,4)="TN" DisplayElementValues SET n=1 WHILE $DATA(client(1,n)) { WRITE client(1,n),! SET n=n+1 } RETURN The following example writes the current value of an object instance property: SET myoref=##class(%SYS.NLS.Format).%New() WRITE myoref.MonthAbbr where myoref is the object reference (OREF), and MonthAbbr is the object property name. Note that dot syntax is used in object expressions; a dot is placed between the object reference and the object property name or object method name. The following example writes the value returned by the object method GetFormatItem(): SET myoref=##class(%SYS.NLS.Format).%New() WRITE myoref.GetFormatItem("MonthAbbr") The following example writes the value returned by the object method SetFormatItem(). Commonly, the value returned by a Set method is the prior value for the argument: SET myoref=##class(%SYS.NLS.Format).%New() SET oldval=myoref.GetFormatItem("MonthAbbr") WRITE myoref.SetFormatItem("MonthAbbr"," J F M A M J J A S O N D") WRITE myoref.GetFormatItem("MonthAbbr") WRITE myoref.SetFormatItem("MonthAbbr",oldval) WRITE myoref.GetFormatItem("MonthAbbr") A write command for objects can take an expression with cascading dot syntax, as shown in the following example: WRITE patient.Doctor.Hospital.Name In this example, the patient.Doctor object property references the Hospital object, which contains the Name property. Thus, this command writes the name of the hospital affiliated with the doctor of the specified patient. The same cascading dot syntax can be used with object methods. A write command for objects can be used with system-level methods, such as the following data type property method: WRITE patient.AdmitDateIsValid(date) In this example, the AdmitDateIsValid() property method returns its result for the current patient object. AdmitDateIsValid() is a boolean method for data type validation of the AdmitDate property. Thus, this command writes a 1 if the specified date is a valid date, and writes 0 if the specified date is not a valid date. Note that any object expression can be further specified by declaring the class or superclass to which the object reference refers. Thus, the above examples could also be written: WRITE ##class(Patient)patient.Doctor.Hospital.Name WRITE ##class(Patient)patient.AdmitDateIsValid(date) WRITE with $X and $Y A WRITE displays the characters resulting from the expression evaluation one at a time in left-to-right order. InterSystems IRIS records the current output position in the $X and $Y special variables, with $X defining the current column position and $Y defining the current row position. As each character is displayed, $X is incremented by one. In the following example, the WRITE command gives the column position after writing the 11–character string Hello world. WRITE "Hello world"," "_$X," is the column number" Note that writing a blank space between the displayed string and the $X value (," ",$X) would cause that blank space to increment $X before it is evaluated; but concatenating a blank space to $X (," "_$X) displays the blank space, but does not increment the value of $X before it is evaluated. Even using a concatenated blank, the display from $X or $Y does, of course, increment $X, as shown in the following example: WRITE $Y," "_$X WRITE $X," "_$Y In the first WRITE, the value of $X is incremented by the number of digits in the $Y value (which is probably not what you wanted). In the second WRITE, the value of $X is 0. With $X you can display the current column position during a WRITE command. To control the column position during a WRITE command, you can use the ? format control character. The ? format character is only meaningful when $X is at column 0. In the following WRITE commands, the ? performing indenting: WRITE ?5,"Hello world",! WRITE "Hello",!?5,"world" Using Format Controls with WRITE The f argument allows you to include any of the following format control characters. When used with output to the terminal, these controls determine where the output data appears on the screen. You can specify any combination of format control characters. ! Format Control Character Advances one line and positions to column 0 ($Y is incremented by 1 and $X is set to 0). The actual control code sequence is device-dependent; it generally either ASCII 13 (RETURN), or ASCII 13 and ASCII 10 (LINE FEED). InterSystems IRIS does not perform an implicit new line sequence for WRITE with arguments. When writing to a terminal it is a good general practice to begin (or end) every WRITE command with a ! format control character. You can specify multiple ! format controls. For example, to advance five lines, WRITE !!!!!. You can combine ! format controls with other format controls. However, note that the following combinations, though permitted, are not in most cases meaningful: !# or !,# (advance one line, then advance to the top of a new screen, resetting $Y to 0) and ?5,! (indent by 5, then advance one line, undoing the increment). The combination ?5! is not legal. If the current device is a TCP device, ! does not output a RETURN and LINE FEED. Instead, it flushes any characters that remain in the buffer and sends them across the network to the target system. # Format Control Character Produces the same effect as sending the CR (ASCII 13) and FF (ASCII 12) characters to a pure ASCII device. (The exact behavior depends on the operating system type, device, and record format.) On a terminal, the # format control character clears the current screen and starts at the top of the new screen in column 0. ($Y and $X are reset to 0.) You can combine # format controls with other format controls. However, note that the following combinations, though permitted, are not in most cases meaningful: !# or !,# (advance one line, then advance to the top of a new screen, resetting $Y to 0) and ?5,# (indent by 5, then advance to the top of a new screen, undoing the increment). The combination ?5# is not legal. ?n Format Control Character This format control consists of a question mark (?) followed by an integer, or an expression that evaluates to an integer. It positions output at the nth column location (counting from column 0) and resets $X. If this integer is less than or equal to the current column location (n<$X), this format control has no effect. You can reference the $X special variable (current column) when setting a new column position. For example, ?$X+3. /mnemonic Format Control Character This format control consists of a slash (/) followed by a mnemonic keyword, and (optionally) a list parameters to be passed to the mnemonic. /mnemonic(param1,param2,...) InterSystems IRIS interprets mnemonic as an entry point name defined in the active mnemonic space. This format control is used to perform such device functions as positioning the cursor on a screen. If there is no active mnemonic space, an error results. A mnemonic may (or may not) require a parameter list. You can establish the active mnemonic space in either of the following ways: Go to the Management Portal, select System Administration, Configuration, Device Settings, IO Settings. View and edit the mnemonic space setting. Include the /mnemonic space parameter in the OPEN or USE command for the device. The following are some examples of mnemonic device functions: For further details on mnemonics, see the I/O Device Guide. Specifying a Sequence of Format Controls InterSystems IRIS allows you to specify a sequence of format controls and to intersperse format controls and expressions. When specifying a sequence of format controls it is not necessary to include the comma separator between them (though commas are permitted.) A comma separator is required to separate format controls from expressions. In the following example, the WRITE command advances the output by two lines and positions the first output character at the column location established by the input for the READ command. READ !,"Enter the number: ",num SET col=$X SET ans=num*num*num WRITE !!,"Its cube is: ",?col,ans Thus, the output column varies depending on the number of characters input for the READ. Commonly, format controls are specified as literal operands for each WRITE command. You cannot specify format controls using variables, because they will be parsed as strings rather than executable operands. If you wish to create a sequence of format controls and expressions to be used by multiple WRITE commands, you can use the #Define preprocessor directive to define a macro, as shown in the following example: #Define WriteMacro "IF YOU ARE SEEING THIS",!,"SOMETHING HAS GONE WRONG",##Continue $SYSTEM.Status.DisplayError($SYSTEM.Status.Error(x)),!! SET x=83 Module1 /* code */ WRITE $$$WriteMacro Module2 /* code */ WRITE $$$WriteMacro Escape Sequences with WRITE The WRITE command, like the READ command, provides support for escape sequences. Escape sequences are typically used in format and control operations. Their interpretation is specific to the current device type. To output an escape sequence, use the form: WRITE *27,"char" where *27 is the ASCII code for the escape character, and char is a literal string consisting of one or more control characters. The enclosing double quotes are required. For example, if the current device is a VT-100 compatible terminal, the following command erases all characters from the current cursor position to the end of the line. WRITE *27,"[2J" To provide device independence for a program that can run on multiple platforms, use the SET command at the start of the program to assign the necessary escape sequences to variables. In your program code, you can then reference the variables instead of the actual escape sequences. To adapt the program for a different platform, simply make the necessary changes to the escape sequences defined with the SET command. WRITE Compared with Other Write Commands For a comparison of WRITE with the ZWRITE, ZZDUMP, and ZZWRITE commands, refer to the Display (Write) Commands features tables in the “Commands” chapter of Using ObjectScript. See Also - - - - - - - Writing escape sequences for Terminal I/O and Interprocess Communications in the I/O Device Guide Terminal I/O in I/O Device Guide Sequential File I/O in I/O Device Guide The Spool Device in I/O Device Guide
https://docs.intersystems.com/irisforhealthlatest/csp/docbook/DocBook.UI.Page.cls?KEY=RCOS_CWRITE
CC-MAIN-2021-43
refinedweb
4,016
55.54
From: Trent Nelson (tnelson_at_[hidden]) Date: 2006-04-18 14:36:51 > Hi Trent, > can you provide me is a minimal example that reproduces this > problem? I've tried multiline description just now, and did not > get any assertion. > > I'd prefer to have a testcase for this bug before fixing it. The following option triggered the assertion error for me every time: desc.add_options() ("type,t", po::value<string>()->default_value("manual"), "startup type (\"auto\" or \"manual\") (--install only)")); If I reduced the description length such that it fit on a single line, the error went away for that particular option (only to crash on a different multiline option down the track). I was triggering the problem via '--help', which equated to 'cout << desc << endl;'. I've got a pretty vanilla VC++ Express 2005 installation, I haven't done anything out of the ordinary environment wise, which means all the new 'Standard C++ Library Security' features are enabled, so all the _SCL_SECURE_* macros are used. The following line: > 395: line_end = line_begin + line_length; Was being caught by the following macro on line 166 of 'C:\Program Files\Microsoft Visual Studio 8\VC\include\xstring': _Myt& __CLR_OR_THIS_CALL operator+=(difference_type _Off) { // increment by integer if (this->_Mycont != _IGNORE_MYCONT) { _SCL_SECURE_VALIDATE(this->_Mycont != NULL); _SCL_SECURE_VALIDATE_RANGE( _Myptr + _Off <= (((_Mystring *)this->_Mycont)->_Myptr() + ((_Mystring *)this->_Mycont)->_Mysize) && _Myptr + _Off >= ((_Mystring *)this->_Mycont)->_Myptr()); } _Myptr += _Off; return (*this); } Which makes sense, as it's checking we don't assign past the end of our underlying string, which is exactly what line 395 of options_descriptions.cpp does in multiline conditions. If you can't reproduce the assertion in VC8 with the option description I listed above, I'd suggest putting a breakpoint on the _SCL_SECURE_VALIDATE_RANGE() macro above. If it's not being hit (which is what I'd expect), then something in your environment is disabling the _SCL_SECURE* stuff. If it is being hit, yet it's not throwing an assertion, then we have a much more interesting situation on our hands ;-) Regards, Trent. -- Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk
https://lists.boost.org/Archives/boost/2006/04/103312.php
CC-MAIN-2022-40
refinedweb
357
52.8
Abalone | Importers of Abalone | Processors of Abalone | Wholesale Suppliers of Abalone | Seafood Agents for Abalone The list comprises companies importing and buying Greenlip Abalone, Blacklip Abalone, Pink Abalone, Red Abalone and White Abalone, Locos and other abalone species... Infinite Exports SINGAPORE - We are an exporter and importer of seafood in Singapore with our branch offices in Pacific Island. Lobster, abalone, dried sea cucumber.).. Lok Tin Seafood Ltd HONG KONG, CHINA - We are trading company mainly deal with seafood - Lobster, oyster, scampi, Alaska crab, crab, geoduck, abalone, fish, tiger prawns and sea cucumber. Champion Pacific Co. Ltd TAIWAN - We are the major seafood traders in Taiwan, our products are Pacific saury, illex squid, mackerel, oil fish, tuna loin, skipjack, blue shark, abalone imitation, mahi mahi and sailfish etc Wang Yip Shark's Fin Ltd HONG KONG, CHINA - Importers, exporters and wholesale suppliers of Abalone, fish maw, sea cucumber, sea cucumber skin, sharks fin, topshell... Yantai Ankang Foods Co., Ltd CHINA - We have been specialized in producing and exported frozen seafood for more than 10 years - Frozen squid products, tube, ring, carved flower, pineapple cut squid, breaded squid ring, T+T, Grade A abalone IQF, Frozen mackerel, Spanish mackerel, monkfish. Austar Korea KOREA - Importers from Australia for fresh tuna, abalone, lobster sea cucumber and prawn. China DSHC Foodstuff Co., Ltd CHINA - China based seafood processor and exporter, HACCP approved and FDA registered of canned pasteurized crabmeat, frozen surimi base, mackerel, sardine, horse mackerel, frog leg, abalone, tilapia Mi Peru Products Export SAC PERU - Import and export of Tuna, Peruvian Seebass,. Frank Mason & Associates AUSTRALIA - experienced Importers and Exporters of Seafood both Nationally and Internationally. Our speciality is to source items that others say are difficult or impossible to obtain. The range of products we trade are infinite. Southern Trading Pty. Ltd AUSTRALIA - a vertically integrated seafood processing and trading entity with more than 15 year extensive experience in the processing and exporting of quality Australian Seafood Wanpin Seafood Co. Ltd CHINA - We are importer of seafoods especially dried sea cucumber and abalone. Smith Trading Company PERU - We are producers and agents for seafood. We produce a number of items in Peru and neighbouring Chile and Ecuador. We provide quality control within these countries on behalf importers from abroad..... Anthony Seafoods LLC USA - We are an importer, exporter, distributor in Southern Florida. Salmon, Snappers, Grouper, kingfish, Shrimp, lobster Whole, lobster tails, abalone, Locos, Salmon bits and pieces, smoked salmon. Oceanwave International Corp. USA - We are specialized in frozen Baby Octopus, Cut Crab (wild), Three-spot crab, Squid Pineapple Cut, T+T, Sliced Octopus, Blue Mackerel, baby clam; Round scad, Frozen fresh Abalone... Topsea Enterprises HONG KONG, CHINA - We are importers and exporters of Dried marine products like shark fins, sea cucumber, fish maws, abalone, operculum, etc with our offices in Singapore, Dubai and India ..... Nisha International Pte Ltd SINGAPORE - We are a reputed company involved in import and export of all types frozen and dried shark fins, sea cucumbers, fishmaws, abalone, operculum.
http://www.trade-seafood.com/directory/seafood/abalone-importers.htm
CC-MAIN-2017-47
refinedweb
499
52.19
This is your resource to discuss support topics with your peers, and learn from each other. 01-09-2013 06:26 PM import bb.cascades 1.0 Page { Menu.definition: MenuDefinition { settingsAction: SettingsActionItem { onTriggered : { settingsSheet.open(); } } } attachedObjects: [ Sheet { id: settingsSheet content: Page { Button { text: "Close" onClicked: { settingsSheet.close() } } } } ] Container { layout: DockLayout {} Button { text: qsTr("Open") onClicked: settingsSheet.open(); } } } Solved! Go to Solution. 01-09-2013 06:34 PM please search on the threads in this forum - there are many threads covering this problem with gold sdk 01-09-2013 06:47 PM 01-09-2013 06:49 PM 01-09-2013 06:56 PM yes it is fixed - one of the reasons why I'm waiting for the next OS update ;-) 01-09-2013 07:32 PM
https://supportforums.blackberry.com/t5/Native-Development/Problem-with-MenuDefinition-and-Sheet/m-p/2086837
CC-MAIN-2016-50
refinedweb
127
67.15
[solved] MetaObject not referencing slots in derived class Hello everyone, I have created this program: base.h #ifndef BASE_H #define BASE_H #include <QObject> class Base : public QObject { Q_OBJECT public: Base(QObject *parent = nullptr): QObject(parent) {} }; #endif // BASE_H derived.h #ifndef DERIVED_H #define DERIVED_H #include "base.h" #include <QDebug> class Derived : public Base { public: Derived(QObject *parent = nullptr): Base(parent) {} void printSlots(){ for(int i = 0; i < metaObject()->methodCount(); i++) qDebug() << "Method:" << metaObject()->method(i).name(); } public slots: void slot1(){} }; #endif // DERIVED_H main.cpp #include <QCoreApplication> #include <QDebug> #include "derived.h" int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); Derived der(0); der.printSlots(); return 0; } The problem is that printSlots is not printing the "slot1" defined in derived. It only prints the slotname if I define "slot1" in the base class like this: base.h #ifndef BASE_H #define BASE_H #include <QObject> class Base : public QObject { Q_OBJECT public: Base(QObject *parent = nullptr): QObject(parent) {} public slots: virtual void slot1(){} }; #endif // BASE_H Is there anyway for the derived metaobject to see the slots defined in the derived class? thanks in advance, Xllr Hi I wonder if Derived class need Q_OBJECT too ? I often just wonder :) nah, i never used metaObject()->methodCount(); so was not 100% sure. @mrjj QObject::metaObject()returns the QMetaObjectassociated with the class (it's a static member, and the method provides virtualization over the class tree). If you don't have the Q_OBJECTmacro, there's no staticMetaObjectmember for the class, and consequently there's no metaObject()override, thus you get the parent's staticMetaObject(or the last class that had the macro). Like in this case, there can't be reflection for the derived type, because the needed meta information isn't generated (i.e. the missing macro); the best you get is the information for the parent class. Although, a need for this kind of introspection is rather rare ... @kshegunov ahh, i never really examined the macro. So thats how it works. Its very cool. I wish it was a pure c++ feature :) - kshegunov Qt Champions 2016 @mrjj Actually it is, somewhat. See here. The moc is needed to generate the meta information about the class, and the methods implementations, but for the static members or virtual functions declarations we have the good ol' preprocessor. ;) Resolved! I tried with the Q_OBJECT before but didn't rerun qmake... my fault :) and the errors I was obtaining made me think that maybe I could only use Q_OBJECT in classes directly derived from QObject, didn't think deeply about it. I am just experimenting with all the metadata classes for a property based system UI. Thanks a lot! Xllr @kshegunov oh. pretty neat. I just wish it could list members variables + type too :) I never used the Qt metasystem. (directly) Can moc be used to extract (plain) variables or does it has to be properties? Not sure, because I have been working with this for 2 days, but I think they must be properties. I just wish it could list members variables + type too Well, this wouldn't be very helpful, as you already know what member variables you have (and some of them may be private), or as in the usual case you only have a PIMPL pointer. You can however get the declared properties (such as declared with the Q_PROPERTYmacro) and this is used extensively, e.g. in QML. @kshegunov well it would be extremely helpful for creating boilerplate code for serialization and trace systems & module tests and all kind of code gen. Without adding ANYTHING to the source code as all serialization frameworks i have seen does. Maybe in c++32 :) well it would be extremely helpful for creating boilerplate code for serialization You have QDataStreamfor that. My suspicion is that moc's source will just explode if you start adding more and more parsing features. It already does a lot, e.g. RTTI without compiler RTTI and of course the signal-slot mechanism. If you need to wrap some boilerplate code you can always use a combination of the preprocessor with virtualization (similarly to what Qt does). I, personally, use a virtual stream operator for such things: class MyClass { friend QDataStream & operator << (QDataStream &, const MyClass &); friend QDataStream & operator >> (QDataStream &, MyClass &); protected: virtual bool serialize(QDataStream &) = 0; virtual bool deserialize(QDataStream &) = 0; } inline QDataStream & operator << (QDataStream & out, const MyClass & obj) { obj.serialize(out); return out; } inline QDataStream & operator >> (QDataStream & in, MyClass & obj) { obj.deserialize(in); return in; } @kshegunov Well I guess it then again boils down to out << var1 << var2 << var3 pr class which is what i would like NOT to have to ever write. :) So if could for ( all member vars : curvar) out << curvar; make me very happy. It seems Qt properties would allow such thing ? :) - kshegunov Qt Champions 2016 It seems Qt properties would allow such thing ? :) Yes, you can list them, but then again you have to declare them with Q_PROPERTY, and also you might want to save internal data that's not exposed through a property ... which could pose a significant problem. I prefer the mentioned method, because I can delegate to the parent. Consider the following example: class MyClassImpl : public MyClass { // ... protected: bool serialize(QDataStream & out) override { out << x; return true; } bool deserialize(QDataStream & in) override { in >> x; return true; } private: int x; } class MyDerivedClassImpl : public MyClassImpl { // ... protected: bool serialize(QDataStream & out) override { MyClassImpl::serialize(out); out << y << str; return true; } bool deserialize(QDataStream & in) override { MyClassImpl::deserialize(in); out >> y >> str; return true; } private: double y; QString str; } @kshegunov Yeah, 50% is not Qt enabled so would be an issue. Im just daydreaming :) Hmm, that is actually neat.
https://forum.qt.io/topic/70351/solved-metaobject-not-referencing-slots-in-derived-class/12
CC-MAIN-2017-43
refinedweb
938
54.32
0 hey guys, i have a project due tomorrow on recursion. the task was to write a recursive program that prints the value of fibonacci numbers and the number of calls made. i wrote the program and it returns the value at the end just fine, but i have been unable to put in a counter to keep track of the calls without different errors. can anybody pleasee help? also, the second part of the project involves memoization, making an array and storing the values that have been calculated already. the program will then look up if the values are stored and return them, it too should have a counter. heres the code import java.util.Scanner; public class Fib { public static void main(String[] args) { int fib; int n; Scanner scan = new Scanner(System.in); System.out.println("input a number"); n = scan.nextInt(); System.out.println("result: " + calcFib(n) + " calls: "); } int count = 0; public static int calcFib (int n) { if (n<2) { int ans = n; return ans; } else { int ans = calcFib(n-1) + calcFib(n-2); return ans; } } } Edited 3 Years Ago by mike_2000_17: Fixed formatting
https://www.daniweb.com/programming/software-development/threads/107815/helpp-recursion
CC-MAIN-2016-50
refinedweb
188
62.68
How To Save Feral Cats and Stop Overpopulation With TNR Ranked #258 in Animals, #6,767 overall Here's how to stop killing Feral Cats and save birds at the same time. ng TNR programs. Millions of feral cats are killed in shelters every year in the United States. TNR (trap-neuter-return) is a program that is practiced throughout the world to save these cats, allowing them to live out their lives -- not killed because they're considered homeless. This lens is dedicated to Tara -- the little cat shown here -- a feral cat that stole our hearts. I'll share with you Tara's story. Check out the wonderful pictures I have of her and other feral cats I've met and come back as I'll add more. I'll also include links to organizations and resource materials on both sides of the issue. I am 100 percent for TNR, however, I'll give you the arguments from both sides of the issue so you can make up your own mind. P.S. The term neutered is used for both males and females, although the term spay is usually used for females. If you love cats and want more information about anything from behavior modification to breeds, ear mites to ticks or anything to do with cats, check out my Frankster aka Cat-Woman lensography that lists all of my lenses, blogs and websites about cats. February 24,2009! Beautiful Pictures Of Feral Cats on Flickr As Up Close And Personal As A Feral Cat Gets Here are pictures of feral cats found on campuses and other locations. They look like any other domestic cat, however, they do not trust people. And, heck, it's hard to blame them! Please vote for your favorites. Add any other pictures of feral cats. And come back to see more and vote. What Is TNR? TNR stands for Trap, Neuter and Return. It refers to using humane traps to trap feral cats, taking them to a shelter or mobile facilty and having them neutered (sterilized) and vaccinated. After they have been neutered, the cat is returned to their home (where they were trapped). Trap-Neuter-Return (TNR) method, in which entire colonies of cats are trapped, vaccinated, and sterilized by a veterinarian works extremely well to curb the numbers of unwanted, feral cats. The right ear of the feral cat is eartipped (cut off) so that you can know which has already been neutered so if they wind up in another trap they can be released immediately. Homes are found for young kittens, who can be tamed. Healthy adults are returned outdoors, where volunteers feed and look after them for the remainder of their lives. Simply put, TNR is the most humane and cost effective way to control the feral cat population. If You Buy Anything From This Lens... Doesn't that feel good? Be sure to tell your friends about feral cats, and send them here () so they can learn first hand about Tara and her brothers and sisters. Thank you and purrs, Frankie Why TNR Is the Best Answer Why TNR Is The Best Answer For Feral Cats TNR is the humane, allowing feral cats to live out their lives like the wild animals they are without the worry of reproducing. 7 points A vacinnated, sterilized cat poses no rabies threat to humans. The most common carriers of rabies are raccoons, skunks, and bats.4 points The number 1 cause of wildlife decline is loss of habitat due to human activity. We are the cause of habitat loss, not feral cats.4 points The returned colony also guards its territory, preventing unneutered cats from moving in and beginning the cycle of overpopulation and problem behavior. 4 points Particularly in urban areas, the cats continue to provide natural rodent control. 4 points The average cost of neutering is $50 and the average cost of 'euthanasia' (killing) is $105. 3 points The No Kill Movement Stop killing all animals The old model is still being practiced by many so-called humane societies and shelters. Even many that claim to be no-kill facilities. Most, if they look like they are going to run out of room, they kill to get back down to whatever their arbitrary numbers are. Or, they have "shelf-life" rules. For instance if a cat or dog is not adopted in 30 days of capture then they are euthanized. The good ones, those run by people who are out to save every single animal they can, go the extra mile to find homes for the animals. 6 Ways Shelters Can Reduce Killing Cats and Dogs 1. TNR education for the public 2. Run TNR programs along with volunteers 3. Spay/Neuter eduction -- Start with the kids 4. Spay/Neuter programs -- low-cost and free 5. Join with rescue groups to find homes 6. Educate people to keep cats indoors Declaration of the No Kill Movement in the US. An exerpt: "This year, some five million dogs and cats." Click here to view the compelete and more on this movement No Kill Center. Redemption: The Myth of Pet Overpopulation & The No Kill Revolution in America A book that will change your life Redemption: The Myth of Pet Overpopulation and the No Kill Revolution in America Amazon Price: (as of 07/10/2009) Nathan Winograd is an amazing writer who tells all about the No Kill movement happening in the US. With over 5 million cats and dogs killed in shelters in the US alone, this book is a must read for anyone wanting to stop the killing. In my opinion, it is a must read for every animal lover. The Saving Of A Feral Cat Tara's Story Tara The Terrified: PART 1 My Experience Socializing Feral Kittens Tara in her cage sitting on Hawk I have been doing foster care for the local humane society since 2000. In 2001, I was asked to try to socialize a litter of 3. They were about 2-1/2 months old and had been living in a barn with all feral cats. Everyone had their fingers crossed because socialization (getting kittens used to people) must begin as soon as possible after birth. The moms with litters that I've foster have allowed me to handle their kittens within a day of delivery. I even had one mother who I had to help with her delivery. In between the 3 births, she would lay beside me with her head on my lap and purr. It was an amazing show of trust. Anyway, kittens need to be touch and handled for at least 20 minutes a day before they are 2 weeks old. If the mother is socialized, the kittens are easy to socialize even if they are a little older. However, if you get kittens after 2 weeks old, mother or not, I have found that they will hiss and haunch up, some even spit. But, I just persist and they've all come around. Tara The Terrified The smallest female of the litter, was terrified and spend the first 12 hours howling and pacing the cage -- almost nonstop. The other female and male kitten did better but needed more socializing than a 2 person household can give. Anyway, eventually they went back to the shelter and were returned to be barn cats (vaccinated and neutered) in exchange for 2 younger ferals we could socialize. Tara the Terrible Tara was also returned to the shelter, however, she would not let anyone near her. She'd hiss, spit and even growl. No one could feed her. In fact everyone was afraid to go near her. The shelter called me, asked if I wanted to adopt her. I could adopt her for free, however, if I did not adopt her, because of space constraints, she would have would be turned over to the County's shelter and since she was feral, they would kill her. Continued in Tara The Terrified: PART 2 below. "Shelters will kill 5 million dogs and cats this year." Tara The Terrified: PART 2 Adding A Feral Kitten To Our Family Tara sharing a bed with Bruce "Kamikaze" Lee The question was would I adopt Tara. My immediate answer was, "I'll be right over to pick her up." I then got off the phone and turned to my husband and told him the situation and bless his warm, big heart, he said, "Let's go get her." We got to the shelter we found her in the Isolation room where they put cats until they have a condo they can put the cat in. The shelter was absolutely packed because it was kitty season. The shelter manager said, "I'll stay out of site. She hates me." My husband and I walked into the room and talked to Tara. She didn't make a sound just sat looking at us intently. We talked to her softly telling her we were taking her back home as we opened the cage door and carefully held the cat carrier in front of the door. Tara literally lunged into the cage without a peep astounding the shelter manager. Tara Joins The Family PART 3 coming soon... They are NOT just strays I found this wonderful quote on It Matters To Me blogspot. . Tara The Terrfied: PART 3 Tara letting me pet her from a "safe" distance" As you can see from this picture, Tara allowed us to become family but at a distance. Look closely at the picture and you can see that she is about to flee. We could only pet her if we stood perfectly still and talked to her softly. Anyway, I'm a little ahead of my story. We brought Tara home and set the carrier on the kitchen floor. When we opened the door she literally bolted. What she did next was amazing. She went up to each cat and talked to them. We'd never see her so talkative. In fact, not only did she talk to each cat (6 of them) but every piece of furniture and every object in the whole house. She did this for 2 hours, non-stop. She just walked from object to object and talked to them. It was like she wanted everyone to know what she'd been through. After 2 hours, she curled up on the living room floor and bathed herself. Lee, her soul mate, joined her and curled up around her. And we knew we had made the right decision. She only allowed us to touch her every now and again. But she bonded with all her brothers and sisters. All of them loved her, especially Lee. They were almost always together. When Tara had lived with us for 4 years, she started hiding. We would spend hours trying to find her. How she could find a place to hide in a 1-bedroom, 1-bath house was a mystery. But we knew something was wrong because cats hide when they are sick or injured. Unlike our other cats, she would not let us pick her up and there was no way to get her into another carrier. In order to get her to the vets office, we had to borrow a humane trap and trick her into it. We managed, but it was an horrendous ordeal. We took her to the vet, who tranquilized her through the cage. When she called us later, it was with the sad news that Tara had several breast cancers and that her lungs were compromised. She did not think she would survive being revived. It was heartbreaking for us to let her go and Lee spent a lot of time looking for his soul mate. She was a very special cat. She was a cat's cat. All cats loved her and she was never tamed. If we had had no other cats, I believe she would have eventually bonded with us, but we had other cats and so she was able to stay wild and yet have the safety and love of an indoor cat. We miss her dearly. "Neuter Now Or Kill Later" If 2 unaltered cats breed 2 times a year, in just 7 years these 2 cats and their offspring can exceed 420,000 cats! What's Next In Feral Cat Control? When Julie Levy, a veterinarian and professor at the University of Florida College of Veterinary Medicine in Gainesville, is asked how to permanently reduce feral cat popultions, her answer is TNR. She says we should TNR entire colonies of ferals. Have them vaccinated, sterilized by a vterinarian, then returned to their colony. She admits that the method, though, is neither quick nor simple. In a study conducted over an 11-year period, Levi found the cats lived an average of 7 years after being spayed and brought back to their territory. Levy says something realistic needs to be done to reduce the feral population. However, she continues, killing the cats, as many wildlife organizations have suggested, is not feasible. New Vaccine In The Works Levy hasn't come up with another way, yet. However, she is currently working with a wildlife research group to develop a new sterilization vaccine for both male and female cats. "We're on the trail of a good one," she said. "We're now one year into a two-year study with male cats, and it's looking extremely promising." When/if the vaccine is developed, trained technicians would go into the field and inject the cats. The vaccine would actually make TNR programs more efficient by helping reduce costs and labor. 3 Deadly Traps For Feral Cats If you find cats or kittens that are feral, you may think that calling the local humane society or county animal shelter is the best thing to do. IT IS NOT! Do NOT Do Any Of These 3 Things If You find feral cats and kittens. Doing these Things will get the cats KILLED! Shelters rountinely KILL feral cats that are bought in because they are unadoptable. 1 point Animal control organizations called about feral cats will trap then then KILL them. 1 point Easy Ways To Help Feral Cats You know the old story of how Hobos mark the homes of nice people who feed them so other hobos know where to go? Well, I think feral cats (all cats) do the same thing -- somehow other cats KNOW I will feed them. Here's are suggestions on how you can help these felines. They too need help surviving in this world. Please add any additional ideas you have on how to help feral cats survive in this world. Find an organization that will pay for the neutering and vaccines. Many non-profits offer certificates that you present at a vet's office that will cover most of the fee of TNR and/or vaccinations.3 points Offer to help a feral cat giver with feeding. Sometimes I need to leave town for a few days and I worry about who will feed my ferals. It'd be nice to have a feral friend to help out when I can't be there.3 points Find out if they are really feral or just wary of strangers. Most of the time, you'll know if the cat is feral. However some cats are more wary than others (for a good reason). So, call on neighbors to see if the cat you are feeding belongs to them.2 points Raise money for TNR programs. Even if you don't want to trap, feed or volunteer, donations are always needed. Sometimes the programs need cash, other times they need sheets, towels and other supplies. We like to have a volunteer bring lunch (usually vegan) for the volunteers to keep us going through a long spay day.2 points Tara - Trying To Get Some Sleep Without Letting Down her Guard Tara half asleep Organizations For TNR Quote by Mahatma Gandhi A man who cherished all living creatures "The greatness of a nation and its moral progress can be judged by the way its' animals are treated." (Mahatma Gandhi) Steve Wozniak of Apple Fame Help To Save Feral Cats Steve Wozniak Saves Feral CatsI worked at Apple Computer for 7 years, but Steve had already left the company. However, I always heard great things about him. Then I had the pleasure of meeting him some years later at an education trade show. He was short, very short - LOL - and he was the most marvelous person. He was really interested in helping this world. I'm thrilled to see him taking care of feral cats. You can read the article announcing this video and his work with feral cats by clicking Feral cats/Steve Wozniak. One population of feral cats is down to 1 or 2 cats! TNR really can and does work if people just do their parts. Steve Wozniak and HSSV - Cats Without a Home Runtime: 3:20 10 Comments: Organizations FOR TNR Alley Cat Allies dedicated to changing ineffective animal control practices like trap and remove, and to providing resources for the thousands of caring individuals an...4 points ASPCA: The American Society for the Prevention of Cruelty to Animals ASPCA: American Society for the Prevention of Cruelty to Animals. The ASPCA was founded in 1866 as the first humane organization in the Western Hemisp...3 points FCP Partnerships with Rescue Organizations, Grass Roots Rescuers, Animal Control The Feral Cat Spay/Neuter Project fosters partnerships with local rescue organizations, grass roots rescuers and our County Animal Care and Control ag...1 point Pet, Dog, & Cat Adoptions-Pennsylvania Pets - Pet Shelters, Dogs, Cats, Horses, Birds List of Pennsylvania Pet Rescue and shelters that support TNR.1 point Animal Welfare Federation of Connecticut (AWFCT) is a state-wide non-profit coalition of animal shelters, rescue organizations & professionals, and animal advocates. Animal Welfare Federation to host Intensive TNR Training Workshop at Central Connecticut State University in New Britain on Sept. 14-15, during 2007 s...1 point Animal Kind is dedicated to the non-proliferation of unwanted animals, the protection and welfare of abandoned, feral and stray cats, and humanely red...1 point Animal Concerns Community - Spay Rescue, rehabilitation and adoption for homeless canines. Also offer lifetime care ... A volunteer organization that works on TNR for Coryell County,...1 point More Organizations FOR TNR Best Friends Animal Society - About Best Friends Best Friends Animal Society runs the nation's largest sanctuary for abused and abandoned animals. Best Friends operates a low-cost spay/neuter program...5 points Humanity For Cats/TNR Feral kittens can be TNR at the cat rate or removed at the cat rate. Removing a feral kitten is more difficult than removing a feral cat. ...2 points Solano Ferals To improve the lives of feral and homeless cats living in Solano County by humanely stopping their breeding through Trap-Neuter-Return (TNR). ...1 point Feral Cat Network: Dispelling The Myths In a TNR program, a feral cat colony caretaker, who is usually a volunteer ... Regardless, feral cat TNR programs routinely immunize cats against rabi...1 point Noah's Ark Sanctuary - Feral Cats - TNR - Trap Neuter Release Did you know that one pair of breeding cats, with all of their offspring, will generate 420000 kittens in just six years and two breeding dogs with th...1 point Operation Cat Nap - Auburn University's Trap-Neuter-Return Program This organization is dedicated to the welfare of feral cats and kittens, and they offer TNR services, as well as taming and adoption of young kittens...1 point Feral Cat Program Fights Pet Overpopulation (CummingHome-Cumming ... TNR is based on perpetual colony maintenance. Cats are prolific breeders but nowhere can they reproduce to the magnitude of 420000. ...1 point The Animal Spirit: Feral Cat Network Feral Cat Network will provide information regarding feral cat rescue, including Trap-Neuter-Return (TNR) and feral cat colonies. ...1 point TLC Newsletter Spring 2001 RENTSCHLER BARN CATS TNR'D Rentschler Farm on Michigan Avenue just east of downtown Saline is a historic farm owned by the City of Saline and operated...1 point First Coast No More Homeless Pets is a low cost/no cost non profit neutering organization in Jacksonville Fl. I have had the privilege to work with th...0 points The real problem! Organizations Against TNR Organizations AGAINST TNR These are all that I've found so far. Add some if you know of them. Thank you. People for the Ethical Treatment of Animals (PETA): The animal rights organization PETA's animal rights campaigns include ending fur and leather use meat and dairy consumption fishing hunting trapping factory farming circuses bull fi...1 point Bird Advocates Bird Advocates0 points PETA Argument and My Rebuttal "We have seen firsthand-and we receive countless similar reports-that cats suffer and die gruesome deaths because they are abandoned to fend for themselves outdoors. Many were in "managed" colonies, which usually means that they were fed. Having witnessed the painful deaths of countless feral cats instead of seeing them drift quietly "to sleep" in their old age, we cannot in good conscience advocate trapping, altering, and releasing as a humane way to deal with overpopulation and homelessness." My Rebuttal All wild animals face the possibility of catching diseases or getting hurt and facing painful deaths. To kill ALL feral cats because a few of them die painful deaths is like killing all lions, tigers and bears because some will be die this same way. Sorry, not on my watch. I won't advocate killing ferals cats (or any other animal) for this reason. Heck, how do we know which cats will die painful deaths? And, before they died, how many years of freedom did they live? And, who is going to play God? Some Bird Enthusiasts: An Argument and My Rebuttal "." My Rebuttal Yes, birds are being killed by cats. But killing cats is not the answer, People caused the problem with the overpopulation of cats. We just can't kill every feral cat just because "stupid and uncaring" people abandoned cats and they became wild. I am 100% for TNR, however, that is only 1 step. Here is my 7 step program: (1) Educate people about spay/neuter (start with kids). (2) Have low-cost and free spay/neuter programs. (3) Relocate feral cat colonies that are near endangered birds. (4) Run TNR programs and allow caregivers to take care of the feral cat colonies with TNR, feeding, and medical care -- people ARE willing to do that. Let them. (5) Educate people to keep cats indoors. (6) Make and enforce laws that punish people for abandoning animals. (7) Make and enforce laws that make spay/neutering mandatory. It has been proven in tests all over the country that just killing cats does NOT stop the problem but a good TNR program does by controlling birth rates. Let's stop looking at all of our problems as "kill them" and work together to "save them" -- both feral cats AND birds. There's enough killing going on in the world. Removing Cats to Protect Birds Backfires on Island An example of why killing cats isn't the answer ." Read the full article at Removing cats to protect birds backfires on island Lensmaster's note: Killing Cats for birds killed more birds and created a eco-nightmare. Killing cats is NOT the answer! These people found out the hard way -- don't muck with Mother nature's eco-system. Instead, practice TNR to control cat population in a systematic way. Never Say Never America has a feral cat crisis. Learn about some of the myths and truths associated with feral cats and how to help them. TNR - Trap, Neuter and Return is the proven, humane solution to a problem that we created. Runtime: 5:10 10 Comments: Here's Some Informational Resources On TNR Newsletters, Courses, Articles, Pamplets And More TNR Informational Resources List of Factsheets and Articles (Alley Cat Alies) Everything you need to understand and create a TNR program: facts, pamplets, sample press release, articles, and much more...4 points ASPCA Online Store: Neighborhood Cats TNR Kit Learn how to run a successful Trap-Neuter-Return program with this comprehensive kit from Neighborhood Cats. The kit includes The Neighborhood Cats TN...2 points PDF File: Humane Society of Silicone Valley Newsletter - Summer 2006 TNR is a hugely cost-effective, humane way of .....1 point Course: TNR: How To Manage A Feral Cat Colony HSUS Secure Gateway offers a Self-paced course called Trap-Neuter-Return: How to Manage a Feral Cat Colony<br /><br /> Instructor: Neighborhood Cats, Inc. <br /><br /> Course...1 point Online Article: Neighborhood Cats | What is a Feral Cat? A feral cat is one who has reverted in some degree to a wild state. They originate from former domestic cats who were lost or abandoned and then learn...1 point Online Article: Neighborhood Cats | What is TNR? Trap/neuter/return, commonly referred to as &amp;amp;quot;TNR,&amp;amp;quot; is the only method proven to be humane and effective at controlli...1 point Alley Cat Rescue The National Cat Protection Association Alley Cat Rescue - The National Cat Protection Association. Cat Rescue Organization. Feral Cat Rescue Group.1 point Resources for Helping Feral Cats | The Humane Society of the United States The Humane Society of the United States1 point Must Read Articles On Taking Care Of Your Cat Find Answers To All Of Your Cat Questions You'll find dozens of articles on Cat Care on my website All Things Related To Cats. Below are a few of them. Click the headline to see the individual article. Allergic To Your Pet? You can still enjoy having a beloved pet, despite having allergies.4 points Play With Your Cats The best possible way to build up a bond between you and your cat is through play.2 points Caterwauling Valuable insight into all that caterwauling.1 point Five Most Common Cat Ailments The common ailments that affect cats and how to spot the symptoms.1 point A Hairy Situation Why the cat hacks up hairballs1 point Alley Cat Allies -- Saving Ferals Cats Everywhere An Organization You Should Know About Alley Cat Allies Ally Cat Allies is an incredible organization to saves feral cats. On their website, you will find: - Caregiver/Advocate Information - Animal Control/Shelter Information - Legal Information - Veterinarian Information - Events & Conferences They have the most extensive library of materials created to help you: 1. Recognize feral cats. 2. Trap, neuter and release information. 3. Organize TNR programs in your area. 4. Talk to people about TNR. 5. Get press for TNR (they even provide a press release template). 6. Raise feral kittens. 7. Build feeding stations for feral cats. 8. Learn how best to help feral cats. 9. Find success stories and statistics to share. 10. Find videos of feral cats and TNR in action. 11. And lots more. For a complete list of their Factsheets and Articles, click Factsheets and Articles To contact them or get other information from their website, click Alley Cat Allies Sent A Feral Cat Ecard Offered Through Alley Cat Allies Valuable Information And Resouces On TNR Programs More About How To Start And Or Maintain TNR Programs More TNR Resources & Reading Neighborhood Cats | What is TNR? Trap/neuter/return, commonly referred to as &amp;quot;TNR,&amp;quot; is the only method proven to be humane and effective at controlling feral...1 point Feral Cats: TNR versus Eradication? Results from college campus groups prove that trap-neuter-release programs work for feral cat management, where eradication does not.1 point ASPCA: Fight Cruelty: Trap-Neuter-Return Fundamental to the success of TNR is continued care of the feral cats by colony ..... Neighborhood Cats TNR Kit: Includes the 108-page The Neighborhoo...1 point ASPCA Online Store: The kit includes The Neighborhood Cats TNR Handbook: A Guide to Trap-Neuter-Return for the ... Using footage from actual Neighborhood Cats TNR project...1 point Implementing a Communitywide Trap-Neuter-Return Program for Feral ... Mr. Kortis serves as executive director of Neighborhood Cats, a New York City-based nonprofit specializing in the management of feral cats using TNR....1 point Humanity For Cats/TNR Feral kittens can be TNR at the cat rate or removed at the cat rate. Removing a feral kitten is more difficult than removing a feral cat. ...1 point volunteers needed for feral cat TNR clinic Please help pass the word to others who might be interested in being part of this great program and to anyone you know who takes care of any feral cat...1 point Miami County Humane Society Union Twp. Cat/Kitten TNR Prog. 2007 Outline of Feral Cat TNR Workshop sponsored by the Miami County Humane Society (Recipient of Kenneth A. Scott Charitable Trust Grants in 2003, .....1 point Austin Feral Cats--Step by Step TNR Instructions Step-by-Step Checklist for Feral Cat TNR. Refer to the reference materials elsewhere on the site for details about any of these points. ...1 point ASPCA Online Store: Learn how to run a successful Trap-Neuter-Return program with this comprehensive kit from Neighborhood Cats. The kit includes The Neighborhood Cats TN...1 point Resource: Homeless Cats and Public Safety In 2005, it cost Santa Clara County taxpayers approximately $2.5 million to pick up, house and eventually euthanize homeless cats. TNR and colony mana...1 point Ferals Management Newbie Tutorial Feral Cats TNR Tutorials. A well-planned management program is critical in saving ... Alley Cat Allies is the vanguard of TNR and advocacy for feral c...0 points Great Gifts You'll Want To Keep For Yourself You Gotta Love The Slogans "The quality of my life is directly proportional to the amount of time I spend with my cat." Kate Hayes Cat Quote Women's Light T-Shirt Cat Quote Women's V-Neck T-Shirt Cat Quote Women's Long Sleeve Dark T-Shirt Cat Quote Tile Coaster Cat Slave Women's Light T-Shirt Tara Napping On Window Perch The Saving Of A Feral Cat Kanzi's Story Free-Roaming But Not Feral - Kanzi's Got a Home By Phila Hoopes I didn't know that I'd learn from her how to balance between caring for the backyard cats and respecting their choice to roam free. Fifteen minutes of frenzied driving later, our vet said a possum or raccoon had bitten her. With good care, she'd recover - she'd be blind in that eye, but there was no apparent brain damage. And recover she did - a strong-willed survivor who refuses to live indoors. Not that I haven't tried! Kanzi stayed with us, skittish and aloof, for just two weeks before she slipped outside. We hunted frantically... until my son saw her, strolling across the backyard with her mother. Under Momcat's care, Kanzi eluded efforts to trap her for spaying... until she walked into the trap one Friday night. I set the spaying for Monday and freed her in my bedroom. Next morning the door was open and Kanzi was gone... and weak mews were sounding from the basement. I raced downstairs, and there, in the darkest, dirtiest corner I found her four deformed babies, with Kanzi nowhere in sight. She'd left them there, dying. While I was at the pet ER, Kanzi escaped outdoors again. If she'd been trap-wise earlier, she was doubly so now, and avoided the Havahart as she became pregnant again. She gave birth to three healthy kittens, raised and weaned them with Momcat's help, and I immediately trapped them for hand-training. "Why don't you take the kittens outside in the cat carrier and set up the trap next to it?" asked our vet. "Kanzi would go to them, and you could bring her inside." It was a good idea... until I set Kanzi free in the bedroom, and she circled it in terror three times without touching the floor. Finally she came to rest atop a bookcase%u2026 I backed away and secured the kittens in their crate before leaving the room to let her settle down. Somehow we got her back in the trap for spaying next day. She recovered in my bedroom...and then slipped out of the room and out of the house. She's 7 years old now, one of our outties - she comes when called and doesn't miss a meal. She likes to sit on the picnic table sometimes, nose-to-nose with her daughters, with the window screen between them. She's scheduled for her rabies/distemper booster next month. But come in? Not a chance. That's her choice, and she's taught me to respect it. --------------------Kanzi, Momcat, and her 16 siblings were trapped, spayed/neutered, and inoculated thanks to a low-cost TNR program through the MD SPCA, Cat Rescue of Maryland and Alleycat Allies. They have all found loving caregivers. My deepest gratitude goes to these two life-saving organizations. For information on local TNR programs, contact Alleycat Allies . --------------------Phila Hoopes of Your Words' Worth is a freelance copy writer serving small and sustainable businesses. A lifelong cat-lover, she also produces The Joy of Cat Herding - Proven Solutions to Your Cat Behavior Problems Books On TNR And Feral Cats Books To Give You More Knowledge About Feral Cats TNR: Past, Present and Future: A History of the Trap-Neuter-Return Movement by Ellen Perry Berkeley A complete history of this most humane, effective, and economical method of controlling feral cat numbers. Comprehensive and authoritative, yet accessible and readable. Helpful to anyone concerned about feral cats in any way. Useful in enabling TNR advocates to reach out to people not yet "on board." Contains excellent rebuttals to arguments about the supposed damage by feral cats to bird populations. Provides solid proof on the advantages of TNR from the most recent academic research and from t...1 point Recent Articles That Discuss TNR -- Both PROS & CONS Very Informative Articles With Arguments Worth Reading - An Interview With Nermal | Itchmo: News For Dogs & Cats - I never knew I was a feral cat until I wasn't one any more. - Julie Zickefo, October 16, 2008 Happy National Feral - Feral Cat Trap-Neuter-Return Program Ignites Controversy Among Vets - I am a life long cat lover. I am continuously amazed by the ability of cats to adapt to almost every environment on earth, and to survive and reproduce (although not truly thrive as individuals) without the help of humans. - LA County Supervisor Enacts Feeding Ban, Trapping Cats - Victory! Thanks to you the trapping at Ranchos Los Amigos has stopped and feeding has resumed. Government officials are working with local caregivers and groups to develop a plan that will be in the best interest of the cats and the community. More than 1,300 Alley Cat Allies supporters took action through our Action Center. Thank you for taking such quick and important action - and standing up for The Ranchos cats. - Wayne Pacelle Under Siege -. - Cats Versus Birds: The Debate Continues - MT. RAINIER, Md., March 20 /PRNewswire-USNewswire/ -- With a new report out from the U.S. Fish and Wildlife Service, the debate of bird versus cat continues. According to a statement from Darin Schroeder, Vice President for Conservatio... - Camp Companion aims to control homeless cat population - n the operating room, four veterinarians were operating on female cats. Just down the hall, surgery preparation and post-operative care took place in a large room. - Volunteers advocate humane cat program - With an increase in the number of feral, abandoned and stray cats, volunteers are calling for Jackson officials to create a trap-neuter-return (TNR) ordinance that will be humane, improve public health and help cut costs. - Squirrels and feral cats are the major threats to songbirds. - The online wildlife magazine for those who like wildlife, wildlife news and watching wildlife, plus a guide to UK nature reserves. - NPO provides unusual solution to Japan's feral cat problem - It used to be that the only two options for dealing with stray cats was putting them to sleep or finding an adoptive home. Obviously, euthanasia is not an ideal solution?even if you don't oppose it on the grounds of cruelty, the cost of trapping and killing animals is high. - How should feral cats be managed? - It has not been easy for scientists to figure out exactly when cats were domesticated. Originally, it was believed that Egyptians were the first to have cats as pets, but recent genetic … - Unknown - ...Trapping and euthanizing is not only ineffective in controlling stray cat populations, the group says. It's not the most cost-effective method either. Triple R Pets is working in Oak Forest to humanely reduce the feral cat population. The group's program involves trapping the cats, having them spayed or neutered and returning them from where they were found. Triple R's own long-term studies show it's a more effective way. Great Books On Cats And Cat Care Poppy's Story -- A Pregnant Feral Cat A Pregnant Feral Cat Pregnant Feral Cat I am fostering a feral cat (actually a kitten) who was pregnant. We named her Poppy because she started looking like she was going to POP! She just had 4 kittens which I chronicle in my blog with pictures. It was too late when I got her to abort the litter. I will however, once the kittens are weaned, I will socialize, test, spay/neuter, and find homes for them. I will also be trying to socialize the momma, who is just a kitten herself and find her a home. No matter what, she will be spayed and if not able to be adopted, I'll see if I can get her adopted as a barn cat or she will go back to the feral cat colony that she came from. To see pictures of Poppy and her litter as they grow up, visit Pregnant Cat Readies To Give Birth. More Animal Rescue Lenses On Squidoo Check these wonderful lenses out and see how they are making a difference in the world. If you know of another one or you have one, please add it here and vote for your favorites! Saving Shelter Pets, Inc. - Help Save a Life Today Saving Shelter Pets, Inc., a 501(c)(3) animal welfare organization needs your help to save pets in need.3 points Feral Kitties Need Love Too! Welcome to my lens about the feral kitties that I am trying to tame and rescue and rehome!!!They are QUITE the little cuties and I figured ... why not...1 point The Pidgie Fund Nearly 250 Squidoo lenses donate money to The Pidgie Fund, but what exactly is The Pidgie Fund? The Pidgie Fund is a non-profit organization which rai...1 point A Book That Will Move You To Tears, But Worth The Read Heart Warming, Wrenching And A Page Turner One at a Time: A Week in an American Animal Shelter This book. You can purchase the book at No Voice Unheard (). How To Create A Squidoo Lens And Change The World I Share What I've Learned On-Line Resources For Successful TNR Programs - A longterm plan for TNR - "You're right, jumping right in and doing TNR is great, and if you want to do TNR for the long-haul and on a comprehensive level, you do need to plan and organize. Generally, I find with many animal-welfare programs, it is easy to get caught up "in the trenches" as there is always another animal who desperately needs your help. And don't get me wrong, the people in the trenches are absolute angels and essential to any good program... - Live Green Orleans » Blog Archive » Earth Friendly Cat Tales - My first encounter with Ramona Billot's cat saving efforts happened in an unlikely place. Both of our families were in Jackson, Ms "living" at the Jameson Inn because of hurricane Katrina...! Petitions to Sign to help save feral cats - Lives Count, Secrets Kill -- Alley Cat Allies Petition - Lives Count, Secrets KillMore than 60,000 cats were killed in Illinois animal pounds and shelters in 2006. That's 5,000 cats killed every month and 160 each day. These same facilities couldn't account for over 17,000 cats. No one knows what happened to them. Insist on the Truth Unfortunately, Illinois in not alone. The most comprehensive research to date indicates that across the country, the majority of all cats entering animal pounds and shelters are killed. And most of it happens in secret. Excellent Articles About Feral Cats More Information About Saving Feral Cats These articles to will introduce you to the world of feral cat rescue. How it was formed and how it is working in different areas. Please add any you feel are appropriate. Feral cats and prejudice I was reading about the feral cats at JFK and about the Port Authority suddenly deciding it was some kind of risk to humans (despite all evidence to t...2 points Goldston: Feral cats have a new champion: Steve Wozniak The homeless cat problem in Santa Clara County went global Tuesday: Apple Computer co-founder Steve Wozniak launched a video on YouTube.com about the...1 point Feral Cats at JFK May be Killed! -Cat Care, Breeds and Resources Blog According to Port Authority officials, the most pressing threat to aviation security at JFK Airport is no longer terrorism, but feral cats! Unbelievab...1 point Stray but Not Forgotten - washingtonpost.com These cats are not the ones that come running when you call, Kitty, kitty.0 points Helping Outdoor Cats A seminar on &quot;Helping Outdoor Cats&quot; drew 80 people, many of whom feed stray and feral cats around Wichita. BY DIANE MCCARTNEY The Wi...0 points Mistrial in bird-watcher's cat-shooting trial Excellent discussion about this episode. A must read in my opinion.0 points Fun Films About Cats From Amazon Enjoy Some DVDs With Your Family Feral Cat books on Amazon Search here for more books on cats or anything ASPCA's Low-Cost Spay/Neuter Resource Find One In Your Area Low-Cost Spay/Neuter ProgramsASPCA has a special link for you to find low-cost spay/neuter programs in your community. Simply go to Low-Cost Spay Neuter Programs and enter in your zip code and you'll get a list of the programs in your area. Great Cat Stuff For Cat Lovers Home For Cats And Cat Lovers -- Blog A Blog Devoted To Cats. If you like this site, you should see my other cat site. To go there right now, click Cats Just Wanna Have Fun Here's an example of what you'll see: The Hip Hop Cat OR Puff Kitty Please Give Me Feedback Tell Me What You Think Of This Lens Please take a moment and go back to the top of the page and give me some purrs (stars) by clicking 1 to 5 stars in the right hand 5-star set above. Also please LensRoll Me and Add Me To Your Favorites Both make it easier to come back -- and you'll want to, to see what I else I add next. Thanks and purrs, Frankie I think all native birds, amphibians and lizards etc. need to be protected from exotic non-native predators. Even neutered ferile cats will want to eat whatever they find and it will not always be non-native rodents. Cats are wonderful companions but they belong indoors. Wearing a bell is not enough. Check out cat t-shirts, neckties, pens and magnets at retail to share with your cat friends or in wholesale quantity to resell and fund rescue efforts at http:whatdidyoubringme.homestead.com What do I think of this lens? It's fabulous. It should answer any and all questions on the topic, you've presented a fair and balanced look at TNR. The work you do is important and I appreciate your passion for the topic. I have cats that were found as strays although they are domesticated, they choose to spend at least 1/2 of their time outdoors, and I think they are happier and healthier for it. But, I am responsible, they are identified and neutered (and I couldn't love them any more than I do)!!! My Other Cat Sites On Squidoo For More Cat Information If you love Tigers too, check out my new Calvin and Hobbes site. To go there right now, click Funniest Calvin-and-Hobbes Cats Just Wanna Have Fun Loaded with funny pictures, videos and stories of cats doing nutty things as well as valuable information on caring for your cat, including ear mites, mange, dealing with cat allergies, grooming, poisonous plants, and much more. There will also be l... links covering breeds, what to.... With facts about each with picture... they are also one of the "hair... What Do You Think? Should TNR be the World's way to counteract overpopulation? Absolutely, the only way to go. AlishaV says: Obviously, the best thing is for everyone to take care of their cats, get them fixed, and not throw them out into the world where they reproduce until they die. Most people that truly care about animals agree on that. But, until we manage to get those basics through those people's heads, we have to save the cats somehow. The only solution that is capable of being done and that is truly humane is to trap, neuter, and release. Killing the cats is not the solution, other cats move in and the problem just continues. TNR works and is the best solution that we have until everyone starts caring about these animals' lives. Posted May 21, 2009 Frankster says: heresy, I did not say they did not pose a threat and NEVER harm native species; I said "...the OVERWHELMING cause of wildlife depletion is destruction of natural habitat due to man-made structures, chemical pollution, pesticides, and drought -- not feral cats." When humans have abandoned cats to fend for themselves and their families, they do just that. That is nature. What a good TNR caregiver does is remove the main reason for this behavior by keeping them fed. Do they still prey on wildlife? Yes, but not to a major destructive amount as people want to accuse them of. TNR cuts down the number of cats and their need to prey on wildlife. I know Hawaii (which I love) has an overwhelming amount of feral cats ALL due to humans. It is a major problem for them but they need to be very careful how they contain, control, remove the cats. See the story further up about the Australian Island that caused more problems from their killing of the feral cats there. Like most of life; the issue/solution isn't black and white. There is some gray area where we need to work in order to save lives -- all of them whether they be native or not. As humans it's time we stopped and found a better way to work with nature than by killing the problem. By the way, my ancestors were not native to this nation either. Were yours? Posted May 18, 2009 heresy says: Frankster, it is simply incorrect and misleading to say that feral cats do not pose a threat to, or NEVER harm native species. Feral cats like ANY OTHER invasive have the potential to cause destruction to native flora and fauna including endangered genus's. Some colonies do and some dont. If you dont believe me just ask any Hawaiian conservationist what feral cats are capable of. This is a great program for urban centers but something else needs to be figured for areas more sensitive ecosystems. I'm indifferent as to the method so long as native species and ecosystems are considered first. AND As long as its black and white with no room to compromise I can live with it. =) Cheers. Posted May 18, 2009 TopStyleTravel says: It is the humane way to control overpopulation while allowing feral cats the right to live out their lives. Cats are beautiful and intelligent animals. People should help feral cats out if they need food, water or are sick, when needed. They probably help with rodent control too. Posted March 19, 2009 calicoskies says: Yes! Great idea. Posted October 12, 2008 RinchenChodron says: I have've had a feral cat, Kisser, for about 15 years and he's great. I love the TNR movement! Posted October 04, 2008 CabinFeverStudios says: Great lens!!!! Very informative. Just this morning I was thinking of writing a page on this topic, but you have done a fantastic job. Many people don't know about or understand TNR. Thanks for writing about it. I am lensrolling you to my sheltie rescue page. Posted September 01, 2008 Ann Stanton says: I currently have a feral mother cat and her 5 kittens living on my front porch. I was feeding her and the kittens had been living under another neighbor's back porch until 7-8 wks old. They then showed up on my porch one morning. I wish the neighbor would have told me about these kittens at a much younger age since I could have taken them, fostered and found them homes. I've done that before and it turns out so well getting homes for these little ones. I've been trying to socialize the kittens (about 3 mos old now) hoping to get them friendly and find homes but they run away from most people. Three of the 5 will let me pet them and pick them up but not for very long. I'm hoping that I can at least find a local place to do TNR so they won't grow up to have more kittens. My neighbor wanted me to trap them and take to our local shelter but I had volunteered there years ago and they automatically euthanize ferals so I refuse to have anything to do with them. I would like to get them spayed/neutered within another month or two. I wish there were more feral rescue groups in this area. Some rescue groups don't want feral kittens at all so what's a cat lover to do. Posted August 15, 2008 No way. Extermination is the only way to stop overpopulation. Frankster says: heresy, (1) Feral cats are NOT the cause of wildlife depletion: Studies show that the overwhelming cause of wildlife depletion is destruction of natural habitat due to man-made structures, chemical pollution, pesticides, and drought -- not feral cats. (2)As far as the cost, it is far cheaper to do TNR than to euthanize as studies have shown. Also, the cat colonies are fed and kept healthy NOT by taxpayer dollars but by caregivers out of their own pockets or donations. The cats live out their lives, as healthy as most cats owned by other folks as pets and they do NOT reproduce. I hate to say it, but we taxpayers pay out money due to irresponsible actions of a few (actually not-so-few) all the time: abortions, drunken drivers, vandals just to name three. (3) I agree that cats should live indoors. I keep all of mine in all of the time. The problem is irresponsible and/or uncaring people who discard cats (and dogs by the way) like they were a piece of trash rather than a living creature. And, others who do not neuter their pets. Millions of dogs and cats are routinely killed in shelters every year because of these stupid, uncaring, irresponsible people. Posted May 18, 2009 heresy says: As long as the released cats aren't harming native species, especially endangered birds and small mammals. Also these programs cost money. Who is to pay for the irresponsible actions of few? Taxpayers I suppose. If people love cats so much, keep them indoors. Once they leave your house they become everyone's problem. Posted May 18, 2009 Want to link to this lens? Here's how WANT TO LINK TO THIS PAGE? Here's the HTML code to copy and paste: <a href="" title="Click Here to visit How to Save Feral Cats...with TNR">Click Here to visit How to Save Feral Cats...with TNR</a> This work is covered by copyright and can not be reprinted in any matter (physical or digital) without prior written consent. by Frankster Related Topics Frankster Recommends... - Cat Trees: The Ultimate Furniture For Pampered Cats - The Joy of Cat Herding - Proven Solutions for Your Cat Behavior Problems - Long Term Care For People You Love - Saving Shelter Pets, Inc. - Help Save a Life Today - Welcome to Chubba Wubba Girl - More... - Cat Trees: The Ultimate Furniture For Pampered Cats - The Joy of Cat Herding - Proven Solutions for Your Cat Behavior Problems - Long Term Care For People You Love - Saving Shelter Pets, Inc. - Help Save a Life Today - Welcome to Chubba Wubba Girl - I Am Not A Poodle! - Get Traffic Like The Gurus With Sales Army Secrets - Cats Rule. How To Select Your New Master - Pit Bull Dog - Debunking Pit Bull Myths - Truth About The Pitbull Dog - Funny Cat Video Showcase - Funny Dog Videos with Bite! - All Polar Bear Ware, All The Time - LifeCell: How To Lose The Wrinkles And Look Younger - Sphynx Cats: What's Hair Got To Do With It? - How To Squidoo And Change The World - How To Take Your Local Business Online - Sculpture Video Showcase - Give A Great Gift They'll Be Glad To Get - Lions, Fu Dogs and Bears (OH MY!) - Polar Bear Videos -- Polar Bears, Here, There, Everywhere - Cats Just Wanna Have Fun - The Funniest Calvin-and-Hobbes Ever - Best Friends Animal Sanctuary - Kartick Satyanarayan - Champion of India's Dancing Bears - Saving The Dancing Bears Of India - Spectacled Bears (aka Andean Bears) - Are You Polar Bear Aware? - Lemonade stand: Turning lemons into dollars for charity - Bolt the Movie - Bird Rescue - Lucky-Our Rescue Cat - Garfield - Feline Extraordinaire - Plastic bag alternatives - Cat Abuse - Big Cat Rescue - Stray Muses...A Language Unspoken - Caring For Animals
http://www.squidoo.com/saveferalcats
crawl-002
refinedweb
9,067
71.85
Insertion sorts are a common sorting technique that many computer science students are asked to learn. Here is a Python implementation of an Insertion Sort. def insertion_sort(items): for i in range(2, len(items) - 1): item = items[i] j = i while (items[j - 1] > item) and (j >= 1): items[j] = items[j - 1] j -= 1 items[j] = item if __name__ == '__main__': items = ['Bob Belcher', 'Linda Belcher', 'Tina Belcher', 'Gene Belcher', 'Louise Belcher'] print(items, '\n') print('Sorting...') insertion_sort(items) print(items) Insertion sorts use nested loops and test if an item at the end of the list is less than an item in the front of the list. If they are, the code does a swap. When run, we get this output: ['Bob Belcher', 'Linda Belcher', 'Tina Belcher', 'Gene Belcher', 'Louise Belcher'] Sorting... ['Bob Belcher', 'Gene Belcher', 'Linda Belcher', 'Tina Belcher', 'Louise Belcher'] Advertisements 2 thoughts on “Insertion Sort—Python” I had a few queries: 1. Why did your range start from 2? 2. You are taking strings here. 1D strings. What if they were 2D and how will you sort that? Like be it any format (strings or int values). Is sorting for 2D lists possible? We start at 2 because of the nested loop. You’ll notice that the variable j starts at i on line 4. Then on line 5, we have j – 1, followed by j – j again on line 6. If we started at 1 rather than two, we would end up with a negative index on line 6, but by starting at 2, we end up at 0, which is the start of the list. It is possible to sort 2D lists. However, you have to decide what a sorted 2D list looks like. Do you sort by columns or rows first? I’ll do a post on this topic since it’s more involved.
https://stonesoupprogramming.com/2017/05/09/insertion-sort-python/
CC-MAIN-2018-05
refinedweb
312
81.83
Opened 8 years ago Closed 8 years ago Last modified 8 years ago #10957 closed (worksforme) Inconsisten behaviour in User admin display Description (last modified by ) I needed to change admin site for User class from auth, because I need to make first name and last name required. I subclassed Admin class for User and changed form: class UserChangeForm(ModelForm): username = RegexField(label=_("Username"), max_length=30, regex=r'^\w+$', help_text = _("Required. 30 characters or fewer. Alphanumeric characters only (letters, digits and underscores)."), error_message = _("This value must contain only letters, numbers and underscores.")) first_name = CharField(label=_('first name'), max_length=30, required=True) last_name = CharField(label=_('last name'), max_length=30, required=True) class Meta: model = User Without first_name and last_name fields defined, admin displays it translated into polish, with first letter capitalized, like this: Imie Nazwiski With first_name and last_name fields defined, which have labels defined exactly as User model ('first name' and 'last name'), admin displays it translated, but not capitalized, like this: imie nazwisko The other labels are capitalized and I would like to be consistent. Is there any way to make it consistent? Change History (4) comment:1 Changed 8 years ago by comment:2 Changed 8 years ago by Fixed formatting. comment:3 Changed 8 years ago by I can't explain why the label in your case isn't being capitalized, but the way you have done this is not how I would approach the problem. Rather, to avoid repeating field definitions, etc., I would create a custom user change form based off of the existing one, and simply override the required attribute for the fields in question. This works for me: from django.contrib.auth.models import User from django.contrib.auth.admin import UserAdmin from django.contrib.auth.forms import UserChangeForm class CustomUserChangeForm(UserChangeForm): def __init__(self, *args, **kwargs): super(CustomUserChangeForm, self).__init__(*args, **kwargs) self.fields['first_name'].required = True self.fields['last_name'].required = True class CustomUserAdmin(UserAdmin): form = CustomUserChangeForm admin.site.unregister(User) admin.site.register(User, CustomUserAdmin) When the language is set to Polish, I then get the labels for first and last name both capitalized and in bold, indicating they are required. If I try to save a user without filling in one of those fields it gets annotated with an error message "To pole jest wymagane." which I assume means "This field is required." (Note it is particularly important to base a custom admin object for User off of the existing django.contrib.auth.admin.UserAdmin class, as it is set up to support changing the password. If you base your custom User admin object off of admin.ModelAdmin you will run into trouble when you try changing the password. Not sure if you did that or not as you didn't include the admin config portion of what you had done.) Finally, if your ticket contains a question like "Is there any way to make it consistent?", that's a signal it is probably better suited to django-users than the ticket tracker. In the future please try django-users first, and open a ticket only if you are absolutely sure the problem is a bug in Django. comment:4 Changed 8 years ago by Django will automatically capitalize labels generated from the model fields but will not change user-provided labels for the form fields. This is a normal behaviour. Just use lowercased names for the model fields and capitalized labels for the form fields. I can't change the example formatting, so I repost it here:
https://code.djangoproject.com/ticket/10957
CC-MAIN-2017-09
refinedweb
593
55.13
Net::DNS::Resolver - DNS resolver class use Net::DNS; $resolver = new Net::DNS::Resolver(); # Perform a lookup, using the searchlist if appropriate. $reply = $resolver->search( 'example.com' ); # Perform a lookup, without the searchlist $reply = $resolver->query( 'example.com', 'MX' ); # Perform a lookup, without pre or post-processing $reply = $resolver->send( 'example.com', 'MX', 'CH' ); # Send a prebuilt query packet $query = new Net::DNS::Packet( ... ); $reply = $resolver->send( $packet ); Instances of the Net::DNS::Resolver class represent resolver objects. A program can have multiple resolver objects, each maintaining its own state information such as the nameservers to be queried, whether recursion is desired, etc. # Use the default configuration $resolver = new Net::DNS::Resolver(); # Use my own configuration file $resolver = new Net::DNS::Resolver( config_file => '/my/dns.conf' ); # Set options in the constructor $resolver = new Net::DNS::Resolver( nameservers => [ '10.1.1.128', '10.1.2.128' ], recurse => 0, debug => 1 ); Returns a resolver object. If no arguments are supplied, new() returns an object having the default configuration. On Unix and Linux systems, the default values are read from the following files, in the order indicated: /etc/resolv.conf $HOME/.resolv.conf ./.resolv.conf The following keywords are recognised in resolver configuration files: The default domain. A space-separated list of domains to put in the search list. A space-separated list of nameservers to query. Except for /etc/resolv.conf, files will only be read if owned by the effective userid running the program. In addition, several environment variables $resolver = new Net::DNS::Resolver(. Domain name suffix to be appended to queries of unqualified names. For more information on any of these options, please consult the method of the same name. : dnsrchis true.olver->query( 'mailhost' ); $packet = $resolver->query( 'mailhost.example.com' ); $packet = $resolver->query( '192.0.2.1' ); $packet = $resolver->query( 'example.com', 'MX' ); $packet = $resolver->query( 'annotation.example.com', 'TXT', 'HS' ); Performs a DNS query for the given name; the search list is not applied. If the name does not contain any dots and defnames is true, the default domain will be appended. The record type and class can be omitted; they default to A and IN. If the name looks like an IP address (IPv4 or IPv6), an appropriate PTR query will be performed. Returns a Net::DNS::Packet object, or undef if no answers were found. If you need to examine the response packet, whether it contains any answers or not, use the send() method instead. olver->tcp_timeout( 10 ); $resolver->tsig( 'Khmac-sha1.example.+161+24053.private' ); $iterator = $resolver->axfr( 'example.com' ); die 'Zone transfer failed: ', $resolver->errorstring unless $iterator; while ( $rr = $iterator->() ) { $rr->print; } @nameservers = $resolver->nameservers(); $resolver->nameservers( '192.0.2.1', '192.0.2.2', '2001:DB8::3' ); Gets or sets the nameservers to be queried. Also see the IPv6 transport notes below $resolver->empty_nameservers(); Empties the list of nameservers. $resolver->print; Prints the resolver state on the standard output. print $resolver->string; Returns a string representation of the resolver state. @searchlist = $resolver->searchlist; $resolver->searchlist( 'a.example', 'b.example', 'c.example' ); Gets or sets the resolver search list. $resolver->empty_searchlist(); Empties the searchlist. print 'sending queries to port ', $resolver->port, "\n"; $resolver->port(9732); Gets or sets the port to which queries are sent. Convenient for nameserver testing using a non-standard port. The default is port 53. print 'sending queries from port ', $resolver->srcport, "\n"; $resolver->srcport(5353); Gets or sets the port from which queries are sent. The default is 0, meaning any port. a response. The program can then perform other tasks while awaiting the response from the nameserver. bgread to get the response packet. Either bgisready or IO::Select may be used to find out if the socket is ready.olver-olver- = $resolver->tsig; $resolver->tsig( $tsig ); $resolver->tsig( 'Khmac-sha1.example.+161+24053.private' ); $resolver->tsig( 'Khmac-sha1.example.+161+24053.key' ); $resolver->tsig( 'Khmac-sha1.example.+161+24053.key', fudge => 60 ); $resolver->tsig( $key_name, $key ); $resolver- would like the resolver to sign packets automatically. Packets can also be signed manually; see the Net::DNS::Packet and Net::DNS::Update manual pages for examples. TSIG records in manually-signed packets take precedence over those that the resolver would add automatically. print 'retrans interval: ', $resolver->retrans, "\n"; $resolver->retrans(3); Get or set the retransmission interval The default is 5 seconds. print 'number of tries: ', $resolver->retry, "\n"; $resolver->retry(2); Get or set the number of times to try the query. The default is 4. print 'recursion flag: ', $resolver->recurse, "\n"; $resolver->recurse(0); Get or set the recursion flag. If true, this will direct nameservers to perform a recursive query. The default is true. print 'defnames flag: ', $resolver->defnames, "\n"; $resolver->defnames(0); Get or set the defnames flag. If true, calls to query will append the default domain to names that contain no dots. The default is true. print 'dnsrch flag: ', $resolver->dnsrch, "\n"; $resolver->dnsrch(0); Get or set the dnsrch flag. If true, calls to search will apply the search list to resolve names that are not fully qualified. The default is true. print 'debug flag: ', $resolver->debug, "\n"; $resolver->debug(1); Get or set the debug flag. If set, calls to search, query, and send will print debugging information on the standard output. The default is false. print 'usevc flag: ', $resolver->usevc, "\n"; $resolver->usevc(1); Get or set the usevc flag. If true, queries will be performed using virtual circuits (TCP) instead of datagrams (UDP). The default is false. print 'TCP timeout: ', $resolver->tcp_timeout, "\n"; $resolver->tcp_timeout(10); Get or set the TCP timeout in seconds. The default is 120 seconds (2 minutes). A timeout of undef means indefinite. print 'UDP timeout: ', $resolver->udp_timeout, "\n"; $resolver->udp_timeout(10); Get or set the UDP timeout in seconds. The default is undef, which means that the retry and retrans settings will be used to perform the retries until they exhausted. print 'Persistent TCP flag: ', $resolver->persistent_tcp, "\n"; $resolver->persistent_tcp(1); Get or set the persistent TCP setting. If true, Net::DNS will keep a TCP socket open for each host:port to which it connects. This is useful if you are using TCP and need to make a lot of queries or updates to the same nameserver. The default is false unless you are running a SOCKSified Perl, in which case the default is true.. print 'igntc flag: ', $resolver->igntc, "\n"; $resolver->igntc(1); Get or set the igntc flag. If true, truncated packets will be ignored. If false, the query will be retried using TCP. The default is false. print 'query status: ', $resolver->errorstring, "\n"; Returns a string containing the status of the most recent query. print 'last answer was from: ', $resolver->answerfrom, "\n"; Returns the IP address from which the most recent packet was received in response to a query. print 'size of last answer: ', $resolver->answersize, "\n"; Returns the size in bytes of the most recent packet received in response to a query. print "dnssec flag: ", $resolver->dnssec, "\n"; $resolver->dnssec(0); The dnssec flag causes the resolver to transmit DNSSEC queries and to add a EDNS0 record as required by RFC2671 and RFC3225. The actions of, and response from, the remote nameserver is determined by the settings of the AD and CD flags. Calling the dnssec() method with a non-zero value will also set the UDP packet size to the default value of 2048. If that is too small or too big for your environment, you should call the udppacketsize() method immediately after. $resolver->dnssec(1); # DNSSEC using default packetsize $resolver->udppacketsize(1250); # lower the UDP packet size A fatal exception will be raised if the dnssec() method is called but the Net::DNS::SEC library has not been installed. $resolver->dnssec(1); $resolver->adflag(1); print "authentication desired flag: ", $resolver->adflag, "\n"; Gets or sets the AD bit for dnssec queries. This bit indicates that the caller is interested in the returned AD (authentic data) bit but does not require any dnssec RRs to be included in the response. The default value is 0. $resolver->dnssec(1); $resolver->cdflag(1); print "checking disabled flag: ", $resolver->cdflag, "\n"; Gets or sets the CD bit for dnssec queries. This bit indicates that authentication by upstream nameservers should be suppressed. Any dnssec RRs required to execute the authentication procedure should be included in the response. The default value is 0. print "udppacketsize: ", $resolver->udppacketsize, "\n"; $resolver->udppacketsize(2048); udppacketsize will set or get the packet size. If set to a value greater than the default DNS packet size, an EDNS extension will be added indicating support for UDP fragment reassembly. The following environment variables can also be used to configure the resolver: # Bourne Shell RES_NAMESERVERS="192.0.2.1 192.0.2.2 2001:DB8::3" export RES_NAMESERVERS # C Shell setenv RES_NAMESERVERS "192.0.2.1 192.0.2.2 2001:DB8::3" A space-separated list of nameservers to query. # Bourne Shell RES_SEARCHLIST="a.example.com b.example.com c.example.com" export RES_SEARCHLIST # C Shell setenv RES_SEARCHLIST "a.example.com b.example.com c Net::DNS::Resolver library will enable IPv6 transport if the appropriate libraries (Socket6 and IO::Socket::INET6) are available and the destination nameserver has at least one IPv6 address. The force_v4(), force_v6() and prefer_v6() methods with a non-zero argument may be used to configure transport selection. The behaviour of the nameserver() method illustrates the transport selection mechanism. If, for example, IPv6 is not available or IPv4 transport has been forced, the nameserver() method will only return IPv4 addresses: $resolver->nameservers( '192.0.2.1', '192.0.2.2', '2001:DB8::3' ); $resolver->force_v4(1); print join ' ', $resolver->nameservers(); will print 192.0.2.1 192.0.2.2 Net::DNS::Resolver is actually an empty subclass. At compile time a super class is chosen based on the current platform. A side benefit of this allows for easy modification of the methods in Net::DNS::Resolver. You can simply add a method to the namespace! For example, if we wanted to cache lookups: package Net::DNS::Resolver; my %cache; sub search { $self = shift; $cache{"@_"} ||= $self->SUPER::search(@_); } bgsend() does not honour the usevc flag and only uses UDP for transport. Portions Copyright (c)2002-2004 Chris Reinhardt. Portions Copyright (c)2005 Olaf M. Kolkman, NLnet Labs. Portions Copyright (c)2014 Dick Franks.
http://search.cpan.org/dist/Net-DNS/lib/Net/DNS/Resolver.pm
CC-MAIN-2014-52
refinedweb
1,729
59.09
Details Description Hi The following patch (the biggest from the series) changes the codes so that Logger caches a LoggerRepositoryPtr instead of a LoggerRepository* otherwise the cached pointer may get "delete"ed before it's last use (as proved by valgrind and SIGSEGV). This patch fixes the first crash I got with log4cxx when trying to log from a destructor of a static object. Activity - All - Work Log - History - Activity - Transitions Hmm, this issue tracker does not seem to have a feature to directly quote on the text so I'll try to emulate it. "Unlike the encoders and decoders in LOGCXX-112, the repo can't be effectively recovered after its destructed." Agreed (I don't know log4cxx that well but to me it seems to be a complex structure so it makes sense). "The repo will need to be destructed at some point unless you want to leak a lot of resources and then others would complain." Of course, we need to make sure it is destructed at some point. ." This I do not fully agree. Acording to my reading and understanding of the ISO C++ features while the compiler HAS to guarantee an exact order to construct and destruct objects from a single translation unit (ie in the same translation unit the static objects are constructed in the order of appearance and are destructed in the reversed order obviously) there is absolutely no guarantee to the order of constructors/destructors across different translation units. Considering that here we are talking about my codes (log4cxx user) and the log4cxx codes they are cleary at least 2 separate translation units. This means that the copiler and the C++ standard offer no guarantee that: 1. the constructors of the static objects of log4cxx are called before any of the static objects of my codes (this you might end up using uninitlized resources if in the constructors you use log4cxx) 2. the destructors of the static objects of log4cxx are called AFTER all the destructors of my static objects are finished (ie I might end up using invalid data) AFAIK, to be able to manage this dependency issue (because it's a dependency issue, some static objects lifetime depends on other static object's lifetime) usually the user has to emply reference counters. The same problem for example is addressed with std::cin/cout/cerr/clog because they are 4 static iostream objects that need to be "constructed" before any of their users and also need to be destroyed after all of their users have finished. The solution employed usually with iostreams is like this: there is a header file included by all cin/cout/clog/cerr users, this header file declares something like "static iostreamreference reference;" meanging that all cin/cout/clog/cerr users get a iostreamreference object created in their own translation unit (as it's "static" in the header file) and this iostreamreference object in the constructor all it does is initilize the cin/cout/cerr/clog streams if not already and increment the usage count, and in the destructor decrements the user count and destroys them if count reaches 0. Because I have seen that log4cxx already makes heavy usage of reference counted smart pointers (probably because it somewhat tries to emulate the log4j aproach) I thought to myself that just adding a reference count for the object used by the Logger's whould be enough and acording to my tests it solves the crash I got. Theoretically any object that is using the services of another object which lifetime is decoupled from the user (ie it is NOT created directly by the user and it is NOT destroyed directly by the user) needs to cache the pointers/references of the used object with a reference count mechanism through a Singleton-like interface to make sure the used object is created already when we need it and that is destroyed only after we don't need it anymore. . " My users are just classes that embed a LoggerPtr object member initilized with log4cxx::getLogger from the constructor. As such there are already reference counter mechanisms (provided by LoggerPtr) that make sure that the Logger used by my object's constructors is alive as long as my object lives. And my experience proved that it indeed works nicely. The only problem is that there is a "blind shared pointer" to a static LoggerRepository object (Hierarcy) in each Logger, that might get destructed before every Logger gets destructed (because we have no guarantee that the static object destructors from the translation unit in log4cxx that included the static Hierarchy object are called after the destructors of my objects which might log using LoggerPtr that point to a Logger that uses the cached LoggerRepository pointer). As such, the example you provided shouldnt solve my problem either. Hope I explained better now The following seems to be a guarantee of the order of destructors by my reading. Section 3.6.3-1 1- Destructors (class.dtor) for initialized objects of static storage duration (declared at block scope or at namespace scope) are called as a result of returning from main and as a result of calling exit (lib.support.start.term).. also suggests that others see the C++ standard as specifying an order for destruction cross compilation units (reverse of the unspecified initialization order). I was mentioning that since it might provide you with a means of controlling destruction sufficient to avoid your current crashes until we find a permanent solution. Yes, log4cxx does try to emulate log4j semantics. I've been "homeless" for a couple of weeks and don't have all the resources (books and time) that I would typically have and this type of problem would require. I'm going to be moving into my new place on Monday and should be able to go deeper on the issue. Many months ago, we had to address static object initialization. log4cxx-0.9.7 would crash a lot on constructor logging since the relative order of initialization was unspecified. That was resolved by eliminating non-local static members. The flip-side wasn't considered at that time. It took a while to understand the nuances of the problem and I expect this will take some time to work through the issues. The ideas in your patch may eventually be adopted, however it changes the API more than I'd like to commit without a thorough review of the issue. It would be great if you could attach some trivial examples that result in crashes while logging in destructors. Please specify what compiler, OS, etc, were used. Yes I was wrong. I think I confused the destruction "no-guarantee" issue with the construction one (which indeed exists, that is you don't have any standard guarantee of the order of object initialization of global data across different translation units). You do have a guarantee of the order of the destructors called it seems. Then I don't know, maybe it's a bug of g++ or their interpretation of the standard that doesn't do this. Because clearly (as valgrind reports) without my patch a destructor of a static object of mine when trying to log is making a call trace that ends up accessing a LoggerRepository dangling pointer which as valgrind shows has been delete-ed from the DefaultLoggerRepository destructor (which is a static object). The "dummyLogger" trick I can try but I need to declare it in every translation unit that declares static objects that contain LoggerPtr in them (although most of my static objects are in main()'s translation unit but not all... yeah it sounds like a bad design but I don't have THAT many static objects ). Forgot about what you lastasked me. I have tried to create a separate test case but failed to reproduce the behaivour Committed changes in r 371612 that check if the repository is non-null before calling one of its methods. This and the changes to objectptr.h in LOGCXX-112 should result in Loggers that are created after the destruction of the default logger repository to be ineffectual, but at least they shouldn't crash. I suspect that there are other improvements to the code that should make log4cxx more stable when logging in static destructors. However full capabilities will require that users understand the initialization and destruction rules, so that log4cxx isn't partially destructed at the time that you want to do logging requests. I'm closing this issue, if there are other scenarios and test cases that you want to add, please report them as a different issue. I'm going to need to understand this one better. Unlike the encoders and decoders in LOGCXX-112, the repo can't be effectively recovered after its destructed. The repo will need to be destructed at some point unless you want to leak a lot of resources and then others would complain..
https://issues.apache.org/jira/browse/LOGCXX-111?focusedCommentId=12356943&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel
CC-MAIN-2015-35
refinedweb
1,494
53.55