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 |
|---|---|---|---|---|---|
The?
The answer is: the
foreach loop semantics were designed before generics were added to the language; a highly likely scenario is that the collection being enumerated is an
ArrayList or other collection where the element type is unknown to the compiler, but is known to the developer. It is rare for an
ArrayList to contain
ints and
strings and
Exceptions and
Customers; usually an
ArrayList contains elements of uniform type known to the developer. In a world without generics you typically have to know that ahead of time by some means other than the type system telling you. So just as a cast from
object to
string is a hint to the compiler that the value is really a
string, so too is
foreach(string name in myArrayList)
a hint to the compiler that the collection contains
strings. You don't want to force the user to write:
foreach(object obj in myArrayList) { string name = (string)obj;
In a world with generics, where the vast majority of sequences enumerated are now statically typed, this is a misfeature. But it would be a large breaking change to remove it, so we're stuck with it.
I personally find this feature quite confusing. When I was a beginner C# programmer I mistakenly believed the semantics of the
foreach loop to be:
while (e.MoveNext()) { current = e.Current; if (!(current is V)) continue; v = current as V; embedded-statement }
That is, the real feature is "assert that every item in the sequence is of type
V and crash if it is not", whereas I believed it was "for every element in this sequence of type
V...".3
You might wonder why the C# compiler does not produce a warning in modern code, where generics are being used. When I was on the C# compiler team I implemented such a warning and tried it on the corpus of C# code within Microsoft. The number of warnings produced in correct code (where someone had a sequence of
Animal but knew via other means that they were all
Giraffe) was large. Warnings which fire too often in correct code are bad warnings, so we opted out of adding the feature.
The moral of the story is: sometimes you get stuck with weird legacy misfeatures when you massively change the type system in version two of a language. Try to get your type system right the first time when next you design a new language.
- This is not exactly what the spec says; I've made one small edit because I don't want to get into the difference between the element type and the loop variable type in this episode. ↩
- Or the
longbeing a constant that fits into an
int. ↩
- If the latter is the behavior you actually want, the
OfTypeextension method has those semantics. ↩
I tend to think of the type specified in the foreach as a request for an explicit conversion. In "foreach(String str in myArrayList)", for example, I am specifying String because I want the compiler to put in a conversion for me. If I didn't want the conversion, I would just specify "var" as the type, and get whatever type the enumerator returns.
And now that you mention 'var', I'm intrigued on how did the spec change when implicit type inference for locals was added (if it changed at all). Given that you cannot cast to var, I'm guessing type inference is performed before expanding the foreach.
Since the element type is inferred from the type returned by Current, the cast becomes a no-op "identity conversion".
foreach(object obj in myArrayList)
{
string name = (object)obj; <--- I think you mean (string)obj
Whoops. Thanks!
A few months ago I suggested ReSharper should implement such a warning:
Sadly, it seems nobody's interested.
In my humble opinion, this almost tacit downcast *is* bad enough to justify forcing the user to do it explicitly.
Does this affect performance or the unnecessary explicit cast can be optimized away by the jitter?
Also you did move the loop variable declaration inside the loop at some point (because of closures), didn't you?
You can determine the performance cost by measuring it. I never have.
And yes, I cut-n-pasted from the C# 4 spec there.
Eric, what does compiler produce if we do not specify the type but use var keyword?
Is there any sense in explicit casting if compiler already inferred the type from the collection's items?
oops, missed you comment above...
Maybe a warning when the cast happens to be a conversion that is not allowed implicitly (like long to int), and no warning when it's a cast?
Pingback: The Morning Brew - Chris Alcock » The Morning Brew #1404
Does that mean that if you use a foreach loop on a generic struct collection, you get the (tiny, but existing) performance cost of a boxing as e.Current is an object before being cast back to a struct?
No; the whole point of this scheme is to avoid that cost if possible.
So I guess in this context we have
* C is IEnumerable of T
* E is IEnumerator of T
to prevent boxing. am I right?
Correct; however, even in C# 1.0 it was possible to avoid boxing if you were clever. That's a subject for another day.
I know the answer to how (I won't spoil it for others), but I'm curious - do Arrays in C# 1.0 do this?
I disagree that this is now a misfeature. The .NET framework and friends (such as the SharePoint API) have numerous collections which do not implement IEnumerable<T> and for which enumeration using var results in type Object being inferred. These are not deprecated APIs either (MatchCollection anyone?). Directly specifying the type remains an elegant way to write the foreach loop without a lot of additional cruft.
Personally, I consider it a problem that all these old collection classes are not generic. It's a bit late to be worth fixing it now (and when they were initially implemented, generics did not exist), but I regret the existence of so many non-generic collection classes.
It would make me happy if a new iteration of these classes implemented the generic IENumerable interface, but I'm sure the costs of this change are much higher than the rather minimal benefits.
Even for dealing with those legacy collections, using the Cast or OfType extension methods (depending on the desired semantics) may be better, as it makes crystal clear what you are actually doing.
It's a good idea never to hide a cast behind a somewhat obscure language feature, even more so a feature a lot of people misinterpret at first. (I assumed that foreach (int i in myCollection) was the same as foreach (var i in myCollection.OfType() before reading this article. It appears it is more (var i in myCollection.Cast()
What I would like to see for this and many other similar situations (e.g. invoking a method on a read-only struct, or trying to pass a property as a `ref` parameter) would be attributes which specify in what cases certain compiler inferences or substitutions would be semantically correct and helpful, and in which cases they should generate warnings or errors. For example, in the absence of an attribute or explicit rule, a compiler might helpfully permit the above-described inference (without a warning) only if `Current` returns a non-generic `Object`, but in the presence of an attribute or explicit rule would allow or forbid the type inference. That would seem to offer the best of all worlds.
I'm not so sure this language feature is all that obscure. The behavior of foreach is one of the very first things you learn when studying a language. The added ugliness and (admittedly miniscule) overhead of calling .Cast() is not worth it to me when its already baked right there into foreach.
If this is a misfeature why was the same feature added to LINQ?
from T x in enumerable
Very handy for .NET legacy collections (MatchCollection, ...), but was that the full justification?
Yes, that's the justification. Also note that the feature does not introduce a cast, in introduces a call to the Cast extension method, which of course you can implement to do whatever you want.
Now you got me curious...
Is there any relation with implementation of interfaces as well?
Consider:
public interface IFoo
{
void Bar();
}
public class MyFoo : IFoo
{
public void Bar()
{
// do something
}
void IFoo.Bar()
{
// do something completely different
}
}
Is it correct that the explicit cast is always going to make MyFoo::IFoo.Bar() be called instead of MyFoo::Bar()?
Well it would be awfully strange if you got a different method called out of
foreach(IFoo ifoo in foos) ifoo.Bar();and
IFoo ifoo = foos[0]; ifoo.Bar();.
Now that we have Cast() and OfType(), I think it makes a lot of sense to warn in this situation.
However, that statement only applies to new code, as there is obviously a lot of legacy code that relies on the magic.
I think the best solution would be to add a Code Analysis rule for this. That way, on older projects the rule could easily be disabled, but for new projects, the rule would be on by default and devs would be discouraged from relying on the now-mis-feature.
Nice post, but I am confused on one part:
E e = ((C)(x)).GetEnumerator();
What is the C?
That's for some subtle cases that I deliberately did not mention. Suppose you are in the incredibly unlikely and foolish situation of having a collection
class F : IEnumerable { public int GetEnumerator; IEnumerator IEnumerable.GetEnumerator() { ... }. What should happen when you do a
foreach(string s in f)on this thing? Surely not
f.GetEnumerator(), because
f.GetEnumeratoris an
int! The right method can only be accessed by converting to the interface type. Thus the compiler generates
((IEnumerable)f).GetEnumerator(). The
Cis just a stand-in for "whatever type was determined to be the type necessary to get the right
GetEnumerator". This is all explained in the specification; see it for more details.
Why does this work if for class F : IEnumerable { as you stated above}, but not for interface I { IEnumerator GetEnumerator(); } and class C : I? Is IEnumerable a special case? If so, why say "the type necessary" as though it could be any type other than IEnumerable or the declared type of x?
"The collection could be a list of longs and V could be int": I never realised that was possible before. For that to work, the enumerator's Current property must have type long. If it has type object, say because you're dealing with an ArrayList, even if the collection only contains longs, the conversion to int will cause an exception to be thrown. Exactly like an explicit cast would. In that case, you could do something like foreach (int i in a.Cast<long>()) { ... }
Why did you write:
v = current as V;
after you've checked that current is of type V (the continue)?
Doesn't the "as" operator also do a type check? I would think
if (!(current is V)) continue;
v = (V)current;
would be better.
en ligne acheter sacs moncler pas cher 2013 france paris | http://ericlippert.com/2013/07/22/why-does-a-foreach-loop-silently-insert-an-explicit-conversion/ | CC-MAIN-2014-15 | refinedweb | 1,896 | 62.98 |
We have IIS running on two servers (IIS8 and 10), and encounter very high memory usage of our ASP.NET WebForms Applications lately, mostly accessed through aspx pages.
What happens is that over time, our application pools consume more and more memory, until the physical memory on the server (64GB) is nearly exhausted. This is definitely not normal.
We tried to find out why this happens but are out of ideas. It is unclear weather this is a memory leak in our application, or normal behaviour, so perhaps someone can shed some light on it.
Facts:
Over time, the application pools reserve AND use more and more memory, that is not freed (task manager says that both working set and commit size are very high, so it is actually used/held, right?)
memory profilers like ANTS, .dotMemory, .NET MemoryProfiler say that the managed memory consumption is rather low, say 20-200MB, and showing a lot of unmanaged memory, that would be used, but free.
they don't give any hint to what might be causing the unmanaged usage, even with snapshots and detailed profiling methods.
if we "hammer" the start page with F5 key while not releasing it, we can shoot memory usage up to 2-5 gigabyte in one minute. This is a little insane.
we know that IIS/Application pools tend to reserve memory in a opportunistic way the more memory that is available, but this is way too much.
the only thing we see is that the front page seems to be held in memory with it's controls and ComponentModel objects, but there is no single reference to any of our page objects or own namespace classes anywhere in the memory profilers.
the memory consumption was anecdotally fine a year ago, and stopped at 2-3 gigabytes total , but we can't reproduce it anymore with an old version of the application.
it happens on a fresh local installation of IIS under WIN10, too.
the applications is built in release mode, optimised, compiled into a single DLL at the moment, also tried without, trace flag on, 5mb in size
It seems that we need to take the application apart, split it into several modules and see how those behave. The assemblies/libraries loaded at runtime can, but shouldn't be the problem. We actually dont reference that much (FreeTextBox, Microsoft ReportViewer, SharpCompress, Crystal Reports, AjaxControlToolKit 15), we removed all but CrystalReports/AjaxControlToolKit already to see what happens but didn't change.
We also use lots of the WebForms controls, including Timers and UpdatePanels sometimes.
We also don't know how to find the culprit using memoryprofilers, assuming there is a hidden reference causing one or more aspx pages to be held in memory because the .NET class instances never show any link to anything.
We'd be happy to get ANY hint what we might misunderstand regarding memory reservation or how to troubleshoot this memory consumption issue.
Thank you very much for your time!
EDIT (forgot to mention): - We added GC.Collect/WaitForPendingFinalizers/GC.Collect to our Page_Load function of the start page to see if it helps, and it indeed helps for a while or a bit, until there is a another pressure situation (with F5) where the memory usage just goes up again in an extreme way. | https://serverfault.com/questions/976018/iis-application-pool-taking-too-much-memory | CC-MAIN-2020-50 | refinedweb | 553 | 59.13 |
Php cms inplace edit jobs
I need a mobile app desinged for ios and android with a desktop front end. I need to create a workflow. The front end will capture maintenance jobs ...various mobile maintenance teams. Maintenance team will need to complete job and report back on app with ability ti upload photos and have geo tags. Full report system must be inplace for the front end
..)
[url removed, login to view] with the sausage man inplace
I need inplace edit for columns from database to be displayed on the webpage. It should be working on django version 2.0 and python 3.6
I am hiring developer for these. Proper installation of Txbits to server. Can add ETH, XRP, TRX, NEO, ETC coins in the...server. Can add ETH, XRP, TRX, NEO, ETC coins in the exchange. Can make some customisations based on design that we will provide Can give support after. * Add Fiat (INR) inplace of USD to Crypto and Crypto to Fiat Trading.
Hello! I need a quick animation video made that correlates with a script that I have inplace that shows how the blockchain works. The video will be under 1 minute long and it will be under 30 mB in file size. The video should be done ASAP, and if any more questions and needed to be answered to do the project, feel free to message me and we can negotiate
import pandas as pd df = pd.read_csv('[url removed, login to view]', encoding='utf-8', skipinitialspace=True ) [url removed, login to view](['序号'], axis=1, inplace=True) # <= Works #[url removed, login to view](['年度'], axis=1, inplace=True) # <= Does NOT work df
Please Sign Up or Login to see details.
We have an inplace wordpress site using the jupiter theme. We need an expert to help us finish the site and launch it. We need management of the site after launch as well - but this will only be a few hours a month. The current site needs a few sections added to it as well as some updated screenshots of our app and service that we are promoting.
we have accounting software in php mysql , we have print page built in html, we want pdf page for print inplace of html page. urgent requirement. we can pay hourly or per page.
I have an existing client website. This website has a login system already inplace where they can sign up to the website. What I need is this: “We sell a product that consumers need to add to their spa/hot tub water every three months. Some of our dealers were asking for a web page or an app that could be used to remind people when to add the next
...Current Website: [url removed, login to view] product development company with full package benefits -Details: onepage theme with one other extra page for a portfolio no inplace pictures only use linked images from my Github repository 3) website requirements: Landingpage: -parallax top of page image with responsive text -responsive icons
improve my website ranking, keyword search. our site use wordpress, and already have yoast seo inplace. I want to increase organic search
...messaging, So one person type in his own language and when message sent out it on receiver's end it should be in reciever's selected language. probably need some translation api inplace. 2) App should detect User Language preference so if language is available in app than it should change the layout based on selection of language, if the language is not
I have a handrawn picture showing general idea to send . A muscule guy from rear view with bent barbell on back with weights with words inplace of barbell
i have a website where a developer was busy designing it, unfortunately i lost contact with ...have a website where a developer was busy designing it, unfortunately i lost contact with him , so i need to complete the online store, The banners and online cart is already inplace. i need to complete the website, and install all the products and prices.
I need a presentation produced to a high level in order to present to investors. The content is sensitive so i will not be able to...colours and fonts artwork as well as stationary (i would like this cleaned up at some point also). The deck is 16 slides in total but may be able to be reduced using visuals inplace of text where deemed appropriate.
If you know anything about Jedox, get in contact, I need a spreadsheet made into a web app. The first beta spreadsheet with macros and VBA is already inplace, but I need to make my current project work on the web.
I have an abantecart website currently on an older version i cannot update due to the amount of modification i have made. I would like to im...categories look on a mobile so when on a pc they look normal but on a phone they have the modern menu sybol at the top which will show my product catagories (i would like this inplace of the ugly Go to.. menu) | https://www.freelancer.com/job-search/php-cms-inplace-edit/ | CC-MAIN-2018-17 | refinedweb | 859 | 70.23 |
I am beginner of ImageJ. Currently I am calculating bubble areas in attachment. When I make image binary and fill holes, I get an Image which you can see in the second file attached. There are still a lot of bubbles(holes) needed to be filled in order to calculate their area, the reason is that some circles are disconnected. Does anyone know how to make these circles connected or other ways to calculate bubble area in the first file attached?
You want something like this, no? Or more precise edge detection, maybe. I am new to measuring bubbles.
It's missing the elongated bubble in the top right, and there are some artefact ROIs between bubbles (38, 101). But these are easily removed.
Total surface area is 166777.
Yes, sure. That's exactly what I want. Of course, it would be better to be more precise. Could you please tell me how you manage to do it?
I will get back to you once I'm on my computer, but the really quick work I did for this example pic:
Process >> Find edges
Process ... fill holes.
Analyze particles, set size to smallest to largest bubbles. Set desired circularity of bubbles.
Then simply measure the area of this selection.
Maybe I applied some more preprocessing, I will get back to you with details.
HTH,Sverre
thanks, following your steps, I still can't get desired results and I don't know which step I miss.
This is what i did from the macro recorder, play around with different filters and the analyze particles parameters to see if you can improve it. You can also try the trainable weka segmentation, it is well documented and you will find guides on youtube!
run("Find Edges");
run("Make Binary");
run("Fill Holes");
selectWindow("bubbles.JPG");
run("Analyze Particles...", "size=200-16000 circularity=0.28-1.00 show=Outlines display summarize add");
Good day Hao Wang,
working with thresholds is difficult and most often they don't generalize well…
For your example image you may try the following ImageJ-macro:
///////////////macro start///////////////requires("1.51k");run("Set Measurements...", "area_fraction redirect=None decimal=3");run("32-bit");setAutoThreshold("Mean dark");run("Analyze Particles...", "size=200-Infinity circularity=0.30-1.00 show=Masks");run("Invert LUT");setOption("BlackBackground", true);run("Dilate");run("Measure");run("Show All");///////////////macro end///////////////
It gives you the following result image with a pore area fraction of 67.76%.
Evidently, there are two glitches at the bottom right and partial pores at the borders are missing.
You may adjust the Particle Size as well as the Particle Circularity.Furthermore, you may repeat "Dilate" and if bubbles fuse, you may separate them by introducing
run("Watershed");
Good luck and be successful
Herbie
I have no idea how you ended up there, can you open your macro recorder, do this again and then copy/paste the record?
plugins >> macros >> recorder
Good day Sverre Grødem
the macro was created by using the macro recorder.
If the macro does what you want, why should I paste the result of the recorder again?
If you are unclear about the processing steps, then you should consult the ImageJ manual:
Regards
I was replying to HW315, no?
You are both H..
Sorry Sverre Grødem,
for my wrong interpretation. In any case it was my fault!
Best
Thanks Herbie. I got a similar result as you suggested. One quick question: when running Analyze particles, does ImageJ find the edges of grayscale 255 or grayscale 0?
Thanks for your reply. Here is the Macro I recorded.
selectWindow("rawimage.JPG");run("Find Edges");run("Make Binary");run("Fill Holes");run("Analyze Particles...", "size=200-16000 circularity=0.28-1.00 show=Outlines display summarize add");
Mmh,
"Analyze Particles..." actually does no edge finding in the sense run("Find Edges") does. It simply takes the binarized image produced by setAutoThreshold("A Method").
However, "Analyze Particles..." assumes bright (255) particles on dark (0) background.
HTH
Thanks you. In my case, gas in bubbles and liquid between bubbles are bright, bubble edges are dark. As you said, when I analysis particle size, if I don't restrict size range, does that mean liquid between bubbles is also count as particle?
In addition, I want to count bubble area, but threshold doesn't achieve a precise result. Do you have any suggestions? Like taking a clearer photo?
Hao Wang,
the quality of your image isn't bad at all. I think it is taken quite carefully, but of course there is always "room" for improvements …
As I've written before, thresholding doesn't generalize well.
However, you should think about an objective measure of precision first. E.g. you could draw ROIs by hand and determine the percentage bubble area plus/minus an allowed tolerance. This would help with finding appropriate approaches.
My current estimate is that the bubble area fraction is 75%+-5%.
Ok Hao, I had some more time and wrote a short ad hoc script for your analysis. This utilizes the trainable weka segmentation plugin. I trained a quick example classifier for you, but I encourage you to make your own, and train it on more than one image, see how robust you can make it! You can for sure improve on the one I made in 5 minutes. Once you have your classifier you can automate this whole procedure, you can run it on files in a directory or large stacks, whatever you prefer.
Regarding making a classifier for WEKA: Video, detailed wiki.
Code in python, copy paste from here to File >> new >> script in IJ. Select language python.
Download the classifier I trained. Remember to set the path to the classifier in the script.
from ij import IJ, WindowManager
from trainableSegmentation import WekaSegmentation
import Watershed_Irregular_Features
from ij.process import ImageConverter
def bubblesizer():
# Please define the path to your classifier.
classifer_path = "D:\\Bubbles.model"
# Gets the image you want to segment.
your_image = IJ.getFilePath("Select image for WEKA segmentation")
target = IJ.openImage(your_image)
#launches weka segmentation.
weka = WekaSegmentation()
weka.setTrainingImage(target)
# Loads the classifier you have trained manually.
weka.loadClassifier(classifer_path)
weka.applyClassifier(False)
# Shows you the segmented image.
segmentation = weka.getClassifiedImage()
segmentation.show()
# Converts to binary, runs watershed segmentation and analyze particles. Outputs area measurements.
ImageConverter(segmentation).convertToGray8()
WindowManager.getCurrentImage()
IJ.run("Make Binary")
IJ.run("Invert")
IJ.run(segmentation, "Watershed Irregular Features", "erosion=1 convexity_treshold=0 separator_size=0-200")
IJ.run("Analyze Particles...", "size=50-Infinity circularity=0.1-1.00 show=Outlines display summarize")
bubblesizer()
And this is the result, which I think is more accurate as the other methods created too much space between bubbles. Not all bubles are segmented but it doesn't really matter, you want total area. By this logic maybe the watershed is redundant, up to you. Oh, and you may need to add the biovoxxel update site to get the watershed irregular features plugin. | http://forum.imagej.net/t/calculate-bubble-areas-in-a-foam-picture-how-to-fill-all-holes/4901 | CC-MAIN-2017-26 | refinedweb | 1,152 | 59.19 |
The code is for driving RGB LEDs through the rainbow via PWM.
The problem is that the code doesn't seem to work for me. I get the output printing to the terminal window but I don't get the expected colour transitions. I know that my pins are connected correctly because some other code (which does random transitions rather than deliberate rainbow transitions) does work.
Here's the code that I'm having a problem with:
and here's the code that is working okay for me:
Code: Select all
import random, time import RPi.GPIO as GPIO import colorsys RUNNING = True GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) red = 8 green = 10 blue = 12 GPIO.setup(red, GPIO.OUT) GPIO.setup(green, GPIO.OUT) GPIO.setup(blue, GPIO.OUT) Freq = 100 RED = GPIO.PWM(red, Freq) RED.start(100) GREEN = GPIO.PWM(green, Freq) GREEN.start(100) BLUE = GPIO.PWM(blue, Freq) BLUE.start(100) outval = 128 def wheel_color(position): """Get color from wheel value (0 - 384).""" if position < 0: position = 0 if position > 384: position = 384 if position < 128: r = 127 - position % 128 g = position % 128 b = 0 elif position < 256: g = 127 - position % 128 b = position % 128 r = 0 else: b = 127 - position % 128 r = position % 128 g = 0 return r, g, b try: while(True): for pos in range(0,385): r, g, b = wheel_color(pos) print (r, g, b) percenttestr = (r/128.0)*100.0 percenttestg = (g/128.0)*100.0 percenttestb = (b/128.0)*100.0 print (percenttestr) print (percenttestg) print (percenttestb) RED.ChangeDutyCycle(percenttestr) GREEN.ChangeDutyCycle(percenttestg) BLUE.ChangeDutyCycle(percenttestb) time.sleep(0.1) except KeyboardInterrupt: GPIO.cleanup()
Code: Select all
import RPi.GPIO as GPIO import threading import time import random R = 8 G = 10 B = 12 PINS = [R,G,B] def initialize_gpio(): GPIO.setmode(GPIO.BOARD) GPIO.setup(PINS, GPIO.OUT, initial=GPIO.LOW) def color_test(channel, frequency, speed, step): p = GPIO.PWM(channel, frequency) p.start(50) while True: for dutyCycle in range(0, 101, step): p.ChangeDutyCycle(dutyCycle) time.sleep(speed) for dutyCycle in range(100, -1, -step): p.ChangeDutyCycle(dutyCycle) time.sleep(speed) def color_test_thread(): threads = [] threads.append(threading.Thread(target=color_test, args=(R, 200, 0.02, 1))) threads.append(threading.Thread(target=color_test, args=(G, 200, 0.035, 1))) threads.append(threading.Thread(target=color_test, args=(B, 200, 0.045, 1))) for t in threads: t.daemon = True t.start() for t in threads: t.join() def main(): try: initialize_gpio() print("\nPress ^C (control-C) to exit the program.\n") color_test_thread() except KeyboardInterrupt: pass finally: GPIO.cleanup() if __name__ == '__main__': main()
Can anyone advise what I should do to find the cause of the problem?
Edit: could it be because I don't have colorsys? If that was the case, the code wouldn't run at all, right? When I type "pip install colorsys", I get the error:
so I don't actually know whether I have it installed but I would expect an error when I try to run the script if it was unable to import a required library, right?
Code: Select all
[email protected]:~ $ pip install colorsys Collecting colorsys Could not find a version that satisfies the requirement colorsys (from versions: ) No matching distribution found for colorsys | https://www.raspberrypi.org/forums/viewtopic.php?p=1471155 | CC-MAIN-2019-51 | refinedweb | 544 | 60.92 |
Investors eyeing a purchase of Acceleron Pharma, Inc. (Symbol: XLRN) stock, but cautious about paying the going market price of $44.77/share, might benefit from considering selling puts among the alternative strategies at their disposal. One interesting put contract in particular, is the August put at the $35 strike, which has a bid at the time of this writing of $2.85. Collecting that bid as the premium represents a 8.1% return against the $35 commitment, or a 19.2% annualized rate of return (at Stock Options Channel we call this the YieldBoost ).
Selling a put does not give an investor access to XLRN Acceleron Pharma, Inc. sees its shares fall 21.5% and the contract is exercised (resulting in a cost basis of $32.15 per share before broker commissions, subtracting the $2.85 from $35), the only upside to the put seller is from collecting that premium for the 19.2% annualized rate of return.
Below is a chart showing the trailing twelve month trading history for Acceleron Pharma, Inc., and highlighting in green where the $35 strike is located relative to that history:
The chart above, and the stock's historical volatility, can be a helpful guide in combination with fundamental analysis to judge whether selling the August put at the $35 strike for the 19.2% annualized rate of return represents good reward for the risks. We calculate the trailing twelve month volatility for Acceleron Pharma, Inc. (considering the last 252 trading day closing values as well as today's price of $44.77) to be 48%. For other put options contract ideas at the various different available expirations, visit the XLRN Stock Options page of StockOptionsChannel.com.
In mid-afternoon trading on Thursday, the put volume among S&P 500 components was 1.14M contracts, with call volume at 1.42. | https://www.nasdaq.com/articles/commit-purchase-acceleron-pharma-35-earn-192-annualized-using-options-2018-03-15 | CC-MAIN-2020-16 | refinedweb | 308 | 66.54 |
Eclipse Community Forums - RDF feed Eclipse Community Forums Questions regarding @Creatable <![CDATA[Hi, I'm working through the Eclipse 4 book by Lars Vogel. I've found the information on adding own objects to the context with the @Creatable annotation useful and tried it like described also online here. So I created a class that holds some configurations and annotated it with @Creatable In my Lifecycle Hook I injected the object with @Inject and filled the instance with some configuration parameters, so it can be used later on in my application. Then I created a handler that gets this configuration object injected with @Inject, and within the execute method, code is executed dependent on values within the configuration object. This didn't work as there was a new instance injected into my handler instead of the instance created first within the lifecycle hook. I changed this to create the object with new and put it to the context manually. In this case the object injected into my handler is the one created within the lifecycle hook. So it seems on using @Creatable the context hierarchy isn't searched for an existing instance, but a new one is created if there is none in the current context. Long text short question, how does @Creatable work? Should it search die context hierarchy for an existing instance or simply create a new instance for the current context? Greez, Dirk]]> Dirk Fauth 2012-10-09T19:43:21-00:00 Re: Questions regarding @Creatable <![CDATA[Try annotating the creatable class with @Singleton also. You would get something like: @Creatable @Singleton public class MyCreatableClass and this should prevent it from being recreated by the injector.]]> Sopot Cela 2012-10-09T22:27:15-00:00 Re: Questions regarding @Creatable <![CDATA[Hi Sopot, thanks for the answer. Yes this solves the issue with creating a new object. So if @Singleton is used together with @Creatable, the context hierarchy is searched if there is an instance already. Without @Singleton the injector will create a new instance for every context. Is this correct? Regarding to what I know about dependency injection right now, this would make sense. Greez, Dirk]]> Dirk Fauth 2012-10-10T06:39:48-00:00 Re: Questions regarding @Creatable <![CDATA[As far as i can tell, if @Singleton is not used, the instance created and put in the context for your Lifecycle hook is garbaged as soon as the hook returns (try overriding #finalize and put a breakpoint or trace in there) because the context only holds soft (or maybe weak) references on objects its creates (but strong references on objects that are manually put in it). And so when it comes to your handler, there is (again) no instance in the context so a new one is created and put in the context (and it too will be garbaged as soon as possible). Using @Singleton creates a reference to self, and thus prevents the garbaging, meaning the first instance will stay in the context and be found (and used) for you handler.]]> François POYER 2012-10-16T10:27:59-00:00 | http://www.eclipse.org/forums/feed.php?mode=m&th=397553&basic=1 | CC-MAIN-2016-40 | refinedweb | 515 | 61.06 |
Re: Server did not recognize the value of HTTP Header SOAPAction
- From: "moondaddy" <moondaddy@xxxxxxxxxxxxxxx>
- Date: Thu, 18 May 2006 01:08:56 -0500
Thanks for the reply.
I'm very puzzled here. I created a new test winforms project in 1.1. it
just has a simple form with 1 button on it. the code behind uses the exact
same code to call the exact same web service as the winforms app described
in my original post. both winforms apps use a have identical web references
to the same web service. The test app works OK, but the original app fails.
both apps should be creating identical credentials and I have not edited any
attributes or name spaces.
What's even more puzzling is that the app having this trouble uses a
different web service to login which works OK. The login uses myLogin.asmx
and the method that fails uses someOtherWS.asmx (all of which run in the
same WS app.). However, the login runs from a different project
(myLoginProject) and the rest of the app runs in myMainProject.
to answer your last question, yes I have a .net 2.0 winforms test app which
successfully calls this ws, but I also have the above mentioned 1.1 test app
which successfully calls this ws. Can you tell me how I can capture the
text of each proxy to compare with the one failing?
--
moondaddy@xxxxxxxxxxxxxxx
"Steven Cheng[MSFT]" <stcheng@xxxxxxxxxxxxxxxxxxxx> wrote in message
news:xC%23%23ZnXeGHA.764@xxxxxxxxxxxxxxxxxxxxxxxx
Hi Moondady,
Welcome to the ASPNET newsgroup.
From your description, I understand you've developed an ASP.NET webservice
which is consumed by a winform client application. Both ones are
constructed under .net framework 1.1. Recently, you upgrade the webservice
from ASP.NET 1.1 to ASP.NET 2.0, after that the 1.1 winform client broke
and reported the "Server did not recognize the value of HTTP Header
SOAPAction" error ,correct?
Based on my experience, since http SoapAction headeris used to identify
the
webmethod of a certain webservice, the problem is likely due to the client
application is sending an unexpected SoapAction header to the service. And
in ASP.NET webservice, the SoapAction header will be determined by both
the
service's namespace and the Action property set on the WebMethod
attribute.
#WebServiceAttribute.Namespace Property
bute.namespace(VS.80).aspx
#SoapDocumentMethodAttribute.Action Property
ocumentmethodattribute.action.aspx
Have you explicitly set this property for your webservice and the
webmethod? Also, for general troubleshooting, you can create a .net 2.0
webservice proxy to see whether it can work correctly. If it works, you
can
compare the 2.0 client's generated proxy code with 1.1 client's code or
you
can use some trace tools to capture the raw SOAP xml message sent by
different clients to find the difference between them.
Hope this helps..)
.
- References:
- Server did not recognize the value of HTTP Header SOAPAction
- From: moondaddy
- RE: Server did not recognize the value of HTTP Header SOAPAction
- From: Steven Cheng[MSFT]
- Prev by Date: Re: Consuming Web Service via WSDL Files
- Next by Date: Re: Consuming Web Service via WSDL Files
- Previous by thread: RE: Server did not recognize the value of HTTP Header SOAPAction
- Next by thread: Re: Server did not recognize the value of HTTP Header SOAPAction
- Index(es): | http://www.tech-archive.net/Archive/DotNet/microsoft.public.dotnet.framework.aspnet.webservices/2006-05/msg00112.html | crawl-002 | refinedweb | 558 | 66.84 |
Working with GUIDs in MongoDB and ASP.NET MVC3
Just a small tip for those looking to use GUIDs as document IDs in MongoDB in conjunction with ASP.NET MVC3: it's a lot more straightforward than it may seem at the onset.
These examples are based off of the ASP.NET MVC3 tutorials...except with MongoDB instead of EF+SQL Server.
I've set up my model class like so:
public class Movie { [BsonId] public Guid ID { get; set; } public string Title { get; set; } public DateTime ReleaseDate { get; set; } public string Genre { get; set; } public decimal Price { get; set; } }
When the application creates an object and persists it to the database, you'll see that it shows up like this in the Mongo console (I've formatted the JSON for clarity):
> db.movies.find() { "_id":BinData(3,"n2FLBkAkhEOCkX42BGXRqg=="), "Title":"Test", "ReleaseDate": ISODate("2011-05-11T04:00:00 Z"), "Genre":"Comedy", "Price":"9.99" }
If you try to serialize this to JSON, instead of getting a GUID string, you'll get:
// Get a document BsonDocument document = movies.FindOneAs<BsonDocument>(); // Direct to JSON document.ToJson(); /* { "_id":new BinData(3, "n2FLBkAkhEOCkX42BGXRqg==" ), "Title":"Test", "ReleaseDate": ISODate("2011-05-11T04:00:00 Z"), "Genre":"Comedy", "Price":"9.99" } */ // With settings JsonWriterSettings settings = new JsonWriterSettings{OutputMode = JsonOutputMode.JavaScript }; document.ToJson(settings); /* { "_id":{ "$binary":"n2FLBkAkhEOCkX42BGXRqg==", "$type":"03" }, "Title":"Test", "ReleaseDate":Date(1305086400000), "Genre":"Comedy", "Price":"9.99" } */
This is somewhat inconvenient if you want to work with it from a pure JavaScript perspective; I was hoping that it would have returned a GUID as a string instead. I was also concerned that this meant that I'd have to manage this manually as well on the server side in my actions, but it turns out that it works better than expected. The only caveat is that you have to use "_id" when creating queries; otherwise, you can use the GUID as-is and the Mongo APIs will convert it behind the scenes:
public ActionResult Details(Guid id) { MongoCollection<Movie> movies = _database.GetCollection<Movie>("movies"); // No need to mess with the GUID; use it as is. Movie movie = movies.FindOneAs<Movie>(Query.EQ("_id", id)); return View(movie); }
You can see the result below in the browser:
So far, so good with my little Mongo+MVC3 experiment
!
I Like Jeffrey Palermo’s Prediction…
I've been playing around with ASP.NET MVC for about a week now and it does everything right that ASP.NET web forms did so wrong. I've hated ASP.NET web forms with a passion as soon as I realized that the model was terrible for the majority of development shops in terms of managing unmanageable code jumbles -- huge methods written on event handlers...
Don't get me wrong, ASP.NET 1.0 was a huge step up from classic ASP, but it has exploded into this huge culture of control based RAD developers. Not that you couldn't roll your own MVC pattern for ASP.NET, but having it as an officially supported development model should help bring more web developers out from the grips of the dark side.
Most consultants (even "senior" ones) simply take the quick-and-dirty route when it comes to ASP.NET web forms development, dragging and dropping controls all day long. Not that it's a bad thing...for prototyping, but it quickly devolves into hard to manage, hard to maintain, and difficult to test codebases with very low levels of reusability. This is especially true once you roll on junior or mid level developers to a web project.
Earlier in the year, Jeffrey Palermo predicted that MVC would replace web forms as the dominant web application development model on the .NET platform. With the recent news of MVC 2, Palermo reasserts his prediction with even greater conviction. I was already long convinced that ASP.NET web forms was a craptastic model for web application development, but I had some skepticism about MVC (after my pretty awesome experience with Django). This past week has convinced me that MVC kicks ass and I hope that Jeffrey's prediction is right.
I wholeheartedly agree; I simply can't wait to dump ASP.NET web forms. | http://charliedigital.com/category/mvc/ | CC-MAIN-2015-06 | refinedweb | 698 | 55.84 |
[RFC v2 0/1] shiftfs: uid/gid shifting filesystem (s_user_ns version)
From:
James Bottomley
Date:
Mon Feb 20 2017 - 19:45:33 EST ]
This is a rewrite of the original shiftfs code to make use of super
block user namespaces. I've also removed the mappings passed in as
mount options in favour of using the mappings in s_user_ns. The upshot
is that it probably needs retesting for all the bugs people found,
since there's a lot of new code, and the use case has changed. Now, to
use it, you have to mark the filesystems you want to be mountable
inside a user namespace as root:
mount -t shiftfs -o mark <origin> <mark location>
The origin should be inaccessible to the unprivileged user, and the
access to the <mark location> can be controlled by the usual filesystem
permissions. Once this is done, any user who can get access to the
<mark location> can do (as the local user namespace root):
mount -t shiftfs <mark location> <somewhere in my local mount ns>
And they will be able to write at their user namespace shifts, but have
the interior view of the uid/gid be what appears on the <origin>
In using the s_user_ns, a lot of the code actually simplified, because
now our credential shifting code simply becomes use the <origin>
s_user_ns and the shifted uid/gid. The updated d_real() code from
overlayfs is also used, so shiftfs now no-longer needs its own file
operations.
---
[original blurb]
My use case for this is that I run a lot of unprivileged architectural
emulation containers on my system using user namespaces. Details here:
They're mostly for building non-x86 stuff (like aarch64 and arm secure
boot and mips images). For builds, I have all the environments in my
home directory with downshifted uids; however, sometimes I need to use
them to administer real images that run on systems, meaning the uids
are the usual privileged ones not the downshifted ones. The only
current choice I have is to start the emulation as root so the uid/gids
match. The reason for this filesystem is to use my standard
unprivileged containers to maintain these images. The way I do this is
crack the image with a loop and then shift the uids before bringing up
the container. I usually loop mount into /var/tmp/images/, so it's
owned by real root there:
jarvis:~ # ls -l /var/tmp/images/mips|head -4
total 0
drwxr-xr-x 1 root root 8192 May 12 08:33 bin
drwxr-xr-x 1 root root 6 May 12 08:33 boot
drwxr-xr-x 1 root root 167 May 12 08:33 dev
something similar with gid_map. So I shift mount the mips image with
mount
and I now see it as
jejb@jarvis:~> ls -l containers/mips|head -4
total 0
dr
unprivileged container to enter and administer the image.
It seems like a lot of container systems need to do something similar
when they try and provide unprivileged access to standard images.
Right at the moment, the security mechanism only allows root in the
host to use this, but it's not impossible to come up with a scheme for
marking trees that can safely be shift mounted by unprivileged user
names ] | http://lkml.iu.edu/hypermail/linux/kernel/1702.2/02795.html | CC-MAIN-2017-30 | refinedweb | 551 | 55.51 |
Important: Please read the Qt Code of Conduct -
New platform based on "minimal" not being recognized.
I am using Qt 5.3.2.
I am using .pro file based on this. Here is mine...
TARGET = qminimal TEMPLATE = lib PLUGIN_TYPE = platforms PLUGIN_CLASS_NAME = QMinimalIntegrationPlugin QT += core-private gui-private platformsupport-private SOURCES = main.cpp \ qminimalintegration.cpp \ qminimalbackingstore.cpp HEADERS = qminimalintegration.h \ qminimalbackingstore.h OTHER_FILES += minimal.json
I copied the other files cpp files as well.
However, when I run my app with
-platform minimal, it says that it cannot find it. The
QT_QPA_PLATFORM_PLUGIN_PATHis set to the correct directory. The moment I replace the distributed
qminimal.dllwith my own, it doesn't show up anymore for me to use.
The error message I get is "The application failed to start because it could not find or load the Qt platform plugin "minimal". The message lists of all the available platforms to choose from, and
minimalisn't showing up there either.
- SGaist Lifetime Qt Champion last edited by
Hi,
Without the implementation details it's hard to say what's going wrong.
Out of curiosity, why replace an existing plugin and not give it a name ?
Out of curiosity, why replace an existing plugin and not give it a name ?
I first wanted to build a plugin to make sure everything is properly configured. Then, I will rename everything and make it "mine".
I'd be willing to pay good money if you (or someone else) is willing to do some contract work.
The issue is in
qlibrary.cpp.
It looks like it is trying to find some sequence of
charitems in the library.
char pattern[] = "qTMETADATA "; pattern[0] = 'Q'; // Ensure the pattern "QTMETADATA" is not found in this library should QPluginLoader ever encounter it.
Any ideas?
It turns out that I had to include the following in my
main.cpp.
#include "main.moc"
Then, it worked!
- SGaist Lifetime Qt Champion last edited by
Glad you found out and thanks for sharing !
Since you have it working now, please mark the thread as solved using the "Topic Tool" button so that other forum users may know a solution has been found :) (you have to first change the original post to a question) | https://forum.qt.io/topic/66108/new-platform-based-on-minimal-not-being-recognized/1 | CC-MAIN-2021-39 | refinedweb | 368 | 58.89 |
”
Has anyone got this to work with Ubuntu and LIRC?
when I plug in the unit it get a “/dev/ttyACM0″ but not sure what driver I need LIRC to use
Works in XP just fine with grinder.
This is how to get this working under Ubuntu 8.04
1: Compile LIRC with IRMan support
2: Next stop the cdc_acm driver and stop it from loading
sudo modprobe -r cdc_acm
echo “blacklist cdc_acm” | sudo tee /etc/modprobe.d/cdc_acm
3: Unplug the device
4: Run this command to load the correct driver
sudo modprobe usbserial vendor=0x04d8 product=0x000a
5: Now you should have a /dev/ttyUSB0 device that you can configure LIRC to use next we need to configure the /etc/lirc/hardware.conf file to use this new device
6: sudo nano /etc/lirc/hardware.conf
and make the needed changes to match the below lines.
REMOTE=”Custom”
REMOTE_MODULES=””
REMOTE_DRIVER=”irman”
REMOTE_DEVICE=””
REMOTE_LIRCD_CONF=”/etc/lirc/lircd.conf”
REMOTE_LIRCD_ARGS=”–device=/dev/ttyUSB0″
START_LIRCD=”true”
LOAD_MODULES=”true”
7: I am using a the Verizon Fios remote model RC14453022/00B programmed for code 0881 on the DVD button, this code gave me the needed rc5 output. Just as a note this remote will not allow you to use the digit keys for the TV,AUX,and DVD buttons and it will not control my Blue Ray Player, have to find me a new remote…
8: Next we need to make a Lircd.conf file. Run
the next code and follow the prompts.
sudo irrecord –disable-namespace –driver irman -d /dev/ttyUSB0 RemoteXXX.conf
9: Next we need to copy the new file to the correct location.
sudo cp RemoteXXX /etc/lirc/lircd.conf
10: Now we start LIRC using the correct driver so we can check if the setup is working.
sudo lircd -n –driver irman -d /dev/ttyUSB0
11: We now need to start irw to see the output of the remote keys, if you do not see any output when a key is pressed then your setup is not working
irw
12: Next you can run mythbuntu-lircrc-generator to make the ~/.lirc/mythtv configuration file for mapping the remote keys, or you can do it manually.
Good Luck
Chris
@ Slater: in short: no because the WinLirc’s serial receiver does not decode the signal, wich is decoded by software. It does’nt do handshacke with the pc and WinLirc access to the Serial port directly. You can still buy one PCI -> Serial card (dont know if those things beeing sold).
@ THE PEOPLE THAT TRIED LOTS OF REMOTES: if your PIC seems to work, but you cant get any data from any remote, try this:
Check your receiver with an osciloscope (if you own one) or with a simple led (remember the resistor!).
Check if your remote IS RC5 (just one of the 6 in my home was RC5, the rest where RC6)
Try in raw mode (or however is called)
If you are shure that everything is working ok (exept that all your remotes are not RC5) just buy a generic control and program it for Philips TV.
@Chris looks ok, i will give it a try
my creative rm-1800 stop work,after windows updates,please if you have something for my.
has anybody added any modifications to the firmware or has the author released new firmware?
My WinTV remote (pictured) broke, so I had to replace it with a universal remote control. Low number Phillips TV codes seemed to be RC5 on the models I tried.
i’ve made it, but so simple, not like it,
i know it from a book. only 5 component.
easy to install,
anyway, your guide is cool
The device its recognized and a serial port is assigned.
Hercules give OK response to “R” but dont return any IR signal from remote controls.
The IR device is SFH 5110 active-low ir demodulator.
The PIC is the 18F2550.
Where is the problem??
@Franciosi – did you use the HEX or compile your own?
i noticed i already have infrared on my pc so does that mean i just have to set up the remote to make it work?
I want to know is it support remote wake up? I want to wake the host PC by pressing the power button of the remote control.
er, guys:
Less geeky, but much easier!
Could anyone help me, how to implement power-off/power-on function by this remote, either by (powerswitch/wakeonlan) or usb-wake-up. Thx in advance.
I built this circuit as a portion for a school project of mine (tube amplifier). Win XP recognizes, allows me to update driver, Hercules send R receive OK. Using a multitude of remotes including a programmable universal remote. Girder and EventGhost will not recognize. I can see signals on my oscope from the IR Receiver, but nothing seems to be output on USB. I programmed the 18F2455 with a Kitsrus.com 149E programmer using Microburn software. There seemed to be issues with the Fuses. The fuses outlined in config.h do not match the available options in Microburn. Might this be my problem? Also, in main.c, which lines of code should be removed to allow all IR signals to be passed to the computer? Any insight is much appreciated as this is the final aspect of my project that is now due in 2 days =(
Thanks in advance!
I got it all working, it was the Fuse info. However, I still need to know which lines of code to comment out in main.c
thanks in advance
Dear “All” !
At first: thank you for publishing this topic.
The question: we opened the .brd file with Eagle (5.7.0 WIN lite and with 5.3 PRO version too) and the GND layer cannot be seen. Please advise what to do to make the GND layer visible. Or advise an Eagle version what can handle this project.
Bye!
@djmcmaster – press the fill button in eagle (X with green dots on the end).
Hello,
I made this receiver on protoboard and pluged it into USB. Windows 7 reconized new hardware and I manualy selected driver, included in project archive. I got error, that driver isn’t made for x64-based system? How can that be possible?
Hello i have made this very nice receiver an i have problems to configure it. My operating sistem is Windows XP(sp2). i programmed the microcontroller PIC18F2550 with the hex code given above, when i plug in the usb cable into computer, the status message shows :” new hardware found” , i installed the driver (INF) and the led on the circuit blinks few times and then stops.
the problem is i can’t configurate the circuit with the girder, UICE,… (maybe i don’t know i how). I tried to use 3 types of remotes but girder, and uice does not recognize nothing.
What cand i do ? if you have any ideas please help me… thanx in advance!
best regards, Rusu
Hello! It works!!!:D
My problem was the remote control. I tried many but only few from Philips worked. I also tried universal remotes but no succes.
Thank you for this project!
I have a question … With Windows vista this circuit should work?
regards, Rusu
i have try it but don’t work properly. what can i should now.
Hello Sanjib,
I have tried the receiver on Windows Vista, and works OK!. I used Girder 5. I also tried to use girder 3 but it don’t works properly. My advise is to try girder 5.
all good, Rusu
You could try implementing a keyboard protocol, in fact I have a reciever that does exactly that. No frontend software required, and no drivers are needed either.
It appears as a HID device.
Most keys translate directly to keyboard keys, but the play/pause/ff etc. buttons translate to media keys, which are really useful if you want to control the media program when it doesn’t have focus.
The only downside is you can’t (easily) customize the action of the keys
WTF is this waffle about “true” serial?
Software decoding does not make it any less serial.
It sure as hell doesn’t magically send the data in parallel.
Can I buy one from you ?. Seriously. If I got the sample it would be alot easier than to look it at the diagram.
Thks
wherer can i find the driver for this circit?
and this ic programer schematic ?
I have spent a lot of time researching verizon internet through fios and the cable and satellite options available. Is there a single person out there believe that traditional cable is really better than Fios high speed? It seems that there is no comparison between the available options when talking about network speed and user experience for managing your channels.
Fios is the best option by far
Can I Connect A Nokia Mobile Through this Curcit & Make An Internet Connection?
I mean Can I USE it to connect a mobile as a IR Modem?
Please Reply me Soooooooooooooon!!!!!!!!1
I know this is an old project, but has anyone gotten the source to compile with the newest libraries from Microchip? I’m getting errors (more info on request). Alternately, would anyone care to share a working .hex file?
mgruisin
you mean you have tried this one ?? and not worked ?
It’s been a long time now, when I posted my error and still no reply! Can anyone please tell me, if this receiver is made for x64 base systems or not? Because it says that driver do not support x64 system, when I manual select driver for unknown device. Please help me.
anyones has modified the code for use any remote control? not only rc5 (philips remotes)
@ljudsko
use this driver! the driver works for Windows 2000/XP/Vista/7 x86 and Vista/7 x64, using it with Windows 2000 is not recommending due the bugs in Windows 2000 CDC driver.
Hello Ian!I have some problem getting the USB-Receiver work(I can see RC5 codes in the oscilloscope but get no more then just “OK”). So I build the project trying to find what the problem is.Then I found there maybe some missing lines in the main.c because it didn’t jump into the interrupt because GIE was not open.I doubt whether the source code is the last version.I use the original main.c to build the HEX and the two files are not in the same size.Check it when you have time and it will help me a lot.Thx in advance.
@argento, I already done that, as I said, but it doesn’t work..It says, that I must use a driver, compatible with windows x64 system..
Any idea, please?
@ljudsko
humm okey please check this first:
program your pic 2550!!
a rc5 ir remote (phillips rc5 tv or universal pre programmed).
check your usb connection replace the cable.
your ir remote soft support winxp/vista/7 x64?.
(i’m using eventghost and work perfect).
install the provided driver!.
if noting work, i needed more info of your test!!!
@argento, I already tried this driver, but it doesn’t work. I tryed eventghost to, but doesn’t recognize device. Usb connection and cable is ok. Everything, that my circuit do, when I connect it to a PC, is that LED flashes.
Anyone re-write this for the Microchip usb demo board?
After a lot of head-scratching, I was able to make it compile and run using Microchip’s v2.7a stack. It turns out you have to edit main.c and: paste the code from the USER_USB_CALLBACK_EVENT_HANDLER function from the demo’s main.c to make it compile; call “USBDeviceAttach();” after the “USBDeviceInit();” line; and call “USBDeviceTasks();” right after variable declarations on the “InterruptHandlerHigh” routine.
For you guys who want to make it work with other remote codes, try using the algorithms / ideas from: and
@crizr
i’dont have any idea in programming!!!
I programmed the microcontroller PIC18F2550 with the hex code given above, when i plug in the usb cable into computer, the led on the circuit blinks few times and then stops.
The problem is i can’t configurate the circuit with the girder. I tried to use 5 types of remotes but girder, does not recognize.
I am getting output ‘OK’ in Hercules. when i send IR.
Can anyone guide me how to check the remote is RC5
Can anyone tell Will the LED blink when we press the remote..
@siva
no the led not blink when you press the remote!!
use a osciloscope is the only way to see the signal!!
for remote im use a phillips tv remote an a sony universal pre-programed in a phillips tv and works fine
I am trying this for past 10 days , I used PIC18f2550, is it necessary to recompile the C file.
when i plug in the usb cable into computer, the led on the circuit blinks few times and then stops.
Will the LED be always ON if we connected to USB or it will blink for three times only when we connect. what is the purpose of LED.
I am getting output ‘OK’ in Hercules. when i send IR. Can anyone guide me whether we receive HEX codes in HERCULES when i press button in remote.
Is there anyone who completed this USB IR remote using 18F2550.
Is there any difference between IR Receiver HS0038 A2 and TSOP1738.
I am using IR Receiver HS0038 A2. and remote RC7812.
@Siva, the LED should stay on when the computer is connected. The precompiled HEX supplied on the project archive works with the PIC18F2550. If the circuit is ok HEX codes should appear on a serial terminal in binary/HEX mode when you press remote buttons. If you want to compile the code with the most recent Microchip USB stack you would have to make the modifications to the code I described above. There are probably differences between HS0038 and TSOP1738, check the datasheets. The TSOP4838 for instance, which I used, has an internal pull-up on the output, so you have to remove the external pull-up resistor.
@crizr Is it necessary to connect serial port, Can i known y serial port is used
No, connecting the serial port is not required.
I made the hardware as per the circuit, In Hercules i am getting Ok when i send IR, i used Phillips remote but i am not getting any HEX output in Hercules when i press remote. In Grider also the remote is not detected | http://hackaday.com/2008/10/30/how-to-usb-remote-control-receiver/comment-page-2/ | CC-MAIN-2015-11 | refinedweb | 2,448 | 74.79 |
-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Moriyoshi Koizumi <address@hidden> writes: > Hmm, seems the attachments were stripped. I placed them on > > > > > Regards, > Moriyoshi > > On 2005/04/24, at 8:04, Moriyoshi Koizumi wrote: > > > Hello, > > > > Attached is a patch against 1.12.12 that fixes the MMAP_ANON > > detection problem in mmap-anon.m4 that would lead to unexpected > > "memory exhausted" error on several platforms. Examples of such platforms would be nice to include for the ChangeLog... > > > > Hope this helps anyway. > > > > Regards, > > Moriyoshi A patch to m4/mmap-anon.m4 would need to be made to the GNULIB master sources. I am CC'ing address@hidden on this message. The patch to look for at using a #include <pam/pam_appl.h> for MacOS X seems reasonable. I'll try to dig up a MacOS X box to as a test before I commit it. For the ChangeLog entry, do you happen to know for which MacOS X releases this support (10.0, 10.1, 10.2, 10.3, ...) applies? Thanks, -- Mark --- cvs-1.12.12.orig/m4/mmap-anon.m4 Tue Mar 8 03:22:03 2005 +++ cvs-1.12.12/m4/mmap-anon.m4 Sun Apr 24 07:50:24 2005 @@ -27,8 +27,8 @@ #endif ], [gl_have_mmap_anonymous=yes]) - if test $gl_have_mmap_anonymous = no; then - AC_EGREP_HEADER([MAP_ANON], [ + if test $gl_have_mmap_anonymous != yes; then + AC_EGREP_CPP([I cant identify this map.], [ #include <sys/mman.h> #ifdef MAP_ANON I cant identify this map. -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.3 (FreeBSD) iD8DBQFCaybd3x41pRYZE/gRAh5WAJ9BBMZWKREjPIFdgbT8L6oLSKz5ewCdG8hx PRqB3KOJvluQ7Y6+nMUcHDI= =a2+C -----END PGP SIGNATURE----- | http://lists.gnu.org/archive/html/bug-gnulib/2005-04/msg00064.html | CC-MAIN-2014-15 | refinedweb | 254 | 69.58 |
- Personally, I would find a list of *all* keys more desirable (that > is, list any key that is found in any of the chosen lexicons). I > took a look at Bibleworks when visiting my brother (he is teaching > OT) and noticed it has a feature where instead of having a window > per dictionary, you have one window displaying the definitions in a > list of selected dictionaries, like this: I think that perhaps this is so. At the least, one could have the option of either the union or intersection. - Your algorithm is O(m * n), which explains the runtime. The > algorithm proposed by Glen looks good, especially as it runs in > linear time (ie, looks at each entry exactly once). However, it can > still be optimized: If an element is > the currently active item, > you use that one to continue your search. Also, you can step the > marker more often. I really don't think an extreme amount of optimization is required; just moving to an O(n) algorithm instead of the current O(m*n) should be sufficient imho. > I implemented the algorithm in perl (just for > fun), but tried to not use perl-specific optimizations. I put some > code into subroutines so the main algorithm reads better. > Not being able to resist the sirens call to compare programming languages using highly contrived examples, I have whipped up an equivalent implementation in C++. It is as follows: ---- #include <algorithm> #include <iostream> #include <numeric> #include <vector> using namespace std; int main() { const int sets[][20] = {{ 0,1,2, 3, 7, 8, 9, 10, 11, 12, 13, 14, 15, -1,}, { 0, 3, 7, 8, 10, 11, 13, 14, 16, -1,}, { 0,1,2, 3, 5, 7, 8, 10, 11, 12, 13, 14, 16, -1,}, { 2,3,4, 6, 7, 8, 10, 11, 12, 14, 16, -1,}, { 0,1,2, 3, 7, 8, 9, 10, 11, 13, 14, 15, -1,}}; vector<int> results(sets[0],sets[0]+sizeof(sets[0])/sizeof(*sets[0])); for(int i = 1; i != sizeof(sets)/sizeof(*sets); ++i) { vector<int> v; v.swap(results); set_intersection(v.begin(),v.end(), sets[i],find(sets[i],(const int*)NULL,-1), back_inserter(results)); } cout << "common items in the sets: "; copy(results.begin(),results.end(),ostream_iterator<int>(cout," ")); cout << "\n"; } --- Note that one can easily change from the intersection to the union by changing set_intersection to set_union. Blessings, -David. | http://www.crosswire.org/pipermail/sword-devel/2003-January/017508.html | CC-MAIN-2015-40 | refinedweb | 398 | 56.49 |
Problem with Consumer/Producer implementation
Anton Shaykin
Ranch Hand
Joined: Dec 13, 2009
Posts: 57
I like...
posted
Apr 04, 2010 06:14:04
0
First of all, I have to admit that I posted this question on Sun Forums earlier. But since Oracle acquisition of Sun, forums seem to be dead, and there's a little chance to get a response there. Every time I log in, I see "0 Users online". So, I do respect JavaRanch community, and therefore apologize for having to copy-paste my original post. Thank you for understanding.
I spent considerable amount of time today trying to figure out what I'm doing wrong to no avail. Sorry for such long code, but I see no way to reduce it. And also, please, do not point at design flaws - I do know that from the point of OO it's not semantically correct to declare Producer and Consumer as inner classes of a single class and such. It doesn't matter here. I'm just trying to understand why it doesn't work. So, in first call to wait Consumer releases lock on prod object. Then Producer thread enters synchronized block (acquires a lock on the prod object). However, after call to notify and exiting synchronized block (therefore releasing a lock), it doesn't wake the Consumer up for no apparent reason (well, in fact it does occasionally, once per 10 loops). Moreover, when I uncomment a line right after Consumer synchronized block, which outputs "Producer should have released lock by now" to console, the behavior changes a bit. Consumer starts to consume values, but again, asynchronously and in chaotic manner. Could anybody clarify what is wrong in this code? Any help would be highly appreciated.
P.S. Also, don't worry about main method inside nested class. After reading Bruce Eckel's "Thinking in Java" I figured it's really neat to have main, designed for
testing
purposes only, inside a nested class, which you could physically remove from your hard drive after testing is done. And I do invoke main correctly as following:
java
threads.WaitDemo$Tester.
So here is the code:
package threads; public class WaitDemo { private class Producer extends Thread { int i; public void run() { System.out.println("Producer gets some sleep before going to work"); try { Thread.sleep(500); } catch(InterruptedException e) { e.printStackTrace(); } for(int i = 0; i < 20; i++) { synchronized(this) { System.out.println("Producer enters synchronized block"); try { Thread.sleep(500); } catch(InterruptedException e) { e.printStackTrace(); } this.i = i; System.out.println(Thread.currentThread().getName() + " produced " + this.i); notify(); } //System.out.println("Producer should have released lock by now"); } } } private class Consumer implements Runnable { public void run() { Producer prod = new Producer(); prod.setName("Producer"); prod.start(); while(true) { System.out.println("Consumer enters while loop"); synchronized(prod) { System.out.println("Consumer enters synchronized block"); try { prod.wait(); } catch(InterruptedException e) { e.printStackTrace(); } Thread t = Thread.currentThread(); System.out.println(t.getName() + " consumed: " + prod.i); } } } } private static class Tester { public static void main(String[] args) { new Thread(new WaitDemo().new Consumer(), "Consumer").start(); } } }
amitabh mehra
Ranch Hand
Joined: Dec 05, 2006
Posts: 98
posted
Apr 04, 2010 23:00:51
0
1) notify() does not guarantee that consumer thread will be the next thread to run. It only guarantees that consumer thread is now *eligible to run*, but, since now both threads - Producer thread and Consumer thread are *eligible to run*, it all depends on the Thread Scheduler to schedule which thread should go next.
2) Consumer thread is not consuming in chaotic manner.
System.out.println(t.getName() + " consumed: " + prod.i);
You are printing the prod.i value. This will be the most recent one.
Better option to implement a Producer/Consumer problem would be to go for BlockingQueues else have some shared DataStructure in which Producer can go on inserting and consumer can pick items from there.
Anton Shaykin
Ranch Hand
Joined: Dec 13, 2009
Posts: 57
I like...
posted
Apr 05, 2010 04:21:54
0
OK. Thank you. The problem is now solved.
Consider Paul's
rocket mass heater
.
subject: Problem with Consumer/Producer implementation
Similar Threads
wait( ) and notify( )
Thread question
After notify()
Multithread program from khalid mughal
Beginner: Threads vs. Runnables
All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter
JForum
|
Paul Wheaton | http://www.coderanch.com/t/490112/threads/java/Consumer-Producer-implementation | CC-MAIN-2013-48 | refinedweb | 727 | 58.89 |
PyX — Example: graphs/change.py
Plotting more than one data set and adding a graph key
from pyx import * g = graph.graphxy(width=8, x=graph.axis.linear(min=0, max=2), y=graph.axis.linear(min=0, max=2), key=graph.key.key(pos="br", dist=0.1)) g.plot([graph.data.function("x(y)=y**4", title=r"$x = y^4$"), graph.data.function("x(y)=y**2", title=r"$x = y^2$"), graph.data.function("x(y)=y", title=r"$x = y$"), graph.data.function("y(x)=x**2", title=r"$y = x^2$"), graph.data.function("y(x)=x**4", title=r"$y = x^4$")], [graph.style.line([color.gradient.Rainbow])]) g.writeEPSfile("change") g.writePDFfile("change") g.writeSVGfile("change")
Description
In this example we demonstrate how to plot more than one data set in a graph. Furthermore, adding a graph key labelling the data is explained.
In order to display more than one data set, we pass a list of data sets to the
plot method of the graph. In the present case, we contruct this list out of three lists of
graph.data.function instances. For each data set we also set a title using the corresponding keyword argument of the data class.
For a more colorful output, we pass the
color.gradient.Rainbow color gradient to the
graph.style.line class. PyX then automatically chooses color spanning the whole range of the rainbow gradient.
If you look at the output, you will notice that not only the colors are cycled through, but also the line style changes. The reason for this behavior is that the default line attributes of the
graph.style.line style contain an
attr.changelist comprising a couple of different line styles. When you pass additional line attributes, these are appended to the default attributes (this is generally the case in PyX). Consequently, you get a change of both the color and the line style. If you only want to change the color, either pass the desired line style explicitly, i.e., use
graph.style.line([style.linestyle.solid, color.gradient.Rainbow])
or clear a previous setting of the line style using the
clear attribute of the corresponding class:
graph.style.line([style.linestyle.clear, color.gradient.Rainbow])
It is also possible to call the
plot method several times. Note that the changing of the styles is also performed when the style instances are used on several plot commands within the same graph as long as the same set of style instances are passed at the
plot method calls.
Finally, when plotting more than one data set you might want to label them in your graph. We already have passed titles identifying each data set, so we only have to add a graph key. This is done by passing a
graph.key.key instance as the
key keyword argument to the graph. Usually, you only need to specify the position of the key using the
pos argument of the
graph.key.key constructor. The syntax should be self-explaining; here we use
br to put the key at the bottom-right position of the graph. In order to save some space, we furthermore decreases the distance between the key entries a little bit by passing a value of 0.1 to the
dist argument. | http://pyx.sourceforge.net/examples/graphs/change.html | CC-MAIN-2015-27 | refinedweb | 554 | 67.04 |
<<Sorry if you happen to see this for the third time, I have been trying to post this on egroups, but have failed on several occasions.>> Hi, Zope newbie here, a bit lost on namespaces... I have created a folder in the zope root called "RandomGreeting". Inside this folder, there is one DTML METHOD called "Greet". "Greet" contains the following line: <p><dtml-var</p> "sayHellos" is a property of the "RandomGreeting" folder, and contains 4 lines which are various ways to say hello : "Ola","Hi","Bonjour","Sawasdi". The purpose of this method is to print out a random greeting. Everytime i click "View" for this DTML Method, i get a random hello. Fine, that is exactly what I want. The problem is that I am trying to use this "method" from its parent folder (the root folder as a matter of fact). I have inserted the following bit into the top level "index_html" DTML Method of my Zope root near the begining, so that it produces a random hello on the front page everytime someone accesses it. I have tried : <dtml-var RandomGreeting.Greet> <dtml-var RandomGreeting.Greet()> <dtml-var "RandomGreeting.Greet()"> <dtml-var /RandomGreeting/Greet> all of these, to know avail. I am getting either a NameError or KeyError. I am pretty sure I'm missing a simple concept here. It is possible to call functions from child objects is it not? Please help with some enlightenment. Many thanks in advance. teep _______________________________________________ Zope maillist - [EMAIL PROTECTED] ** No cross posts or HTML encoding! ** (Related lists - )
- Re: [Zope] Lost in name Space... Prateep Siamwalla
- Re: [Zope] Lost in name Space... Pierre-Julien Grizel | https://www.mail-archive.com/zope@zope.org/msg14739.html | CC-MAIN-2016-44 | refinedweb | 274 | 68.06 |
> > But that is really stupid, yet nothing else works properly. I assure
>you,
> > ".svn" is going to bite a lot of Windows users.
>
>Not Windows users in general.
If all goes well (Subversion takes off), a lot of ASP.NET users will start
using Subversion. They will get into trouble.
>We had a report earlier about problems with using VS.NET developing
>WebApps.
>The thing wants to mount a network share and then do 'stuff'. The 'stuff'
>includes doing some magic apparently tripping over the .svn directory,
>leading to an error message.
>
>Sounds like a general case of VS.NET needing a fix IMHO.
OK.. So the File Explorer needs a fix. And VS.NET needs a fix.
Hey, wait... perhaps svn on windows needs a fix? Cus' I don't think M$ is
going to issue a patch for this any time soon ;-)
>That's a shame and just plain broken. I'm kind of having a hard time
>believing this to be honest.
I'm not a liar, to be honest. But granted, since I haven't tested all the IO
functions in .NET, it may not be a real problem. The one that hit me was
recursive deletion using some standard stuff in the system.io namespace
(.net fw 1.1.)
> > "wc.svn" for instance? For migration purposes, both .svn and wc.svn
>could be
> > supported for a while.
>
>-1 to wc.svn or any other name that ends up in the middle of a sorted
>directory listing.
"_svn", then, as another guy suggested.
> > Please, fix this before it's to late. PRI 1 in my head.
>
>Maybe when we get more reports...
Damn it :-)
_________________________________________________________________
It's fast, it's easy and it's free. Get MSN Messenger today!
---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@subversion.tigris.org
For additional commands, e-mail: dev-help@subversion.tigris.org
Received on Thu Sep 25 01:18:12 2003
This is an archived mail posted to the Subversion Dev
mailing list. | https://svn.haxx.se/dev/archive-2003-09/1199.shtml | CC-MAIN-2016-36 | refinedweb | 333 | 80.48 |
GR-LYCHEE is an IoT prototyping board with a camera and wireless capability (Wi-Fi, Bluetooth Low Energy (BLE)). It is the Gadget Renesas reference board for the Renesas RZ/A1LU group of microprocessors (MPUs). GR-LYCHEE is pin-compatible with Arduino UNO and ARM® Mbed™ enabled development platforms. You can also sketch like Arduino with the Renesas web compiler and IDE for GR.
GR-LYCHEE Board
Equipped with an ARM Cortex-A RZ/A1LU (R7S721030VCFP). Various Arduino shields can be mounted, but 3.3V I/F. The camera is attached as standard. Arduino shield connector, USB host interface connector is not mounted, parts are attached in -FULL version.
GR-LYCHEE (Backside)
On the backside are a camera interface, an SD socket and a general-purpose LCD expansion connector is mounted.
GR-LYCHEE Key Features
- Enables getting a VGA (640 x 480) image with attached camera. When transferring with USB CDC, a transfer rate of 60fps can be realized.
- OpenCV v3.2 is applied and various SDKs are provided. Computer vision can be enjoyed right away.
- Equipped with ESP32. Cloud connection with Wi-Fi, smartphone communication with BLE possible.
- Equipped with a 4-pole audio jack. Audio input/output is possible.
- SD card can be inserted. FlashAir™ is also OK. (More about FlashAir Connection can be found on the Resources tab.)
- Mbed™ easy programming. If you copy it to storage, you can run it.
- Optional USB A connector can be equipped. Can be used for connection of USB memory etc.
Demonstration Video Running OpenCV Canny Function (Edge Detection) with GR-LYCHEE
GR-LYCHEE Pin Map
Detailed Specification
- Microprocessor
- RZ/A1LU (R7S721030VCFP 176-pin QFP)
- ROM/RAM
- External FLASH 8MB/Internal 3MB
- Operating Frequency
- 384MHz
- RTC Clock
- 32.768kHz
- Operating Voltage
- 3.3V/1.18V
- Camera
- Shikino High-Tech KBCR-M04VG-HPB2033VGA 640x480, up to 60fpsHorizontal angle 98 degree, vertical angle 75 degree
- Board Function
- Camera interface (camera module included) ESP32 wireless module (Wi-Fi, BLE) USB peripheral(Micro B connector) USB host (option) 4 pole audio input/output jack SD socket LCD connector User button switch (2 pcs) Reset button switch JTAG interface Connector for Arduino shield (option) LED for user (4 pcs)
How to Program
- Create a GR-LYCHEE Arduino Sketch with Web Compiler Project
- Mbed site
- IDE for GR (sketch like Arduino style offline)
- e2 studio (Eclipse based)
Project File for e2 studio
Project file for sketching in Eclipse-based development environment e2 studio. For downloading and installing e2 studio, please refer to the e2 studio product page.
You can import as an archive file (zip) as an existing workspace from the e2 studio menu "File" -> "Import".
Do the menu "Project" -> "Update all dependencies" at the initial build. Only sources changed since the next build will be compiled.
- Project with OpenCV (Updated Dec. 13, 2019)
GR-LYCHEE Sketch OpenCV v10602 Project File (Arduino style, OpenCV included)
GR-LYCHEE Mbed Style OpenCV v10602 Project File (Mbed style, OpenCV included)
- OpenCV project for library generation
OpenCV Neon 02 Project File
DisplayApp
DisplayApp is an application that displays the camera image sent by USB CDC.
- For Windows
DisplayApp File (Windows)
Installing the USB driver is required on versions earlier than Windows 10.
- For Mac
DisplayApp File (Mac)
Below is an Arduino-like sketch example.
#include <Arduino.h> #include <Camera.h> #include "DisplayApp.h" Camera camera; static DisplayApp display_app; void setup() { camera.begin(); } void loop() { display_app.SendJpeg(camera.getJpegAdr(), (int)camera.createJpeg()); delay(10); } }
About FlashAir™ Connection
You can connect FlashAir to the SD socket on the back of GR-LYCHEE. You can access photos saved with GR-LYCHEE's camera from your smartphone or tablet. It can also be used as a Wi-Fi interface using iSDIO. For details on how to use FlashAir, refer to the FlashAir Developers site.
Products whose operation have been confirmed are as follows.
- FlashAir W-03 (8GB, 16GB, 32GB)
- FlashAir W-04 (16GB, 32GB)
Note: For W-04, the iSDIO function by CMD 17/24 can be used with firmware W 4.00.01 or later.
3D Data for Fusion 360
3D data that can be imported with Autodesk Fusion 360. Use it when making cases for GR-LYCHEE.
Technical Support
Technical Information
Related Websites
GR-LYCHEE Board Distributors
GR-LYCHEE boards and other shields can be purchased through the following sites:
Gadget Renesas provides boards that make it possible to prototype ideas quickly, a community where users can interact, and events to help users build their projects to make their ideas a reality. Below are some projects that utilized the GR-LYCHEE board. | https://www.renesas.com/eu/en/products/gadget-renesas/boards/gr-lychee.html | CC-MAIN-2020-50 | refinedweb | 759 | 57.37 |
A friendly place for programming greenhorns!
Big Moose Saloon
Search
|
Java FAQ
|
Recent Topics
|
Flagged Topics
|
Hot Topics
|
Zero Replies
Register / Login
JavaRanch
»
Java Forums
»
Java
»
Beginning Java
Author
error "variable not read"
Bonnie Rossi
Greenhorn
Joined: Jan 01, 2011
Posts: 3
posted
Jan 01, 2011 12:49:44
0
Hi folks,
Another "nooby" here (one week). Hope someone can help with my problem(s). I'm trying to write a simple beginner's program that allows input from the keyboard of 12 temperatures and then displays the highest temperature and the corresponding month. It's not going so good. My
first
problem occurs in line 14 where I get the error "highestMonth not read." I've changed everything around so many times I've lost count. Cannot figure out why it doesn't find the variable. Problems continue from there, but I can't go further until I figure this one out. Any help, comments, recommendations/pointers for ANY code would be greatly appreciated. Thanks in advance.
So far I have written:
//TemperatureReader.java import java.util.Scanner; public class TemperatureReader { public static void main(String[] args) { Scanner in = new Scanner(System.in); TemperatureClass highest = new TemperatureClass(); //Class defined below double highestTemp = in.nextDouble(); int highestMonth = 1; //first error occurs here for (int currentMonth = 2; currentMonth <= 12; currentMonth++) { double nextTemp = in.nextDouble(); if(nextTemp > highestTemp) { highestTemp = nextTemp; highestMonth = currentMonth; } } boolean done = false; while (!done) { String input = in.next(); if (input.equalsIgnoreCase("Q")) { done = true; } else { System.out.println("Highest Temperature = " + highest.getHighestTemp()); System.out.println (Highest Month = " + highest.getHighestMonth()); } } if (done = true) System.exit (0); } }
public class TemperatureClass { private int currentMonth; //counter used to store month currently being evaluated. private int highestMonth; //counter used to store last month evaluated private double currentTemp; //used to store next temperature to be evaluated private double highestTemp; //used to store value for highest temperature so far in processing /*public TemperatureClass() { set all counters currentMonth = 0; highestMonth = 1; highestTemp = 0; temp = 0; */ public int getHighestMonth() { if (currentMonth > highestMonth) { currentMonth = highestMonth; return currentMonth; } else { return highestMonth; } } public double getHighestTemp() { if (currentTemp > highestTemp) { currentTemp = highestTemp; return currentTemp; } else { return highestTemp; } } }
Jesper de Jong
Java Cowboy
Saloon Keeper
Joined: Aug 16, 2005
Posts: 14493
23
I like...
posted
Jan 01, 2011 13:15:43
0
Welcome to JavaRanch and happy new year!
Bonnie Rossi wrote:
My
first
problem occurs in line 14 where I get the error "highestMonth not read."
Are you sure that's really an
error
or just a
warning
? The code doesn't look wrong; you're just not doing anything with the variable later on in your program. So your IDE is warning you that you're not reading the variable anywhere in your program, which is an indication that the program most likely isn't doing what you think it does.
Did you mean to put the value of
highestMonth
in the
TemperatureClass
object that you're creating in line 11?
Carefully and slowly look at your program line by line. Start at the beginning of the main() method. For each statement on each line, think about what it does. Make sure you understand it before you go to the next line. Reason about what's happening and why the program isn't doing what you want it to do. Don't go too quickly; if you're not sure, go back and carefully look again to understand how exactly it works.
In lines 13-25 you are reading in the temperature values and keeping track which value is the highest, and what the matching month number is. Where are these values stored when you reach line 25?
In lines 38 and 39 you are printing the highest temperature value and month value that you found. Where are you getting those values from there? Why don't you see the values that you kept track of in lines 13-25?
What is the role of the TemperatureClass? What is line 11 of your first code snippet for?
What exactly do the methods getHighestMonth() and getHighestTemp() in class TemperatureClass do? Where are these called in your first code snippet?
Java Beginners FAQ
-
JavaRanch SCJP FAQ
-
The Java Tutorial
-
Java SE 8 API documentation
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 40518
28
posted
Jan 02, 2011 07:05:21
0
You should never never write
== true
or
== false
. You have managed to copy it as
= true
at one point, which isn't what you want; it will assign the value to the boolean, and can cause logic errors. I think where you have got it, it only covers an exit call, so won't do that much harm
Avoid System.exit; it is unnecessary where you have it, and can cause nasty errors in threaded applications.
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 40518
28
posted
Jan 02, 2011 07:07:11
0
. . . and welcome to the Ranch
(again)
Bonnie Rossi
Greenhorn
Joined: Jan 01, 2011
Posts: 3
posted
Jan 02, 2011 10:43:19
0
Thanks. I practically started over from scratch with this program. I don't know if it's better or not, but it's shorter and almost works!
I really don't understand why the initial value for currentMonth has to start with 3 when it seems it should be a 2. Have I messed up another variable somewhere else? Also, I don't think the Q to quit works the way it's supposed to, but it does exit the program, albeit with a long list of red errors.
// define Class that will accept 12 months with their corresponding temperatures // and display the highest temperature and month it occurred. import java.util.Scanner; public class TemperatureReader { public static int currentMonth; public static int highestMonth; public static double highestTemp; public static double nextTemp; public static void main(String[] args) //method called from a class w/o creating an instance of the class { boolean done = false; //set Boolean variable to false while (!done) //while Boolean type is true perform following operation until Boolean type is false { Scanner in = new Scanner(System.in); //accepts input from keyboard, constructs Scanner object System.out.println("Enter value or, Q to quit"); //prompts user to input temperatures or to quit double highestTemp = in.nextDouble(); int highestMonth = 1; // local variable initializes counter for number of months String input = in.next(); if(input.equalsIgnoreCase("Q")) done = true; //computation is finished so set Boolean type to true else for (int currentMonth = 3; currentMonth <= 12; currentMonth++) //initial month, test for next month, adds to counter for months { double nextTemp = in.nextDouble(); if(nextTemp > highestTemp) { highestTemp = nextTemp; highestMonth = currentMonth; } } { System.out.println("Highest Temperature = " + ((double) highestTemp)); System.out.println("Hottest Month = " + ((int) highestMonth)); } } } }
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 40518
28
posted
Jan 02, 2011 11:24:09
0
You can see it's an improvement when the whole thing gets shorter
Have you been told to put everything into the main method? The main method is really only there for starting off an application and its ideal size is one line.
Pleased to see you have get rid of the = true bit.
Please check your indentation. Get a text editor which supports automatic indentation (eg NotePad2, NotePad++, jEdit if on Windows, Gedit, Kate, on Linux), and write your code like this
//stage 1 public class Foo { }
Compile.
//stage 2 public class Foo :wink: { :wink: public void(bar(Baz b) { } }
Compile
//stage 3 public class Foo { public void(bar(Baz b) { b.buz(); } }
Compile. Yes, compile every time you write another 5 lines, and run every new method as soon as it is written. You find errors much faster like that.
Yes, it looks strange to add code in the middle of a block, but it gets your {} all paired off nicely above and below one another; if you have two }} above each other as in your lines 48-49 above, you can see you have your {} not paired correctly. that makes it a lot easier to understand some of the obscurer compiler errors. You will find suggestions about indentation
here
, which I prefer to the Sun/Oracle style suggestions. I shall leave you to find the compiler error in what I posted
Why are you starting your loop at month = 3? You obviously expect January and February to be very cold!
Move the instantiation for the Scanner to before the loop; otherwise you are instantiating it every time you enter a value. [It is possible the compiler can optimize that problem away, but that isn't a "beginning" topic.]
Copy the inner loop into a new method, without the bit about enter "Q". Get a little program working, then enlarge it. Much easier than trying to get something big working. Try your loop running through all twelve months, and instantiate the maximum value before the loop. Instantiate it to something so low (in the case of temperature, maybe -273.15°C) that you can be certain that the first value entered will be greater. Then run the loop for all twelve months. You can print
"Enter temperature for month " + monthNumber
and get a nice output on screen.
You don't need the two casts towards the end of the application.
Bonnie Rossi
Greenhorn
Joined: Jan 01, 2011
Posts: 3
posted
Jan 02, 2011 12:25:48
0
I set the currentMonth variable to 3 because if I set it to 1 the loop ran 14 times instead of 12. I can't follow the logic very well obviously. I just tinkered until it hit 12 which turns out to be a 3. I should be able to have the highestMonth initialize at 1 and the currentMonth at 2 it seems, but this doesn't work. What have I missed?
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 40518
28
posted
Jan 02, 2011 13:16:34
0
Try the inner loop on its own. Forget all about "enter Q". Get the inner loop running correctly, then add "enter Q" later. Put a print statement at the beginning of the loop, so you can see how often it runs.
Don't tinker. Get the logic right for the inner loop, by writing the values on a piece of paper. You want a loop which runs from 1 to 12 (but beware: there are standard API classes where January = 0). So write a loop from 1 to 12, and get it to print "Enter temperature for month 1" for its first iteration.
Where you say "enter value or Q" and try to read that as a double, you are liable to get confused about whether you have entered Q or 123.4. You are omitting that bit for the time being, so you can correct that later.
I agree. Here's the link:
subject: error "variable not read"
Similar Threads
learning how to use classes
compiling help
Why is my type unexpected? required variable found value
My loop isn't working
need help with calculation in my spreadsheet array
All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter
JForum
|
Paul Wheaton | http://www.coderanch.com/t/522176/java/java/error-variable-read | CC-MAIN-2015-06 | refinedweb | 1,851 | 63.29 |
.\" $NetBSD: directory.3,v 1.38 2012/10/08 18:15:09 njoly .\" .Dd October 15, 2011 .Dt DIRECTORY 3 .Os .Sh NAME .Nm fdopendir , .Nm opendir , .Nm readdir , .Nm readdir_r , .Nm telldir , .Nm seekdir , .Nm rewinddir , .Nm closedir , .Nm dirfd .Nd directory operations .Sh LIBRARY .Lb libc .Sh SYNOPSIS .In dirent.h .Ft DIR * .Fn opendir "const char *filename" .Ft DIR * .Fn fdopendir "int fd" .Ft struct dirent * .Fn readdir "DIR *dirp" .Ft int .Fn readdir_r "DIR * restrict dirp" "struct dirent * restrict entry" "struct dirent ** restrict result" .Ft long .Fn telldir "DIR *dirp" .Ft void .Fn seekdir "DIR *dirp" "long loc" .Ft void .Fn rewinddir "DIR *dirp" .Ft int .Fn closedir "DIR *dirp" .Ft int .Fn dirfd "DIR *dirp" .Sh DESCRIPTION The type .Vt DIR represents a directory stream; an ordered sequence of all directory entries in a particular directory. The purpose of the .Vt DIR structure is similar to that of the .Vt FILE structure maintained by the .Xr stdio 3 library functions. .Sh FUNCTIONS The following standard directory operations are defined. .Bl -tag -width XXX .It Fn opendir "filename" The .Fn opendir function opens the directory named by .Fa filename and associates a directory stream with it. The directory stream is positioned at the first entry. Upon successful completion, a pointer to .Vt DIR type is returned. Otherwise, .Fn opendir returns .Dv NULL . .It Fn fdopendir "fd" The .Fn fdopendir function associates a directory stream with the directory file descriptor .Fa fd . The file offset associated with .Fa fd at the time of the call determines which entries are returned. .Pp Upon failure, .Fn fdopendir returns .Dv NULL . Otherwise the file descriptor is under the control of the system, and if any attempt is made to close the file descriptor, or to modify the state of the associated description, other than by means of .Fn closedir , .Fn readdir , .Fn readdir_r , .Fn rewinddir , the behavior is undefined. The file descriptor can be closed by calling .Fn closedir . .It Fn readdir "dirp" The .Fn readdir function returns a pointer to the directory entry at the current position in the directory stream specified by .Fa dirp , and positions the directory stream at the next entry. It returns .Dv NULL upon reaching the end of the directory or detecting an invalid .Fn seekdir operation. The returned structure is described in .Xr dirent 3 . .Pp The returned pointer to the .Em dirent structure points to data which may be overwritten by another call to .Fn readdir on the same directory stream. This data is not however overwritten by another call to .Fn readdir on a different directory stream. .It Fn readdir_r "dirp" "entry" "result" The .Fn readdir_r function . The .Fn readdir_r function returns 0 on success or an error number to indicate failure. .Pp Like .Fn readdir , the .Fn readdir_r function may buffer several directory entries per actual read operation. Both functions mark for update the .Em st_atime field (see .Xr stat 2 ) of the directory each time the directory is actually read. .It Fn telldir "dirp" The .Fn telldir function returns the current location associated with the directory stream specified by .Fa dirp . .Pp If the most recent operation on the particular directory stream was a .Fn seekdir , the directory position returned from .Fn telldir is the same as .Fa loc supplied as an argument to the .Fn seekdir call. .It Fn seekdir "dirp" "loc" The .Fn seekdir function sets the position of the next .Fn readdir operation on the directory stream specified by .Fa dirp . The value of .Fa loc should come from a previous call to .Fn telldir using the same directory stream. .Pp The new position reverts to the one associated with the directory stream when the .Fn telldir operation was performed. Values returned by .Fn telldir are good only for the lifetime of the .Vt DIR pointer, .Fa dirp , from which they are derived. If the directory is closed and then reopened, the .Fn telldir value cannot be re-used. .It Fn rewinddir "dirp" The .Fn rewinddir function resets the position of the named directory stream to the beginning of the directory. It also causes the directory stream to refer to the current state of the corresponding directory, as if a call to .Fn opendir would have been made. .Pp If .Fa dirp does not refer to a valid directory stream, the behavior is undefined. .It Fn closedir "dirp" The .Fn closedir function closes the directory stream and frees the structure associated with the .Fa dirp pointer, returning 0 on success and \-1 on failure. .It Fn dirfd "dirp" The .Fn dirfd function returns the integer file descriptor associated with the directory stream specified by .Fa dirp . Upon failure, .Fn dirfd returns \-1. The returned file descriptor should be closed by .Fn closedir instead of .Xr close 2 . .Pp The rationale of .Fn dirfd is to provide a mechanism by which a file descriptor can be obtained for the use of the .Xr fchdir 2 function. .El .Sh EXAMPLES Sample code which searches a directory for entry .Dq name is: .Bd -literal -offset indent len = strlen(name); dirp = opendir("."); if (dirp != NULL) { while ((dp = readdir(dirp)) != NULL) if (dp-\*[Gt]d_namlen == len \*[Am]\*[Am] !strcmp(dp-\*[Gt]d_name, name)) { (void)closedir(dirp); return (FOUND); } (void)closedir(dirp); } return (NOT_FOUND); .Ed .Sh COMPATIBILITY The described directory operations have traditionally been problematic in terms of portability. A good example is the semantics around .Sq \&. (dot) and .Sq \&.. (dot-dot). Based on historical implementations, the rules about file descriptors apply to directory streams as well. The .St -p1003.1-2008 standard does not however any more mandate that directory streams are necessarily implemented by using file descriptors. .Pp The following additional remarks can be noted from the .St -p1003.1-2008 standard. .Bl -bullet -offset 2n .It If the type .Vt DIR is implemented using a file descriptor, like in .Nx , applications should be able to open only .Dv OPEN_MAX files and directories. Otherwise the limit is left as unspecified. .It When a file descriptor is used to implement the directory stream, the .Fn closedir function behaves as if the .Dv FD_CLOEXEC had been set for the file descriptor. In another words, it is mandatory that .Fn closedir deallocates the file descriptor. .It If directory streams are not implemented by using file descriptors, functions such as .Fn dirfd may fail with .Er ENOTSUP . .It If a file is removed from or added to the directory after the most recent call to .Fn opendir or .Fn rewinddir , it is unspecified whether a subsequent call to .Fn readdir returns an entry for that file. .It When using the function .Fn seekdir , note that if the value of .Fa loc was not obtained from an earlier call to .Fn telldir , or if a call to .Fn rewinddir occurred between the calls to .Fn telldir and .Fn seekdir , any subsequent call to .Fn readdir is unspecified, possibly resulting undefined behavior. .It After a call to .Xr fork 2 , either the parent or child (but not both) can continue processing the directory stream using .Fn readdir , .Fn rewinddir , or .Fn seekdir . However, if both the parent and child processes use these functions, the result is undefined. .El .Sh ERRORS .\" .\" XXX: The errors should be enumerated. .\" All described functions may set .Vt errno to indicate the error. .Sh SEE ALSO .Xr close 2 , .Xr lseek 2 , .Xr open 2 , .Xr read 2 , .Xr dirent 3 .Sh STANDARDS The .Fn opendir , .Fn readdir , .Fn rewinddir and .Fn closedir functions conform to .St -p1003.1-90 . The other functions conform to .St -p1003.1-2008 . .Sh HISTORY The .Fn opendir , .Fn readdir , .Fn telldir , .Fn seekdir , .Fn rewinddir , .Fn closedir , and .Fn dirfd functions appeared in .Bx 4.2 . The .Fn fdopendir function appeared in .Nx 6.0 . | http://cvsweb.netbsd.org/bsdweb.cgi/src/lib/libc/gen/directory.3?rev=1.38&content-type=text/x-cvsweb-markup | CC-MAIN-2014-52 | refinedweb | 1,300 | 71.51 |
Iodine
Please notice that this change log contains changes for upcoming releases as well. Please refer to the current gem version to review the current release.
Changes:
Change log v.0.7.36
Fix: avoids clobbering the namespace when attempting to set Rack's default handler. Credit to Caleb Albritton ( @WA9ACE ) for issue #80 and PR #81.
Fix: avoids some
SIGINT signals during the shutdown procedure (rollback).
Change log v.0.7.35
Fix: fix memory leak in the x-sendfile path where Ruby objects no longer in use would still be protected by iodine.
Update: (
iodine) add the
Iodine.running? method. Credit to Ian Ker-Seymer (@ianks) for PR #78.
Change log v.0.7.34
Security: (
facil.io,
http) updated to facil.io 0.7.3, incorporating it's bug fixes and security updates.
Change log v.0.7.33
Fix: (
iodine) exception protection would fail and crash if the exception throws wasn't of type
Exception. I'm not sure how this would happen, but on some Ruby versions it appeared to have occur, maybe where a custom
raise would be called with a non-exception type. The issue was fixed by testing for the availability of the
message and
backtrace functions. Credit to Jan Biedermann (@janbiedermann) for exposing this issue (#76).
Fix: (
cli) the CLI interface no longer requires Rack to be installed. If Rack is installed, it will be used. Otherwise, a copy of the Rack::Builder code will execute, licensed under the MIT license from the Rack source code (Copyright (C) 2007-2019 Leah Neukirchen).
Compatibility: (
facil) iodine would raise the signal
SIGINT when shutting down in cluster mode, even if shutdown was initiated using
Iodine.stop. Although this was designed to ensure worker processes would stop, this approach caused RSpec to stop testing and report an error. A temporary fix was applied and might be upstreamed to the facil.io repo. Credit to Jan Biedermann (@janbiedermann) for exposing this issue (#76).
Change log v.0.7.32
Fix: (
http1) fixes a race-condition between the
on_ready and
on_data events, that could result in the
on_data event being called twice instead of once (only possible with some clients). On multi-threaded workers, this could result in the CPU spinning while the task lock remains busy. Credit to Néstor Coppi (@Shelvak) for exposing the issue and providing an example application with detailed reports. Issue #75.
Change log v.0.7.31
Security: a heap-overflow vulnerability was fixed in the WebSocket parser. This attack could have been triggered remotely by a maliciously crafted message-header. Credit to Dane ([email protected]) for exposing this issue and providing a Python script demonstrating the attack.
It's recommended that all iodine users update to the latest version.
Change log v.0.7.30
Update: (
cli) added support for the
-pid flag - stores the master processes PID in a file.
Update: (
cli) added support for the
-config (
-C) flag - loads a configuration file immediately after loading iodine.
Change log v.0.7.29
Fix: fixed an issue where
env['rack.input'].read(nil, nil) would return
nil instead of
"" on zero-content requests (i.e., an empty POST request). Credit to @thexa4 (Max Maton) for exposing this issue and providing a POC for debugging (issue #71).
Change log v.0.7.28
Fix: fixed an issue where iodine would crush (or hang) if unprotected exceptions were raised within a response body's
each loop. This also fixes Fiber support when streaming with Roda (note: iodine will concat the body in a buffer before sending it). Credit to @adam12 (Adam Daniels) both for exposing the issue (#70) and testing possible solutions.
Change log v.0.7.27
Compatibility: (
iodine) fixed the HTTP request
SCRIPT_NAME variable (in the Rack
env) to default to the global environment variable
SCRIPT_NAME when
SCRIPT_NAME isn't root (
/). Credit to @thexa4 (Max Maton) for exposing this compatibility concern (issue #68).
Change log v.0.7.26
Fix: (
http) fixed HTTP date format to force the day of the month to use two digits. Credit to @ianks (Ian Ker-Seymer) for exposing this issue (issue #64).
Fix: (
iodine) fixed static file service without an application (when using iodine as a stand-alone static file server).
Fix: (
fio) miscellaneous compatibility updates.
Change log v.0.7.25
Fix: (
iodine) fixed host name binding when running
iodine using
rackup or through
Rack. Credit to @adam12 (Adam Daniels) for PR #60.
Fix: (
iodine) removed bundler requirement in the
iodine.gemspec file.
Change log v.0.7.24
Fix: (
fio) fixed server shutdown on pub/sub stress, where internal pub/sub stress was mistakingly identified as a Slowloris attack. Credit to @moxgeek (Marouane Elmidaoui) for exposing this issue (plezi#32).
Fix: (
fio): fixed Slowloris detection for buffer attack variation.
Fix: (
fio): fixed
pending result, where packet count wouldn't decrement until queue was drained.
Updates: (
fio) facil.io updates, including pub/sub memory improvements for cluster mode.
Change log v.0.7.23
Fix: (
fio): fixed logging message for overflowing log messages. Credit to @weskerfoot (Wesley Kerfoot) and @adam12 (Adam Daniels) for exposing the issue (issue #56).
Updates: (
fio) facil.io updates.
Change log v.0.7.22
Fix: (
fio,
redis) fixed IPC messages between redis connections (in the master process) and callback blocks (executed in the worker processes). Credit to @moxgeek (Marouane Elmidaoui) for exposing this issue (plezi#31).
Change log v.0.7.21
Fix: (
iodine,
redis) Redis response was attempting to create Ruby objects outside the GIL. This is now fixed by entering the GIL earlier (before objects are created). Credit to @moxgeek (Marouane Elmidaoui) for exposing this issue (plezi#31).
Fix: (
redis) fixed Redis reconnection. Address and port data was mistakingly written at the wrong address, causing it to be overwritten by incoming (non-pub/sub) data.
Fix: (
redis) fixed a race condition in the Redis reconnection logic which might have caused more then a single pub/sub connection to be established and the first pending command to be sent again.
Change log v.0.7.20
Security: (
fio) lower and smarter Slowloris detection limits (backlog limit is now 1,024 responses / messages per client).
Security: (
http) HTTP/1.1 slow client throttling - new requests will not be consumed until pending responses were sent. Since HTTP/1.1 is a response-request protocol, this protocol specific approach should protect the HTTP application against slow clients.
Fix: (
iodine) remove redundant Content-Type printout. Credit to @giovannibonetti (Giovanni Bonetti) for exposing the issue (#53).
Fix: (
fio) fix capacity maximization log to accommodate issues where
getrlimit would return a
rlim_max that's too high for
rlim_cur (macOS).
Fix: (
fio) fix uninitialized
kqueue message in
fio_poll_remove_fd.
Fix: (
docs) @giovannibonetti (Giovanni Bonetti) fixed an error in the Rails README section, PR #52.
Change log v.0.7.19
Deprecation: (
iodine) deprecated the CLI option
-tls-password, use
-tls-pass instead.
Security: (
fio) Slowloris mitigation is now part of the core library, where
FIO_SLOWLORIS_LIMIT pending calls to
write (currently 4,096 backlogged calls) will flag the connection as an attacker and close the connection. This protocol independent approach improves security.
Fix: (
iodine) log open file / socket limit per worker on startup.
Fix: (
iodine) application warm-up error was fixed. Deprecation warnings will still print for deprecated symbols loaded due to the warm-up sequence.
Update: (
iodine,
cli) Support the environment variables
"WORKERS" and
"THREADS" out of the box (jury is out regarding
"PORT" and
"ADDRESS", just use CLI for now).
Change log v.0.7.18
Fix (
pubsub) fixed pub/sub for longer WebSocket messages. Issue where network byte ordering wasn't always respected and integer bit size was wrong for larger payloads. Credit to Marouane Elmidaoui (@moxgeek) for exposing the issue.
Change log v.0.7.17
Security: (
fio) improved security against hash flooding attacks.
Update: (
iodine) SSL/TLS support!
Update: (
iodine) WebSocket client connections are now supported using
Iodine.connect (both
ws:// and
wss://)!
Deprecation: (
iodine) deprecated
DEFAULT_HTTP_ARGS in favor of
DEFAULT_SETTEINGS.
Deprecation: (
iodine) deprecated
Iodine.listen2http in favor of
Iodine.listen service: :http.
Fix: (
iodine /
pubsub) fixed possible issue with global subscriptions (non-connection bound subscriptions).
Fix: (
Iodine::Mustache) fixed support for named argument, documentation and loading template from memory (rather than file) when creating a new
Iodine::Mustache object.
Fix: (
redis) fixed an issue where destroying the Redis engine and exiting pre-maturely, could cause a segmentation fault during cleanup.
Fix: (
iodine,
fio) fixed logging message when listening to Unix Sockets.
Fix: (
iodine) fixed CLI argument recognition for WebSocket message limits and HTTP header limits. Typos in the CLI argument names prevented the CLI from effecting the default values.
Fix: (
fio) fixed unaligned memory access in SipHash implementation and added secret randomization for each application restart.
Optimization: (
iodine) caching common header names to decrease Ruby memory allocations per request.
Change log v.0.7.16
Security: (
fio) security fixes from the facil.io core library (updated to 0.7.0.beta6).
Update: (
iodine) better Redis support from CLI and environment (by setting the
IODINE_REDIS_URL environment variable).
Optimization: (
Iodine::Mustache) optimized worst case scenario seeking by seeking Symbols before Strings, which improved seeking times.
Change log v.0.7.15
Fix: (
fio) fixed a minor memory leak in cluster mode, caused by the root process not freeing the hash map used for child process subscription monitoring (only effected hot restarts).
Fix: (
fio) fixed superfluous and potentially erroneous pub/sub engine callback calls to
unsubscribe, caused by (mistakingly) reporting filter channel closure.
Fix: (
http/1.1) avoid processing further requests if the connection was closed.
Fix: (
iodine) fixed some errors in the documentation and added a missing deprecation notice.
Update: (
fio) updated the automatic concurrency calculations to leave resources for the system when a negative value is provided (was only available for worker count calculations, now available for thread count as well).
Change log v.0.7.14
Fix: (
facil.io) fixed superfluous ping event.
Fix: (
iodine_tcp) fixed responsiveness to the argument name
timeout (a spelling mistake was testing for
timout).
Fix: (
iodine_store) fixed missing EOL marker in DEBUG messages when reporting iodine's GC guard activity.
Update: (
iodine) added support for dynamic (hot) connection callback switching.
Change log v.0.7.13
Fix: (
mustache) added support for padding in template partials.
Fix: (
mustache) added support for method names as keys (i.e.,
{{user.to_json}} or
{{#user}}{{to_json}}{{/user}}). Note: no arguments may be passed (no Ruby code parsing, just testing against method names).
Change log v.0.7.12
Fix: (
mustache) fixed multiple issues with
Iodine::Mustache and added lambda support for mustache templates.
Change log v.0.7.11
Fix: (
fio) Deletes Unix sockets once done listening. Fixes an issue where the files would remain intact.
Optimization: (
fio) significant memory allocation optimizations. The facil.io allocator (included with iodine) helps to protect against heap fragmentation and improves speed for concurrent memory allocations when forking / multi-threading.
Change log v.0.7.10
Fix: (pub/sub) fixed connection lock for pub/sub tasks. Now pub/sub Ruby tasks will lock the connection, protecting the user's code against concurrent access to the connection's data.
Fix: (installation) fixed
CFLAGS compilation value to allow for pre-existing values set by Ruby.
Fix: (installation) fixed possible issues than could occur when installing iodine with
FIO_FORCE_MALLOC.
Optimization: (pub/sub) leverages facil.io broadcasting optimizations, minimizing memory allocations when broadcasting pub/sub messages directly to multiple WebSocket clients.
Update: (fio) updated the facil.io code to leverage it's urgent task queue for outbound IO, which minimizes reliance on the IO backup thread.
Update: (IO) minor tweaks to the IO backup thread and CLI output format.
Change log v.0.7.9
Fix: fixed the background IO backup thread initialization and sleep interval. This thread isn't critical. It's only used to (slowly) flush sockets when all the actual threads are blocked by long running Ruby application code.
Feature: added the
Iodine.worker? and
Iodine.master? methods, for process identification.
Update: Updated the automatic ActiveRecord
fork handling code and added automatic Sequel
fork handling, to protect against possible database communication errors related to the risk of connection sharing across worker processes.
Update: Moved the command line option parsing code, to leverage facil.io's
fio_cli... It appears more flexible than Ruby's
optparse (where command line naming is concerned).
Deprecation: deprecated the global namespace DSL (
after_fork, etc'). Use the new
Iodine.on_state(:after_fork) method instead.
Change log v.0.7.8
Fix:
unsubscribe possibly wouldn't unsubscribe from a connection-bound subscription when instructed to do so. This was discovered during a review of a issue #45 submitted by @ojab.
Fix: Documentation typo fixed by @ojab in PR#46.
Fix: Documentation errors exposed by @ojab regarding the pub/sub specification draft and the WebSocket/SSE specification draft.
Change log v.0.7.7
Fix: (facil.io) fixed critical issue with cookies, where no more than a single cookie could be set (duplicate headers would be zeroed out before being set). Credit to @ojab for exposing the issue.
Change log v.0.7.6
Fix: (facil.io edge) timeout review was experiencing some errors that could cause timeouts to be ignored. This was fixed in the facil.io edge branch.
Fix: (Ruby 2.2) fixed a possible error with the Mustache parser on Ruby 2.2. I don't run Ruby 2.2, but this came up as a warning during CI tests.
Fix:
on_worker_boot was mistakenly updated to a pre-fork callback (instead of a post fork callback) when attempting to fix the
on_worker_fork behavior. This timing issue is now fixed and
on_worker_boot is called after forking (both on the master process and the worker).
Change log v.0.7.5
Fix: fixed issue with direct calls to
publish in the pre-defined pub/sub engines. These direct calls are used by custom engines when the default engine was replaced and would attempt (erroneously) direct engine access rather than use the
fio_publish function.
Fix: fixed possible Array overflow risk that could result in memory corruption in some cases.
Fix: fixed more missing
static keywords in the code. these should have little or no effect on the namespace (they were using long unique names with the
iodine prefix).
Change log v.0.7.4
Fix: fixed a missing
static keyword in the Ruby<=>C storage bridge which caused performance degradation and introduced namespace conflict risks.
Fix: fixed the
on_worker_fork callback timing, to be performed before forking the process (Puma compatibility).
Fix: fixes to minor issues are included in the facil.io edge update.
Optimize: minor optimization to memory use, included in facil.io edge updates.
Change log v.0.7.3
Fix: (facil.io) updating facil.io fixes a channel name memory leak that was fixed in facil.io's edge version.
Updated: Improved logging for server data, allowing for total log silencing - this doesn't effect HTTP logging, only iodine's core logging system.
Change log v.0.7.2
Updated: updated the logging for HTTP services startup, to minimize log clutter.
Feature: (mustache) added features to
Iodine::Mustache, to expose more of the functionality offered by facil.io.
Fix: (facil.io) updated from the facil.io edge (master) branch. This should fix some exposed symbols (that should have been private), minimize name-collision risks, and fix an unknown issue with the mime-type registry cleanup and other possible issues.
Change log v.0.7.1
Fix: Fixed compilation issues with older
gcc compilers.
Change log v.0.7.0
This version bump is performed because the internal engine changed significantly and might be considered less mature. The public API remains unbroken.
Fix: Fixed a documentation error. Credit to @Fonsan (Erik Fonselius) for PR #41.
Feature: (mustache) Added a bridge to facil.io's mustache template rendering engine. This isn't really a server concern, but facil.io's C code includes this functionality anyway and it offers increased XSS protection by utilizing aggressive HTML escaping (and it's also faster than the Ruby canonical version).
Update: (facil.io) Updated to facil.io version 0.7.0 (edge). This could effect memory consumption behavior but otherwise shouldn't effect iodine all that much.
Change log v.0.6.5
Fix: (facil.io - logging) Fix typo in log output. Credit to @bjeanes (Bo Jeanes) for PR #39.
Change log v.0.6.4
Fix: (HTTP/WebSockets) fixed an issue where negative status return values (such as ActionCable's
-1 status code) could cause iodine to assume an abnormal error and shut down the connection. Credit to @mdesantis (Maurizio De Santis) for opening issue #38.
Change log v.0.6.3
Fix: (WebSockets) fixed an issue where WebSocket message events would attempt to create a String object outside the GVL.
Fix: (
Iodine::Connection) minor updated to the documentation and memory validation system.
Change log v.0.6.2
Fix: (
Iodine::PubSub) fixed an issue where lazy initialization would cause the shutdown process to crash if no Pub/Sub engines were ever registered (fixes an attempt to seek within an uninitialized data structure). Credit to @sj26 (Samuel Cochran) for reporting the issue.
Change log v.0.6.1
Fix: (
Iodine::PubSub) fixed typo,
Iodine::PubSub.detach is now correctly spelled.
Fix: (
Iodine::PubSub) fix issue #37 where iodine would crash after the server's shutdown process due to Ruby Pub/Sub engines still being attached (or set as default) even after the Ruby interpreter freed all the Ruby objects. Credit to @sj26 (Samuel Cochran) for reporting the issue.
Change log v.0.6.0
I apologize to all my amazing early adopters for the rapid changes in the API for connection objects (SSE / WebSockets) and Pub/Sub. This was a result of an attempt to create a de-facto standard with other server authors. Hopefully the API in the 0.6.0 release will see the last of the changes.
API BREAKING CHANGE: The API for persistent connections (SSE / WebSockets) was drastically changed in accordance with the Rack specification discussion that required each callback to accept a "client" object (replacing the
extend approach). Please see the documentation.
API BREAKING CHANGE:
Iodine.attach was removed due to instability and issues regarding TLS/SSL and file system IO. I hope to fix these issues in a future release. For now the
Iodine.attach_fd can be used for clear-text sockets and pipes.
API BREAKING CHANGE: Pub/Sub API was changed, replacing the previously suggested pub/sub object with an updated
unsubscribe method. This means there's no need for the client to map channel names to specific subscriptions (Iodine will perform this housekeeping task for the client).
Fix: Iodine should now build correctly on FreeBSD. Credit to @adam12 (Adam Daniels) for detecting the issue.
Change log v.0.5.2
Fix: fixed compilation issues on FreeBSD. Credit to @adam12 (Adam Daniels) for opening issue #35 and offering a patch.
Change log v.0.5.1
Fix: fixed compilation issues on OS X version < 10.12 and Alpine Linux. Credit to @jdickey (Jeff Dickey) for opening issue #32.
Fix: fixed some documentation errors. Credit to @janko-m (Janko Marohnić) for catching typos in the README.
Change log v.0.5.0
Changed... everything. At least all the internal bits and some of the API.
Iodine 0.5.0 is a stability oriented release. It also supports the updated Rack specification draft for WebSocket and SSE connections (yes, iodine 0.5.0 brings about SSE support).
Deprecated the
each function family in favor of the more scalable pub/sub approach.
Moved the HTTP network layer outside of the GIL, more robust pub/sub (using Unix Sockets instead of pipes), hot restart (in cluster mode) and more.
Larger header support. The total headers length now defaults to 32Kb, but can be adjusted. A hard coded limit of 8Kb per header line is still enforced (to minimize network buffer).
Improved concurrency and energy consumption (idling CPU cycles reduced).
Higher overall memory consumption might be observed (some security and network features now perform data copying rather than allowing for direct data access).
Improved automatic header completion for missing
Content-Length,
Date and
Last-Modified.
Support for the Unicorn style
before_fork and
after_fork DSL as well as the Puma style
on_worker_boot DSL.
Credit to Anatoly Nosov (@jomei) for fixing some typos in the documentation.
Change log v.0.4.19
Feature: (
iodine) added requested feature in issue #27,
Iodine.running? will return Iodine's state.
Change log v.0.4.18
Fix: (
iodine pub/bus) fixed issue #27 (?) where the
block used for subscriptions would be recycled by the GC and the memory address (retained by
iodine) would point at invalid Ruby objects (at worst) or become invalid (at best). Credit to Dmitry Davydov (@haukot) for exposing this issue.
Fix: (
facil pub/bus) fixed issue #27 (?) where the
memcpy was used instead of
memmove, resulting in possibly corrupt data in cluster messaging system. Credit to Dmitry Davydov (@haukot) for exposing this issue.
Change log v.0.4.17
Fix: (
iodine RubyCaller) fixed issue #26 that exposed an issue in the exception handling logic. This fix enforces exception handling whenever entering the Ruby GVL (GIL), allowing C functions to safely enter the user's Ruby code (where before C functions were assumed to be safe and user code would be executed unprotected when routed through certain functions). Credit to Dmitry Davydov (@haukot) for exposing this issue (issue #26).
Change log v.0.4.16
Fix: (
websocket_parser) The websocket parser had a memory offset and alignment handling issue in it's unmasking (XOR) logic and the new memory alignment protection code. The issue would impact the parser in rare occasions when multiple messages where pipelined in the internal buffer and their length produced an odd alignment (the issue would occur with very fast clients, or a very stressed server).
Change log v.0.4.15
Update: (
facil.io) updating the facil.io library version to use the 0.5.8 released version.
This includes the following changes (as well as other minor changes), as detailed in facil.io's CHANGEL.
Compatibility: (
gcc-6) Fix some compatibility concerns with
gcc version 6, as well as some warnings that were exposed when testing with
gcc.
Change log v.0.4.14
Fix: (
facil.io) fixes an issue where timer monitoring would report failure when the timer exists and is being monitored.
Change log v.0.4.12
Fix: (
facil.io) fixes some lingering issues with the new Websocket parser, namely an issue where certain network packet lengths would cause the parser to fail. Credit to Tom Lahti (@uidzip) for exposing the issue.
Change log v.0.4.11
Fix: (
iodine) use Ruby
fork instead of system
fork, allowing Ruby hooks to run before and after forking. This also fixes an issue where the Ruby timer thread isn't (re)initialized.
Change log v.0.4.10
Portability: (
mac OS High Sierra) iodine will load the Objective C library on macOS machines before starting up the server - this will prevent
fork from crashing the server on macOS High Sierra, see discussion here.
Fix: (
facil.io) fixes an error with the new Websocket parser (introduced in v. 0.4.9) that caused medium sized messages (127 Bytes - 64Kib) to be parsed incorrectly. Apologies. The test program I used seems to have validated messages using length comparison (instead of data comparison). Credit to Tom Lahti (@uidzip) for exposing the issue.
Change log v.0.4.9
Change: (
facil.io) the internal Websocket parser was replaced with something easier to read, for maintainability reasons. Performance seems to be mostly unaffected (sometimes it's faster and sometimes it's slower, common case is slightly optimized).
Change: (
facil.io) iodine will compile facil.io with the
NO_CHILD_REAPER flag, in order to workaround the Rails ExecJS gem that assumes no child reaping is performed. This workaround is, hopefully, temporary. Credit to @jerryshen for exposing the issue.
Fix: (
Iodine) test for timer creation error in
run_after and
run_every.
Fix: (
facil.io) timer creation now correctly detects if the reactor was stopped, allowing the creation of new timers before the reactor's reactivation.
Fix: (
facil.io) timer timeout review is now correctly ignored, preventing the timer from being shut down prematurely.
Change log v.0.4.8
Change: (
facil.io) the internal HTTP parser was replaced with something easier to read, for maintainability reasons. Performance seems to be unaffected.
Fix: HTTP request logging included an extra info line which was a debug/testing message inherited from
facil.io v.0.5.3-pre-release. This is now removed.
Performance: The
now HTTP Date string is now cached for up to 2 seconds, improving performance for
Date,
Last-Modified and Iodine logging messages that relate to the current time. However, it's likely that Rack will write it's own date string, masking this feature.
Change log v.0.4.7
Update: Now using
facil.io edge (stripped down v.0.5.3).
Fix: (
websocket) fix #21, now correctly initializes the
udata pointer to NULL fore each new request.
Fix: (
defer) a shutdown issue in
defer_perform_in_fork was detected by @cdkrot and his fix was implemented.
Change log v.0.4.6
Update: Now using
facil.io v.0.5.2.
Fix: (from
facil.io) fix
SIGTERM handling, make sure sibling processes exit when a sibling dies.
Change log v.0.4.5
Fix: fix static file service for
X-Sendfile as well as static error file fallback pages (404.html etc').
Change log v.0.4.4
Fix: fixed an issue related to Ruby 2.3 optimizations of String management (an issue that didn't seem to effect Ruby 2.4). This fix disables the recyclable buffer implemented for the
on_message Websocket callback. The callback will now receive a copy of the buffer (not the buffer itself), so there is no risk of collisions between the network buffer (managed in C) and the
on_message(data) String (managed by Ruby).
Change log v.0.4.3
Fix: fixed a possible issue in fragmented pipelined Websocket messages.
Change log v.0.4.2
Fix: fixed an issue where Websocket
ping timeouts were being ignored for the default
Iodine::Rack server, causing the default (40 seconds) to persist over specified valued.
Fix: fixed a possible issue with high-jacking which might cause the server to hang.
Change log v.0.4.1
Fix: postpone warmup in fear of abuse and collisions when using
fork. i.e., during warmup, an application might perform actions that conflict with
fork and worker initialization, such as creating a database connection pool during warmup, or maybe spawning a thread. Now
warmup is postponed until after worker processes are up and running, resulting in a per-process warmup rather than a per-cluster warmup.
Fix move the
rake-compiler dependency to "development" instead of "runtime". Credit to Luis Lavena (@luislavena) for exposing the issue (#19).
Change log v.0.4.0
Braking change: Some of the API was changed / updated, hopefully simplified.
DEPRECTAION / Braking change: The
websocket#write_each function is gone. Future (planned) support for a Pub/Sub API would have caused confusion and since it's barely used (probably only there as a benchmarking proof of concept) it was removed.
Update: Now using
facil.io v.0.5.0 The extended features include the following listed features.
Fixes: This was such a big rewrite, I suspect half the fixes I want to list are things I broke during the rewrite... but there were plenty of fixes.
Feature: Iodine now support native Websocket Pub/Sub, with an example in the
examples folder. i.e.:
# Within a Websocket connection: subscribe "chat" publish "chat", "Iodine is here!"
Feature: Iodine's Pub/Sub API supports both direct client messages and server filtered messages. i.e.
# Within a Websocket connection: subscribe("chat-server") {|msg| write "Notice: #{msg}" }# v.s subscribe("chat-client") publish "chat-server", "Iodine is here!"
Feature: Iodine's Pub/Sub API includes support for home made Pub/Sub Engines connecting Iodine to your Pub/Sub service of choice.
Feature: Iodine's Pub/Sub support includes a Process Cluster engine (pub/sub to all Websockets sharing the process cluster) as well as a Single Process engine (pub/sub to all websockets supporting a single process).
Feature: Iodine's Pub/Sub support includes a native Redis Pub/Sub engine. The parser is written from the ground up in C to keep the Iodine licensing as MIT. It's young, so keep your eyes pealed and submit any issues you encounter.
Feature + Breaking Change: Iodine now support multiple HTTP servers at once. i.e.:
# `Iodine::HTTP.listen` initializes an HTTP service in the C and system levels, so it can't be changed once initialized. Iodine::HTTP.listen port: 3000, app: my_app1 Iodine::HTTP.listen port: 3000, app: my_app2, public: "./www" Iodine.start
Change log v.0.3.6
Update: Now using
facil.io v.0.4.3. This fixes some delays in websocket packet flushing (latency), as well as other internal polishes. It also promises some possible future feature extensions that could add a major performance boost.
Change log v.0.3.5
Fix: (
sock) Fixed an issue with the
sendfile implementation on macOS and BSD, where medium to large files wouldn't be sent correctly.
Minor changes: This release incorporates some more minor changes from the
facil.io 0.4.2 update.
Change log v.0.3.4
Fix: (
sock,
facil, bscrypt) Add missing
static keywords to prevent state collisions with other libraries.
Change log v.0.3.3
Update: Now using
facil.io v.0.4.1
Fix: (from
facil.io) fixed the default response
Date (should have been "now", but wasn't initialized).
Compatibility: (from
facil.io) Now checks for HTTP/1.0 clients to determine connection persistence.
Compatibility: (from
facil.io) Added spaces after header names (
: =>
:), since some parsers don't seem to read the RFC.
Change log v.0.3.2
Fix: (from
facil.io) fixed thread throttling for better energy conservation.
Fix: (from
facil.io) fixed stream response logging.
Change log v.0.3.1
Update: Follow
facil.io's update for healthier thread throttling and energy consumption.
Change log v.0.3.1
Fix: Fixed a minor issue with the logging of responses where the size of the response is unknown (streamed).
Gem Specification update: We updated the gem specification to allow for Rack 1.x users and to update the gem description.
Change log v.0.3.0
facil.io C Core Update: The C library core that drives Iodine
facil.io was updated to version 0.4.0 and Iodine follows closely on the heels of this update. The transition was easy enough and the API remains unchanged... but because the performance gain was so big and because it's a new code base, we opted to bump the minor release version.
Change log v.0.2.17
Performance: Enhanced Performance for single threaded / blocking applications by adding a dedicated IO thread. This is related to issue #14.
Change log v.0.2.16
Update: iodine can now run as a basic HTTP static file server without a Ruby application (no
config.ru) when the
-www option is used from the command line.
Change log v.0.2.15
Fix: Fixed typo in logging and code comments, credit to @jmoriau in PR #13.
Change log v.0.2.14
Fix: fixed the experimental
each_write. An issue was found where passing a block might crash Iodine, since the block will be freed by the GC before Iodine was done with it. Now the block is correctly added to the object Registry, preventing premature memory deallocation.
Fix: fixed another issue with
each_write where a race condition review was performed outside the protected critical section, in some cases this would caused memory to be freed twice and crash the server. This issue is now resolved.
Deprecation: In version 0.2.1 we have notified that the the Websocket method
uuid was deprecated in favor of
conn_id, as suggested by the Rack Websocket Draft. This deprecation is now enforced.
Change log v.0.2.13
Fix: Fixed an issue presented in the C layer, where big fragmented Websocket messages sent by the client could cause parsing errors and potentially, in some cases, cause a server thread to spin in a loop (DoS). Credit to @Filly for exposing the issue in the
facil.io layer. It should be noted that Chrome is the only browser where this issue could be invoked for testing.
Credit: credit to Elia Schito (@elia) and Augusts Bautra (@Epigene) for fixing parts of the documentation (PR #11 , #12).
Change log v.0.2.12
Fix: removed
mempool after it failed some stress and concurrency tests.
Change log v.0.2.11
Fix: C layer memory pool had a race-condition that could have caused, in some unlikely events, memory allocation failure for Websocket protocol handlers. This had now been addressed and fixed.
Experimental feature: added an
each_write feature to allow direct
write operations that write data to all open Websocket connections sharing the same process (worker). When this method is called without the optional block, the data will be sent without the need to acquire the Ruby GIL.
Update: lessons learned from
facil.io have been implemented for better compatibility of Iodine's core C layer.
Change log v.0.2.10
Update: added documentation and an extra helper method to set a connection's timeout when using custom protocols (Iodine as an EventMachine alternative).
C Layer Update updated the
facil.io library used, to incorporate the following fixes / update:
Better cross platform compilation by avoiding some name-space clashes. i.e, fixes a name clash with the
__useddirective / macro, where some OSs (i.e. CentOS) used a similar directive with different semantics.
Reviewed and fixed some signed vs. unsigned integer comparisons.
Smoother event scheduling by increasing the event-node's pool size.
Smoother thread concurrency growth by managing thread
nanosleeptimes as thread count dependent.
Cleared out "unused variable" warnings.
Streamlined the
acceptprocess to remove a double socket's data clean-up.
SERVER_DELAY_IOis now implemented as an event instead of a stack frame.
Fixed a possible Linux
sendfileimplementation issue where sometimes errors wouldn't be caught or
sendfilewould be called past a file's limit (edge case handling).
bscryptrandom generator (where
dev/randomis unavailable) should now provide more entropy.
Change log v.0.2.9
Fix: fixed a gcc-4.8 compatibility issue that prevented iodine 0.2.8 from compiling on Heroku's cedar-14 stack. This was related to missing system include files in gcc-4.8. It should be noted that Heroku's stack and compiler (which utilizes Ubuntu 14) has known issues and / or limited support for some of it's published features... but I should have remembered that before releasing version 0.2.8... sorry about that.
Change log v.0.2.8.
Housekeeping: Cleaned up some code, removed old files, copied over the latest
facil.io library. There's probably some more housekeeping left to perform, especially anywhere where documentation is concerned. I welcome help with documentation.
Change log v.0.2.7
Minor Fix: fixed an issue where a negative number of processes or threads would initiate a very large number of forks, promoting a system resource choke. Limited the number of threads (1023) and processes (127).
Update: Automated the number of processes (forks) and threads used when these are not explicitly specified. These follow the number of cores / 2.
Change log v.0.2.6
Update: The IO reactor review will now be delayed until all events scheduled are done. This means that is events schedule future events, no IO data will be reviewed until all scheduled data is done. Foolish use might cause infinite loops that skip the IO reactor, but otherwise performance is improved (since the IO reactor might cause a thread to "sleep", delaying event execution).
Change log v.0.2.5
Fix:: fix for issue #9 (credit to Jack Christensen for exposing the issue) caused by an unlocked critical section's "window of opportunity" that allowed asynchronous Websocket
each blocks to run during the tail of the Websocket handshake (while the
on_open callback was running in parallel).
Minor Fix: Fix Iodine::Rack's startup message's
fprintf call to fit correct argument sizes (Linux warnings).
Change log v.0.2.4
Minor Fix: Patched Iodine against Apple's broken
getrlimit on macOS. This allows correct auto-setting of open file limits for the socket layer.
Minor Fix: Fixed the processor under-utilization warning, where "0" might be shown for the number processes instead of "1".
Update: Added support for the
env keys
HTTP_VERSION and
SERVER_PROTOCOL to indicate the HTTP protocol version. Iodine implements an HTTP/1.1 server, so versions aren't expected to be higher than 1.x.
Update: Iodine::Rack startup messages now include details regarding open file limits imposed by the OS (open file limits control the maximum allowed concurrent connections and other resource limits).
Change log v.0.2.3
Update: The
write system call is now deferred when resources allow, meaning that (as long as the
write buffer isn't full)
write is not only non-blocking, but it's performed as a separate event, outside of the Ruby GIL.
Update: The global socket
write buffer was increased to ~16Mb (from ~4Mb), allowing for more concurrent
write operations. However, the
write buffer is still limited and
write might block while the buffer is full. Blocking and "hanging" the server until there's enough room in the buffer for the requested
write will slow the server down while keeping it healthy and more secure. IMHO, it is the lesser of two evils.
Change log v.0.2.2
Update The static file service now supports
ETag caching, sending a 304 (not changed) response for valid ETags.
Update: A performance warning now shows if the CPUs are significantly under-utilized (less than half are used) of if too many are utilized (more than double the amount of CPUs), warning against under-utilization or excessive context switching (respectively).
Change log v.0.2.1
Notice: The Rack Websocket Draft does not support the
each and
defer methods. Although I tried to maintain these as part of the draft, the community preferred to leave the implementation of these to the client (rather then the server). If collisions occur, these methods might be removed in the future.
Update: Websockets now support the
has_pending? method and
on_ready callback, as suggested by the Rack Websocket Draft.
Update: deprecated the Websocket method
uuid in favor of
conn_id, as suggested by the Rack Websocket Draft.
Fix: fixed an issue were the server would crash when attempting to send a long enough websocket message.
Change log v.0.2.0
This version is a total rewrite. The API is totally changed, nothing stayed.
Iodine is now written in C, as a C extension for Ruby. The little, if any, ruby code written is just the fluff and feathers.
deprecation of the 0.1.x version line
Change log v.0.1.21
Optimization: Minor optimizations. i.e. - creates 1 less Time object per request (The logging still creates a Time object unless disabled using
Iodine.logger = nil).
Security: HTTP/1 now reviews the Body's size as it grows (similar to HTTP/2), mitigating any potential attacks related to the size of the data sent.
Logs: Log the number of threads utilized when starting up the server.
Change log v.0.1.20
Update/Fix: Updated the
x-forwarded-for header recognition, to accommodate an Array formatting sometimes used (
["ip1", "ip2", ...]).
Update: native support for the
Forwarded header HTTP.
API Changes:
Iodine::HTTP.max_http_buffer was replaced with
Iodine::HTTP.max_body_size, for a better understanding of the method's result.
Change log v.0.1.19
Update: added the
go_away method to the HTTP/1 protocol, for seamless connection closeing across HTTP/2, HTTP/1 and Websockets.
Change log v.0.1.18
Update: The request now has the shortcut method
Request#host_name for accessing the host's name (without the port part of the string).
Change log v.0.1.17
Credit: thanks you @frozenfoxx for going through the readme and fixing my broken grammar.
Fix: fixed an issue where multiple Pings might get sent when pinging takes time. Now pings are exclusive (run within their own Mutex).
Fix: HTTP/2 is back... sorry about breaking it in the 0.1.16 version. When I updated the write buffer I forgot to write the status of the response, causing a protocol error related with the headers. It's now working again.
Update: by default and for security reasons, session id's created through a secure connection (SSL) will NOT be available on a non secure connection (SSL/TLS). However, while upgrading to the encrypted connection, the non_encrypted session storage is now available for review using the
Response#session_old method.
- Remember that sessions are never really safe, no matter how much we guard them. Session hijacking is far too easy. This is why Iodine stores the session data locally and not within the session cookie. This is also why you should review any authentication before performing sensitive tasks based on session stored authentication data.
Change log v.0.1.16
Performance: HTTP/1 and HTTP/2 connections now share and recycle their write buffer when while reading the response body and writing it to the IO. This (hopefully) prevents excess
malloc calls by the interpreter.
Change log v.0.1.15
Update: IO reactor will now update IO status even when tasks are pending. IO will still be read only when there are no more tasks to handle, but this allows chained tasks to relate to the updated IO status. i.e. this should improve Websocket availability for broadcasting (delay from connection to availability might occur until IO is registered).
Update: Websockets now support the
on_ping callback, which will be called whenever a ping was sent without error.
Change log v.0.1.14
Update: the Response now supports
redirect_to for both permanent and temporary redirection, with an optional
flash cookie setup.
Performance: the Protocol class now recycles the data string as a thread global socket buffer (different threads have different buffer strings), preventing excessive
malloc calls by the Ruby interpreter. To keep the
data (in
on_message(data)) past the
on_message method's scope, be sure to duplicate it using
data.dup, or the string's buffer will be recycled.
Change log v.0.1.13
Change: Session cookie lifetime is now limited to the browser's session. The local data will still persist until the tmp-folder is cleared (when using session file storage).
Fix: renamed the SSL session token so that the SSL session id isn't lost when a non-secure session is used.
Fix: The
flash cookie-jar will now actively prevent Symbol and String keys from overlapping.
Compatibility: minor fixes and changes in preparation for Ruby 2.3.0. These may affect performance due to slower String initialization times.
Change log v.0.1.12
Update: Passing a hash as the cookie value will allow to set cookie parameters using the Response#set_cookie options. i.e.:
cookies['key']= {value: "lock", max_age: 20}.
Security: set the HTTPOnly flag for session id cookies.
Change log v.0.1.11
Fix: fixed the Rack server Handler, which was broken in version 0.1.10.
Change log v.0.1.10
Fix: make sure the WebsocketClient doesn't automatically renew the connection when the connection was manually closed by the client.
Performance: faster TimedEvent clearing when manually stopped. Minor improvements to direct big-file sending (recycle buffer to avoid
malloc).
Change log v.0.1.9
Fix: WebsocketClient connection renewal will now keep the same WebsocketClient instance object.
Update Creating a TimedEvent before Iodine starts running will automatically 'nudge' Iodine into "Task polling" mode, cycling until the user signals a stop.
Update: repeatedly calling
Iodine.force_start! will now be ignored, as might have been expected. Once Iodine had started,
force_start! cannot be called until Iodine had finished (and even than, Iodine might never be as fresh nor as young as it was).
Change log v.0.1.8
Fix: Websocket broadcasts are now correctly executed within the IO's mutex locker. This maintains the idea that only one thread at a time should be executing code on behalf of any given Protocol object ("yes" to concurrency between objects but "no" to concurrency within objects).
Fix fixed an issue where manually setting the number of threads for Rack applications (when using Iodine as a Rack server), the setting was mistakenly ignored.
Fix fixed an issue where sometimes extracting the HTTP response's body would fail (if body is
nil).
Feature: session objects are now aware of the session id. The session id is available by calling
response.session.id
Fix fixed an issue where HTTP streaming wasn't chunk encoding after connection error handling update.
Fix fixed an issue where HTTP streaming would disconnect while still processing. Streaming timeout now extended to 15 seconds between response writes.
Change log v.0.1.7
Removed a deprecation notice for blocking API. Client API will remain blocking due to use-case requirements.
Change log v.0.1.6
Fix: fixed an issue where a session key-value pair might not get deleted when using
session.delete key and the
key is not a String object. Also, now setting a key's value to
nil should delete the key-value pair.
Fix: fixed an issue where WebsocketClient wouldn't mask outgoing data, causing some servers to respond badly.
Performance: minor performance improvements to the Websocket parser, for unmasking messages.
Deprecation notice:
(removed after reviewing use-cases).
Change log v.0.1.5
Feature: The Response#body can now be set to a File object, allowing Iodine to preserve memory when serving large static files from disc. Limited Range requests are also supported - together, these changes allow Iodine to serve media files (such as movies) while suffering a smaller memory penalty and supporting a wider variety of players (Safari requires Range request support for it's media player).
Fix: Fixed an issue where Iodine might take a long time to shut down after a Fatal Error during the server initialization.
Change log v.0.1.4
Fix: fixed an issue with where the WebsocketClient#on_close wouldn't be called for a renewable Websocket connection during shutdown.
Fix: fixed an issue where a protocol's #on_close callback wouldn't be called if the Iodine server receives a shutdown signal.
Fix: fixed an issue where HTTP2 header size limit condition was not recognized by the Ruby parser (a double space issue, might be an issue with the 2.2.3 Ruby parser).
Change log v.0.1.3
Fix: fixed an issue with the new form/multipart parser, where the '+' sign would be converted to spaces on form fields (not uploaded files), causing in-advert potential change to the original POSTed data.
Change log v.0.1.2
Fix: fixed an issue where the default implementation of
ping did not reset the timeout if the connection wasn't being closed (the default implementation checks if the Protocol is working on existing data and either resets the timer allowing the work to complete or closes the connection if no work is being done).
Change log v.0.1.1
Fix: Fixed an issue where slow processing of HTTP/1 requests could cause timeout disconnections to occur while the request is being processed.
Change/Security: Uploads now use temporary files. Aceessing the data for file uploads should be done throught the
:file property of the params hash (i.e.
params[:upload_field_name][:file]). Using the
:data property (old API) would cause the whole file to be dumped to the memory and the file's content will be returned as a String.
Change/Security: HTTP upload limits are now enforced. The current default limit is about ~0.5GB.
Feature: WebsocketClient now supports both an auto-connection-renewal and a polling machanism built in to the
WebsocketClient.connect API. The polling feature is mostly a handy helper for testing, as it is assumed that connection renewal and pub/sub offer a better design than polling.
Logging: Better HTTP error logging and recognition.
Change log v.0.1.0
First actual release:
We learn, we evolve, we change... but we remember our past and do our best to help with the transition and make it worth the toll it takes on our resources.
I took much of the code used for GRHTTP and GReactor, changed it, morphed it and united it into the singular Iodine gem. This includes Major API changes, refactoring of code, bug fixes and changes to the core approach of how a task/io based application should behave or be constructed.
For example, Iodine kicks in automatically when the setup script is done, so that all code is run from within tasks and IO connections and no code is run in parallel to the Iodine engine.
Another example, Iodine now favors Object Oriented code, so that some actions - such as writing a network service - require classes of objects to be declared or inherited (i.e. the Protocol class).
This allows objects to manage their data as if they were in a single thread environment, unless the objects themselves are calling asynchronous code. For example, the Protocol class makes sure that the
on_open and
on_message(data) callbacks are executed within a Mutex (
on_close is an exception to the rule since it is assumed that objects should be prepared to loose network connection at any moment).
Another example is that real-life deployment preferences were favored over adjustability or features. This means that some command-line arguments are automatically recognized (such as the
-p <port> argument) and that Iodine assumes a single web service per script/process (whereas GReactor and GRHTTP allowed multiple listening sockets).
I tested this new gem during the 0.0.x version releases, and I feel that version 0.1.0 is stable enough to work with. For instance, I left the Iodine server running all night under stress (repeatedly benchmarking it)... millions of requests later, under heavy load, a restart wasn't required and memory consumption didn't show any increase after the warmup period.
License
The gem is available as open source under the terms of the MIT License. | https://www.rubydoc.info/gems/iodine/0.7.36/file/CHANGELOG.md | CC-MAIN-2020-05 | refinedweb | 8,418 | 59.7 |
I'm writing some Perl code to do some statistical analysis on two data files which contain records that may or may not be related. I have some code that creates a scoring system to rank matches bewtween records - all records from file a are matched with those records from file b that are possible matches. Each possible match is assigned a score. I have approx. 10 million possible combinations.
My data is stored like this:
$rMatch->{$File1RecordID}->{$File2RecordID} = $ranking;
[download]
My first step in matching the data is to find all those records in file 2 that are a top ranked match with only one record in file 1. I consider those "strong matches" and want to eliminate them from the pool of records before matching the remaining data.
The second step is to create combinations of probable matches all remaining records from file 1 and all records from file 2. The lowest overall "score" for that match will be the recordset alignment that I go with for the remaining records.
My problem? The process of identifying the "strong matches" is too CPU intensive, running at 100% usage for a long time. My CPU is actually overheating and my machine is shutting down. I can mitigate that with a sleep(1) statement, but that's not very elegant...it slows this massive task down...and I suspect the problem is the number of times that I sort my hash in the program to identify strong matches. In other words, inefficiency in my code ;) Is there a better way to do this? This sort is the only way I know to find the lowest value in my hash.
In the code below, id1 is my id from the first file, id2 is the id from the second file, and $rC holds the ranking for the combination of id1 and id2. Basically, I want to check all other combinations of records for the existence of id2 as a top rank. If I do not find any other combinations, I'm reasonably confident that those 2 records should be matched.
sub IsStrongMatch
{
# Return true if id2 is only top ranked match for id1
my $id1 = shift;
my $id2 = shift;
my $rC = shift;
for my $i1 ( keys %{$rC} )
{
next if $i1 == $id1;
foreach my $i2 ( sort { $rC->{$i1}->{$a} <=> $rC->{$i1}->{$b}
+} keys %{$rC->{$i1}} )
{
if ( $id2 == $i2 )
{
return 0;
}
}
}
return 1;
}
[download]
2006-08-31 Retitled by planetscape, as per Monastery guidelines: one-word (or module-only) titles hinder site navigation ( keep:0 edit:14 reap:0 )
Original title: 'Efficiency'
That said, i would do a Matrix(nxn) (square not a requirement, dimensions might change based on num of records of course) to keep track of scores. Consider the following table
Sorting to finx max/min is an overkill. I might be missing your porblem so please correct me if i am wrong.
cheers
SK
I was thinking about the use of arrays...my ids are pretty big numbers so I wouldn't use them alone as array indices. I could always use $., however, when I read in the file rather than the id.
My ranking is based on # of seconds from last log entry in one file to first log entry in the second file. So I create scoring by looking at # of seconds between each record. My ability to identify a "strong match" comes from the rate of concurrent users in the application that my data comes from. Low concurrent users, I'll have lots of strong matches - records that clearly line up. If I have high concurrent users with lots of log file entries, then I've got to get a little creative.
I was sorting b/c my hash is being used to store # of elapsed seconds...not a true "rank" in terms of 1, 2, 3, etc.
I'm considering the use of arrays, but don't want to lose the elapsed seconds as data quite yet b/c that will be used in the next step to figure out the best match from the remaining data.
This sort is the only way I know to find the lowest value in my hash
use List::Util;
#... later in the code
sub IsStrongMatch {
# Return true if id2 is only top ranked match for id1
my $id1 = shift;
my $id2 = shift;
my $rC = shift;
for my $i1 ( keys %{$rC} ) {
next if $i1 == $id1;
my $href = $rc->{$i1};
my $minid = reduce {
$href->{$a} < $href->{$b} ? $a : $b
} keys %$href;
return 0 if defined $minid && $id2 == $minid;
}
return 1;
}
[download]
Update: I realised that this answer is a little cryptic. reduce in List::Util allows you to visit each element in an array and do "something" based on the values you encounter along the path. What this code does (more or less) is probably best explained by mrborisguy in this post.
Flavio
perl -ple'$_=reverse' <<<ti.xittelop@oivalf
It may be that sorted arrays are the way to go, as mentioned elsewhere. But it might make sense to go from the data you have now to an inverted list of best matches, so as to sort each list only once:
my $inv = {};
for my $index (keys %$rc) {
my $subhash = $rc->{$index};
my @sorted = sort { $subhash->{$a} <=> $subhash->{$b} } keys %$sub
+hash;
if ($subhash->{$sorted[0]} < $subhash->{$sorted[1]}) {
# this is the best match
push @{ $inv->{$sorted[0]} }, $index;
}
}
[download]
return (@{ $inv{$id2} } == 1) ? 1 : 0;
[download]
I'm not sure that I fully understand the problem, so the code might need some tweaking ...
Hugo
Update: I just read frodo72's post, which makes the point better than this code.
In that case, if you are just going to use the first one, wouldn't finding the first one be faster than sort?
sub IsStrongMatch
{
# Return true if id2 is only top ranked match for id1
my $id1 = shift;
my $id2 = shift;
my $rC = shift;
for my $i1 ( keys %{$rC} )
{
next if $i1 == $id1;
my $i2;
for ( keys %{ $rC->{ $i1 } } ) {
$i2 = $_ if not defined( $i2 );
# if there's a good way to find a starting $i2
# before beginning, then take this out, and
# don't check every time
$i2 = $_ if
$rC->{ $i1 }->{ $_ }
<
$rC->{ $i1 }->{ $i2 };
}
if ( $id2 == $i2 )
{
return 0;
}
}
return 1;
}
[download]
-Bryan. | http://www.perlmonks.org/?node_id=481551 | CC-MAIN-2017-30 | refinedweb | 1,046 | 75.03 |
OpenCV #006 Sobel operator and Image gradient
Digital Image Processing using OpenCV (Python & C++)
Highlights: In this post, we will learn what Sobel operator and an image gradient are. We will show how to calculate the horizontal and vertical edges as well as edges in general.
What is the most important element in the image? Edges! See below.
Tutorial Overview:
1. What is the Gradient?
Let’s talk about differential operators. When differential operators are applied to an image, it returns some derivative. These operators are also known as masks or kernels. They are used to compute the image gradient function. And after this has been completed, we need to apply a threshold to assist in selecting the edge of pixels.
And what is then multivariate? Multivariate means that a function is actually a function of more than one variable. For example, an image is a function of two variables, \(x \) and \(y \). When we have functions that are a function of more than one variable, we refer to it as a partial derivative. Which is the derivative in the \(x \) or in the \(y \) direction. And the gradient is the vector that’s made up of those derivatives.
$$ \bigtriangledown f= \left [ \frac{\partial f}{\partial x},\frac{\partial f}{\partial y} \right ] $$
So what operator are we going to use in showing the gradient? It’s the vector above.
If we recall, what an image is. It is a two vector, made up \(\partial f \) with respect to \(x \), (The gradient of the image in the x direction) and the \(\partial f \) with respect to \(y \).
\(\partial f \) respect to \(x \)
Base on the vector above, the image only changes in the x-direction. So, the gradient would be whatever the changes are in the x-direction and \(0 \) in the y-direction. The same method can be applied to the changes in the y-direction.
We have explained horizontal and vertical edge detectors before. You can find more about it in posts CNN002 and CNN003.
Python
C++
#include <iostream> #include <opencv2/opencv.hpp> using namespace std; using namespace cv; int main() { Mat image = cv::imread("truck.jpg", IMREAD_GRAYSCALE); cv::imshow("Truck", image); cv::waitKey(); // we have already explained linear filters for horizontal and vertical edge detection // reference -->> CNN #002, CNN #003 posts. cv::Mat image_X; // this is how we can create a horizontal edge detector // Sobel(src_gray, dst, depth, x_order, y_order) // src_gray: The input image. // dst: The output image. // depth: The depth of the output image. // x_order: The order of the derivative in x direction. // y_order: The order of the derivative in y direction. // To calculate the gradient in x direction we use: x_order= 1 and y_order= 0. // To calculate the gradient in x direction we use: x_order= 0 and y_order= 1. cv::Sobel(image, image_X, CV_8UC1, 1, 0); cv::imshow("Sobel image", image_X); cv::waitKey();
\(\partial f \) respect to \(y \)
As we can see, the direction of the gradient in y is getting more positive as you go down. In the sense that, it’s getting brighter in this direction. So in our image, the gradient would be 0, \(\partial f \) respect to \(x \), yet, we would have \(\partial f \) respect to \(y \).
Python
C++
cv::Mat image_Y; // this is how we can create a vertical edge detector. cv::Sobel(image, image_Y, CV_8UC1, 0, 1); cv::imshow("Sobel image", image_Y); cv::waitKey();
And, of course we have changes in both directions and that’s the gradient itself.
It’s \(\partial f \) respect to \(x \), and the \(\partial f \) respect to \(y \). It has both magnitudes, which shows how things are getting brighter. And also an angle \(\theta \) that represents the direction the intensity is increasing. Here we are just expressing all of this.
Python
C++
// When we combine the horizontal and vertical edge detector together cv::Mat sobel = image_X + image_Y; cv::imshow("Sobel - L1 norm", sobel); cv::waitKey();
The gradient of an image – Here, the gradient is given by the two partial derivatives. \(\partial f \) respect to \(x \), and the \(\partial f \) respect to \(y \).
$$ \bigtriangledown f= \left [ \frac{\partial f}{\partial x},\frac{\partial f}{\partial y} \right ] $$
The gradient direction is given by – The direction can be computed by computing the arctangent. This is the arctan of the changes in \(y \) over the change in \(x \). Sometimes, it’s also recommended to use atan2. So if the \(\partial f \) with respect to \(x \) is zero, that your machine doesn’t explode.
$$ \theta = tan^{-1}\left ( \frac{\partial f}{\partial y}/\frac{\partial f}{\partial x} \right ) $$
The amount of change is given by the gradient magnitude – This shows us how rapidly the function is changing, which is very much related to finding edges by looking for large magnitudes of gradients on the image.
$$ \left \| \bigtriangledown f \right \|= \sqrt{\left ( \frac{\partial f}{\partial x} \right )^{2}+\left ( \frac{\partial f}{\partial y} \right )^{2}} $$
2. Finite Differences
The above calculus story is just fine. However, how do we compute the gradients in our images because we work with discrete variables and not with continuous ones. Let’s see more about discrete gradients:
$$ \frac{ \partial f\left ( x,y \right )}{\partial x}= \lim_{\varepsilon \rightarrow 0}\frac{f\left ( x+\varepsilon ,y \right )-f\left ( x,y \right )}{\varepsilon } $$
In continuous math, the partial derivative \(\partial f \) with respect to \(x \) is this limit. So we move a little bit in the \(x \) direction, subtract off the original one and divide by \(\varepsilon \). Meanwhile, when the limit reaches zero, that becomes our derivatives.
In the discrete world, we can’t move closer. We have to take the finite difference.
$$ \frac{ \partial f\left ( x,y \right )}{\partial x}\approx \frac{f\left ( x+1,y \right )-f\left ( x,y \right )}{1 }\approx f\left ( x+1,y \right )-f\left ( x,y \right ) $$
When approximating our partial by finite difference. We take one step in the \(x \) direction, then subtract off the original and divide by \(1 \). Since that’s how big of a step we took.
So that’s become the value \(f\left (x+1,y \right )-f\left ( x,y \right ) \) . In other words, this is called the right derivative because it takes one step to the right. For instance, let’s take a closer look at our finite differences, to think about these derivatives the right way.
A simple illustration of finite difference.
We have a picture of this truck. This is a good illustration of those finite difference images. First question, is this the finite difference in \(x \) or in \(y \)? Let’s have a look.
Going through the image in the \(x \)-direction, we get some kind of transition between these vertical stripes. To clarify, we get a change from bright values, to dark values, then bright values again, across the image horizontally.
In addition, we can hardly see any changes in \(y \), but only in \(x \). Hence, this is going to be a finite difference in \(x \).
The image we are presenting contains both negative and positive numbers. When showing an image, we make black-0, and other numbers white. However, it is preferable to say some minimum values are black, and some maximum is white. So we can make \(-128 \) to be black, \(+ 127 \) to be white. The in-between values will be gray (also zero values).
3. The Discrete Gradient
How do we pick an “operator” (mask/kernel) that can be applied to any image to implement these gradients? Well, here is an example below of an operator \(H \).
So looking at this operator, with 3 rows and 2 columns above. Is this a good operator? Well, you figured it. NO!!!.
Why is that? One reason is there are no middle pixel values.
Now you might ask yourself, why is it a plus half and minus a half? Um… A good question, only if you did wonder why.
It is the average or normalization of the right derivative and the left derivative. The right derivative would be a \(+1 \) at the right of the kernel, and \(-1 \) at the middle. The left derivative would be a \(+1 \) at the left of the kernel, and \(-1 \) at the middle.
Average of “left” and “right” derivative
To get the average, we would add them and divide by two. Which is the sum. So, we get \(-1 \) (left), \(0 \) (middle), \(1 \) (right). Then when we divided by two to get \(-\frac{1}{2} \) (left), \(+\frac{1}{2} \) (right) with a \(0 \) in the middle.
4. Sobel Operator
The most common filter for doing derivatives and edges is the Sobel operator. It was named after \(Irwin Sobel\) and \(Gary Feldman \), after presenting their idea about an “Isotropic 3×3 Image Gradient Operator” in 1968. The operator looks like the image below.
But instead of \(-\frac{1}{2} \) and \(+\frac{1}{2} \), it’s got this weird thing where it’s doing these eighths. And you can see that it does, not only \(+2 \), \(-2 \), which we would then divide by \(4 \) and we get the same value. But it also does a \(+1 \), \(-1 \) on the row above, and below the row.
The idea is, to compute a derivative at a pixel, we won’t look left, and right at ourselves but also look nearby.
Another equation to be familiar with
By the way, the \(y \) is here as well, and in this case, \(y \) is positive going up. Remember, it can go in either direction.
Sobel gradient is: Made up of the application of this \(s_ {x} \) and \(s_ {y} \) to get us these values.
$$ \bigtriangledown I= \begin{bmatrix}g_{x} & g_{y}\end{bmatrix}^{T} $$
The gradient magnitude: Is the square root of the sum of squares.
$$ g= \left ( g_{x}^{2}+g_{y}^{2} \right )^{1/2} $$
The gradient direction: Is what we did before. And here, it is \(arctan2 \) we were talking about to get the gradient.
$$ \theta = atan2\left ( g_{y},g_{x} \right ) $$
Here is an example. The picture on the left is an image. The one in the middle is a gradient magnitude. We applied the Sobel operator, then took the square root of the sum of squares. Then threshold it. And you will notice two things. One, it’s not an awful edge image and it’s not a great edge image. So we are partly towards getting that done.
Python
C++
// this idea is inspired from the book // "Robert Laganiere Learning OpenCV 3:: computer vision" // what it actually does, makes the non-edges to white values // and edges to dark values, so that it is more common for our visual interpretation. // this is done according to formula // sobelImage = - alpha * sobel + 255; double sobmin, sobmax; cv::minMaxLoc(sobel, &sobmin, &sobmax); cv::Mat sobelImage; sobel.convertTo(sobelImage, CV_8UC1, -255./sobmax, 255); cv::imshow("Edges with a sobel detector", sobelImage); cv::waitKey(); cv::Mat image_Sobel_thresholded; double max_value, min_value; cv::minMaxLoc(sobelImage, &min_value, &max_value); //image_Laplacian = image_Laplacian / max_value * 255; cv::threshold(sobelImage, image_Sobel_thresholded, 20, 255, cv::THRESH_BINARY); cv::imshow("Thresholded Sobel", image_Sobel_thresholded); cv::waitKey();
// Also, very popular filter for edge detection is Laplacian operator // It calculates differences in both x and y direction and then sums their amplitudes. cv::Mat image_Laplacian; // here we will apply low pass filtering in order to better detect edges // try to uncomment this line and the result will be much poorer. cv::GaussianBlur(image, image, Size(5,5), 1); cv::Laplacian(image, image_Laplacian, CV_8UC1); cv::imshow("The Laplacian", image_Laplacian); cv::waitKey(); cv::Mat image_Laplacian_thresholded; double max_value1, min_value1; cv::minMaxLoc(image_Laplacian, &min_value1, &max_value1); //image_Laplacian = image_Laplacian / max_value * 255; cv::threshold(sobel, image_Laplacian_thresholded, 70, 220, cv::THRESH_BINARY); cv::imshow("Thresholded Laplacian", image_Laplacian_thresholded); cv::waitKey(); return 0; }
Summary
If you are just starting with an image processing, this post gave you insights on how we can calculate image gradients. We will use these ideas heavily in image processing and they will assist us in how to detect edges and objects.
More resources on the topic:
- The Sobel and Laplacian Edge Detectors
- CNN Edge detection
- CNN More On Edge Detection
- Image Gradient Wikipedia
- Sobel Operator Wikipedia | http://datahacker.rs/opencv-sobel-operator-and-image-gradient/ | CC-MAIN-2021-39 | refinedweb | 2,020 | 64.71 |
aclysmaMember
Content count28
Joined
Last visited
Community Reputation180 Neutral
About aclysma
- RankMember
What language should I write my indie game in?
aclysma replied to MagusGatesIgnition's topic in General and Gameplay ProgrammingDo you want to make a game or learn how to program? Do you know any languages yet? If you don't even know what language/technology you want to leverage, you might want to use something that less programming-oriented. In any case, it would let you do some prototyping so you can figure out if your idea is fun or not.
Once you go OO, you never go back?
aclysma replied to azonicrider's topic in General and Gameplay Programming[quote name='darkhaven3' timestamp='1355935655' post='5012486'] After being a C++ programmer for a little while and dabbling with Java, I have to say that in my opinion object-oriented programming is relatively worthless to me. I honestly don't see why I should ever bother worrying about whether or not a particular set of functions can "see" each other, or whether or not I can make two functions with the same name. Why would I ever want more code obfuscation like that -- two functions with identical names that can do two completely different operations? Why on earth would I ever want such a thing? But this is of course only my opinion. I'm not unique in the way I think, surely, but I'm also probably not at all a rare, dying species of programmer. [/quote] Most of the projects I've worked on professionally did NOT do much in the way of data hiding. 99% of the member variables in a class were public. It was annoying at times.. every time you reached in to set a value you had to be careful that you wouldn't cause side effects, but ultimately those projects shipped. Unrealscript is an example of an everything-is-public OO implementation. Data hiding is a good idea. But can you ship without doing it? Yes, definitely. It raises the requirement of others not screwing up when working with your code though. In the case of unrealscript, they made the explicit choice to not hide data for performance reasons of calling a getter/setter (in C++ it's essentially no extra cost due to inlining, but in script.. there was definitely cost.) But that decision was not without other consequence in the form of maintenance hassle.
Once you go OO, you never go back?
aclysma replied to azonicrider's topic in General and Gameplay ProgrammingI have no statistics so I'll make unsubstantiated sweeping generalizations instead [img][/img] Most places outside of games DEFINITELY do OOP, whether or not they understand why they are using it and its advantages and disadvantages. Most game studios/engines I'm aware of also do OOP. I've seen a very small shift away from OOP in favor of thinking in terms of data transformations. In my opinion OOP is very often a good choice. But unfortunately it seems like this is the way *everyone* learns how to program and don't understand the pros/cons of that style. "This is the way thou shalt make software." You benefit from OOP by easy data hiding/encapsulation, and if we mean OOP as in common language features, ability to use polymorphic functions and type safety/inheritance. It's also a well-understood style by the person coming behind you. A bad side of OOP is that few people succeed in only having a single concern per each object type and so what often happens is you get large classes that throw a bunch of unrelated functionality together with its data, and it makes it very difficult to extract a single aspect of the class out for reuse. You end up creating generalized objects that are more complex than necessary to solve a problem. OOP is also a trap for people to make code that attempts to model the real world (i.e. your objects are "chair" or "car" when maybe the better solution would be SitableComponent or DrivableComponent that's attached to something more general). It's difficult to have the discipline to break down a seemingly simple object into the various concerns it has, but failing to do so makes bad OOP designs. One alternative might be a data transformations style, where you have lots of homogeneous data and you simply rip through it all using loose functions. Even with such a style, you can think in terms of OOP and limit how/when/where you access data in those lists. And yet you can keep data and logic separated. In other words, you can get the advantages of OOP without using the class keyword. I think OOP is so prevalent because it's almost always a decent solution and it's very intuitive. So for big companies that just want to grow a workforce of moderately skilled people who can make standard business software without needing to have the depth of understanding to choose what style to use, OOP is a good choice. I think the most important thing is realize that you can get the benefits of OOP without using the class keyword, while skirting the negative aspects of it by either being careful to keep your objects single-minded or thinking in a more raw form of data transformations in sequence. Consider many solutions/styles and *think* about the tradeoffs you make with your choice.
std::Queue and multithreading
aclysma replied to Anand Baumunk's topic in General and Gameplay ProgrammingThe easy solution is to use a lock or someone else's thread safe queue as has already been suggested. If you're just trying to solve a problem, this is definitely the way to go. If you're interested in really digging into concurrent programming for the purpose of learning, you may want to investigate writing your own lockless queue where exactly one thread can write and exactly one thread can read. It doesn't require a ton of code to do something simple and it's well worth the learning experience. The need to pass data continuously from thread A to thread B in this way is extremely common. An easy implementation is to have a "read pointer" and a "write pointer" that wraps in a circular buffer - just be careful of order of operations and make the read pointer and write pointer volatile. The "pointer" can be an index into the static-sized circular buffer. Using a queue like this is great for passing data to be processed. It can also proxy a function call to another thread by using the "command" pattern. You can even pass exceptions this way.
Exporting template instantiations to DLL
aclysma replied to aclysma's topic in General and Gameplay ProgrammingI'm thinking #1 won't work for me as I don't think static members in the template would be shared across DLLs. I was hoping I wouldn't have to do something like #2 but looks like there aren't better options. Thanks for the suggestions.
Is it generally wrong to style a C++ library like Java or C#?
aclysma replied to KanonBaum's topic in General and Gameplay ProgrammingThere's two ways I read your post. Here's my opinion on your question approached from both angles, and it's worth exactly what you paid for it. "Cosmetic" Style: I wrap all my enums with a namespace and typedef it kind of like what you did with a class. I tend to name like this: ClassNames, _param_vars, and local_vars. You won't see any of that in STL, but it's all opinion. Unlike C# or java, c++ doesn't have "accepted standards." If you look at a bunch of different c++ libraries, they all approach the nuts and bolts of the code differently. In some ways is unfortunate to not have consistency, but on the other hand, different people have different opinions. There is absolutely nothing built-in to the language to force you to go in a particular direction. I'd look at the API for stl and see how they do their naming, but I personally don't care for it and prefer my own "standard" I've settled on over my time with C++. The only thing I'd suggest is that you consider namespaces rather than classes to wrap your constants because it seems like a more natural fit to me. Not that it will really matter after the compiler gets done with your code. Do what feels comfortable. "Functional" Style: Java/C# treat memory completely differently from C++. They are meant to be more restrictive than C++ (i.e. you can't just dereference whatever memory you want at will.) There's plenty of good/bad aspects to this. But this abbreviated conclusion is that the optimal design in Java/C# that embraces OOP may not be the optimal design in C++. I'd say in general if you want to do something "like Java/C#" you can, but in C++ you may be able to work in a different paradigm more suited to your problem. In particular if you're creating a library you'll want to be careful about how memory gets passed around. This can bite you, especially if you want to distribute it as a DLL. While Java/C# will make sure everything magically works, in C++ you need to be aware of what you're actually asking the computer to do (i.e. if you allocate memory in one DLL and free it in another, will it try to return that memory to the same heap?). If you want your design to succeed, carefully consider the problem AND the environment you're trying to solve it in!
Exporting template instantiations to DLL
aclysma posted a topic in General and Gameplay ProgrammingI have the following code: [code]template <class T> class __declspec(dllexport) MyTemplate1 { }; template <class T> class MyTemplate2 { }; template MyTemplate1<int>; template __declspec(dllexport) MyTemplate2<int>;[/code] In dependency walker, I can see that this exports the symbol "??4?MyTemplate1..." There is no export for MyTemplate2. In my case, I have multiple projects that can be built as a single monolithic .exe or into a small .exe with a collection of DLLs. I want multiple projects to be able to export different instantiations of the template. I have no need to "hide" the templates implementation code from downstream projects. I cannot use the syntax in MyTemplate1 because each project has its own define for __declspec(...) (i.e. RENDERER_API, FRAMEWORK_API, etc.). If I used the syntax of MyTemplate1, only one of the DLLs could ever export the template. I was really hoping the syntax I am using in MyTemplate2 would work, but this sample demonstrates that it does not. I understand that DLLs and templates do not play well together. I also understand that __declspec(...) needs to be a define, and that downstream projects will need to extern the template instantiation. In my actual project, I have done this. What I'm asking specifically is this: Is there a way to write MyTemplate2 such that it is declared once but can have different instantiations exported by different DLLs? Thanks in advance!
Implementing a pure virtual function by inheriting it from a base class
aclysma replied to aclysma's topic in General and Gameplay ProgrammingThank you both for your help! In particular, the explanation of *why* ClassA and ClassB don't implement InterfaceA::fn() or InterfaceB::fn(). I haven't finished what I'm working on, but I fully expect that making a "shared" interface is the right answer.
Implementing a pure virtual function by inheriting it from a base class
aclysma replied to aclysma's topic in General and Gameplay ProgrammingThanks for your suggestion alvaro. I think I stripped down my sample source too much, so here's a version that's a bit closer to what I'm actually doing: [code] struct InterfaceA { virtual void fn() = 0; virtual void fnA() = 0; }; struct InterfaceB { virtual void fn() = 0; virtual void fnB() = 0; }; class BaseClass { public: void fn() { } }; class ClassA : public BaseClass, public InterfaceA { void fnA() { } }; class ClassB : public BaseClass, public InterfaceB { void fnB() { } }; [/code] While your suggestion certainly works well for my original post, it does not work for this case. The above code will complain that ClassA and ClassB do not have an implementation for fn(). If I make the base class extend both interfaces, ClassA will complain about missing fnB() and ClassB will complain about missing fnA(). Using your idea, I did come up with this. While it's a bit weird, it does remove the need for the proxy functions, and it gives compile-time errors because the dummy functions in BaseClass are private. [code]struct InterfaceA { virtual void fn() = 0; virtual void fnA() = 0; }; struct InterfaceB { virtual void fn() = 0; virtual void fnB() = 0; }; class BaseClass : public InterfaceA, public InterfaceB { public: void fn() { } private: // Dummy methods that should always be extended.. we get compile errors // if we try to call them because they are private void fnA() { assert(0); } void fnB() { assert(0); } }; class ClassA : public BaseClass { public: void fnA() { } }; class ClassB : public BaseClass { public: void fnB() { } }; [/code] Far from elegant, and I'm not really sure that it's better than having proxy functions. I am still interested in: - Solutions that are not a hack like this one that uses visibility - An explanation as to why a compiler couldn't or shouldn't do what I expected with the very original code sample
Implementing a pure virtual function by inheriting it from a base class
aclysma posted a topic in General and Gameplay ProgrammingI'm writing a library that is exposed as a DLL, so I am using the standard pImpl method with exposed factory functions to create the Impl objects. I'd like for some of the common "Impl" functionality to be in a base class, and have those implementation satisfy the exposed interface. So, I have some code that's like this: [code]struct InterfaceA { virtual void fn() = 0; }; class ClassA { public: void fn() { } }; class ClassB : public ClassA, public InterfaceA { }; [/code] I expected that this would work, however, I get the following: [code]1>****(38) : error C2259: 'ClassB' : cannot instantiate abstract class 1> due to following members: 1> 'void InterfaceA::fn(void)' : is abstract 1> ****(19) : see declaration of 'InterfaceA::fn' [/code] I know that I could include something in class B like [code]void fn() { ClassA::fn(); }[/code] but at that point I might as well just use composition rather than inheritance. While in general I'm a huge fan of composition, I wanted to use inheritance so that the "ClassB" classes have only the unique code in them (would make the code pleasant to read.) Is there a way to make ClassB automatically use the method in ClassA to satisfy InterfaceA? My question is exactly the same as [url=""][/url], but I didn't see a real "solution" to my question of not having to add a proxy function. Also, if there is a good reason why this is not possible for a compiler to figure out, or why you wouldn't want this behavior, I'd love to know.
implementing an arbitrary size integer class
aclysma replied to _Sauce_'s topic in Math and Physics1) You don't need a big int class to solve the linked problem. There is a much, much easier way to do it. (Apologies if you already know that.) 2) To answer your more direct question, I would implement a software ALU. While I have not done it myself, you could consider keeping an array of 64-bit numbers. You'll have to do the carrying manually (i.e. add the low order pair of 64-bit numbers together.. if you detect an overflow manually add 1 to the next higher order 64-bit numbers. It may help to look up some very basic computer engineering stuff to see how an ALU works so that you can imitate it.. you'd use the hardware though to do 64 bits at a time.. certainly not bit-by-bit :) Detecting the overflow is easy.. C = A + B. If C < A, you overflowed. Addition is the easy operation though. I'd suggest taking a look at how Melekor's linked code works. 3) Wikipedia has a page specifically about how to find square roots, but using Newton's Method is just dead simple. Your equation would be 0 = x^2 - Y where x is your answer and Y is the number you're taking the square root of. I'm sure an algorithm at is much faster though (particularly the one using digit by digit work on binary numbers.) BTW, don't try to think in base 10. Think in base 2 or 16. A + 9 = 14. That's an overflow to the next digit (the 1) and you have 4 left for the ones column. The next column is the 16s column, the next is the 256s column, etc. F00 is 15*16*16 + 0*16 + 0*1 = 3840
- Quote:Original post by Hodgman From what I remember, type_info's name function will return different strings depending on the compiler that was used, *but* it's == operator always works. Quote:I understand that if I use typeid(T) on two different types that live in different DLLs, I can get matching type_info pointers when the types are not the same. Even if this is true (which I don't think it is), you shouldn't be comparing the pointer values anyway! You should be comparing the actual type_info objects themselves (using their overloaded == operator). Good point on the ==s. I need to go double-check that that's how I'm testing for equality. I decided to go back and re-read what I had found that led me to my conclusion about type_info non-uniqueness across DLLs: The comment by dmail at the end concerns me. The page he linked makes it seem that boost python developers decided that string comparisons of the name are safer than the == comparison on GCC and a couple other platforms (not MSVC though). I am wondering if I'm going to have to adopt a similar strategy, and that's what got me to thinking there might be some other nasty traps I don't know about. But of course, if this is not true, (which would explain why SiCrane made no mention of it in that post, and why I could not find any additional information about this) then I would be very pleased. :) Thanks!
- I am not interested in turning this into a performance/pros/cons thread, as I said first thing. For clarity, by DLL I mean whatever dynamic linking mechanism that happens to be on the target OS. I would like to support msvc, gcc, and try to be standard enough that any other modern compiler should be expected to work fine. From my understanding, .so files on linux have the same sorts of issues. And btw, I'm sure almost any implementation of dynamic linking is going to have some quirks, simply because the dynamically linked code at compile time has no way to guarantee uniqueness between modules. What I'm looking for here is to find out about as many gotchas up front as possible, and to confirm that what I *think* is right, is correct, before I get too invested into my own ignorance. :)
[C++] Dll Issue
aclysma replied to force_of_will's topic in General and Gameplay ProgrammingI have never messed much with DLLs but it sounds like something is out of sync - have you tried doing a full rebuild? If you swap the two functions like that of identical prototypes, it would not surprise me if now the functions had swapped memory addresses.
Speed up Compile Times
aclysma replied to RealMarkP's topic in General and Gameplay ProgrammingNot to derail but.. /MP cannot be used at the same time as /Gm (enable incremental build). In which cases is one better than the other? As for release mode, Gm was already turned off for me, but I don't notice a difference in debug mode.. I post numbers when I try them both. EDIT: Dropped my 3.5 min compile time to 2.5 min - so MP is an improvement but still not sure if it is faster than incremental builds). [Edited by - aclysma on May 15, 2008 1:51:21 PM] | https://www.gamedev.net/profile/120960-aclysma/?tab=blog | CC-MAIN-2018-05 | refinedweb | 3,429 | 60.35 |
Create Interface For Your Machine Learning Models Using Gradio Python Library
Introduction
Making Machine Learning models these days is turning out to be progressively simple because of many open-source and exclusive based administrations (for example Python, R, SAS). Even though professionals may consistently think that it’s hard to effectively make interfaces to test and share their finished model with associates or partners.
One potential answer for this issue is Gradio, a free open-source Python bundle that assists you with making model UIs which you can easily impart to connect to associates and companions.
What is Gradio?
Gradio is an open-source python library that permits you to rapidly make simple to utilize, adjustable UI parts for your ML model, any API, or any subjective capacity in only a couple of lines of code. It makes it easier to play with your models in your web browser by just drooping and dragging your images, text, or recording of your own voice, etc, and seeing live the output in an interactive way. You can coordinate the GUI straightforwardly into your Python notebook, or you can share the link with anybody.
Gradio helps in building an online GUI in a couple of lines of code which is convenient for showing exhibitions of the model presentation. It is quick, simple to set up, and prepared to utilize, and shareable as the public connection which anybody can get to distantly and parallelly run the model in your machine. Gradio works with a wide range of media-text, pictures, video, and sound. Aside from ML models, it very well may be utilized as should be expected python code embeddings.
Uses of Gradio:
- You can create demos of your machine learning codes that could be useful for your clients/ users/ team members.
- During development, you can interactively debug your models.
- You can get feedback on model performance from users. As a result, you can improve your model easily and faster.
It can be integrated with TensorFlow and PyTorch models for better understanding. In this article, we will examine Gradio with its execution. So let’s get started.
Installation
You can install Gradio via pip. Below code can be used for installation:
pip install gradio
Import the library
The below code can be used for importing the library:
import gradio as gr
Getting started
To quickly give you an idea of how this library works, let’s run the below code as a python script or you can use Python Notebook (Google colab as well):
import gradio as gr def start(name): return "Hello " + name + " ! "
face = gr.Interface(fn=start, inputs="text", outputs="text") face.launch()
As soon as you run the above code, the below interface will automatically get appears in Python Notebook, or pop in your browser on if you run the python script.
The Interface
Gradio can wrap practically any Python work with a simple-to-utilize interface. That capacity could be anything from a straightforward assessment adding a machine to a pre-trained model. The interface class has three parameters. These are described below:
- inputs: input component type
- outputs: output component type and
- fn: function to wrap
By using these three arguments, we can easily create interfaces for your model and launch them in the browser or Python Notebook.
Customizable Components
We can create customized components according to our requirements. For example, if we want to see large text and some text hint, then we can pass different parameters in the inputs parameter of the Interface class. Gradio offers a large number of customizations. Check the below code:
import gradio as gr def start(name): return "Hello " + name + " ! " face = gr.Interface( fn=start,inputs=gr.inputs.Textbox(lines=2, placeholder="Name Here… "), outputs="text") face.launch()
Examples of Customizations are shown below:

Slider:
For more information on customizations, check this Link
Multiple Inputs And Outputs
Suppose we had a considerably more complex function, with numerous information sources and yields. In the model underneath, we have a capacity that takes a string, boolean, and number, and returns a string and number. Investigate how we pass a rundown of info and yield segments. Check
the below code:
import gradio as gr def start(name, morning_is, temp): msg = "Good morning" if morning_is else "Good evening" greeting = "%s %s. It is %s degrees today" % (msg, name, temp) cels = (temp - 32) * 5 / 9 return greeting, round(cels, 2)
face = gr.Interface(fn=start, inputs=["text", "checkbox", gr.inputs.Slider(0, 100)], outputs=["text", "number"]) face.launch()
Output:
Working With Images
Now let’s work with images. The Image input Interface takes a NumPy array of some specified size, having a shape (width, height, 3), here the last dimension represents the RGB values. It will return an image in the form of a NumPy array. Moreover, the Input interface comes up with an EDIT button which opens a tool that is being used for cropping, rotating, flipping, and applying filters to an image. Isn’t it fabulous, right? We’ve discovered that controlling pictures in this manner will frequently uncover covered-up imperfections in a model. The below image shows how this tool works:
Working With Machine Learning
After you’re comfortable with the rudiments of the Gradio library, you’ll likely need to give it a shot like a machine learning model. We should see Gradio working with a couple of machine learning models.
Image Classification using TensorFlow
First, in machine learning exemplary, we are starting with image classification. We are starting with the Inception Net Image Classifier, which is loaded with the help of TensorFlow. We know, then this is an image classification problem, we are using the Image input interface. This Image input interface gives you a nice test Inception Net interface where you can drag and drop images and also allows us to use edit images by clicking on the EDIT button. The output would be a dictionary of labels and their corresponding confidence scores. Check the below image:
Image Classification using PyTorch
Let’s now use a similar model, ResNet but we are using PyTorch this time. Check the below image:
Text Generation with Transformers (GPT-2)
Now let’s work with some text. We are using a text generation model called GPT-2. And in this case, we are using Text Text Interface. You have to just write some input and it will automatically show output in the Output box. Check the below image:
Some More Examples:
Answering Questions With BERT-QA
Titanic Survival Model
Image classification with Interpretation
For more information, check official documentation: Link
Final Note
You can check my articles here: Articles
Thanks for reading this article and for your patience. Do let me in the comment section about feedback. Share this article, it will give me the motivation to write more blogs for the data science community.
Follow me on LinkedIn: LinkedIn
The media shown in this article are not owned by Analytics Vidhya and is used at the Author’s discretion.
Leave a Reply Your email address will not be published. Required fields are marked * | https://www.analyticsvidhya.com/blog/2021/04/create-interface-for-your-machine-learning-models-using-gradio-python-library/ | CC-MAIN-2022-21 | refinedweb | 1,179 | 53 |
Instructive and Persuasive Examples
I recently read No excuses, write unit tests, which argues Unit Tests are Good and You Should Write Them. For the most part I strongly agree with their message, which is why I feel kinda bad criticizing the essay. They provide this as “an example of simple testing”:
const add = (...numbers) => { return numbers.reduce((acc, val) => { return acc + val; }, 0); }; it('should add numbers', () => { const expected = 15; const actual = add(1, 2, 3, 4, 5); expect(actual).to.equal(expected); // true });
This is a bad example. More specifically, it’s inappropriate. By reading it I get a sense of what a unit test is. If the article was titled “What is unit testing?”, it’d be just fine.
But it’s not called “What is unit testing?” It’s called “No excuses, write unit tests.” The target audience isn’t people who haven’t heard of testing before. It’s people who know about unit testing but aren’t convinced it’s worth doing. The example needs to show the benefits of having a unit test, not just what it is. And this example doesn’t do that. For one, it’s pretty obvious that
add is correct; why should I bother to write test code if I can tell it’s right by just looking at it? For another, the test code is longer than the entire function, so it’s a big investment for no clear benefit. Etc etc etc.
The issue is that
add is an instructive example, when what we want is a persuasive example. Instructive examples show you what and how, while persuasive examples show you why and why not. Without making that distinction clear, it’s easy to accidentally write the former when you really need the latter.
It is also a lot harder to write a good persuasive example.
- If your example is too simple, people brush it off.
- If your example is too complicated, people won’t follow. They’re also less likely to trust it, because you complicated example might be concealing a simpler way.
- If your example is too abstract, people won’t see how it’s useful in practice.
- If your example is too concrete, people won’t see how it generalizes to their own problems.
So a good persuasive example has to be simple without being trivial, complex without being convoluted, and just the right balance between general and specific. On the other hand, instructive examples just need to be understandable.
I don’t blame the article for using the wrong ‘kind’ of example. Let’s try to find a better one.
Finding an example
Unit tests catch bugs. We want an example function that looks easy to implement but has a bug in it. Show how the unit test catches the bug. Then, either show how unit tests catch edge cases or they catch regressions, both things that mean bugs in your code.
When I think “simple but finicky” I immediately jump to string processing. This is also good because everybody’s dealt with string processing before, and everybody’s gotten burnt by it. Let’s try a string processing problem then:
You have a list of citations in MLA format. Write a function that takes the list of citations and two authors and returns if they have ever been coauthors.
To keep this example lean, we’ll make two assumptions: first, that there are at most two authors per cite (no et. al), and that when testing authors, we always submit them in “Lastname, Firstname” format.1
def are_coauthors(citations, author1, author2) -> bool: ... citations = ["Ayers, Alice and Bob Barker. Title1", "Chen, Carol and Alice Ayers. Title2", "Barker, Bob and Don Diez. Title3"] are_coauthors(citations, "Ayers, Alice", "Barker, Bob") == True are_coauthors(citations, "Ayers, Alice", "Diez, Don") == False
As you can probably tell, the main challenge (or at least the obvious one) is that the second author of a citation is in “Firstname Lastname” format, not “Lastname, Firstname”. Let’s write a couple of unit tests.
def test_are_coauthors(): assert are_coauthors(citations, "Ayers, Alice", "Barker, Bob") def test_are_not_coauthors(): assert not are_coauthors(citations, "Ayers, Alice", "Diez, Don")
And then a simple function that passes both tests:
def are_coauthors(citations, author1, author2): author2_names = author2.split(", ") author2 = f"{author2_names[1]} {author2_names[0]}" for cite in citations: if author1 in cite and author2 in cite: return True return False
This looks mostly correct, but we can add a new test case that will fail:
def test_are_coauthors_flip(): assert are_coauthors(citations, "Barker, Bob", "Ayers, Alice")
That’s because
are_coauthors isn’t commutative! We can fix that by redefining authors:
def are_coauthors(citations, author1, author2): def first_last(author): names = author.split(", ") return f"{names[1]} {names[0]}" for cite in citations: if author1 in cite and first_last(author2) in cite: return True if author2 in cite and first_last(author1) in cite: return True return False
Another finicky edge case we missed is if there’s a name in the title. This will fail:
def test_ignores_title(): assert not are_coauthors(["Ayers, Alice and Bob Barker. Life of Don Diez"], "Ayers, Alice", "Diez, Don")
We could fix that too, but would that potentially regress something else? What about books with only one author? Etc etc etc. After a while, there are too many edge cases to track, and you can no longer be confident about the correctness of your program by just looking at it. I’d argue this example is more ‘persuasive’ than ‘adding numbers’.
One downside is this took me a while to think up. Writing persuasive examples is hard. I think it’s worth it, though, because it leads to a stronger article.
Thanks to Alex Koppel and Noah Tye for their feedback. | https://hillelwayne.com/post/persuasive-examples/ | CC-MAIN-2018-17 | refinedweb | 951 | 65.32 |
Hello,
We recently enabled DFS Replication and I had a question. We've got it configured to only replicate after hours. If a change is made to a file outside of the replication schedule will users see two different files through the same DFS namespace?
May 22, 2014 at 5:41 UTC
This has good info on the file conflict process
8 Replies
May 22, 2014 at 5:40 UTC
If it's only going to replicate afterhours then you should ensure that only a single folder target has the referral status enabled to ensure that only one location/server is handling user changes.
No, users will see a single file.
Why limit replication to afterhours? Is it across a WAN (pretty sure you say this in another post, but I can't recall)
May 22, 2014 at 5:41 UTC
This has good info on the file conflict process
May 22, 2014 at 5:42 UTC
as does this:
"DFS Replication uses a conflict resolution heuristic of last writer wins for files that are in conflict"
May 22, 2014 at 5:43 UTC
We've got it replicating afterhours because we're doing initial replications and they're large and we don't want to hammer the machine. We had to go live with one of the shares because one of the servers dropped this morning and I was wondering if we needed to change the schedule or if we were good for another day or so.
May 22, 2014 at 5:48 UTC
You can limit the bandwidth the replication uses.
May 22, 2014 at 6:09 UTC
You can limit the bandwidth the replication uses.
Exactly, I would just limit bandwidth, and then ensure that only one of the target folders has referrals enabled to it.
If User1 modifies on target1 (and they have no control over where they hit, only you do via referrals being enabled or disabled) and User2 modifies on target2, then you'll have a conflict when replication kicks in and last write will win moving the "loser" version of the file to a hidden location.
Ensuring all users are hitting a single referral target is much safer during initial replication or when limiting replication times to only afterhours.
May 22, 2014 at 6:10 UTC
I managed to drag my boss out of a meeting and we went ahead and expanded the replication schedule to cover all hours. Thank ya'll very much for the information!
May 22, 2014 at 6:13 UTC
Glad it helped
Also keep in mind the "highwater" mark or staging quote. This will likely get hit more often during initial replication. Any "loser" versions of files in conflict could be lost if it hits the highwater mark frequently. A single referral enabled would help reduce the possibility of this.
This discussion has been inactive for over a year.
You may get a better answer to your question by starting a new discussion. | https://community.spiceworks.com/topic/501041-dfs-replication | CC-MAIN-2017-51 | refinedweb | 495 | 65.35 |
This document describes Emacsy version 0.4.1.26-89e9-dirty, An embeddable Emacs-like library using GNU Guile.
Next: Introduction, Previous: Top, Up: Top [Contents][Index]
This project is an experiment, actually two experiments. Firstly, it’s an experiment to see whether there’s any interest and utility in an embeddable Emacs-like environment. Secondly, I’d like to see how literate programming fares in comparison to the conventional approach. Let me elaborate a little on each.
Emacs is the extensible programmer’s text editor. For decades, it’s gobbled up functionality that sometimes seems far removed from text editing. I will expand upon why I believe this is the case and what particular functionality I hope to replicate later. I’d like to discuss a little about why I’m bothering to start with Emacs rather than just writing something entirely new. Emacs has fostered a community of people that are comfortable using, customising, and extending Emacs while its running. The last part is most important in my mind. Extending Emacs is a natural part of its use; it’s a tinkerer’s dream toy. And I want to grease the rails for people who already get what kind of tool I’m trying to provide. Had I chosen another perfectly competent language like Lua instead of a Lisp, that would erect a barrier to that track. Were I to write a completely different API, that’s yet another barrier. Were I to “modernize” the terminology used by Emacs, e.g., say “key shortcut” instead of “key binding”, or “window” instead of “frame”, that’s a barrier to drawing the community of people that already get it to try this out.
Let me say a little about why I’m choosing to do this as a literate program1. I’ve written a lot of code, none of which was written literately. Recently I had an experience that made me want to try something different. I began a group project. There wasn’t that much code. Yet not too far into the project, it had become opaque to one of the original contributors. This was a small codebase with someone who was there from the start, and already we were having problems. Maybe the code was bad. Maybe we were bad programmers (Eek!). Whatever the case, assuming there’s no simple fix for opaque code, it is something that can be addressed. Better communication about the code may help. So I would like to invest a good faith effort in attempting to write this program in a literate fashion.
A few notes on my personal goals for this document and the code. The writing style I’m leaving as informal for purposes of expediency and lowering the barrier of contribution. Also for expediency, my initial interest is in fleshing out the functionality. I’m not concerned about optimality of the implementation yet. Only in cases where the design cannot be reimplemented to be more efficient would I be concerned. If we can make a useable system, optimization will follow and hopefully be informed by profiling.
There’s a ton of work left to do! Please feel free to contribute to the effort.
Next: The Garden, Previous: Preface, Up: Top [Contents][Index].
Up: Introduction [Contents][Index]
Emacs has been extended to do much more than text editing. It can get your email, run a chat client, do video editing2, and more. For some the prospect of chatting from within one’s text editor sounds weird. Why would anyone want to do that? Because Emacs gives them so much control. Frustrated by a particular piece of functionality? Disable it. Unhappy with some unintuitive key binding? Change it. Unimpressed by built-in functionality? \verb|M-x| in other applications to run commands. I would like to see authors introduce a new version: “Version 3.0, now extendable with Emacsy.” I would like hear power users ask, “Yes, but is it Emacsy?”
Next: Overlooked Treasure, Up: Vision [Contents][Index].
Next: Emacsy, Previous: Motivation, Up: Vision [Contents][Index]
Emacs has a powerful means of programmatically extending itself while it is running. Not many successful applications can boast of that, but I believe a powerful idea within Emacs has been overlooked as an Emacsism rather than an idea of general utility. Let me mention another idea that might have become a Lispism but has since seen widespread adoption.
The Lisp programming language introduced the term Read-Eval-Print-Loop (REPL, pronounced rep-pel), an interactive programming feature present in many dynamic languages: Python, Ruby, MATLAB, Mathematica, Lua to name a few. The pseudo code is given below.
<<Lisp REPL>>= (while #t (print (eval (read)))) The REPL interaction pattern is to enter one complete expression, hit the return key, and the result of that expression will be displayed. It might look like this:
> (+ 1 2) 3
The kernel of Emacs is conceptually similar to the REPL, but the level of interaction is more fine grained. A REPL assumes a command line interface. Emacs assumes a keyboard interface. I have not seen the kernel of Emacs exhibited in any other applications, but I think it is of similar utility to the REPL—and entirely separate from text editing. I’d like to name this the Key-Lookup-Execute-Command-Loop (KLECL, pronounced clec-cull).
Next: Goals, Previous: Overlooked Treasure, Up: Vision [Contents][Index].
> (read-key) #\a > (lookup-key #\a) self-insert-command > (execute-command 'self-insert-command) #t.
Next: Anti-goals, Previous: Emacsy, Up: Vision [Contents][Index]
The goals of this project are as follows.
Emacsy will use Guile Scheme to make it easy to embed within C and C++ programs.
Emacsy should be easy enough to learn that the uninitiated may easily make parametric changes, e.g., key ’a’ now does what key ’b’ does and vice versa. Programmers in any language ought to be able to make new commands for themselves. And old Emacs hands should be able to happily rely on old idioms and function names to change most anything.
Emacsy should be configured with a sensible set of defaults (opinions). Out of the box, it is not tabla rasa, a blank slate, where the user must choose every detail, every time. However, if the user wants to choose every detail, they can.
It wouldn’t be Emacs-like if you couldn’t tinker with it.
New commands can be defined in Guile Scheme or C/C++.
That is to say, commands can call other commands. No special arrangements must be considered in the general case.
The core functions that must be called by the embedding application will be few and straightforward to use.
Next: Emacsy Features, Previous: Goals, Up: Vision [Contents][Index]
Just as important as a project’s goals are its anti-goals: the things it is not intended to do.
Emacsy will not do general purpose text editing out of the box, although it will have a minibuffer.
Emacs is full featured programmer’s text editor with more bells and whistles than most people will ever have the time to fully explore. Emacsy extracts the Emacs spirit of application and UI extensibility to use within other programs.
There have been many attempts to replace Emacs and elisp with an newer Lisp dialect. Emacsy is not one of them.
Although Emacsy may adopt some of naming conventions of Emacs, it will not use elisp and will not attempt to be in any way source code compatible with Emacs.
I will not steal your runloop. You call Emacsy when it suits your application not the other way around.
Previous: Anti-goals, Up: Vision [Contents][Index]
These are the core features from Emacs that will be implemented in Emacsy.
Next: Installation, Previous: Introduction, Up: Top [Contents][Index]
Now for a little entertainment.
Next: Hello Emacsy, Previous: The Garden, Up: Top [Contents][Index]
Emacsy is available for download from its website at. This section describes the software requirements of Emacsy, as well as how to install it and get ready to use it.
Next: Running the Test Suites, Up: Installation [Contents][Index]
This section lists requirements when building Emacsy from source. The build procedure for Emacsy is the same as for GNU software, and is not covered here. Please see the files README and INSTALL in the Emacsy source tree for additional details.
Emacsy depends on the following packages:
The following dependencies are optional:
Previous: Requirements, Up: Installation [Contents][Index]
After a successful
configure and
make run, it is a good
idea to run the test suites.
make check
Next: Api, Previous: Installation, Up: Top [Contents][Index]
I have received a lot of questions asking, what does Emacsy3 actually do? What restrictions does it impose on the GUI toolkit? How is it possible to not use any Emacs code? I thought it might be best if I were to provide a minimal example program, so that people can see code that illustrates Emacsy API usage.
Next: The Simplest Application Ever, Up: Hello Emacsy [Contents][Index]
Here are a few function prototypes defined in emacsy.h, see C Api for the full list.
Initialize Emacsy.
Enqueue a keyboard event.
Run an iteration of Emacsy’s event loop, does not block.
Return the mode line.
Terminate Emacsy; run termination hook.
Next: Conclusion, Previous: Embedder's API, Up: Hello Emacsy [Contents][Index]
Let’s exercise these functions in a minimal FreeGLUT program we’ll call hello-emacsy.4. This simple program will display an integer, the variable counter, that one can increment or decrement.
Hello Emacsy’s state is captured by one global variable. Hello Emacsy will display this number.
Initialize everything in main and enter our runloop.
Initialize GLUT.
Initialize Guile.
Initialize Emacsy.
Register primitives.
Try to load hello-emacsy.scm
Enter GLUT main loop, not return.
Let’s look at how Emacsy interacts with your application’s runloop since that’s probably the most concerning part of embedding. First, let’s pass some input to Emacsy.
Send key events to Emacsy.
int key; // The Key event (not processed yet).
The keys C-a and C-b return
1 and
2
respectively. We want to map these to their actual character values.
The function display_func is run for every frame that’s drawn. It’s effectively our runloop, even though the actual runloop is in FreeGLUT.
Our application has just one job: Display the counter variable.
Setup the display buffer the drawing.
Process events in Emacsy.
Display Emacsy message/echo area.
Display Emacsy mode line.
Draw a string function. Draws a string at (x, y) on the screen.
At this point, our application can process key events, accept input on the minibuffer, and use nearly all of the facilities that Emacsy offers, but it can’t change any application state, which makes it not very interesting yet.
Let’s define a new primitive Scheme procedure get-counter, so
Emacsy can access the application’s state. This will define
a C function
SCM scm_get_counter (void) and a Scheme procedure
(get-counter).
Let’s define another primitive Scheme procedure to alter the application’s state.
Once we have written these primitive procedures, we need to register them with the Scheme runtime.
Locate the hello-emacsy.scm Guile initialization and load it.
We generate the file example/hello-emacsy.c.x by running the
command:
guile-snarf example/hello-emacsy.c. Emacsy can now
access and alter the application’s internal state.
Bind inc-counter to
=.
Bind inc-counter to
-.
Let’s implement another command that will ask the user for a number to set the counter to.
Now we can hit M-x change-counter and we’ll be prompted for the new value we want. There we have it. We have made the simplest application ever more Emacs-y.
We can add commands easily by changing and reloading the file. But we can do better. Let’s start a REPL we can connect to. example/hello-emacsy.scm.
(use-modules (system repl server)) (spawn-server)
Start a server on port 37146.
Next: Plaintext Please, Previous: The Simplest Application Ever, Up: Hello Emacsy [Contents][Index]
We implemented a simple interactive application that displays a number. We embedded Emacsy into it: sending events to Emacsy and displaying the minibuffer. We implemented primitive procedures so Emacsy could access and manipulate the application’s state. We extended the user interface to accept new commands + and - to change the state.
Now we can telnet localhost 37146 to get a REPL.
Previous: Conclusion, Up: Hello Emacsy [Contents][Index]
/* <>. */ /* * Let's exercise these functions in a minimal FreeGLUT program we'll call * @verb{|hello-emacsy|}.@footnote{Note: Emacsy does not rely on FreeGLUT. * One could use Gtk+, Ncurses, Qt, or whatever}. This simple program * will display an integer, the variable @var{counter}, that one can * increment or decrement. * * @image{images/minimal-emacsy-example,,,,.png} */ #ifndef SCM_MAGIC_SNARFER #include <libgen.h> #ifdef __APPLE__ #include <GLUT/glut.h> #else #include <GL/glut.h> #endif #include <emacsy.h> #include <stdio.h> #include <string.h> #include <unistd.h> #endif #include <libguile.h> void display_func (); void keyboard_func (unsigned char glut_key, int x, int y); void draw_string (int, int, char*); char * try_load_startup (char const* prefix, char const* dir, char const* startup_script); void primitives_init (); /* * @defvar int counter = 0; * Hello Emacsy's state is captured by one global variable. * Hello Emacsy will display this number. * @end defvar */ int counter = 0; int interactive = 1; /* * Initialize everything in @var{main} and enter our runloop. */ int main (int argc, char *argv[]) { int err; /* glutInit (&argc, argv); * Initialize GLUT. */ glutInit (&argc, argv); glutInitDisplayMode (GLUT_RGB|GLUT_DOUBLE); glutInitWindowSize (500, 500); glutCreateWindow ("Hello, Emacsy!"); glutDisplayFunc (display_func); if (interactive) glutKeyboardFunc (keyboard_func); /* void scm_init_guile (); * Initialize Guile. */ scm_init_guile (); /* emacsy_initialize (@dots {}); * Initialize Emacsy. */ if (argc == 2 && strcmp ("--batch", argv[1]) == 0) interactive = 0; err = emacsy_initialize (interactive ? EMACSY_INTERACTIVE : EMACSY_NON_INTERACTIVE); if (err) exit (err); /* primitives_init (); * Register primitives. */ primitives_init (); /* char * try_load_startup (@dots{}); * Try to load @file{hello-emacsy.scm} */ char const *startup_script = "hello-emacsy.scm"; char prefix[PATH_MAX]; strcpy (prefix, argv[0]); if (getenv ("_")) strcpy (prefix, getenv ("_")); dirname (dirname (prefix)); if (!try_load_startup (0, 0, startup_script) &&!try_load_startup (getenv ("EMACSY_SYSCONFDIR"), "/", startup_script) &&!try_load_startup (prefix, "/", startup_script) &&!try_load_startup (prefix, "/etc/emacsy/", startup_script)) fprintf (stderr, "error: failed to find '%s'.\n", startup_script); /* void glutMainLoop (); * Enter GLUT main loop, not return. */ glutMainLoop (); return 0; } /* * @subsection Runloop Interaction * * Let's look at how Emacsy interacts with your application's runloop * since that's probably the most concerning part of embedding. First, * let's pass some input to Emacsy. */ /* void keyboard_func (unsigned char glut_key, int x, int y) * Send key events to Emacsy. */ void keyboard_func (unsigned char glut_key, int x, int y) { /* * int key; // The Key event (not processed yet). */ int key; int mod_flags; int glut_mod_flags = glutGetModifiers (); mod_flags = 0; if (glut_mod_flags & GLUT_ACTIVE_SHIFT) mod_flags |= EMACSY_MODKEY_SHIFT; if (glut_mod_flags & GLUT_ACTIVE_CTRL) mod_flags |= EMACSY_MODKEY_CONTROL; if (glut_mod_flags & GLUT_ACTIVE_ALT) mod_flags |= EMACSY_MODKEY_META; if (glut_key == 8) glut_key = 127; else if (glut_key == 127) { glut_key = 4; mod_flags += EMACSY_MODKEY_CONTROL; } /* * The keys @verb{|C-a|} and @verb{|C-b|} return @code{1} and @code{2} * respectively. We want to map these to their actual character values. */ key = mod_flags & EMACSY_MODKEY_CONTROL ? glut_key + ('a' - 1) : glut_key; emacsy_key_event (key, mod_flags); glutPostRedisplay (); } /* void display_func () * The function @var{display_func} is run for every frame that's * drawn. It's effectively our runloop, even though the actual runloop is * in FreeGLUT. * * Our application has just one job: Display the counter variable. */ void display_func () { /* glClear (GL_COLOR_BUFFER_BIT); * Setup the display buffer the drawing. */ glClear (GL_COLOR_BUFFER_BIT); glMatrixMode (GL_PROJECTION); glLoadIdentity (); glOrtho (0.0, 500.0, 0.0, 500.0, -2.0, 500.0); gluLookAt (0, 0, 2, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0); glMatrixMode (GL_MODELVIEW); glColor3f (1, 1, 1); char counter_string[255]; sprintf (counter_string, "%d", counter); draw_string (250, 250, counter_string); /* * Process events in Emacsy. */ if (emacsy_tick () & EMACSY_QUIT_APPLICATION_P) { emacsy_terminate (); exit (0); } glutSetWindowTitle (emacsy_current_buffer ()); /* * Display Emacsy message/echo area. */ draw_string (0, 5, emacsy_message_or_echo_area ()); /* * Display Emacsy mode line. */ draw_string (0, 30, emacsy_mode_line ()); glutSwapBuffers (); } /* void draw_string (int x, int y, char *string) * * Draw a string function. * Draws a string at (x, y) on the screen. */ void draw_string (int x, int y, char *string) { glLoadIdentity (); glTranslatef (x, y, 0.); glScalef (0.2, 0.2, 1.0); while (*string) glutStrokeCharacter (GLUT_STROKE_ROMAN, *string++); } /* * At this point, our application can process key events, accept input on * the minibuffer, and use nearly all of the facilities that Emacsy * offers, but it can't change any application state, which makes it not * very interesting yet. */ /* * @subsection Plugging Into Your App */ // /* * @deffn {Scheme Procedure} get-counter * @deffnx {C Function} SCM scm_get_counter () * Let's define a new primitive Scheme procedure @var{get-counter}, so * Emacsy can access the application's state. This will define * a @var{C} function @code{SCM scm_get_counter (void)} and a Scheme procedure * @code{(get-counter)}. * * @end deffn */ SCM_DEFINE (scm_get_counter, "get-counter", /* required arg count */ 0, /* optional arg count */ 0, /* variable length args? */ 0, (), "Returns value of counter.") { return scm_from_int (counter); } /* * @deffn {Scheme Procedure} set-counter! value * @deffnx {C Function} SCM scm_set_counter_x (SCM value) * Let's define another primitive Scheme procedure to alter the * application's state. * @end deffn */ SCM_DEFINE (scm_set_counter_x, "set-counter!", /* required, optional, var. length? */ 1, 0, 0, (SCM value), "Sets value of counter.") { counter = scm_to_int (value); glutPostRedisplay (); return SCM_UNSPECIFIED; } /* void primitives_init () * Once we have written these primitive procedures, we need to register * them with the Scheme runtime. */ void primitives_init () { #ifndef SCM_MAGIC_SNARFER #include "hello-emacsy.c.x" #endif } /* char * try_load_startup (char const* prefix, char const* dir, char const* startup_script) * Locate the @file{hello-emacsy.scm} Guile initialization and load it. */ char * try_load_startup (char const* prefix, char const* dir, char const* startup_script) { static char file_name[PATH_MAX]; if (prefix) strcpy (file_name, prefix); if (dir) strcat (file_name, dir); strcat (file_name, startup_script); if (access (file_name, R_OK) != -1) { fprintf (stderr, "Loading '%s'.\n", file_name); scm_c_primitive_load (file_name); return file_name; } else fprintf (stderr, "no such file '%s'.\n", file_name); return 0; }
;;; Emacsy --- An embeddable Emacs-like library using GNU Guile ;;; ;;; Copyright (C) 2012, 2013 Shane Celis <shane.celis@gmail.com> ;;; ;;; <>. ;; We generate the file @file{example/hello-emacsy.c.x} by running the ;; command: @code{guile-snarf example/hello-emacsy.c}. Emacsy can now ;; access and alter the application's internal state. ;;. ;; @subsection Changing the UI Now let's use these new procedures to ;; create interactive commands and bind them to keys by changing our ;; config file @file{example/hello-emacsy.scm}. (use-modules (emacsy emacsy)) ;;. (define-interactive (incr-counter #:optional (n (universal-argument-pop!))) "Increment the counter." (set-counter! (+ (get-counter) n))) ;;. (define-interactive (decr-counter #:optional (n (universal-argument-pop!))) "Decrement the counter." (set-counter! (- (get-counter) n))) ;; Bind @var{inc-counter} to @code{=}. (define-key global-map "=" 'incr-counter) ;; Bind @var{inc-counter} to @code{-}. (define-key global-map "-" 'decr-counter) ;; We can now hit @verb{|-|} and @verb{|=|} to decrement and increment the ;; @var{counter}. This is fine, but what else can we do with it? We could ;; make a macro that increments 5 times by hitting ;; @verb{|C-x ( = = = = = C-x )|}, then hit @verb{|C-e|} to run that macro. ;; (set! debug-on-error? #t) ;; Let's implement another command that will ask the user for a number to ;; set the counter to. ;;. ;; Now we can hit @verb{|M-x change-counter|} and we'll be prompted for ;; the new value we want. There we have it. We have made the simplest ;; application ever more @emph{Emacs-y}. (define-interactive (change-counter) "Change the counter to a new value." (set-counter! (string->number (read-from-minibuffer "New counter value: ")))) ;; @subsection Changing it at Runtime ;; ;; We can add commands easily by changing and reloading the file. But ;; we can do better. Let's start a REPL we can connect to. ;; @file{example/hello-emacsy.scm}. ;;. ;; @example ;; (use-modules (system repl server)) ;; (spawn-server) ;; @end example ;; Start a server on port 37146. ;;. ;; Start a server on port 37146. (use-modules (system repl server)) (spawn-server)
/* <>. */ #ifndef __EMACSY_H #define __EMACSY_H 1 #ifdef __cplusplus extern "C" { #endif #include <libguile.h> /* Here are the constants for the C API. */ /* */ /* */ /* <emacsy-c-api:Defines>= */ #define EMACSY_MODKEY_COUNT 6 #define EMACSY_MODKEY_ALT 1 // A #define EMACSY_MODKEY_CONTROL 2 // C #define EMACSY_MODKEY_HYPER 4 // H #define EMACSY_MODKEY_META 8 // M #define EMACSY_MODKEY_SUPER 16 // s #define EMACSY_MODKEY_SHIFT 32 // S #define EMACSY_MOUSE_BUTTON_DOWN 0 #define EMACSY_MOUSE_BUTTON_UP 1 #define EMACSY_MOUSE_MOTION 2 #define EMACSY_INTERACTIVE 1 #define EMACSY_NON_INTERACTIVE 0 /* Here are the return flags that may be returned by \verb|emacsy_tick|. */ /* */ /* */ /* <emacsy-c-api:Defines>= */ #define EMACSY_QUIT_APPLICATION_P 1 #define EMACSY_ECHO_AREA_UPDATED_P 2 #define EMACSY_MODELINE_UPDATED_P 4 #define EMACSY_RAN_UNDEFINED_COMMAND_P 8 /* * Emacsy provides a C API to ease integration with C and C++ * programs. The C API is given below. */ /* Initialize Emacsy. */ int emacsy_initialize (int init_flags); /* Enqueue a keyboard event. */ void emacsy_key_event (int char_code, int modifier_key_flags); /* Enqueue a mouse event. */ void emacsy_mouse_event (int x, int y, int state, int button, int modifier_key_flags); /* Run an iteration of Emacsy's event loop, does not block. */ int emacsy_tick (); /* Return the message or echo area. */ char *emacsy_message_or_echo_area (); /* Return the mode line. */ char *emacsy_mode_line (); /* Return the name of the current buffer. */ char *emacsy_current_buffer (); /* Run a hook. */ int emacsy_run_hook_0 (char const *hook_name); /* Return the minibuffer point. */ int emacsy_minibuffer_point (); /* Terminate Emacsy; run termination hook. */ int emacsy_terminate (); /* Attempt to load a module. */ int emacsy_load_module (char const *module_name); /* Load a file in the emacsy environment. */ //int emacsy_load(const char *file_name); /* Convert the modifier_key_flags into a Scheme list of symbols. */ SCM modifier_key_flags_to_list(int modifier_key_flags); /* SCM scm_c_string_to_symbol (char const* str) */ SCM scm_c_string_to_symbol (char const* str); /* Ref @var{name} from emacsy module. */ SCM scm_c_emacsy_ref (char const* name); #ifdef __cplusplus } #endif #endif // __EMACSY_H
Next: Contributing, Previous: Hello Emacsy, Up: Top [Contents][Index]
I expounded on the virtues of the Key Lookup Execute Command Loop (KLECL) in see Overlooked Treasure. Now we’re going to implement a KLECL, which requires fleshing out some concepts. We need events, keymaps, and commands. Let’s begin with events.
Next: Emacsy Facade, Up: Api [Contents][Index]
Emacsy provides a C API to ease integration with C and C++ programs. The C API is given below.
Initialize Emacsy.
Enqueue a keyboard event.
Enqueue a mouse event.
Run an iteration of Emacsy’s event loop, does not block.
Return the mode line.
Run a hook.
Return the minibuffer point.
Terminate Emacsy; run termination hook.
Attempt to load a module.
The function scm_c_use_module throws an exception if it cannot find the module, so we have to split that functionality into a body function load_module_try and an error handler load_module_error.
Attempt to load a module. Returns 0 if no errors, and non-zero otherwise.
Convert integer flags to a list of symbols.
Ref name from emacsy module.
So that users of our library don’t have to import all of our nicely partitioned modules individually, we’ll expose a facade module that re-exports all of the public interfaces for each module. Just use
(use-modules (emacsy emacsy))
or
#:use-module (emacsy emacsy)
Next: Keymap, Previous: Emacsy Facade, Up: Api [Contents][Index]
One of the idioms we want to capture from Emacs is this.
(define-key global-map "M-f" 'some-command)
They [[keymap]] and [[command]] module will deal with most of the above, except for the [[kbd]] procedure. That’s something events will be concerned with. One may define a converter for a [[kbd-entry]] to an event of the proper type. Note that a [[kbd-string]] is broken into multiple [[kbd-entries]] on whitespace boundaries, e.g., “C-x C-f” is a [[kbd-string]] that when parsed becomes two [[kbd-entries]] “C-x” and “C-f”.
Basic event class.
Event to capture key strokes, including the modifier keys.
Event to capture key strokes, including the modifier keys.
Event to capture mouse events.
Event to capture mouse drag events.
Now we have the function [[kbd-entry->key-event]]. [[kbd]] needs to know about this and any other converter function. So let’s register it.
Let’s write the converter for the [[<key-event>]] class that will accept the same kind of strings that Emacs does. If the [[kbd-entry]] does not match the event-type, we return false [[#f]].
For the modifier keys, we are going to emulate Emacs to a fault.
Now we convert the [[<key-event>]] back to a [[kbd-entry]].
Instead of using [[define-generic]] I’ve written a convenience macro [[define-generic-public]] that exports the symbol to the current module. This mimics the functionality of [[define-public]]. In general, any *-public macro will export the symbol or syntax to the
Display the <key-event> in a nice way.
The kbd-entry for mouse events is similar to key events. The regular expression is ^(([ACHMsS]-)*)((up-|down-|drag-)?mouse-([123]))\$.
The keymap stores the mapping between key strokes—or events—and commands. Emacs uses lists for its representation of keymaps. Emacsy instead uses a class that stores entries in a hash table. Another difference for Emacsy is that it does not convert S-C-a to a different representation like [33554433]; it leaves it as a string that is expected to be turned into a canonical representation “C-A”.
Here is an example of the keymap representation in Emacs.
> (let ((k (make-sparse-keymap))) (define-key k "a" 'self-insert-command) (define-key k "<mouse-1>" 'mouse-drag-region) (define-key k "C-x C-f" 'find-file-at-point) k) (keymap (24 keymap (6 . find-file-at-point)) (mouse-1 . mouse-drag-region) (97 . self-insert-command))
When I initially implemented Emacsy, I replicated Emacs’ keymap representation, but I realized it wasn’t necessary. And it seems preferrable to make the representation more transparent to casual inspection. Also, Emacsy isn’t directly responsible for the conversion of keyboard events into [[key-event]]s—that’s a lower level detail that the embedding application must handle. Here is the same keymap as above but in Emacsy.
> (let ((k (make-keymap))) (define-key k "a" 'self-insert-command) (define-key k "mouse-1" 'mouse-drag-region) (define-key k "C-x C-f" 'find-file-at-point) k) #<keymap a self-insert-command C-x #<keymap C-f find-file-at-point> mouse-1 mouse-drag-region>
There are a few differences in how the keymap is produced, and the representation looks slightly different too. For one thing it’s not a list.
Our keymap class has a hashtable of entries and possibly a parent keymap.
If words of command are not clear and distinct, if orders are not thoroughly understood, then the general is to blame.
The command module is responsible for a couple things. In Emacs one defines commands by using the special form [[(interactive)]] within the body of the procedure. Consider this simple command.
(defun hello-command () (interactive) (message "Hello, Emacs!"))
Emacsy uses a more Scheme-like means of defining commands as shown below.
(define-interactive (hello-command) (message "Hello, Emacsy!"))
One deviation from Emacs I want to see within Emacsy is to have the commands be more context sensitive. To illustrate the problem when I hit M-x TAB TAB it autocompletes all the available commands into a buffer. In my case that buffer contains 4,840 commands. This doesn’t seem to hurt command usability, but it does hurt the command discoverability.
I want Emacsy to have command sets that are analogous to keymaps. There will be a global command set [[global-cmdset]] similar to the global keymap [[global-map]]. And in the same way that major and minor modes may add keymaps to a particular buffer, so too may they add command maps.
The class holds the entries, a string completer for tab completion, and potentially a parent command map.
We have accessors for adding, removing, and testing what’s in the set. Note that the parent set is never mutated.
We’re going to capture these blocking continuations into a class.
[[call-blockable]] will handle any aborts to the [[’block]] prompt. If the thunk aborts, it adds an instance of the class [[<blocking-continuation>]] to a list of such instances.
To possibly resume these continuations, we’re going to call [[block-tick]]. Additionally, continuations come in two flavors: serial and non-serial. The constraints on resuming are different. A non-serial block can be resumed whenever the [[continue-when?]] thunk return true. A serial block, however, will only be resumed after every other serial block that has a greater number, meaning more recent, has been resumed.
In addition to simply yielding we can block until a particular condition is met.
And if we have [[block-until]], it’s easy to write [[block-while]].
Sometimes we may just want to kill a blocking continuation. One could just forget the reference and let it be garbage collected. Here, we’re going to throw an exception such that whatever the continuation was doing can potentially be cleaned up.
A box without hinges, key, or lid, yet golden treasure inside is hid.
We finally have all the pieces to properly build the KLECL. First, we have to accept input.
With the command loop I’ve also adopted a prefix of [[primitive-]] which signifies that it does not do any error handling. The command loop sets up a fair amount of state.
Each command loop is given a different number.
This is a convenience procedure to enqueue a key event.
And mainly for testing purposes we also want to discard all input. Or there are cases where we want to unread an event and push it to the front of the queue rather than the rear.
[[read-event]] is the lowest-level procedure for grabbing events. It will block if there are no events to read.
read-key-sequence #:optional prompt #:key keymaps
We also check all the maps for a quit key, typically defined as C-g.
I find it convenient to begin emitting messages in case of error. However, I would like for there to be a clean separation between Emacsy and its KLECL such that someone may write a clean vim-y using it if they so chose. So this message will merely go to the stdout\; however, it will be redefined later.
primitive-command-tick #:optional prompt #:key keymaps undefined-command XXX Rename this to klec, for Key-Lookup-Execute-Command (KLEC)—just missing the loop component?
Now let’s write the command loop without any error handling. This seems a little messy with the continue predicate procedure being passed along. I’m not sure yet, how best to organize it.
We have finished the KLECL. Note that although we have used Emacs-like function names, we have not implemented the Emacs-like UI yet. We have not defined any default key bindings. I want to encourage people to explore different user interfaces based on the KLECL, and one can start from this part of the code. If one wanted to create a modal UI, one could use the [[(emacsy klecl)]] module and not have to worry about any “pollution” of Emacs-isms.
…
We will now add a keyboard macro facility familiar to Emacs users. We hook into the [[read-event]] procedure using a hook.
XXX This also may record the key event that stops the keyboard macro, which it shouldn’t.
FIXME
In addition to regular keyboard macros, Emacsy can execute keyboard macros such that they reproduce the keys at the same pace as they were recorded.
And when you gaze long into an abyss the abyss also gazes into you.
A buffer in Emacs represents text, including its mode, local variables, etc. A Emacsy buffer is not necessarily text. It can be extended to hold whatever the host application is interested in. Emacs’ concepts of buffer, window, and mode are directly analogous to the model, view, and controller respectively—the MVC pattern.
A convenience macro to work with a given buffer.
A convenience macro to do some work
Buffer’s have a name, and there is always a current buffer or it’s false. Note that methods do not work as easily with optional arguments. It seems best to define each method with a different number of arguments as shown below.
This is scary, we will override it when we have <text-buffer>.
method
The buffers are kept in a most recently used stack that has the following operators: add!, remove!, contains?, recall!, and list.
The order of the elements may not change yet the index may be moved around.
Next: Minibuffer, Previous: Buffer, Up: Api [Contents][Index]
Editing and stuff.
.
Alias for delete-forward-char
Alias for delete-backward-char
A child of <buffer>, such as <text-buffer>, <minibuffer> or a custom UI buffer may override these, for efficiency or otherwise.
<text-buffer> inherits from buffer and implements the simplest text editing for the Gap Buffer.
The minibuffer provides a rich interactive textual input system. It offers TAB completion and history. The implementation of it inherits from the <text-buffer>.
We define a keymap with all the typical self-insert-commands that would be expected in an editable buffer
When we show the minibuffer, we’ll show the prompt, the contents (user editable), and the minibuffer-message if applicable.
history can be #f, a symbol, or a <cursor-list>.
We want to be able to look up file names.
Some commands for manipulating the minibuffer history.
Next: Advice, Previous: Minibuffer, Up: Api [Contents][Index]
Now we’re going to put in place some core functionality that makes Emacsy an Emacs-like library.
We need a global keymap.
Sometimes we may want to track the motion events generated by a mouse. We don’t do this all the time because it seems unnecessarily taxing.
When the minibuffer is entered, we want to clear the echo-area. Because the echo-area is defined in core, it seems best to deal with it in core rather than placing echo-area handling code in minibuffer.
These are most of the C API calls.
There is one command that I consider fundamental for an Emacs-like program. Whenever I’m presented with a program that claims to be Emacs-like, I try this out M-: (+ 1 2). If it doesn’t work then it may have Emacs-like key bindings, but it’s not Emacs-like. That command is [[eval-expression]]. Let’s write it.
The second fundamental command is [[execute-extended-command]] invoked with M-x.
This [[universal-argument]] command is written using a different style than is typical for interative Emacs commands. Most Emacs commands are written with their state, keymaps, and ancillary procedures as public variables. This style has a benefit of allowing one to manipulate or extend some pieces; however, there are some benefits to having everything encapsulated in this command procedure. For instance, if the minibuffer were written in this style, one could invoke recursive minibuffers.
We want to be able to load a scheme file.
The *scratch* buffer.
Override kill-buffer; make sure the buffer list does not become empty.
Wise men don’t need advice. Fools won’t take it.
No enemy is worse than bad advice.
Emacs has a facility to define “advice” these are pieces of code that run before, after, or around an already defined function. This article provides a good example.
How will this work? Before we try to make the macro, let’s focus on building up the functions. We want to have a function that we can substitute for the original function which will have a number of before, after, and around pieces of advice that can be attached to it.
Emacsy aims to offer the minimal amount of intrusion to acquire big gains in program functionality. Windows is an optional module for Emacsy. If you want to offer windows that behave like Emacs windows, you can, but you aren’t required to.
The window class contains a renderable window that is associated with a buffer.
The internal window class contains other windows.
Emacs uses the edges of windows (left top right bottom), but I’m more comfortable using bounded coordinate systems (left bottom width height). So let’s write some converters.
Be careful with deep-clone. If you deep clone one window that has references to other windows, you will clone entire object graph.
Cycling order for recenter-top-bottom.
Emacs offers a fantastic comprehensive help system. Emacsy intends to replicate most of this functionality. One distinction that would be nice to make is to partition Scheme values into procedures, variables, and parameters. In Scheme, all these kinds of values are the handled the same way. In Emacs, each are accessible by the help system distinctly. For instance, [[C-h f]] looks up functions, [[C-h v]] looks up variables. In addition to defining what kind of value a variable holds, this also allows one to include documentation for values which is not included in Guile Scheme by default. (XXX fact check.)
XXX Rename from variable-documentation to just documentation.
We also want to be able to collect up all the variables in some given module.
Parameters behave similarly to variables; however, whenever they are defined, their values are set.
Next: Acknowledgments, Previous: Api, Up: Top [Contents][Index]
Next: Running Emacsy From the Source Tree, Up: Contributing [Contents][Index]
If you want to hack Emacsy itself, it is recommended to use the latest version from the Git repository:
git clone git://git.savannah.gnu.org/emacsy.git
The easiest way to set up a development environment for Emacsy is, of course, by using Guix! The following command starts a new shell where all the dependencies and appropriate environment variables are set up to hack on Emacsy:
GUIX_PACKAGE_PATH=guix guix environment -l .guix.scm
Finally, you have to invoke
make check to run tests
(see Running the Test Suites). If anything fails, take a look at
installation instructions (see Installation) or send a emacsysage to
the bug-emacsy@gnu.org mailing list.
Next: The Perfect Setup, Previous: Building from Git, Up: Contributing [Contents][Index]
First, you need to have an environment with all the dependencies
available (see Building from Git), and then simply prefix each
command by
./pre-inst-env (the pre-inst-env script
lives in the top build tree of Emacsy).
Next: Coding Style, Previous: Running Emacsy From the Source Tree, Up: Contributing [Contents][Index]
The Perfect Setup to hack on Emacsy is basically the perfect setup used for Guile hacking (see Using Guile in Emacs in Guile Reference Manual). First, you need more than an editor, you need Emacs, empowered by the wonderful).
Next: Submitting Patches, Previous: The Perfect Setup, Up: Contributing [Contents][Index]
In general our code follows the GNU Coding Standards (see GNU Coding Standards). However, they do not say much about Scheme, so here are some additional rules.
Scheme code in Emacsy is written in a purely functional style..
If you do not use Emacs, please make sure to let your editor knows these rules.
Additionally, in Emacsyile-user Emacsy
#guile on the Freenode IRC network or on
guile-user@gnu.org to share your experience—good or bad.
Please send bug reports with full details to guile-user@gnu.org.
Next: Resources, Previous: Contributing, Up: Top [Contents][Index]
We would like to thank the following people for their help:
Next: GNU Free Documentation License, Previous: Acknowledgments, Up: Top [Contents][Index]
Next: Programming Index, Previous: Resources,: Keyboard command Index, Previous: GNU Free Documentation License, Up: Top [Contents][Index]
Next: Concept Index, Previous: Programming Index, Up: Top [Contents][Index]
Previous: Keyboard command Index, Up: Top [Contents][Index]
Emacsy has since been converted from a literate noweb program to plain Guile Scheme and this Info document
Kickstarter page
Note: Emacsy does not rely on FreeGLUT. One could use Gtk+, Ncurses, Qt, or whatever | https://www.nongnu.org/emacsy/manual/emacsy.html | CC-MAIN-2020-34 | refinedweb | 6,571 | 58.38 |
A few weeks ago, Fernando Perez, the creator of IPython, wrote a post about blogging with IPython notebooks. I decided to take a stab at making this work in Octopress.
I started by following Fernando's outline: I first went to and obtained the current version of the notebook converter. Running
nbconvert.py -f blogger-html filename.ipynb produces a separate html and header file with the notebook content. I inserted the stylesheet info into my header (in octopress, the default location is
source/_includes/custom/head.html) and copied the html directly into my post.
I immediately encountered a problem.
nbconvert uses global CSS classes and style markups, and some of these (notably the "hightlight" class and the
<pre> tag formatting) conflict with styles defined in my octopress theme. The result was that every post in my blog ended up looking like an ugly hybrid of octopress and an ipython notebook. Not very nice.
So I did some surgery. Admittedly, this is a terrible hack, but the following code takes the files output by nbconvert, slices them up, and creates a specific set of CSS classes for the notebook markup, such that there's no longer a conflict with the native octopress styles (you can download this script here):
#!/usr/bin/python import os import sys try: nbconvert = sys.argv[1] notebook = sys.argv[2] except: print "usage: python octopress_notebook.py /path/to/nbconvert.py /path/to/notebook_file.ipynb" sys.exit(-1) # convert notebook os.system('%s -f blogger-html %s' % (nbconvert, notebook)) # get out filenames outfile_root = os.path.splitext(notebook)[0] body_file = outfile_root + '.html' header_file = outfile_root + '_header.html' # read the files body = open(body_file).read() header = open(header_file).read() # replace the highlight tags body = body.replace('class="highlight"', 'class="highlight-ipynb"') header = header.replace('highlight', 'highlight-ipynb') # specify <pre> tags body = body.replace('<pre', '<pre class="ipynb"') header = header.replace('html, body', '\n'.join(('pre.ipynb {', ' color: black;', ' background: #f7f7f7;', ' border: 0;', ' box-shadow: none;', ' margin-bottom: 0;', ' padding: 0;' '}\n', 'html, body'))) # create a special div for notebook body = '<div class="ipynb">\n\n' + body + "\n\n</div>" header = header.replace('body {', 'div.ipynb {') # specialize headers header = header.replace('html, body,', '\n'.join((('h1.ipynb h2.ipynb h3.ipynb ' 'h4.ipynb h5.ipynb h6.ipynb {'), 'h1.ipynb h2.ipynb ... {', ' margin: 0;', ' padding: 0;', ' border: 0;', ' font-size: 100%;', ' font: inherit;', ' vertical-align: baseline;', '}\n', 'html, body,'))) for h in '123456': body = body.replace('<h%s' % h, '<h%s class="ipynb"' % h) # comment out document-level formatting header = header.replace('html, body,', '/*html, body,*/') header = header.replace('h1, h2, h3, h4, h5, h6,', '/*h1, h2, h3, h4, h5, h6,*/') #---------------------------------------------------------------------- # Write the results to file open(body_file, 'w').write(body) open(header_file, 'w').write(header)
This code should be run with two arguments: first the file to be converted, then the path to
nbconvert.py. Like the native
nbconvert.py this produces a separate file of header code (which is inserted once into the master blog header) and body code which can be copied verbatim into the post.
If you haven't noticed already, this post is written entirely in an IPython notebook. So let's see how some things look.
First of all, we can write some math, which is rendered using mathjax:
$f(x) = \int_0^\infty \left(\frac{\sin(x)}{x^2}\right)dx$
As we see, it renders nicely.
Or we can do some inline plotting:
%pylab inline
Welcome to pylab, a matplotlib-based Python environment [backend: module://IPython.zmq.pylab.backend_inline]. For more information, type 'help(pylab)'.
import numpy as np x = np.linspace(0, 10, 100) pylab.plot(x, np.sin(x))
[<matplotlib.lines.Line2D at 0x2cdba90>]
You can do pretty much anything else a notebook does as well. The IPython team did the hard part.
There's clearly a cleaner way to do this. If the IPython team would be open to the idea, I think their HTML stylesheets should be modified so that notebooks can be embedded within any CSS framework with as few conflicts as possible. This means getting rid of all top-level formatting in the style-sheets, and removing potentially common class names like "highlight". Once this is done,
nbconvert.py could output this directly, obviating the need for my unforgivable hack shown above.
Second, I'd love to build notebook support directly into octopress. If
nbconvert.py is available on the user's system, it could be called directly from the Ruby script that generates Octopress HTML. I have about as much experience with Ruby as I do with Swahili (read: None) so this would take some work for me. I'd be happy to pass the baton to any Octopress gurus out there...
Either of those options will smooth out the notebook/blogging combo considerably, and give me the potential to prognosticate Python in perpetuum. By the way, the notebook used to generate this page can be downloaded here. Happy coding! | http://nbviewer.jupyter.org/github/jakevdp/jakevdp.github.com/blob/master/downloads/notebooks/nb_in_octopress.ipynb | CC-MAIN-2018-13 | refinedweb | 824 | 59.3 |
Feedback
Getting Started
Discussions
Site operation discussions
Recent Posts
(new topic)
Departments
Courses
Research Papers
Design Docs
Quotations
Genealogical Diagrams
Archives
A promising approach for set comprehension and set processing is to utilize generative grammars. Generative grammars essentially denote the set of 'sentences' they will generate, and a set of sentences can carry complex information about the world and one's designs for it.
With grammar-based computation, the primary operations would be composition and refinement of grammars. Working with the 'sentences' directly is marginalized except to the extent that literals describe relatively trivial grammars. This breaks from traditional application of grammars, which is to analyze a sentence for 'matches' and to provide rewrite rules that generate a new sentence. This traditional application mirrors common functional programming (pattern matching and production rules), and is often 'lossy' in the sense that one cannot regenerate the original sentence from the matching rules. Grammar-based computation doesn't involve 'rewriting'; there is no explicit 'generated sentence'.
Instead, grammar-based computation is very close to logic-programming. A grammar can be understood as a sort of predicate that will classify the sentences it generates. For example, a grammar named 'Sum' might generate sentences of the form (A B C) where A, B, C represent integers and A+B=C. One might refine this into a new grammar Add4 that generates sentences of the form (B C) where 4+B=C. Simple constraint programming is also feasible - i.e. all (B C) sentences where C < 100 - and then one can 'generate' solutions to the constraint problem.
At the edges of the system, one could ask for sample sentences. Within a grammar, 'queries' would need to be simple without hindering composition of grammars. Perhaps G1\G2 is a composition that generates G1 if G1 is not empty, otherwise generates as G2. (Another useful query might be whether G1 produces a unique sentence... perhaps some sort of 'at least one, at most one' approach.)
The challenge I've been facing is making this practical. By practical I mean supporting properties such as:
Some of these features feed one another. For example, if grammars denote sets of sentences, then supporting 'sets' within a sentence effectively means having 'grammars' within sentences. And supporting grammars within sentences, along with expressive patterns to adapt those grammars, might be sufficient to describe continuous fields.
Anyhow, I'm curious as to state-of-the-art and prior-art that I haven't discovered yet, and for any opinions/ideas.
A quick summary of what I have discovered: Attribute grammars and derivatives are simply too darn complex - they attempt to combine functional composition of attributes with grammatical productions, and the result is painful to write, difficult to read, and functions are generally irreversible (analytic rather than generative)... and they certainly weren't designed for reasoning across grammar compositions. Alessandro Warth's OMETA and Parsing Expression Grammars are designed for composition, but are also analytic grammars. The Language Machine seemed related, but really is all about stream-rewriting.
I'm still reading John Shutt's 93 thesis on RAGs, which seem related to what I'm seeking, but I've yet to fully grok them; I'll admit to being put-off by the emphasis on achieving "Turing-power" as though it were a virtue rather than an often unnecessary evil. I just now located an older LtU discussion referencing a paper on 2-level grammars and semantics which seems related. Matt Estes wrote Properties of Infinite Languages and Grammars, which I'll need to read.
I also picked up Grammar Systems: A Grammatical Approach to Distribution and Cooperation and Grammatical Models of Multi-Agent Systems, though I'm really hoping to find something to which I can apply a distributed security model (object capabilities, preferably) and these books describe systems that involve 'trustful' collaboration.
I'm not totally sure what you are after and don't understand your selection of notation ( why are sums represented as tuples (A B C ...) instead of, well, as sums (A + B = C)? ) but ).
You write "grammars are predicates over sets of sentences". The common procedure of evaluation of the predicate is the creation of a parse-tree. If the parser succeeds in parsing a sentence, the sentence can be considered as classified/accepted by the grammar.
I recently found a simpler method to achieve the same goal, which is also applicable for expression generation. I called the corresponding machine a TokenTracer. In essence a TokenTracer operates like a top-down-parser on first and follow sets generated by a parser generator but the TokenTracer ignores everything but the token.
Suppose you have defined a grammar 'Sum':
Sum: Symbol ('+' Symbol)* '=' Symbol
Symbol: INT | NAME
Here INT and NAME shall be terminals and Sum and Symbol are non-terminals.
We initialize the TokenTracer with the language generated from the grammar and the start symbol Sum:
tracer = TokenTracer(Language(Grammar), Sum)
tracer.selectable() // selectable token [INT, NAME]
Iterate a few steps
tracer.select(INT)
tracer.selectable() // ['+', '=']
tracer.select('+')
tracer.selectable() // [INT, NAME]
tracer.select(NAME)
tracer.selectable() // ['+', '=']
tracer.select('=')
tracer.selectable() // [INT, NAME]
tracer.select(INT)
tracer.selectable() // []
The TokenTracer can validate a token stream by successively feeding the token-types of the token sequence into select(). If the complete sequence is passed through it is o.k. otherwise it contains an error. It is also a cheap method to liberate the parser from error reporting: if the parser fails to accept a token, so does the TokenTracer and vice versa - the TokenTracer can always detect a wrong token with ease.
Since the TokenTracer determines all possible token in each step, it is possible to randomly select an admissible token and fill in a token-string from whatever source ( user, random-generator, file, ... ). I recently used this method to "breed" grammars to test a parser generator using genetic programming. I could have used exhaustive generation as well, but where is the fun with that?
why are sums represented as tuples (A B C ...) instead of, well, as sums (A + B = C)?
Sum is represented by a grammar named 'Sum'. The triples would be the sentence accepted by 'Sum'. I could have 'Sum' accept sentences of the form 'A + B = C', but if using Sum in the role of a predicate it would still need be passed to the Sum grammar to see whether the sentence is generated by the Sum grammar:
Sum('4 + 11 = 7')
Sum('4 + 7 = 11')
You might be wondering: why don't "+" and "=" form some sort of implicit grammar in the environment? Well, I'm sure we could make that happen, but it wouldn't be effective for illustrating modularity, first-class grammars, or refinement. I.e. with the above example, it is clear that I could replace Sum with some other grammar. ).
If restricted to CFGs, you cannot express the Sum grammar, which accepts (generates) sentences such as (4 7 11) but rejects sentences such as (4 11 7). Is that convincing, or do I need more?
If we're going to use grammars as the basis for computation, we'll need grammars stronger than CFGs. But we can stop short of Turing-power.
Re: TokenTracer - I agree that one needn't always build a 'tree' in order to generate or classify a sentence.
I'm assuming a sort of scannerless parsing - i.e. no separate lexer; all 'tokens' are represented in the grammar directly (down to the character level, if sentences are represented in strings). How the traces are implemented is under-the-hood and might be selected for performance or predictability on a situational basis.
If restricted to CFGs, you cannot express the Sum grammar, which accepts sentences such as (4 7 11) but rejects sentences such as (4 11 7).
Why are you trying to enforce a semantic property by means of syntax?
Grammars must serve as comprehensions for 'interesting' sets - i.e. sets that carry databases of useful information (constraints, patterns), and we must be able to produce progressively more interesting sets by composition and refinement. That's the basis of generative grammar-based computation (just as developing 'interesting' functions is the basis for functional programming).
The 'syntax' you're concerned with would be whatever syntax is used to describe the Grammars in the first place, or at least bootstrap said descriptions. In that particular case, the syntax would be mapped onto a semantics.
[Edit] Also, it isn't so bad to ask that question in reverse: why do we insist on separating syntax from semantics? What does that indirection buy us, precisely?
why do we insist on separating syntax from semantics? What does that indirection buy us, precisely?
I think their are two big things that come to mind immediately, one mainly practical and one possibly more technical.
The practical benefit is manageability. It is much easier to break the details of a language up into its syntactic and semantic components rather than having to deal with the whole ball of a wax at once. You stand a much better chance of cleanly describing each separately than hoping to find a single, uniform system that nicely handles all the properties you are trying to model.
The technical benefit is that you ensure that you don't inadvertently hobble yourself by preventing the expression of useful counterfactuals. To use your example, how would you express the set of numbers that are not the sum of 4 and 7? You can see that is as useful a definition relative to sums as the positive cases but very hard to express in a syntax with semantic restriction to actual sums.
Are you assuming that composition of grammars would be much less modular than the alternatives?
Re: how would you express the set of numbers that are not the sum of 4 and 7? [...] hard to express in a syntax with semantic restriction to actual sums
You would describe a grammar that denotes that set - perhaps:
exists C. Nat - C where Sum(4 7 C)
exists C. Nat - C where Sum(4 7 C)
In this, C would be the grammar describing all clauses for which Sum(4 7 C) holds. In this particular case, there happens to be a unique answer. (Unrestricted use of negation might be troublesome if we wish to ensure the ability to decide whether the grammar is empty. I'd like to find something weaker.)
The restriction to expressing actual sums is only true for the language described by the grammar 'Sum'. The language for describing the grammar 'Sum' is not so restricted. For grammar-based computation, developers work primarily in the latter language: the language for describing and composing grammars.
Oh. I didn't expect your grammars knowing arithmetic. Now I also do understand why you read Shutts master-thesis. He avoids ugly hybridizations with semantic actions but retains their computational power in the grammar formalism. I still don't know what can be better solved that way than using more conventional tool pipelines. It would be cool if you would come up with some positive results.
As I mentioned at the top, my goal is effective, modular set processing and set comprehensions.
A grammar can be understood as describing a (potentially infinite) set of sentences. A set of sentences is a natural mechanism to carry information - i.e. in the same sense that a set of tuples is 'relation' in a relational model. Naturally, information is finite even if the language is not. Thus, one can understand the informational content of 'grammars' as carried by the constraints describing which sentences are included or excluded from the language: the information (in the form of constraints) is contained by the whole grammar, and the context in which the grammar appears, rather than by any individual sentences.
In this sense, we can understand grammars as related to both logic and constraint programming. Grammars describe modular sets of constraints, and can be composed to refine those constraints (e.g. via intersection) or weaken them (e.g. via union) or relate them (e.g. via joins or sequences). Similar to constraint-programming, with 'generative' grammars we can also generate a sentence as a solution to these constraints (if one exists). Logic programming can be expressed by grammars and vice-versa, but the bases for information and composition are different, and logic predicates are rarely first-class.
Anyhow, conventional tool pipelines would be ineffective and extremely awkward for first-class grammars and reasoning about properties of languages across grammar compositions.
Now since you have shown us what you mean by the Sum grammar I would be curious how you intend to compose a Sum grammar with a Product grammar in a sensible way using set operations like intersection and union and how you "reason about properties" of Sums and Products across this composition.
I'm still studying that problem, which is why I asked in the OP for pointers to state-of-art and prior-art on the subject that my Google-fu was too weak to find. There are many possible mechanisms for describing composition of sums and products into a grammar. Among the more traditional is to use unification based approach. For example, one might express sentences where a^2 + b^2 = c^2 as {(A B C) | exists D E F : Prod(A A D), Prod(B B E), Prod(C C F), Sum(D E F)}.
But unification of this sort has its own costs; the existentials hide expensive searches. I'm interested in finding other designs.
For reasoning about properties, I'm imagining some sort of structural and sub-structural type-system for grammars might appropriate. I'm rather fond of TRS's ability to 'declare' properties such as commutativity, associativity, and identity. I'm very interested in approaches that would describe these structurally in sentences and enforced for grammar processing. Beyond the sentences produced, there are many other properties that are useful to know across grammar compositions - decidable generation and analysis, constraints on uniqueness (at least one sentence, at most one sentence), ambiguity (substructural: at most one way to form a given sentence), and so on.
What you are doing is using the trace to define what language is accepted by an automaton in state X. Bart Jacobs has most definitely written papers about this - viewing context-free grammars as coalgebraic structures.
As far as I know, there is only one route you can take, which is context sensitive parsing. I see that it is what you're trying to avoid, but when you've got a context sensitive grammar, you got a context sensitive grammar, you can't dumb it down any more.
You say 2-level grammars are too complex? There are a wide variety of 2-level formalisms used and developed in compiler building and natural language recognition projects. It just depends a lot on how you define the second level (fixed value over a lattice, string type, structural value, fixed unification order, there's a lot to play with).
You might want to look at Early's algorithm since that effectively calculates the intersection of a grammar and an r.e.
[What the *bleep* are coalgebraic structures doing here? Category theory is pseudo-science, best you can get out of it is a reformulation of what you already know? ok, a^2=b^2+c^2 has its uses too, but I don't see the relevance here.]
I'm making no attempt to avoid 'context sensitive'. What gave you that impression? What I seek is a tractable, composable, modular formulation of grammars - i.e. expressive enough for most jobs (Ackermann, sorts, same-fringe, etc.), but supporting local reasoning and useful decisions. (For generative grammars, the most important decision is whether the grammar is empty. Other useful decisions are whether it contains exactly one sentence, whether it is finite, whether it is ambiguous.)
I said attribute grammars are too complex. I'm still learning 2-level grammars, reading some works by Barrett Bryant. Those I've read about rely heavily on existential unification; I suspect that would be remarkably expensive to process.
I'll check out Early's algorithm. Thanks for the pointer.
[To what do you refer wrgt. coalgebraic structures? And isn't the reformulation of what we already know the purpose of all in-the-small computations?]
Sometimes reformulations are good. Like a^2=b^2+c^2, that took a few millenia. Or deriving termination of Collatz from looking at the bit representation of numbers and observe that it's just all bit-cancellation, therefor there's a decreasing measure, the thing is Noetherian. But I don't see the relevance of coalgebras here.
I also don't see the relevance. More precisely, I don't even see the referent. To what are you referring?
Some postings up.
You forget that Prolog is, accept for its cut-rule, a 2-level formalism.
[hmm, i see you didn't.]
I agree that there is a close relationship between logic programming and grammar-based programming. A given logic predicate, or even a whole program, can be treated as representing a specific grammar. But what I'm seeking is one level higher than that: composition of grammars (or logic programs) and local reasoning about the properties of these compositions.
I.e. effectively, I could have agents sending logic programs to one another, generating new logic programs, combining logic programs provided by multiple agents. And I wish to reason about performance, termination, whether a composed grammar is empty, finite, or has a unique element, what information is hidden, etc.. Prolog is unlikely the best choice for this.
If you want to do the following:
then it seems you're going to have to work to find a class of grammars that does the trick: nothing in the Chomsky hierarchy will work, for sure, nor will two-level grammars.
I'm guessing you're not really attached to the whole of that list: it'd make me get a better idea of where you wanted to go if I knew what trade-offs you were willing to make.
I do want #1,3,4. Though, regarding 3, I don't need all true arithmetic expressions, just a useful subset along the lines of total functional programming.
It is unclear to me what you mean by #2. But I would like the grammar descriptions and compositions to effectively support both generation and recognition of the same sentences, if that is what you mean by "grammatical".
I don't care about #5. As I noted to Kay earlier, I'm okay with giving types to the grammars, and I imagine that would help greatly with local reasoning about the properties of grammar composition. But I would strongly favor structural, implicit typing rather than nominative or manifest typing. When working with total functional programming, I utilized purely structural typing to good effect, complete with support existential typing and limited support for dependent types (via partial functions) and even first-class abstract data types (via sealer/unsealer pairs generated in the agent layer) and open recursive functions (via careful, explicit treatment of recursion). TFP was, unfortunately, too awkward for set processing.
I'll be happy also to reject 'sequences of atoms' as the basic underlying sentence. In doing so, I also obtain some rich alternatives to concatenation.
Sequences add far too much semantic noise. The intended semantics of a generated sentence don't always depend upon the ordering of the elements, but sequences enforce an ordering anyway. This can create extra work on output from a grammar (generating various permutations of sentences). It also can also increase complexity of composition (to explicitly remove ordering) - and one gains no help from the type-system to enforce independence from ordering.
Similarly, namespaces and labels (e.g. for vertices in a graph) are areas where one might pointlessly generate sentences in infinite variation.
Currently, I'm playing with the idea of sentences based on atoms, extended sets, spaces, and (recursively) more grammars. To keep it tractable, generation of grammars would be based only upon composition (as opposed to reflective representation of grammar descriptions). I could also use grammars as the only composition primitive, but I'm unsure whether that makes things too challenging for users.
A 'space' serves as the basis for namespaces and graphs. When I was working with TFP space S: [({S 1} {S 2}) ({S 1} {S 3}) ({S 2} {S 4}) ({S 3} {S 4})] might be understood as a simple digraph whose points are labeled 1,2,3,4 - but where these labels are strictly for representation, and thus is semantically identical to space S: [({S d} {S c}) ({S d} {S b}) ({S c} {S a}) ({S b} {S a})] (using atoms d,c,b,a). Spaces combine effectively with xsets to eliminate semantic noise wrgt. ordering. I'd like to further support associativity, in order to have at least the set supported by common term rewriting systems.
space S: [({S 1} {S 2}) ({S 1} {S 3}) ({S 2} {S 4}) ({S 3} {S 4})]
space S: [({S d} {S c}) ({S d} {S b}) ({S c} {S a}) ({S b} {S a})]
Anyhow, the basic tradeoffs I'm willing to make are:
And I'm willing to work to find a class of grammars that does the trick. But it seems wise to see if anyone else has already accomplished something near to what I seek.
[Marco, thanks for the ref to CDL3.]
Sorry for the delay in replying. By #2, I was getting at the distinction between the fairly algebraic approach to grammar in the Chomsky hierarchy, which is friendly to different kinds of automata, and the very operational notion of state you have in PEGs, which is basically fixed to packrat parsers.
I don't know what you mean by "extended sets".
Spaces I like very much: the point about representing graphs alone is compelling enough. They are going to make the language design hard though, in the sense of mathematically hard, I think.
I think typing is the right path, but it's easy to pile on complexity this way: you offer a dozen different regular expression types, each having different complexity properties when forming, say, intersections with other grammars — in the end, the programmer will need to read all the formal languages papers you read in order to understand the type system.
Pessimism done: I think it sounds great.
Extended sets (xsets) are, in practice, sets of pairs - of ElementScope where 'Scope' describes the structural role in the set. Element and Scope may each be extended sets or some primitive value (such as an atom). It is the ElementScope pair - as a whole - that exists uniquely in an xset. So {1a, 1b, 2a} is a possible xset.
I require at least one structured composition primitive for sentences, and in the interest of language minimalism I would favor using only one primitive. A common option is sequences or records, which may be composed recursively to describe lists and trees and other 'data' structures. But these options force ordering in the composite 'data structure' that is unnecessary or undesriable to its intended interpretation, or structural ordering induced semantic noise. (Semantic noise is semantic content introduced by the host language that is unnecessary or undesirable for the problem domain. Its presence resists optimization, flexibility, and formalization.) xsets allow control regarding where structural order is introduced. Where ordering is necessary, one can use recursive xsets: {Hhead, Ttail}. Or one may use ordered scopes: {A1, B2, C3}.
As an added benefit, some xset operators would overlap grammar operators (seeing as grammars denote sets of sentences). So programmers would have fewer concepts to learn.
Extended sets were the brainchild of David Childs some decades ago, and are described here, though the focus on those pages is a particular application of extended sets. Unfortunately, the salient points on David Childs' page are buried among mounds of unjustified marketing manure written seemingly for pointy-haired bosses. Less biased descriptions of the subject are also available.
Spaces I like very much: the point about representing graphs alone is compelling enough. They are going to make the language design hard though, in the sense of mathematically hard, I think.
In general, whether two spaces are equivalent is indeed a computationally hard problem.
But I'm hoping(!) to avoid the 'general' hard problem. For generative grammars, it may be feasible to avoid generating two identical spaces from a single grammar, or to otherwise generate them in such a manner such that recognition of identical spaces is a relatively easy problem. Outside of avoiding replicated searches, most operations should consist of generating and recognizing spaces rather than comparing them for equivalence.
Spaces are about avoiding labeling-induced semantic noise, just as xsets avoid structural-ordering-induced semantic noise. In the cases where we really do need to compute whether one space is equal to another, as opposed to generating or recognizing or unifying a space, we should need to do the same regardless of whether spaces were first-class. The 'hard' complexity should(!) only be introduced where it is essential complexity.
Unstructured spaces combine with xsets to denote multi-sets. For example, if I want a multi-set, I could express it as: space S: {1S a, 2S b, 2S c, 3S d}. This says elements 1, 2, 2, and 3 are structured by distinct points (temporarily labeled a,b,c,d, for convenience) in an anonymous space (temporarily labeled S, for convenience).
space S: {1S a, 2S b, 2S c, 3S d}
A problem with spaces is finding means to effectively work with and compose them (after initial construction). My approach with functional programming was to introduce a keyword operator 'probe' that could pass a function into a space; a probe can return a value that contains no points from the space being probed, and may test equivalence between points within the space. Probe was expressive enough to do the job, but very verbose for composing two or more spaces. Without better alternatives to 'probe' that work for multi-space composition, I had decided to table 'spaces' from the functional language. The same might happen for grammar-based computations.
From what I've read, the point behind xsets is its ability to use a single structuring technique to represent indexed, associative, and nested data. When coupled with a suitable algebra, an optimizer has a lot to work with, as the entire state of computation from the initial read of data to an output format can be captured in xset notation.
Childs lists some sample operators in an algebra for xsets.
What is the equivalent of a lambda calculus for xsets? Something kanren-like that operates against the xset, instead of the cons cell.
the point behind xsets is its ability to use a single structuring technique to represent indexed, associative, and nested data
Unfortunately, that point fails to distinguish xsets from S-expressions, recursive structures, object graphs, untyped lambda calculus, or even regular ZF sets. The 'ability to represent' is not a difficult target. One should discuss instead the relative efficacy of the representation. One could discuss the 'precision' of a representation as being distance to the intended semantics of the data: semantic noise exists if there is too much constraint, and ambiguity exists if there is too little constraint. A precise representation allows more optimizations.
Similarly, 'the entire state of computation from input to output' is achieved in any declarative, pure computation language. If xsets and their algebras have an optimization advantage, it is due only to relative precision of the representation. (Since optimizers must not violate semantic constraints, any semantic noise becomes an unnecessary constraint against optimization. Since optimizers must not assume a particular interpretation, ambiguity can require extra information about non-local processing context in order to achieve local optimizations.)
Xsets are superior to many alternatives for these properties. But before deciding their utility, one should determine how precisely the xsets and algebra will represent graphs, numbers, matrices and multi-sets, fractals, scene-graphs, and other challenges.
What do you mean by 'kanren-like'? And could you clarify the meaning of your question? (What does "lambda calculus for X" mean?)
After further work on this, it seems to me that favoring partial grammars, composed in a point-free style, offers a more promising foundation for computation. I'll explain.
A complete grammar describes the formal language (set of sentences) it generates. Because I'm unconcerned with 'parsing', I may always replace a grammar with that set of sentences without loss of semantics. This is problematic for several reasons. Among them, I lose the grammar semantics: grammars are not languages. Grammars are rich, condensed structures that describe languages. By working with 'partial' grammars, I can guarantee that much of this rich structure is maintained across composition, persistence, distribution. And partial grammars achieve this without limiting abstract interpretation, type-safety, or partial-evaluation.
Partial-grammars compose similarly to functions. For example, if P1 and P2 are partial grammars, and G is a 'complete' grammar, then P2<G> is a complete grammar produced by inputting G into P2, and (P1 . P2)<G> is the same as P1<P2<G>>. When I say I favor a "point-free style", I mean only to forbid the introduction of 'complete' grammars such as G, at least with regards to syntax and composition. We are free to introduce 'constant' partial grammars such as Pg, where forall X: Pg<X> = G. Thus (P1 . Pg . P2) generates the same language as P1<G> (and may be optimized), but we are allowed to compose to arbitrary depth. For convenience, we could utilize a simple substitution theory (such as lambda calculus) to support the more complex compositions. The common compositions for complete grammars, however, are readily adjusted for point-free partial grammars: if G1 | G2 is a grammar composition (representing union), then P1 | P2 is a point-free grammar composition with semantics (P1 | P2)<G> = (P1<G> | P2<G>).
G1 | G2
P1 | P2
(P1 | P2)<G> = (P1<G> | P2<G>)
These partial grammars are generative. However, they are partial, and thus generate incomplete languages - i.e. a subset of complete sentences. They may also generate incomplete sentences (sentences with 'holes' in them), but that is of less interest to me than is the generation of complete sentences. Many compositions of partial grammars improve opportunity to generate a complete sentence; effectively, if P1 is a partial grammar, then (P1 . P2) is a less-partial grammar; some of those 'sentences with holes in them' might have those holes filled to generate complete sentences.
For computation to be interesting, it must model predictions and decision-making. For functional programming today, this is usually via pattern-matching on inputs. For generative grammar based computation, however, an interesting question is: "does this grammar generate at least one complete sentence?". Context-sensitive grammars embody various constraints on the sentences generated, and so this question represents a constraint-satisfaction problem. A grammar can be expressed in such a manner that it makes represents an interesting conditional test.
Anyhow, that's for in-the-small programming. In-the-large, the question is how we compose separately developed programs. Partial grammars also benefit us here: a program is a partial grammar, and composition allows both input to programs and output from them (with both input and output also being partial grammars). This also scales to distributed operation: remote partial grammars, mobile partial grammars, 'agents' that represent active queries and time-varying partial grammars. Everything is a partial grammar, modulo effect typing.
My initial pursuit of partial grammars was due to this in-the-large aspect. I could not see how to effectively integrate IO while assuming complete grammars. But with partial grammars, interaction with remote agents (that behave as partial grammars) expresses interest in both satisfying a modular constraint set, and in determining whether the distributed constraint set is satisfiable. Computation in-the-large becomes a test of whether a big, distributed, partial-grammar can generate at least one complete sentence. Computation 'spreads' across the network of partial grammars until 'complete enough' to generate one such sentence or determine that no such sentence can be generated. When we need more complex behavior, we express a more constrained partial grammar.
Given some careful (effect-typing or security typing) constraints on the expression of unification in-the-large, this should integrate very effectively with reactive demand programming, and should integrate moderately well with variations on the traditional message passing or functional reactive programming designs. A great deal of laziness and parallelism are feasible. Only at the very edges of the system - at interaction with users, hardware, and third-party services - are we to concern ourselves with actually 'browsing' generated sentences.
It seems to me that a good reformulation of all the "point free" stuff is to say that "partial grammars form a monoid." A bit further along, I suspect that given that you can view certain grammars as rings, the concept of a monoid ring may then make itself useful as well...
The set of all partial grammars form monoids from more than one choice of operator and identity element - Compose and ID, Union and Empty, and so on. But I'm not seeing how this observation is a "good reformulation of all the 'point free' stuff." Would you mind explaining and clarifying your assertion?
I simply meant to say that I think one can summarize your description of "point free composition" by just saying that partial grammars form a monoid with compose and id. And from this, there arises the question of how much additional algebraic structure you can endow partial grammars with.
(I should have said seminearring rather than ring above, by the way, I think...)
I agree that partial grammars form a near-semiring with, as one example, 'compose' as multiplication and 'union' as addition. (Union lacks the inverse element needed for a near-ring. And compose does not annihilate with respect to Empty on the right, as required for a semiring.) Beyond the properties of 'near-semiring', we can note also that compose is monotonic: P1 ⊆ (P1 . P2) with regards to generation of complete sentences. Further, union is commutative, monotonic, and idempotent - nice properties for incremental and parallel computation.
I am interested in algebraic properties of partial grammars and the various operators with which one might compose them. A proof of associativity and commutativity will support deterministic aggregations over sets. Add identity, and you can parallelize and merge those aggregations. Monotonicity can allow incremental computation and shortcut constraint resolutions. Idempotence allows redundancy (which is important for large-scale parallelism) and reduces concerns regarding ambiguity (allowing a space/time performance tradeoff between remembering information processed vs. processing information more than once). I understand these individual properties well enough.
But I'm not comfortable enough with abstract algebras that recognizing a 'monoid' or a 'near-semiring' allows me to extrapolate anything. That is, I can look at the definitions and say, "yes, this qualifies", but I am unable to extrapolate from "X is a monoid" to conclude "X is a good summary of point-free composition". There are many options other than compose and union to form monoids or near-semirings, such as concat and union or concat and compose. And I understand that commutativity and associativity can simplify syntax. But, in my earlier request for clarification, I was hoping for some explanation as to why you assert that "partial grammars form a monoid with compose and id" is a good summary or reformulation of point-free composition. By which steps do you extrapolate this conclusion?
I think I may have promised too much with my comments, although they prompted some very nice thoughts on your part. Of course the judgement that some structure obeys some algebraic laws comes after you have defined the structure, not before. (Although, one may of course aim to design structures which have as many nice algebraic properties as possible.) My point was simply that, given what you described, it could be summarized, to someone familiar with the terminology, as a monoid over compose and id. This is not the same as saying that it is "better" at being that monoid than it is at being other monoids.
In other words, if you tell me that "partial grammars form a monoid with compose and id" then I know that partial grammars can compose with at most one other partial grammar; i.e. that compose :: PG -> PG -> PG. I know that there is a partial grammar that does nothing. I know that there is no way to compose any two partial grammars to get something which *cannot* be further composed. Thus the algebraic structure summarizes a number of the properties of partial grammars given above into a simple and well understood structure.
The one side point is that of course nice algebraic structures lend themselves to taking advantage of nice algebraic laws (and specifying which laws do and do not hold is a way to further understand your structure and the operations on it). And if one uses very general structures, then one can plug in different concrete types, to obtain different effects.
The "Play on Regular Expressions" Functional Pearl accepted to ICFP 2010 shows this quite nicely, I think.
But then, I suspect you know this all better than me already.
Thank you for the explanation, and for the reference.
For a while I had abandoned Generative Grammars for my work because I had many problems fitting them into the RDP communications framework. But some recent thoughts breathe new life into this idea. I'll just note them here, as I believe they're interesting enough to ensure are documented under this header and worthy of further discussion.
First is the notion of "temporal" generative grammars, which generate sentences that are finite in space and logically infinite (and ideally continuous) in time. This is in the same vein as temporal logics, temporal constraint programming, UTCC and Dedalus and Functional Reactive Programming (of the Yampa or Reactive brand).
A sentence might describe a point event happening at a specific time, or a periodic event, or a continuous signal. Infinite sentences could normally be hugely troublesome from a compute perspective since you cannot generate one in finite space. But we can leverage temporal logic to alleviate these issues: sentences may be infinite through time, but at any given moment in time the spatial property of the generated sentence should be finite - i.e. there is a finite (but not necessarily bounded) number of elements in the sentence. (A 'sentence' might be the size of a PhD thesis in English, of course.) By correlation of the grammar's logical time to 'real' time, we can view generation of a sentence as it progresses through time - and since time serves as our source of logical monotonicity, the spatial properties of that sentence may be non-monotonic in time (shrinking and growing over time).
Being grammars, Temporal Generative Grammars don't (usually) describe only one possible sentence, but rather a finite or infinite number of potential sentences. They describe 'patterns' in space-time, of which any particular sentence is a particular instance. A pattern in space-time corresponds (roughly) to a transitive verb in English - something that can be applied to many different 'instance' situations, like "running" or "bicycling". (In this sense, the generation of any particular sentence may be non-deterministic within the rules of the grammar.) Rather than a particular event happening at a specific time, a simple temporal grammar might assert that a generic sort of event (described by a spatial grammar) happens within a temporal window.
Now, a single temporal grammar isn't anything special by itself... just as one wouldn't take a single function of time (t→d) and call it FRP, one can't take a single grammar describing behavior in time and call it TGG.
(t→d)
What matters is composition. When all your functions are temporal, you get to compose them in interesting ways. Signal transformations such as (t→d)→(t→r), describe one temporal function as reacting to another - the basis of FRP. You can describe switching behaviors, waiting behaviors, delays, numeric integration. With fixpoint and some care to avoid divergence, you can describe mutually interactive behaviors. Additionally, you can compose behaviors that coincide at a given point in time in the normal functional way... e.g. taking (t→a) and (t→b) and producing (t→(a+b)). Further, there are many nice implementation characteristics... if implemented right, the CPUs will be performing advance computation for the next significant moment, allowing you to mask real-time latencies by computing the next observable event before time catches up to it. User input can be integrated as a 'function of real-time' so long as you don't allow expressions to peek into the future.
(t→d)→(t→r)
When generative partial-grammars are temporal, you can describe whole patterns of reaction, interaction, cause-and-effect. And you may still compose grammars via the normal constraint mechanisms - joins, et al. One may specialize the implementation, and compute a future to mask real-time latencies.
Now, the possibility of generating temporal grammars does raise at least one issue: we don't want to start computing an infinite sentence, then discover at some unbounded point in the future that our sentence is invalid and we need to try another sentence. Thus, we are under restriction to only generate valid sentences at least in the temporal dimension. It would be nice, certainly, to also generate valid sentences in the spatial dimension - but we do have a little more flexibility for backtracking there.? Do seemingly impossible functional programs hold a potential answer?
Or maybe we could use a cost-analysis basis... e.g. associate 'costs' with different temporal behaviors, and guarantee that the cost of a given behavior has a fixed bound in time.
Well, I'll probably be banging my head on the 'mechanism' for a while yet.?
As I found your ideas interesting, I refrained from commenting on this too prematurely, that is, before I've been banging my head enough on this as well. So, now, FWIW:
Do seemingly impossible functional programs hold a potential answer?
Yes, I think it's a good intuition that I'd follow if I had the same interests as yours and I had come to the same rationale and choice of path of investigation.
Note I leave alone/aside the rest of your thinking about the nice algebraic properties you're (still?) figuring important to have. So I'm actually trying to share here only about this:
the trick is to be expressive enough to describe interesting* constraints
(* emphasis mine and by "interesting" I take it you're before anything else interested in having the checking of your grammars against them, the described constraints, whatever they are, feasible in finite time and before any attempt to generate anything out of those grammars?)
that I found the most interesting sub-problem where my reflections can (hopefully) be helpful — as a matter of a possible high level strategy to tackle with this specific aspect (so, not at all an actual solution yet, even on paper, of course) :
The seemingly impossible functional programs paper gives a very nice realm of computation where computational decidability over "largely-infinite" sets such as the Cantor space is nevertheless something you can hope to achieve in finite time.
I believe it's easy enough to mentally represent oneself the Cantor space w.r.t its compactness property (well, my own mental view, anyway) : take an infinite sheet of paper divided in x and y in little squares all the same size, number them starting with 0, by following the "escargot"/spiral pattern:
Y
|
|
[12][11][10][ 9]
[13][ 2][ 1][ 8]
[14][ 3][ 0][ 7]_____ X
[15][ 4][ 5][ 6]etc
[16][17][18][19]...
then see the space as a whole as the (infinite) number of combinations where the grid's squares are either filled or empty (0/1)
"Et voila".
Ok, now what?
Well, the very fundamental bottom line of the aforementioned paper is if you're able to devise a scheme where your "things" representations are reductible to projections over this compact space then you can actually rule out (resp. find) in finite time, in that space, functions belonging to the type Cantor -> y, depending on some criteria (resp. "exists for some" or "not exists forall") where the type y itself has decidable equality (like e.g., booleans).
Now, let's say your sub-problem S consists in determining the equality of two functions F : Cantor -> y and G : Cantor -> y.
Hence my idea of a "strategy"(maybe, no promise!) : you could decide to try reduce it to two other sub-problems S1 and S2 (one is about F, the other about G) of verifying N-1 points (in each sub problem) of a N-point shared secret — let's say N=3, for which you have the (arbitrary) point zero, and a pivot-point, the latter distinct between F and G — via Shamir's Secret Sharing algorithm. The points being in the Cantor space, mapped from whatever representation you have for your PG algebra's and/or constraint mechanism's constructs...
No? (or I'm just rather tired and totally missing something either totally impractical or theoretically impossible/irrelevant)
Well, again FWIW (as it's mostly intuition again) & HTH.
[Edit]
(Hmm... after putting some more thinking into this)
Actually, according to this idea/scheme, you'd rather pick N=4 with a choice of two not-so-random constant points, used to determine the fourth via SSS, in the Cantor space:
1. "z" aka "point zero" or "origin" — i.e., this one would be the mapped representation, by design, of the (single) empty set of constraints over the grammars considered, or the analogous "peer" of your wildcard grammar "_", mentioned at the end of your other post.
2. "e" aka "the point of empty" — i.e., the mapped representation, by design, of the infinite set of all ever imaginable constraints (expressed in your algebra) over the grammars considered (which, by imposing "so many" restrictions, end up allowing only the empty language to be generated), or the analogous "peer" of the (single) complete grammar S ::= (empty) (S being its axiom, and which thus generates the empty language).
Now let "x" be the variable ranging in the (infinite) set of mapped representations of all (finite) sets of constraints over the grammars considered (but different from both z and e).
Then, you'd let something like:
F = x -> Checked(x)
G = x -> SSS(z, SSS(z, ToCheck(x), x), x)
(Note when z appears above, you might be interested in putting e, instead, depending on the context.)
Where the 4-point SSS algorithm guarantees us:
given a, b, c: if SSS(a, b, c) == d, then SSS(a, d, c) == b, hence SSS(a, SSS(a, b, c), c) == b)
The "trick" (read: difficulty) is to introduce those two intermediary functions ToCheck, Checked : Cantor -> Cantor in the above, as practically and relevant as possible w.r.t your algebra, and the intersection of the domains of which conceptually represent the one "relevant" set for the initial problem:
* on one side, from ToCheck's domain: i.e., specifically the set of "still to be checked, and maybe interesting enough-constraints"
* and on the other side, Checked's domain subset where ToCheck(x) == Checked(x): i.e., specifically the set of "now checked and chosen as being interesting enough-constraints".
So that you reuse the ideas of the paper to enumerate thru the Cantor space looking for some x where the following does not hold:
F = G => Checked(x) == SSS(z, SSS(z, ToCheck(x), x), x)
(where "=>" denotes the logical implication)
(?)
[Edit bis]
Oh yes, finally:
I reckon, it may seem strange to introduce the use of SSS and those two functions ToCheck and Checked for the purpose, but the core idea is to find a scheme (I tried to devise here) to take this wish there, into account:
For the purposes I pursue generative grammar programming, the generated sentence is mostly irrelevant. What matters is the proof and process of meeting constraints.
where, as much as ToCheck can probably be implemented once for all and in a declarative/purely functional fashion with a, say, "static" semantic, over your PG algebra, the other function Checked is still I think useful to introduce as being actually a (I, Cantor) -> Cantor where I is the domain of input you have in mind there, as well:
The answer to that question would be 'yes', 'no', or 'needs input'. One might 'need input' for a particular position, so there are infinite variations on 'needs input' such as 'need input 1' and 'need input 2' and 'need input 3'. [...] PGs provided as input are recursively asked the same question: can you generate a sentence within contextual constraints. This can lead to 'interactive' recursive partial grammars.
(so that while ToCheck is pure, Checked, OTOH, can be dependent on the state of your constraints checking/filtering)
And as far as the use of SSS is concerned, it's just basically (as you may have guessed) just a "cheap" way to provide some kind of inverse function of ToCheck/Checked — more accurately, the inverse of the restriction of ToCheck to the subdomain where constraints will happen to be filtered as "interesting" by its Checked peer afterwards (but is known cannot be computed by the only knowledge/algorithm of ToCheck a priori) — "almost for free" — well, modulo the use of SSS, precisely.
(the values of x where ToCheck(x) == Checked(<state>, x) are these "interesting enough" constraints you are only interested in at any given <state> at the end of the day)
HTH (but again, maybe I totally missed something in your actual problem space/what you're trying to have possible to implement later on w.r.t PG's)
[Edit ter]
(Corrected the defs of F, G, and fixed the discriminant equation in the implication)
But anyway: this being said, and although that's a pretty challenging problem space you've got yourself here, it's pretty interesting too; and btw, I'd love to read more about some application use cases you have in mind for PGs that you consider to be likely practically impossible to do using other, "more traditional" computation schemes(?)
Most 'traditional' computation schemes fail 'in-the-large' scale. In-the-large, it is necessary to compose mutually distrustful components, integrate with a market and society of services and code, degrade gracefully under partial-failure and recover resiliently, tolerate bugs and disruption and power cycling, support continuous upgrade and maintenance, deal with a changing environment of resources. Further, it remains important to have good performance - and control of performance (efficiency, utilization, latency) - at scale, which means utilizing multiple cores, distributing code, incremental computation and using partial results, etc.
Most 'traditional' computation schemes also fail to effectively and efficiently propagate concerns between domain models. For example, given a simple robot, it is difficult to coordinate: the motion of its wheels, the motion of its arm and camera, the obstacle recognition and avoidance concerns, the balance concerns. Simply moving around an object and taking pictures of it from different angles becomes a huge, painful deal. Anything more complex than that, such as coordinating two robots at once, is practically impossible. Constraint programming and concurrent constraint programming are a decent model for this sort of cross-domain integration..
Constraint programming and concurrent constraint programming are a decent model for this sort of cross-domain integration.
Generative grammars are promising as a base for fitting into the intersection of these concerns.
Interesting. I'm not sure I understood everything of your rationale re: "temporal grammars"; while the "partial grammars" part along with the design rationale surrounding the nice algebraic properties for filtering out "uninteresting" constraints over PGs (or, conversely, the positive selection of "interesting" ones) did make more sense (to me). My guess is I still have to re-read you and put some more thought into it given your last reply here. Thanks.
Pervasive temporal semantics allow many rich forms of system integration to be expressed efficiently and without explicit state. For example: streaming audio and video, animation, UI, robotic motion, real-time synchronization and coordination of streams and behaviors, etc.. Avoiding explicit state is, itself, a very useful feature because explicit state introduces problems for replication and code-distribution (and, thus, for performance).
Pervasive temporal semantics can reduce need for small, periodic updates to keep a system up-to-date. "Small" updates tend to cascade through a system, burning bandwidth and CPU. With temporal semantics, however, one pushes a whole 'model' of future behavior, then only updates that model when it later proves invalid. There is a cascading update of these 'large models', but they occur orders of magnitude less often. For example, one might predict movement of a vehicle to be a function of the lane it is following, in which case we only need to send an update if the vehicle significantly changes speed or starts changing lanes.
Additionally, a window for peeking into the anticipated future is excellent for developing 'planners' that can coordinate and collaborate effectively even in the face of temporary communications disruption and mutual distrust.
With temporal grammars, these qualities are magnified.
The incremental and choiceful nature of grammars allows more intelligent decisions on how far updates should be propagated - a sort of 'stubbornness' whereby one minimizes changes in choice or propagated constraints when accommodating new observations and incoming constraints. By minimizing changes, one gains 'stability' in the system and also improves efficiency even further, surpassing the benefits achieved with temporal semantics alone. Basically, temporal semantics can save us an order of magnitude or two for rate updates cascade through the system, and these incremental stubbornness properties can save us an order of magnitude for the distance that updates cascade through the system.
And the 'planning' mentioned earlier actually occurs implicitly with temporal grammars: one constrains a sentence not only for present behavior, but also for anticipated future behavior. There is no need to explicitly 'peek' into the anticipated future, instead the different constraints come together implicitly to choose a future amenable to all parties. The resulting plans are very simplistic - having no support for contingency - but that's okay, since contingency can be handled by other means (such as reactive dataflow) and the lack of contingency can simplify the planning process itself. A small bit of intelligence can go a very long way.
Speaking of small bits of intelligence, reactive generative grammars and other reactive constraint systems are very promising: given non-deterministic choice, they can 'learn' which choices are most likely to lead to success. This is a small bit of intelligence, but when replicated and scaled up to millions of agents (each with its own concerns and agendas) we end up with a worldwide neural network that 'learns' how to effectively everyone's specified needs and preferences within the limits of priority and authority. Stable constraint semantics provide stubbornness, and temporal semantics provide the rich planning.
Anyhow, I'm still putting the carriage way ahead of its horse with this long term 'vision' of mine. I feel with temporal RDP I've made a major step forward on the scalability side, though, so I've spent some time pursuing ways to combine RDP-like semantics with a model for effective domain integration, such as constraint programming. There are many practical issues still in need of resolution: I need to reconcile security properties for the incremental computation of grammars, and I'm not yet satisfied regarding integration of grammars and other constraint models with FFI and sensors/effectors.
I'd like to be clear: I don't consider temporal grammars to be the only promising possibility. I'm also exploring possibilities based upon stable fixpoint functions, true continuous functions, and bi-temporal integrals (generating a continuous integral of one's anticipated futures as they change over time). I prefer to keep a lot of possibilities open, until I find good reason to close them. To contradict your later post: I've not made any 'choice' as of yet. I figure I'll be implementing a few models as a PL atop RDP before I'm anywhere near satisfied.
Thank you for the explanation and the related link hints. I'll certainly catch- and follow-up on this later.
I can understand this easily:
Most 'traditional' computation schemes fail 'in-the-large' scale. In-the-large, it is necessary to compose mutually distrustful components, integrate with a market and society of services and code, degrade gracefully under partial-failure and recover resiliently, tolerate bugs [...] Further, [...] at scale, [it] means utilizing multiple cores, distributing code, incremental computation and using partial results, etc.
I believe this is certainly meaningful to anyone having gone thru just a couple of years of intensive experience in software composition in-the-large, and as they've been exposed on a regular basis to the tensions between the various languages, tools, and products they had to try "marry" hard — or just have interoperate "nicely enough", which, granted, is way easier said than done! — (and for any given business purpose or whatever). But I have another question, though:
I'm now curious about which most determining, specific, factor(s), or event(s)/experience(s) (or project(s), etc) did re-orient your interest by a sort of "180 degrees turn" (just so to speak) into this direction of Generative Grammar-Based computation?
(As this has a very much paradigmatic taste of a choice to me, unlikely to be anodyne, no?).
Are you looking at generative grammars because you see a kind of "language" to parse there?
Wouldn't that be more in the domain of neural networks/AI?
Generative grammars basis for computation isn't used for parsing. The 'generative' aspect is purely creative (albeit, guided by need for partial intersection).
Perhaps think of it more like one of those games where ten or twenty authors are mad-libbing a story together, except in this case the 'story' involves OpenGL output, music, car designs, dancing robots, etc. The difficulty isn't telling them to write the story, but rather in keeping it relatively sane. For generative grammars, context freedom is insanity.
For example, I'd perhaps like for you to give me a story about display layout, but there are rules: the buttons cannot overlap, they should line up horizontally if feasible, the text shouldn't run beyond the width of the button... and you need (some set of) buttons.
But, unlike constraint programming, say, these 'rules' get expressed almost uniformly as grammars. There might be a few specializations for generating real numbers and such, but mostly we use choice, various forms of sequencing, etc. The 'sentences' generated probably shouldn't be linear, because we don't want any more constraints than absolutely necessary. One could generate sets or record structures instead.
The flexibility here lies somewhere between concurrent constraint programming and logic programming. There are many of the same issues with performance and divergence concerns.
So it's all sort of a pipe dream at the moment. I've yet to find a satisfactory way to constrain the generative grammars for termination and controllable performance, though a simple cost-benefits system seems promising, offering a way to limit the size and complexity of sentences. More importantly, I've yet to find an implementation technique that doesn't violate object capability model, which I consider important for code distribution and (therefore) scalability. I plan to get back to the problem in a few years.
'AI' isn't a computation model, but a generative grammar based computation model could be used for AI. It could even be a learning AI, similar to a neural network, if every agent memoizes just a little bit about which 'sentences' work the most often (they can do this whenever non-deterministic choice exists in the grammars).
Somehow this morning, it gotta hit me: genetic programming.
Of course you don't grow your sentences ( 'chromosomes' ) in this setting using grammars but rather constrain them with those. Change happens using sets or operators including edit-operations like crossovers. What becomes crucial then is to lower admissibility thresholds. A sentence is not just evaluated to true/false but to a real value which might be [0..1] normalized which is important for progressive improvement.
On a (broadly) related note, I was aware a while back of some work in which the rules of an adaptive grammar were the genes — here.
I wasn't even aware that there is research activity, called GE, which widens the GP approach. I did GE recently for evolving test grammars with special properties for testing a parser generator. There are some particular constraints which are not encoded grammatically, foremost the one that an NT which appears on the RHS must have been introduced on the LHS.
A long and cold winter is predicted. So I'll perhaps find some time to look at non-standard grammar formalisms in more depth. Thanks to your master thesis I'll even have some overview over adaptive grammars which were introduced to me to your thesis.
Ah yes: not a long while ago (last year, I think) I've tinkered my own example of use of a 4-point SSS algorithm JavaScript implementation here btw (with a couple other tweaks for the example's purpose).
[Credits]
Basically just a simple port from David Madore's C implementation (in public domain).
[Edit] Correction made: not a 3-point version of the SSS algo; a 4-point one, indeed, just as in "our" use case here :)
Earlier I described use of partial grammars.
They were unary in nature: type PG = G → G. My assumption was that one didn't actually have syntactic access to a complete grammar G, leading to point-free composition (P1 . P2).
Unfortunately, that is quite inflexible, inexpressive.
I was, perhaps, imagining that partial-grammars would curry effectively - e.g. I can generate tuples from a grammar, so is that not similar to a tuple of grammars? It is not! A grammar that generates tuples imposes constraint relationships that must be preserved, and so one cannot generally 'extract' a grammar without carrying along the other elements in that tuple. (I.e. one can perform an intersection or a join, but not an extraction.)
Fortunately, generative partial-grammars have an interesting property: they can generate output without input. As noted above, composition is monotonic in the number of complete sentences that can be generated (P1 ⊆ P1 . P2). So is application: (P1 ⊆ P1(G)). Having the input only increases the number of potential sentences a partial grammar can generate.
So allowing multiple inputs should increase this further.
What I suggest here is to abandon the point-free style and allow partial grammars to be points: type PG = PG → PG. This is similar to the untyped λ-calculus, in that every operation between partial-grammars will generate a partial-grammar.
However, applicative substitution is only one means for composition and computation for partial grammars. One may compose partial-grammars with the grammatical forms: unordered choice (A | B), ordered choice (A / B), and certain constraint forms such as intersection (∩) or difference (-) or relational join - though the actual set of primitives needs to be restricted if we're going to answer important questions like "does this partial grammar generate a sentence?"
The answer to that question would be 'yes', 'no', or 'needs input'. One might 'need input' for a particular position, so there are infinite variations on 'needs input' such as 'need input 1' and 'need input 2' and 'need input 3'. Providing an input will add to the number of complete sentences that can be generated, but also constrains and specializes the partial grammar, so providing extra input might result in a 'needs input' becoming a yes or no.
PGs provided as input are recursively asked the same question: can you generate a sentence within contextual constraints. This can lead to 'interactive' recursive partial grammars.
For the purposes I pursue generative grammar programming, the generated sentence is mostly irrelevant. What matters is the proof and process of meeting constraints. To that end, it is also useful to introduce a wildcard grammar - a sort of boolean true - which I'm notating as (_). The wildcard grammar can generate whatever you want, which wouldn't be useful if the sentence actually matters, but does allow (A ∩ (_) = A) and (A ∪ (_) = (_)). (Its opposite end is empty choice, false, or bottom.) The wildcard isn't free license to do anything... you still need to meet any existing constraints, but the wildcard itself won't impose any new constraints.
Whether integrated as dmbarbour suggested or not, the process of scanning characters to make lexemes is necessary, and the process of analyzing syntax is necessary. On the other hand, making a module for each process is a design decision, and no matter how good it is, it may not always be the best.
IMO integrating the two processes would not be a disadvantage assuming another set of modules are used to improve manageability.
A related TCS Stack Exchange question | http://lambda-the-ultimate.org/node/4012 | CC-MAIN-2020-34 | refinedweb | 10,907 | 51.78 |
Windows.Form.DataGrid
Discussion in 'ASP .Net Datagrid Control' started by Sebastián_UY, Aug 20, 2003.
Want to reply to this thread or ask your own question?It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
- Similar Threads
Bug with DataGrid using Windows.Form... namespaceRA, Jan 5, 2004, in forum: ASP .Net
- Replies:
- 0
- Views:
- 387
- RA
- Jan 5, 2004
How to retrieve form field value if form is EncType=multipart/form-dataForm?Li Zhang, May 20, 2005, in forum: ASP .Net
- Replies:
- 4
- Views:
- 6,141
- softip
- Feb 27, 2009
DataGrid Fixed Columns on Windows FormFred Zolar, Feb 12, 2004, in forum: ASP .Net Datagrid Control
- Replies:
- 0
- Views:
- 148
- Fred Zolar
- Feb 12, 2004
[Datagrid,web form]: How the get the correct row values after sorting datagrid by headerAlainCD, Jan 12, 2006, in forum: ASP .Net Datagrid Control
- Replies:
- 0
- Views:
- 213
- AlainCD
- Jan 12, 2006
<form>...</form> - how to supress blank space after </form> in IE?rob c, Dec 30, 2005, in forum: Javascript
- Replies:
- 4
- Views:
- 362
- McKirahan
- Dec 30, 2005 | http://www.thecodingforums.com/threads/windows-form-datagrid.759370/ | CC-MAIN-2014-52 | refinedweb | 198 | 75 |
This is a description of the redux-tdd project and how its API works. If you’re looking for a more high-level explanation of test-driven development with redux, please check out my freeCodeCamp article.
Redux TDD is a simple library that let’s you test React components along with the Redux data-flow in a test-driven development (TDD) fashion.
After several iterations of the API, I came up with a simple abstraction that concentrates less on the implementation details of your components or state, and more on the actions dispatched and the props your components should receive:
import reduxTdd from 'redux-tdd';
reduxTdd({ counter: counterReducer }, state => [
<Counter
onClick={incrementAction}
counter={state.counter.count} />
])
.action(props => props.onClick())
.toMatchProps({ counter: 1 })
.contains(<span>1</span>)
In this piece of code above we are shallow rendering (from enzyme) the Counter component, and passing it props which are mapped to a specific part of the state.
The counter prop is mapped to the state value state.counter.count. The
state => [] function acts in fact not only as our render function, but also as our mapStateToProps function.
As first argument reduxTdd takes our reducers and therefore the shape of our state.
Next we call
.action(props => props.onClick()) which is where the magic happens. Anything returned by the callback passed to the action operator will essentially be dispatched (even though we’re not using redux’s dispatch — more on this later).
The action operator will therefore update the internal state and also update the props of our components based on such new state.
toMatchProps and contains simply check at this point that our component receive the correct values after the action has been dispatched.
TodoList example
In the next example we’ll try to implement a simple TodoList in a TDD fashion — what else 😄?
We start with simply passing our not-yet-existing TodoList component to reduxTdd:
reduxTdd({}, state => [ <TodoList /> ])
Our list items will probably live in state, so let’s go ahead next and introduce a
list reducer, and pass that along to our component as a prop called “listItems”.
reduxTdd({ list }, state => [ <TodoList listItems={state.list} /> ])
Running this will of course fail, since nothing is yet implemented, but let’s write more tests before implementing our logic.
A todo-list is meant to have an input-box where you add todos so let’s also add an AddTodo component (remember we’re returning an array so we can test multiple components):
reduxTdd({ list }, state => [
<TodoList listItems={state.list} />,
<AddTodo onAdd={addTodo} />
])
Great now let’s continue the dot-chaining from the above example and actually simulate the addition of a todo by calling the
onAdd action creator:
.it('should add todo items')
.switch(AddTodo) // the next dot-chained calls will work on AddTodo
.action(props => props.onAdd('clean house')) // add 'clean house'
So next we should be seeing the “clean house” todo in the TodoList, right? Let’s test that:
.switch(TodoList) // back to TodoList
.toMatchProps({ listItems: ["clean house"] })
We can even add another todo:
.switch(AddTodo).action(props => props.onAdd('water plants'))
.switch(TodoList).toMatchProps({ listItems: [
"clean house",
"water plants"
]})
Great that’s enough for now, let’s run this code and start implementing our components, reducers and actions:
const TodoList = ({ listItems }) =>
<div>{listItems.map(item => <div>{item}</div>)}</div>
const AddTodo = ({ onAdd }) =>
<button onClick={onAdd}>add todo</button>
(hint: the text-input logic is purposely left out of AddTodo)
Our addTodo action:
function addTodo(todoText) {
return { type: 'ADD_TODO', payload: todoText }
}
And finally our reducer:
function list(state = {}, action) {
switch (action.type) {
case 'ADD_TODO':
return { ...state, [action.payload]: {} }
default:
return state
}
}
If we run our code again some things will fail:
TypeError: listItems.map is not a function
This is because our state.list is an object, but the listItems prop expects an array. Let’s fix that using a selector (you can even use reselect if you want) ❤️
In our initial reduxTdd definition let’s change the way state maps to props for our TodoList component:
reduxTdd({ list }, state => [
<TodoList listItems={getVisibleItems(state)} />,
And the selector:
function getVisibleItems(state) {
return Object.keys(state.list).length
? Object.keys(state.list).map(key => key)
: []
}
Now if we run our tests again we get:
TodoList
✓ should add todo items (1ms)
🎉
Let’s also TDD the idea of “setting a todo item as complete”.
For this I’m thinking there should be a TodoItem component that is clickable right? Let’s add it to our initial list:
reduxTdd({ list }, state => [
<TodoList listItems={getVisibleItems(state)} />,
<AddTodo onAdd={addTodo} />,
<TodoItem onClick={completeTodo} />
])
But there’s a problem! The TodoItem must know which item it must complete. And it must work with a single item, but in our state we keep an object! To solve this we can simply pass a single item from our state.list object:
reduxTdd({ list }, state => [
<TodoList listItems={getVisibleItems(state)} />,
<AddTodo onAdd={addTodo} />,
<TodoItem onClick={completeTodo} item={state.list['water plants']}
/>
])
Next we mark it as complete:
.switch(TodoItem)
.action(props => props.onClick('water plants'))
At this point we realize that our TodoList component has no way of showing whether the item is complete or not (there should be a striked line over it). So we pass a new “completedItems” prop which is an array of the items that are complete:
.switch(TodoList)
.toMatchProps({
listItems: ["clean house", "water plants"]
completedItems: ["water plants"]
})
And we change again our definition to work for such behavior:
reduxTdd({ list }, state => [
<TodoList
listItems={getVisibleItems(state)}
completedItems={getCompletedItems(state)} />,
...
If we run our tests, they tell us some things need to be implemented like our completeTodo action creator:
function completeTodo(todoText) {
return { type: 'COMPLETE_TODO', payload: todoText }
}
And we update our reducer accordingly:
function list(state = {}, action) {
switch (action.type) {
case 'ADD_TODO':
return { ...state, [action.payload]: {} }
case 'COMPLETE_TODO':
return { ...state, [action.payload]: { status: 'complete' } }
default:
return state
}
}
Again running our tests will tell us our getCompletedItems is missing:
function getCompletedItems(state) {
return Object.keys(state.list)
.map(item => state.list[item])
.filter(item => item.status === 'complete')
}
And we’re done!
We can go further and use other operators like contains and view to test more fine-grained parts of our UI. But the main parts of our app have been implemented step-by-step in a TDD way.
More importantly we didn’t have to come up with intricate engineering decisions about our state or our props beforehand. We implemented them as we went ahead and as we saw the need.
I hope these examples helped you understand the idea behind Redux TDD and how you can use it for your own projects. To look at more complex examples please have a look at the tests/ folder inside the repo. You’ll find another important operator called epic which can be used to test async behavior!
Thanks and happy TDD 🤗 | https://hackernoon.com/redux-tdd-a-deep-dive-344cd7682a54?source=rss----3a8144eabfe3---4 | CC-MAIN-2019-43 | refinedweb | 1,134 | 53.61 |
The presentation of this document has been augmented to identify changes from a previous version. Three kinds of changes are highlighted: new, added text, changed text, and deleted text.
Copyright © 2006 W3C ® (MIT, ERCIM, Keio), All Rights Reserved. W3C liability, trademark and document use rules apply.
Canonical XML 1.1 is a revision to Canonical XML 1.0 to address issues raised while producing the xml:id specification. 1.1. This diff-marked version is being made available for review by W3C members and the public. It is intended to give an indication of the W3C XML Core Working Group's intentions for this new version of Canonical XML and our progress in achieving them. It attempts to be complete in indicating what will change from version 1.0, but does not specify in all cases how things will change. A subsequent Last Call draft will consist of a regular, non-diff-marked version of this specification.
Please send comments on this Working Draft to www-xml-canonicalization in XML.:nsto the default namespace node if it existsunless it is the default namespace node. For the default namespace node, use
.
<?),.
[Definition:] Simple inheritable
attributes are attributes that have a value that requires at
most a simple redeclaration. This redeclaration is done by
supplying a new value in the child axis. The redeclaration of a
simple inheritable attribute A contained in an
element E is done by supplying a new value to an
attribute with the same name contained in a descendant element of
E. Simple inheritable attributes are
xml:lang and
xml:space.) after the last slash of the former and then
normalizes the result. We describe
here a simple method for providing this function. This method uses
a separate string buffer in a manner similar to that found in
section 5.2 of RFC 2396. Perform the following steps in
order:
This function may also be called with a
null URI, i.e. when no
xml:base attribute exists in
E (not to be confused with
xml:base="").)inheritable attributes in the xml namespace, such as the
attributes
xml:lang,
xml:space and
xml:base (whether or not they are in the node-set).
From this list of attributes, remove any simple inheritable
attributes that are in E's attribute axis (whether or
not they are in the node-set). An
xml:base attribute can only be removed from the list if the the
nearest occurrence of an
xml:base attribute along
E's ancestor axis will also be rendered, otherwise
the attribute remains after it's value has been processed using the
"join URI" function described previously. in XML).
Demonstrates:
Demonstrates:
Note: In this example, the input document and canonical form are identical. Both end with '>' character.
Demonstrates:).
Demonstrates: character references other than are not affected by attribute value normalization [XML]. people provided valuable feedback that improved the quality of the 1.0 version of this specification: | http://www.w3.org/TR/2006/WD-xml-c14n11-20060915/ | CC-MAIN-2015-27 | refinedweb | 489 | 57.37 |
The QDialog class is the base class of dialog windows. More...
#include <QDialog>.(), to perform a long operation,. event().
This property holds whether the size grip is enabled.
A QSizeGrip is placed in the bottom-right corner of the dialog when this property is enabled. By default, the size grip is disabled.
Access functions:
Constructs a dialog with parent parent. bar of the dialog, pass Qt::WindowTitleHint | Qt::WindowSystemMenuHint in f.
See also QWidget::setWindowFlags().
Destroys the QDialog, deleting all its children.
Hides the modal dialog and sets the result code to Accepted.
See also reject() and done().().
In general returns the modal dialog's result code, Accepted or Rejected.
Note: When used from QMessageBox instance the result code type is QMessageBox::StandardButton
Do not call this function if the dialog was constructed with the Qt::WA_DeleteOnClose attribute.
Sets the modal dialog's result code to i.
Note: We recommend that you use one of the values defined by QDialog::DialogCode.
Reimplemented from QWidget::setVisible().
Reimplemented from QWidget::showEvent().
Reimplemented from QWidget::sizeHint(). | https://doc-snapshots.qt.io/4.8/qdialog.html | CC-MAIN-2015-48 | refinedweb | 173 | 53.98 |
TinyPicSharer v 1.0.3.4 New Version 08 June 2013
By
wakillon, in AutoIt Example Scripts
Recommended Posts
Similar Content
- By Ascer
Hello,.
- ruslanas402
Greeting, so I've been trying to come up with solution, but no luck. Despite I tried to automate upload function, I released that it freezes after "Choose File to Upload" window appears..
#include <IE.au3> ;#include <_Dbug.au3> Global $oIE = _IECreate("", 1) Global $upload2 = _IEGetObjById($oIE, "the_file") _IEAction($upload2, "click") ;Sleep(1000) $hWnd = WinGetHandle("Choose File to Upload") MsgBox(0, "", $hWnd) Have anybody faced this situation?
btw: srry for the advertise Besides it's no matter which site I'm trying to do this it's all the same. | https://www.autoitscript.com/forum/topic/122168-tinypicsharer-v-1034-new-version-08-june-2013/ | CC-MAIN-2018-17 | refinedweb | 115 | 56.86 |
Ticket #9009 (closed Bugs: fixed)
flat_set.insert() is ambigious
Description
Here is the code:
#include "boost/container/flat_set.hpp"
int main() {
boost::container::flat_set<int> const fs0;
boost::container::flat_set<int> fs1;
fs1.insert(fs0.begin(), fs0.end());
}
This is with C++03 not C++11.
The error is that the call to insert is ambiguous.
This is a regression. It doesn't happing in 1.49. (I think it was introduced by move support.)
I believe the issue is that if the iterators are of the same type, then the iterator pair insert is supposed to be preferred because the template that has both parameters being the same time is more specialized. But with the move semantic implementation macros, the form (const_iterator, value) is only templated on the second parameter so it isn't less specific.
You are right. It was introduced by the move support. I think I have a fix for it. | https://svn.boost.org/trac/boost/ticket/9009 | CC-MAIN-2015-11 | refinedweb | 155 | 60.82 |
hey
I have my wcf service hosted in the iis of the my development server.I am able to directly access the url of the service from both the server and the client browsers.I am also able to see the wsdl generated.
But when i add service reference from Visual studio 2008/2010,i get the following 'There was an error downloading ''.'.
- The request failed with HTTP status 503: Service Unavailable.
- Report from 'XML Schema' is 'The document format is not recognized (the content type is 'text/html; charset=UTF-8').'.
- Report from 'WSDL Document' is 'The document format is not recognized (the content type is 'text/html; charset=UTF-8').'.
Metadata contains a reference that cannot be resolved: ''.
The HTTP request is unauthorized with client authentication scheme 'Anonymous'. The authentication header received from the server was 'Negotiate,NTLM'.
The remote server returned an error: (401) Unauthorized.
If the service is defined in the current
Hi,
I’ve been trying to write some C# in Visual Studio 2008 to leverage SharePoint Web Services. I’ve scoured the web for help on this problem. I’m just beginning to learn .NET programming, but I’ve done a bunch with SharePoint Web Services
with javascript and then with jQuery.SPServices.
If I start a new Console Application project and try to add a Service Reference, I put in my url: …/_vti_bin/Authentication.asmx and try to attach it. It tells me that there’s a problem with the certificate (which I get in the browser and SP
Designer).
I get this error:
The HTML document does not contain Web service discovery information.
Metadata contains a reference that cannot be resolved: ''.
The HTTP request is unauthorized with client authentication scheme 'Anonymous'. The authentication header received from the server was 'Basic Realm="example.com"'.
The remote server returned an error: (401) Unauthorized.
If the service is defined in the current solution, try building the solution and adding the service reference again.
If I click Advanced and Add Web Reference, I try again. This time, the browser window brings up the form we use to authenticate. From what I understand about the architecture, the MOSS
Hello!
System: VS.NET 2010 Professional on Windows 7, targeting framework 4.0
I am developing a Win Forms app. Within my company another developer (he has now left his position) has developed a NET- component with some nice features I would like to use. The component has some references to System.Web. When I add a reference to the component
Compax, I get Intellisense in VS.NET for writing
using Compax.Framework.DataAccess
But as soon as I try to compile I get two errors:
The type or namespace name 'Compax' could not be found (are you missing a using directive or an assembly reference?)
The other one reveals a bit more:
Warning 1 The referenced assembly "Compax.Framework, Version=1.1.10908.1, Culture=neutral,.
So I try to add a reference to System.Web. But it is not in the list, probably since the current project is a win forms app. I can find the System.Web.dll by browsin | http://www.dotnetspark.com/links/33172-problem-with-using-outlook-reference-on.aspx | CC-MAIN-2016-44 | refinedweb | 524 | 67.25 |
Hi,
I got a problem. Imagine my app uses OpenCL but it requires to be compatible with old OSs and computers. The user might use an old driver without OpenCL suport.
Currently, if I link my program with the OpenCL.lib/OpenCL.dll then the dynamic-library reference will make my program impossible to be executed. It's neither possible to use "delayed DLL" calls, because Windows will emit a "Sorry can't find OpenCL.dll DLL" message box the first time you call a clXXXXXXX function.
To solve that, you should add an INLINED function in the OpenCL.h file to know if OpenCL is available. For instance, in case of Windows, it could be like this:
Code :
void inline int IsOpenCLInstalled () { #ifdef WIN32 FILE *f = fopen("$WINDIR\\system32\\OpenCL.dll"); if ( f!=NULL ) { fclose(f); return 1; } return 0; #else /* perform OpenCL runtime detection for other OSs */ #endif }
Thanks. | https://www.khronos.org/message_boards/printthread.php?t=7277&pp=10&page=1 | CC-MAIN-2015-35 | refinedweb | 151 | 68.36 |
Any or all of the parameter-marshalling, body, and result-marshalling statements may be omitted. If they are omitted, Green Card will fill in plausible statements instead, guided by the function's type signature. The rules by which Green Card does this filling in are as follows:
A missing %call statement is filled in with a DIS for each curried argument. Each DIS is constructed from the corresponding argument type as follows:
A tuple argument type generates a tuple DIS, with the same algorithm applied to the components.
All other types generate a DIS function application, Section 9.1. The DIS function name is derived from the type of the corresponding argument, except that the first letter of the type is changed to lower case. The DIS function is applied to as many argument variables as required by the arity of the DIS function.
The automatically-generated argument variables are named left-to-right as arg1, arg2, arg3, and so on.
If the body is missing, Green Card fills in a body of the form:
where
f is the function name given in the type signature.
a_1 ... a_n are the argument names extracted from the %call statement.
r is the variable name for the variable used in the %result statement. (There should only be one such variable if the body is automatically filled in).
A missing %result statement is filled in by a %result with a DIS constructed from the result type in the same way as for a %call. The result variables are named res1, res2, res3, and so on.
Green Card never fills in %fail statements.
Some C header files define a large number of constants of a particular type. The %const statement provides a convenient abbreviation to allow these constants to be imported into Haskell. For example:
This statement is equivalent to the following %fun statements:
After the automatic fill-in has taken place we would obtain:
Each constant is made available as a Haskell value of the specified type, converted into Haskell by the DIS function for that type. (It is up to the programmer to write a %dis definition for the function -- see Section 9.2.)
There's a variant way of declaring constant within the `%const' directive: you may specify the Haskell name that the C constant name maps to:
The %const declarations allows you to map external names/constants onto Haskell Ints. A more typesafe mapping of constants is provided by the %enum declaration, which maps a set of constants to a Haskell type. [1]
For example, here's PosixError expressed using %enum:
This creates the following data type plus marshalling functions:
Additionally, it also implicitly creates a DIS:
In the event you want the Haskell compiler to automatically generate instances for the enumeration type it generates, %enum supports this too:
will generate a data type with the derived instances Eq and Show:
In C, some libraries give all their exported names the same prefix, thereby minimizing the impact on the shared namespace. In Haskell we use qualified imports to achieve the same result. To simplify the conversion of C style namespace management to Haskell the %prefix statement specifies which prefixes to remove from the Haskell function names.
This would define the two functions init and sphere which would be implemented by calling OpenGLInit and glSphere respectively.
It is sometimes useful to be able to write arbitrary lines of C code outside any procedure specification, for instance to include a helper C function or define a C structure. The ``%C'' statement is provided for this purpose:
The C code is added directly to the generated C file. | http://haskell.cs.yale.edu/greencard/downloads/greencard-latest/fill-in.html | crawl-001 | refinedweb | 604 | 57.71 |
Splunk_ML_Toolkit 0.9.1 complains that Python for Scientific Computing is not installed (even after restart). App Splunk_SA_Scientific_Python_windows_x86_64 1.0.0 is installed and shows up in the application list on the manage applications screen. Can someone advise how to troubleshoot?
The scientific flavor of python (on Windows) requires Microsoft Visual C++ 2008 runtime to be installed. After installing vcredest_x64.exe, ML toolkit started working. Problem solved!
If you encounter this problem, please install the newest version of the app(1.0.1) which bundles MSVCRT90.DLL.
The scientific flavor of python (on Windows) requires Microsoft Visual C++ 2008 runtime to be installed. After installing vcredest_x64.exe, ML toolkit started working. Problem solved!
Flagging the Python... app as visible was tried, but this did not fix the problem.
Hi brad! Sorry you are having trouble here. Could you check a couple of things for me?
First, can you confirm that your Splunk search head is running version at least 6.3.0 and running on 64-bit Windows? (and not, e.g. 32-bit Windows 7).
Second, could you go to the "Search" tab in the ML Toolkit and Showcase app and try running the following two searches and report back the output?
| fit
and
| listmodels
Best regards, -jacob
Jacob,
The environment in question is a single instance with the search head and indexer on the same server. If I issue splunk version the response back is "Splunk 6.3.0 (build aa7d4b1ccb80)". The host operating system is Windows 2008R2 Enterprise (x64). | fit returns "fit: Failed to load Splunk_SA_Scientific_Python (Python for Scientific Computing App) ". | listmodels returns "No results found."
Thanks,
John
Great, thanks for trying these two things!
I'm suspecting that the Python for Scientific Computing app didn't install correctly. There are a couple of ways to test this:
(1) Delete %SPLUNK_HOME%\etc\apps\Splunk_SA_Scientific_Python and all of its contents, restart Splunk, and then try to reinstall it.
(2) Open cmd.exe, and run:
cd %SPLUNK_HOME%\etc\apps\Splunk_SA_Scientific_Python_windows_x86_64\bin\windows_x86_64
python.exe
import sys, pandas
sys.exit()
If (1) fixes it, then indeed something went wrong when installing Python for Scientific Computing. If (2) doesn't raise any errors, then Python for Scientific Python is probably installed correctly, and there is likely a bug in the "fit" command that we'll need to track down.
Best regards,
-jacob
Jacob,
Suggestion 1 did nothing. I attempted suggestion two and found that python fails to start. It generated this error in the application event log:
Activation context generation failed for "C:\Program Files\Splunk\etc\apps\Splunk_SA_Scientific_Python_windows_x86_64\bin\windows_x86_64\python.exe"..
John
John, super helpful. Thanks so much for going the extra distance to help diagnose this! I'm glad you found a workaround. Cheers, -jacob | https://community.splunk.com/t5/All-Apps-and-Add-ons/Why-is-Machine-Learning-Toolkit-and-Showcase-0-9-1-on-Splunk-6-3/td-p/203916 | CC-MAIN-2020-45 | refinedweb | 457 | 61.22 |
Join the community to find out what other Atlassian users are discussing, debating and creating.
Hello,
I have a plan that is using a remote triggering via a python scripts:
import urllib;
baseUrl = ''
buildKey = 'GD-DUV'
remoteCall = baseUrl + "/api/rest/updateAndBuild.action?buildKey=" + buildKey
fileHandle = urllib.request.urlopen(remoteCall)
fileHandle.close()
If I launch it from a location without access it receive the ip list message, so I know it reaches the Bamboo server. But after white listing the IP the trigger doesn't start the plan. I am using it as a remote trigger. Can you please tell me if I am doing something work?
Found the issue Bamboo will only accept this remote call if it originated from the IP address of the source control server.
Small update also the rest response is A build of GD-DUV was triggered by remote http. | https://community.atlassian.com/t5/Bamboo-questions/Bamboo-plan-trigger-doesn-t-work/qaq-p/687058 | CC-MAIN-2019-26 | refinedweb | 145 | 56.35 |
Project 1: GUI Design
Project due Monday night Feb 17, 2014
The purpose of this assignment is to start the process of building an interactive visualization system. In the project, you will be adding menus, mouse callbacks, listboxes, and a dialog window to your program.
Tasks
- Add new menu items and key bindings.
- Write a method that clears all the data points. It should have the signature
def clearData(self, event=None):
- Bind the method to Cmd-N. You should model this after the binding of Cmd third mouse button,
- widgets to make it possible for the user to control how many random data points are added.
--Cmd-mouse-button-1 will delete the point underneath it.
- Make it so the distributions dialog box begins with the current values of the x and y distributions as the initially selected items.
Writeup and Hand14project1
Turn in your code by putting it into a Proj1 directory in your private directory on the Courses server. | http://cs.colby.edu/courses/S14/cs251/labs/lab01/assignment.php | CC-MAIN-2017-51 | refinedweb | 162 | 62.38 |
Re: Coexistence with Atom ?
Expand Messages
- View Source--- In rss-media@yahoogroups.com, "Marc Canter" <marc@b...> wrote:
>Atom?
> I vote to support AS MANY ways possible to stay in sync with Atom.
>
> This is critical.
>
> Sam perhaps you could comment on other ways of staying in sync with
I don't really see much more as necessary. However, for completeness,
some consistency in the names of attributes might be worth considering.
Instead of url, atom uses href.
Instead of fileSize, atom uses length.
Again, not necessary.
> Does Atom wanna get into keeping track and officiate over all theseKeep track? yes.
> extensions and schemas or just let the 'marketplace decide'?
>
> :-)
Officiate? no.
Keeping track could be as formal as an IANA registry, or as informal
as a wiki page. Either way, I want there to be a central place where
people can go to find out about other extensions.
> - marcSam is:
>
> YES - Atom has a place for extensions/namespaces. So my question to
> "Atom's role in these extensions?" (i.e. do they care about theshit going
> through the pipe?)Different consumers may care about different things. Tim tends to
look at things at a very low level.
- Sam Ruby
Your message has been successfully submitted and would be delivered to recipients shortly. | https://groups.yahoo.com/neo/groups/rss-media/conversations/topics/195?o=1&d=-1 | CC-MAIN-2014-15 | refinedweb | 213 | 69.58 |
Hi
What you could do is hook up an event handler to LoadedDefaultContent and check if ContentLink is not null or empty (that is what differs a new language version of a page from a new page). And if so copy all values from master language, something like:
[ModuleDependency(typeof(EPiServer.Web.InitializationModule))]
public class PopulateLanguage : IInitializableModule
{
public void Initialize(Framework.Initialization.InitializationEngine context)
{
context.Locate.Advanced.GetInstance<IContentEvents>().LoadedDefaultContent
+= delegate(object sender, ContentEventArgs args)
{
if (!ContentReference.IsNullOrEmpty(args.ContentLink))
{
//For a new language branch will contentLink not be empty
var masterLanguage = context.Locate.ContentLoader()
.Get<IContent>(args.ContentLink,
LanguageSelector.MasterLanguage());
foreach (var prop in masterLanguage.Property
.Where(p => p.IsLanguageSpecific && !p.IsMetaData))
{
args.Content.Property[prop.Name].Value = prop.Value;
}
}
};
}
public void Preload(string[] parameters)
{
}
public void Uninitialize(Framework.Initialization.InitializationEngine context)
{
}
Also take a look at this:
It's an attribute so you can specify content copying on a per-property basis.
Hi Johan
We tried your approach and the ContentLink is always null/empty.
We noticed that this happens on pages/blocks that have [Required] properties.
As we use [Required] to force the content admins to add the required master content, this is not a usable solution.
When we have a page/block with no [Required] properties it fires the twice, with the first time ContentLink being null, and the second being the actual ContentLink ID of the page/block.
I am guessing this is because of the flow of execution.
As we never see the second request in content with a [Required] field, then I am assuming the system attempts to create a blank content type, cannot do so because of the [Required] fields, and so never actually gets to the second call to LoadedDefaultContent which would populate the content.
Are you aware of this behaviour, or are you aware of a work around?
Thanks
Marin Graney
Are there any updates for this?
We have the exact same issue and required properties are not automatically passed through. We can't do anything about it as the data doesn't appear to be there, on the first pass (ContentLink is empty/null), but IS available, on the second pass, to fill in the rest of the properties.
This is for an Episerver 7.5 site.
Hi
When you localise a page/block to a target culture the translatable fields are emptied, and you have to re-enter them.
Is this the expected behaviour?
As a page/block can contain a lot of translatable fields this forces the end user to enter the translation there and then, block-by-block and page-by-page.
Our client would like to globalise content from english to a target culture without being forced to change it, i.e. copy the english content from en-GB to de-DE say, and then allow translation teams to change the english copy to their native tongue at a later date before publishing the content.
It is also easier for their translation teams if they see the original english master copy in the block/page they are going to translate.
If the abvoe is the expected behviour for translating/globalising pages/blocks in CMS 7.1, can we override it so that when you globalise content from one language branch to another the content is copied from the source culture page/block to the destination culture page/block?
Could we achieve this behaviour using workflows?
Thanks
Martin Graney | https://world.optimizely.com/forum/legacy-forums/Episerver-7-CMS/Thread-Container/2013/6/GlobalizationTranslation-behaviour/ | CC-MAIN-2021-39 | refinedweb | 573 | 54.22 |
:
Regex
Regular expressions are a sophisticated generalization of the "wildcard" syntax that users of Unix, MSDOS, Perl, AWK, and other systems are already familiar with. For example, in MSDOS, one can say:
dir *.exe
to list all of the files with the exe extension. Here the asterisk is a wildcard that matches any character string and the period is a literal that matches only a period. For decades, much more complex systems have been used to great advantage whenever it is necessary to search text for complex patterns in order to extract or edit parts of that text. The .NET framework provides a class called Regex that can be used to do search and replace operations using regular expressions. In .NET, for example, suppose we want to find all the words in a text string. The expression \w will match any alphanumeric character (and also the underscore). The asterisk character can be appended to \w to match an arbitrary number of repetitions of \w, thus \w* matches all words of arbitrary length that include only alphanumeric characters (and underscores).
Expresso provides a toolbox with which one can build regular expressions using a set of tab pages from which any of the syntactical elements can be selected. After building an expression, sample data can be read or entered manually, and the regular expression can be run against that data. The results of the search are then displayed, showing the hierarchy of named groups that Regex supports. The tool also allows testing of replacement strings and generation of code to be inserted directly into a C# or Visual Basic .NET program.
The purpose of this article is not to give a tutorial on the use of regular expressions, but rather to provide a tool for both experienced and novice users of regular expressions. Much of the complex behavior of regular expressions can be learned by experimenting with Expresso.
The reader may also find it helpful to explore some of the code within Expresso to see examples of the use of regular expressions and the Regex class.
To use Expresso, download and run the executable file, which requires the .NET Framework. If you want to explore the code, download and extract the source files, open the solution within Visual Studio .NET, then compile and run the program. Expresso will start with sample data preloaded into the "Input Data" box (refer to the figure above). Create your own regular expression or select one of the examples from the list box. Click "Find Matches" to test the regular expression. The matches are shown in a tree structure in the "Results" box. Multiple groups and captures can be displayed by expanding the plus sign as shown above.
To begin experimenting with your own regular expressions, click the "Show Builder" button. It will display a set of tab pages as shown here:
In this example, the expression \P{IsGreek}{4,7}? has been generated by setting options that specify: match strings of four to seven characters, but with as few repetitions as possible, of any characters other than Greek letters. By clicking the "Insert" button, this expression will be inserted into the regular expression that is being constructed in the text box that contains the regular expression that will be used by the "FindMatch" or "Replace" buttons. Using the other tab pages, all of the syntactical elements of .NET regular expressions can be tested.
The Regex class supports a number of options such as ignoring the case of characters. These options can be specified using check boxes on the main form of the application.
Replacement strings may be built using the various expressions found on the "Substitutions" tab. To test a replacement pattern, enter a regular expression, a replacement string, some input data, and then click the "Replace" button. The output will be shown in the "Results" box.
Once a regular expression has been thoroughly debugged, code can be generated by selecting the appropriate option in the "Code" menu. For example, to generate code for a regular expression to find dates, create the following regular expression (or select this example from the drop down list):
(?<Month>\d{1,2})/(?<Day>\d{1,2})/(?<Year>(?:\d{4}|\d{2}))
By selecting the "Make C# Code" from the "Code" menu, the following code is generated. It can be saved to a file or cut and pasted into a C# program to create a Regex object that encapsulates this particular regular expression. Note that the regular expression itself and all the selected options are built into the constructor for the new object:
using System.Text.RegularExpressions;
Regex regex = new Regex(
@"(?<Month>\d{1,2})/(?<Day>\d{1,2})/(?<Yea"
+ @"r>(?:\d{4}|\d{2}))",
RegexOptions.IgnoreCase
| RegexOptions.Multiline
| RegexOptions.IgnorePatternWhitespace
| RegexOptions.Compiled
);
After creating this tool, I discovered the Regex Workbench by Eric Gunnerson, which was designed for the same purpose. Expresso provides more help in building expressions and gives a more readable display of matches (in my humble opinion), but Eric's tool has a nice feature that shows Tooltips that decode the meaning of subexpressions within an expression. If you are serious about regular expressions, try both of these tools!
Original Version: 2/17/03
Version 1.0.1148: 2/22/03 - Added a few additional features including the ability to create an assembly file and registration of a new file type (*.xso) to support Expresso Project Files.
Version 1.0.1149: 2/23/03 - Added a toolbar.
My brother John doesn't like the name Expresso, since he says too many people are already confused about the proper spelling and pronunciation of Espresso. Somehow, I doubt this program will have any impact on the declining literacy of America, but who knows. John prefers my earlier name "Mr. Mxyzptlk", after the Superman character with the unpronounceable name.
For the latest information on Expresso (if any),. | https://www.codeproject.com/Articles/3669/Expresso-A-Tool-for-Building-and-Testing-Regular-E?fid=14574&df=10000&mpp=10&sort=Position&spc=Relaxed&select=2507731&tid=2273586&PageFlow=Fluid | CC-MAIN-2018-22 | refinedweb | 977 | 53.61 |
Re: namespace?
- From: "Scott M." <smar@xxxxxxxxxxxxx>
- Date: Tue, 15 Jan 2008 17:17:29 -0500
"cj" <cj@xxxxxxxxxxxxx> wrote in message
news:eaqL%23H7VIHA.4440@xxxxxxxxxxxxxxxxxxxxxxx
Yes, that helps. Making a namespace look like a web address is just
asking for confusion IMHO but that's life.
What you need to understand is that using what looks like a URL for a
namespace name is not directly related to .NET at all and is also not done
just for web service use.
It is an XML standard per the World Wide Web Consortium (the W3C). The
reason for needing namespaces in XML is because the very nature of XML
allows you to make up tag and attribute names yourself based on the data you
will be passing. If 2 departments within a single company were to be using
XML to represent employee data (for just their department), they each might
inadvertently use the same tag names and/or attribute names. Now, if those
two lists of XML were to get mixed up, it would be very hard to separate
who's data is who's - - namespaces are needed to prevent this from occuring
(because although the tag names might be the same, the xmlns="" value would
be different).
Now, you may ask "Ok, that makes sense, buy why use URL's and not some other
identifier?". Well, what if the two departments were "Human Resources" and
"Accounts Payable", couldn't they just use "HR" and "AP" as the namespace
names? Perhaps, but what happens if this company were to merge with another
company who is also using XML for just the same purpose and that company is
most likely going to have Human Resources and Accounts Payable departments
as well. If the two companies had been using "HR" and "AP" as their
namespace qualifiers, there would be no way to tell who's data was who's.
This is why namespaces are generally specified using URL's, because each
company/organization on the planet is guaranteed to have a unique URL and so
in the first senario above, the namespaces could be:
And, those namespaces would keep, not only those two departments XML data
separate, but when the new company gets merged with ACME, we still can keep
it all straight because the new company's namespaces would look like this:
So what I'm still wondering is why would it matter if you and I both use
the same namespace--or would it? It's not actually telling the client
where to send the request is it?
No. Again, namespaces are not actually resolved by any software, they just
serve as names to group related XML data. As in my example above, it could
be very confusing if your data and my data got mixed up. Namespaces are not
required in all uses of XML because sometimes making "groups" of XML isn't
really necessary, but with web services, they are because there are many
services out there and different services can still result in similar XML,
so we need to keep each service's XML separate from another's.
Does the client know the namespace before it calls the service?
Yes. The proxy classes that are built by Visual Studio (usually hidden
files in the Solution Explorer) will have knowledge of the service
namespace.
Perhaps it does and then it waits for a response to come that says it's
from that web service.
No. Again, namespaces are just strings that identify a group of XML. They
aren't used in web services in this way.
In which case it wouldn't matter if both of us used the same namespace as
long as a client wasn't requesting data from both of us in which case it
would get confused on responses.
True, but your missing the bigger point. Although it *may* not cause a
problem if two entities use the same namespace, the fact is that it *could*
and to eliminate the possibility, we make sure that different services use
different namespaces. It's more of a programming standard than a
programming issue.
-Scott
Scott M. wrote:
A "namespace" looks like a URL, but it is not. In this case "tempuri"
stands for "temporary URI", meaning that it is dummy data that you are
supposed to change.
Namespaces are used in XML (which is the format that your web service
sends/receives data) to organize/group XML tags and attributes. This is
conceptually the same as how namespaces are used in .NET - - to
organize/group classes. The difference being that in .NET, the syntax
uses dot notation (i.e. System.Web.UI) and in XML, namespaces use URI
(uniform resource indicators), such as "".
Although they look like URL's, they are not and they are not meant to be
resolved - - they are just names that you make up to keep your XML tags
and attributes used by your web service organized and marked as belonging
to you.
Generally, an XML namespace should start with the ACTUAL URL of your
company/organization, but again, not so that they can be browsed to, but
because it is highly unlikely that anyone else on the planet would start
their XML namespaces with your company/organization URL. After the
beginning of the URL, you generally add something else that defines what
your web serivice is. For example, my company is Technical Training
Solutions and my URL is. If I were making
a web service that retrieves course ID's from a database, I might use the
following to indicate that all the xml coming back from the service be
"grouped" in the same namespace.
<System.Web.Services.WebService(Namespace:="")>
After adding such a namespace, you'll be able to actually see it used
when you examine the results of your web service call. You'd see
something like this:
<string
xmlns="">012-4A</string>
Hope this helps.
-Scott
"cj" <cj@xxxxxxxxxxxxx> wrote in message
news:usFByT5VIHA.1184@xxxxxxxxxxxxxxxxxxxxxxx
I'm still not getting this. Namespace:="" looks like
a web address and I've opend it but don't understand what it's saying.
Can you try again to explain what a namespace does and why my web
service needs to refer to one?
Also I think this has something to do with the WebMethodAttribute that
we are discussing in my other post. Am I correct?
Steven Cheng[MSFT] wrote:
Hi Cj,
As for the following attribute:
<System.Web.Services.WebService(Namespace:="")> It
is used to describe and decorate your webservice service class(applied
on class level). Certainly, you can use the same one for C# code,
they're the same. Also you can find more properites(that you can set on
this attribute for your service class): #WebServiceAttribute Class
bute.aspx
In addition, to better understand its usage, you can visit the
service's WSDL document (view through yourservice.asmx?WSDL url).
Change the attribute setting and refresh the WSDL document to see the
changes..
--------------------
Date: Fri, 11 Jan 2008 15:07:05 -0500
From: cj <cj@xxxxxxxxxxxxx>
User-Agent: Thunderbird 2.0.0.6 (Windows/20070728)
Subject: namespace?
Newsgroups: microsoft.public.dotnet.framework.webservices
What does the line
<System.Web.Services.WebService(Namespace:="")> _
do in the example below?
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.ComponentModel
'
And why don't I see a similar line in the C# example at
?
.
- Follow-Ups:
- Re: namespace?
- From: cj
- References:
- namespace?
- From: cj
- RE: namespace?
- From: Steven Cheng[MSFT]
- Re: namespace?
- From: cj
- Re: namespace?
- From: Scott M.
- Re: namespace?
- From: cj
- Prev by Date: <%@ WebService Language ="Vb" Class="....
- Next by Date: Re: <%@ WebService Language ="Vb" Class="....
- Previous by thread: Re: namespace?
- Next by thread: Re: namespace?
- Index(es): | http://www.tech-archive.net/Archive/DotNet/microsoft.public.dotnet.framework.webservices/2008-01/msg00077.html | crawl-002 | refinedweb | 1,293 | 71.75 |
Code of Conduct: - Website:
import { getSolidDataset, saveSolidDatasetAt } from "@inrupt/solid-client";so my stupid question, how can I use JSON-LD to get Data and save data in JSON-LD format? thanks a lot for your help
0, which means that the client doesn't expire — where as ESS expires clients after a certain amount of time (configurable)
["authorization_code", "refresh_token"]
Hi, i have a question: I'd like to authenticate to a (REST) API endpoint(s) (written with express.js) with a Solid identity. (Sort of like we authenticate to solid data pods with Solid identity all the time, but instead of data pod it's a custom API). Is there a library to take care of that, server-side?
I've briefly tried out @solid/access-token-verifier (not successful, yet) and maybe somebody knows if it's the right choice and perhaps even has some tips or examples how to use it?
(i also looked at express-openid-connect, but it seems to expect a fixed
issuerBaseURL, which doesn't work in Solid context with many issuers, otherwise it would be a perfect fit)
In other words, we send an authenticated fetch request from our app to the API endpoint (perhaps using @inrupt/solid-client-authn-browser). The API receives the request.
Now, it should look at the
authorization header, do the necessary talking with identity provider, or whatever business it needs to do, and tell us that it's a valid token and return the requester's webId, and clientId, or throw error otherwise.
We need a library that does the part written in italics. If it's already wrapped as express middleware, even better.
Thank you!
I'd like to use it for solid index. It's a little server, you give it a uri, it looks at it and saves relationships (triples) it's interested in (into mysql database). Then others can find you and your things via these relationships, using a ldf server on top of the database.
I have it working (without auth) at the indexed data can be queried at and it's all used by (all in early stages of development).
solid:storagewas indeed one I used (as a basis for then adding things to
solid:publicTypeIndexand/or
solid:privateTypeIndex), and the fact that its presence apparently also can't be relied on ( kinda was the final straw that caused me to give up on further app development for now. So looking forward to your work :)
Following along here but I don't understand this bit:
"If you sign as yourself on your own pod, you already have control because pod owners automatically have control..."
Isn't that what I'm doing every time I sign into any app? In other words, any app I sign in as has full control over my pod? | https://gitter.im/solid/app-development | CC-MAIN-2022-21 | refinedweb | 473 | 56.69 |
This document describes Django’s built-in template tags and filters. It is recommended that you use the automatic documentation, if available, as this will also include documentation for any custom tags or filters installed. %}
Defines a block that can be overridden by child templates. See Template inheritance for more information.
Ignores everything between
{% comment %} and
{% endcomment %}. An optional note may be inserted in the first tag. For example, this is useful when commenting out code for documenting why the code was disabled.
Sample usage:
Rendered text with {{ pub_date|date:"c" }}p> {% comment "Optional note" %}
Commented out text with {{ create_date|date:"c" }}p> {% endcomment %}
comment tags cannot be nested.
This tag is used for CSRF protection, as described in the documentation for Cross Site Request Forgeries.> {% endfor %}
Variables included in the cycle will be escaped. You can disable auto-escaping with:
{% for o in some_list %} ... tr> {% endfor %}
You can mix variables and strings:
{% for o in some_list %} ... tr> {% endfor %}
In some cases you might want to refer to the current value of a cycle without advancing to the next value. To do this,:
...td> ...td> tr> ...td> ...td> tr>
would output:
...td> ...td> tr> ...td> .. %} {% include "subtemplate.html" %}tr> {% endfor %}
This will output a list of
elements with
class alternating between
row1 and
row2. The subtemplate will have access to
rowcolors in its context and the value will match the class of the
that encloses it. If the
silent keyword were to be omitted,
row1 and
row2 would be emitted as normal text, outside.
Outputs a whole load of debugging information, including the current context and imported modules..
Outputs the first argument variable that is not “false” (i.e. exists, is not empty, is not a false boolean value, and is not a zero numeric value). "fallback value" %} {% endautoescape %}
Or if only some variables should be escaped, you can use:
{% firstof var1 var2|safe var3 "fallback value"|safe %}
You can use the syntax
{% firstof var1 var2 var3 as value %} to store the output inside a variable.
Loops over each item in an array, making the item available in a context variable. For example, to display a list of athletes provided in
athlete_list:
{% for athlete in athlete_list %}
{{:
The
for tag can take an optional
{% empty %} clause whose text is displayed if the given array is empty or could not be found:
{% for athlete in athlete_list %}
- {{ athlete.name }}li> {% empty %}
Sorry, no athletes in this list.li> {% endfor %} ul>
The above is equivalent to – but shorter, cleaner, and possibly faster than – the following:
{% if athlete_list %} {% for athlete in athlete_list %}
- {{ athlete.name }}li> {% endfor %} {% else %}
Sorry, no athletes in this list.li> {% endif %} ul>
Template:Athlete list variable.:
Equality. Example:
{% if somevar == "x" %} This appears if variable somevar equals the string "x" {% endif %}
Inequality. Example:
{% if somevar != "x" %} This appears if variable somevar does not equal the string "x", or if somevar is not found in the context {% endif %}
Less than. Example:
{% if somevar < 100 %} This appears if variable somevar is less than 100. {% endif %}
Greater than. Example:
{% if somevar > 0 %} This appears if variable somevar is greater than 0. {% endif %}
Less than or equal to. Example:
{% if somevar <= 100 %} This appears if variable somevar is less than 100 or equal to 100. {% endif %}
Greater than or equal to. Example:
{% if somevar >= 1 %} This appears if variable somevar is greater than 1 or equal to 1. {% endif %} contained within. This is the negation of the
in operator. %}
Deprecated since version 3.1.
{% ifequal a b %} ... {% endifequal %} is an obsolete way to write {% if a == b %} ... {% endif %}. Likewise, {% ifnotequal a b %} ... {% endifnotequal %} is superseded by {% if a != b %} ... {% endif %}.:
Archive for {{ year }}h1> {% for date in days %} {% ifchanged %}
{{ date|date:"F" }}h3>{% endifchanged %} {{ %}
{{ match }}div> {% endfor %}.
Additionally, the variable may be an iterable of template names, in which case the first that can be loaded will be used, as per select_template()..
Support for iterables of template names was added.
{% lorem 2 w random %} will output two random Latin words.late for example:
{% now "Y" as current_year %} {% blocktranslate %}Copyright {{ current_year }}{% endblocktranslate %} %}
{% for country in country_list %}
{{ country.grouper }}
{% for city in country.list %}
{{ %}
{% for country, local_cities in country_list %}
{{ country }}
{% for city in local_cities %}
{{.
Resets a previous cycle so that it restarts from its first item at its next encounter. Without arguments,
{% resetcycle %} will reset the last
{% cycle %} defined in the template.
Example usage:
{% for coach in coach_list %}
{{ coach.name }}h1> {% for athlete in coach.athlete_set.all %}
{{ athlete.name }}p> {% endfor %} {% resetcycle %} {% endfor %}
This example would return this HTML:
José Mourinhoh1>
Thibaut Courtoisp>
John Terryp>
Eden Hazardp>
Carlo Ancelottih1>
Manuel Neuerp>
Thomas Müllerp>
Notice how the first block ends with
class="odd" and the new one starts with
class="odd". Without the
{% resetcycle %} tag, the second block would start with
class="even".
You can also reset named cycle tags:
{% for item in list %}
{{ item.data }} p> {% ifchanged item.category %}
{{ item.category }}h1> {% if not forloop.first %}{% resetcycle tick %}{% endif %} {% endifchanged %} {% endfor %}
In this example, we have both the alternating odd/even rows and a “major” row every fifth row. Only the five-row cycle is reset when a category changes.
Removes whitespace between HTML tags. This includes tab characters and newlines.
Example usage:
{% spaceless %}
Fooa> p> {% endspaceless %}
This example would return this HTML:
Only space between tags is removed – not space between tags and text. In this example, the space around
Hello won’t be stripped:
{% spaceless %} Hello strong> {% endspaceless %}:! %}
For creating bar charts and such, this tag calculates the ratio of a given value to a maximum value, and then applies that ratio to a constant.
For example:late like this:
{% widthratio this_value max_value max_width as width %} {% blocktranslate %}The width is: {{ width }}{% endblocktranslate %}.
Adds slashes before quotes. Useful for escaping strings in CSV, for example.
For example:
{{ value|addslashes }}
If
value is
"I'm using Django", the output will be
"I\'m using Django".
Capitalizes the first character of the value. If the first character is not a letter, this filter has no effect.
For example:
{{ value|capfirst }}
If
value is
"django", the output will be
"Django".
Centers the value in a field of a given width.
For example:
"{{ value|center:"15" }}"
If
value is
"Django", the output will be
" Django ".
Removes all values of arg from the given string.
For example:
{{ value|cut:" " }}
If
value is
"String with spaces", the output will be
"Stringwithspaces"." }}
If value evaluates to
False, uses the given default. Otherwise, uses the value.
For example:
{{ value|default:"nothing" }}
If
value is
"" (the empty string), the output will be
nothing.
nothing." }}
Takes a list of dictionaries and returns that list sorted in reverse order by the key given in the argument. This works exactly the same as the above filter, but the returned value will be in reverse order.
Returns
True if the value is divisible by the argument.
For example:
{{ value|divisibleby:"3" }}
If
value is
21, the output would be
True.
Escapes a string’s HTML. Specifically, it makes these replacements:
<is converted to
<
>is converted to
>
'(single quote) is converted to
'
"(double quote) is converted to
"
&is converted to
& %}
Escapes characters for use in JavaScript strings. This does not make the string safe for use in HTML or JavaScript template literals, but does protect you from syntax errors when using templates to generate JavaScript/JSON.
For example:
{{ value|escapejs }}
If
value is "testing
javascript 'string" escaping", the output will be
"testing\u000D\u000Ajavascript \u0027string\u0022 \u003Cb\u003Eescaping\u003C/b\u003E"..
Returns the first item in a list.
For example:
{{ value|first }}
If
value is the list
['a', 'b', 'c'], the output will be
.
In older versions, a negative zero
-0 was returned for negative numbers which round to
HTML elements created by the linebreaks filter:
{% autoescape off %} {{ body|linebreaks|force_escape }} {% endautoescape %}".
Joins a list with a string, like Python’s
str.join(list)
For example:
{{ value|join:" // " }}
If
value is the list
['a', 'b', 'c'], the output will be the string
"a // b // c".
Safely outputs a Python object as JSON, wrapped in a
tag, ready for use with JavaScript.
Argument: HTML “id” of the
tag.
For example:
{{ value|json_script:"hello-data" }}
If
value is the dictionary
{'hello': 'world'}, the output will be: | https://getdocs.org/Django/docs/3.1.x/ref/templates/builtins | CC-MAIN-2021-39 | refinedweb | 1,364 | 66.54 |
Spent more time than I’ve wanted to today trying to get this to work, and even managed to drag Chafic in with me part of the time. It’s a delicate process, and you can easily screw the whole thing up. Suddenly, I feel good about myself as a human being, claiming that I can create Flash components. Damn straight. EAT IT FLASH, I WIN!!!
“…so lemme get this straight. Your saying that in order for you to feel good about yourself in life, you just need to succeed in creating Flash components?”
SHUT UP, I WIN CHING WONG FONG TONG>>>.jasfjklasjdf.!!!!
:: whips out glock, aims towards celing :: *bang* *bang* *blam*
Yeah, sucka!
11 Replies to “SWC’s Within SWC’s Confirmed: It Works!”
Some Bad Arse: “Well I’ve known that for months… hell, I did it in beta, but thanks for the lively update!”
GOOD FOR YOU, MOFO! I STILL WIN!!!
All your base is belong to Flash MX… HAR HAR HAR…
Why a glock? why not a spoon.. it hurts more…
ROFL! Good combo.
“Because it’ll hurt more you twit!”
Hey Jester,
So what was the problem? I saw your post on flashcoders. I spend a lot of time creating components and never really had the issue you described…so I am curious and also just want to know in case I run into it. In fact I am sure a lot of people are curious :) I don’t want to end up with a headache like you did.
I always just put the components on the second frame of the component (with a stop on the first of course) like the documentation suggests and then compile the swc.
I took the shotgun approach to make it work. Therefore, I’ll have to remove each step one by one to determine what it was that caused it to work, and didn’t work. For now, here’s what MAY have caused it to not work (guesses):
– didnt’ have static var symbolName:String = “MyComponentsSymbolName”; at the top of my class
– didn’t have static var symbolOwner:Object = my.package.ComponentClass; for my createClassObject to work
– one of my classes wasn’t compiling in Flash, but the FLA worked just fine. I think the global Flash class path was pointing to an older base class.
– one of my sub-components used to be a shared library, therefore had Export for runtime sharing. I don’t know why this would negatively affect it as it was exporting, not importing.
The rest were minor things like you said, putting all of your components on frame 2, etc. I’ll post more once I’ve found the culprit, if any.
Oh yeah… abbreviating class paths. Like, you use import your.package.Class, and then later just do Class as an alias to your class. For some reason, it wasn’t being put into the SWC. For now, I’m writing out all of my class paths. Looking at my SWF ASV’d, Flash just puts them all in there anyway…
Yea having just an import statement will not do anything you have to reference the class somewhere in your code.
Well, there are 2 problems with that.
First, this:
import mx.controls.Button
private var my_b:Button;
Does NOT export the Button class you think… it’s using Flash’ intrinsic Button class. That was strike #1.
#2, I thought that this:
import mx.controls.Label;
private var my_lbl:Label;
Exported the class to the SWC, but I don’t know who or what figured that they just wanted for the base class. I consider both of the above explicit references to the class, therefore, Flash should export it, but it wasn’t happening. #2 is iffy, because I don’t know where the problem was in my case.
The problem I’ve had with SWCs in SWCs, is later when you need to have that same “SWC” used by itself somewhere else in your .fla. For example, if you have a SWC with a Button or Combo box component embedded, then you need to use a Button or ComboBox somewhere else in the .fla. This caused *really strange things to happen, and I had to opt out of the SWC within a SWC campaign. I either now compile the source comp (not the swc) in with my SWC, or just document the dependancy.
You might want to ASV (ActionScript Viewer) the source, and see if the #initclip order is changed or not; maybe since Flash see’s the other one, it causes it to be off. I doubt duped classes is the problem, but rather init order.
I’ve been looking around for a while, and I would really appreciate any help you can give me.
I’ve been looking for a way to set the loading order of classes. In other words, I have a class ( lets say scrollPane ) that uses another class ( lets say scrollbar ). I need to set the scrollbar class to load before the scrollpane class, and I’m really stuck. I used to use #initclip, but this does not work in class files.
If there is any help you can give me, I would REALLY appreciate it.
Thanks,
Paul | https://jessewarden.com/2004/03/swcs-within-swcs-confirmed-it-works.html | CC-MAIN-2022-27 | refinedweb | 874 | 81.73 |
Agregado por Arch D. Robison (Intel)
This article covers a topic of interest to both Cilk and TBB programmers. It's about holders in Intel® Cilk and a similar pattern in TBB, which are good to know about when programming with those frameworks. The key point is the difference between "left holders" and "right holders", and the scenarios where each is appropriate.
Two Kinds of Holders
A "holder" in Cilk Plus is a hyperobject for a reduction operation opthat "forgets" one of the values. There are two kinds of holders:
- "left holders", where x op y → x.
- "right holders", where x op y → y.
TBB does not have direct support for holders like Cilk does, but does support parallel reductions using tbb::parallel_reduce, and you can specify either variant of op for the reduction operation. For both TBB and Cilk, op is associative but not commutative. Reducing the sequence a b c ... z results in a for a left holder, and z for a right holder. Here is one way to implement a right holder in Cilk Plus:
#include <cilk/reducer.h> template<typename U> class RightHolder { struct Monoid : cilk::monoid_base<U> { static void reduce(U *left, U *right) { swap(*left,*right); } }; cilk::reducer<Monoid> impl; public: inline U& get_view() { return impl.view(); } };
Method reduce must implement *left = *left op *right, and can assume that *right is never used again. Invoking swap does this, and is more efficient than doing *left=*right in some contexts. In C++0x, using a "move assignment" instead of swap would be natural. A left holder is similar, but with the swap removed. Thus left holders have a slighty efficiency advantage, and work even when type U does not support swap. Earlier I said that reducing the sequence a b c ... z results in a for a left holder and z for a right holder. So if you are using the final result, it's obvious which one to use. However, sometimes holders are used when the final result is notgoing to be used, and only intermediate results are of interest. The next three sections give examples of this use case, and advice on how to choose left versus right.
Pattern 1: Optional Loop Carried Dependence
The pattern is when there is a loop carried dependence that can be optionally removed, but the removal is expensive. Use a right holder to reduce the expense to where it is required for actual parallelism instead of paying it for potential parallelism. Here is a sketch of the pattern, which is quite common in serial programming.
x = initial_value; for( int k=0; k<n; ++k ) { foo(x); x = next(x); }
Assume that it is safe to run multiple invocations of foo(x) in parallel. The only thing stopping us from executing iterations in parallel is the assignment x=next(x). This is called a loop carried dependence. Such dependences can sometimes be eliminated by transforming the code. For example, if next(x) is "x+c", the value of x for the invocation of foo is always foo(initial_value+k*c). Let's generalize this transformation by supposing that we can create a function kth(initial_value,k) that computes the value that x should have when entering the kth iteration. The general transformation is:
x = initial_value; cilk_for( int k=0; k<n; ++k ) { foo(xkth(initial_value,k)); x = next(x); } x = kth(initial_value,n);
When doing this kind of hand transformation, do not forget to compute the last value of x if it is used after the loop. Sometimes kth is much more expensive to evaluate than next, possibly undoing gains from parallelism. The ideal solution will use next when evaluating consecutive iterations, and only use kth when we do not know the previous value of x. For example, in the prime finder example that comes in the TBB distribution, x is a std::vector full of counters that are advanced by various stride values by the foo operation. In that code, next requires doing nothing, but kthrequires doing some arithmetic to compute each vector element. Here's how to implement the ideal solution using a holder. Have a special value that identifies a holder view as uninitialized. It's simplest if that value can be the default value. For example, in the "primes" example , x is a std::vector that is not normally empty, so an empty vector can serve as the special value. Then a right holder does the trick. The general scheme is:
RightHolder<X> x; ... x = initial_value; cilk_for( int k=0; k<n; ++k ) { if( x is default value ) x = kth(initial_value,k); foo(x); x = next(x); }
To see why it is important to use a right holder, and not a left holder, suppose that n==6. The serial execution of the loop can be summarized as shown:
Each ... stands for "foo(x); x=next(x);" In the serial execution, x is never the default value. There are many possible parallel executions of the loop. Here is one to demonstrate why a right holder is appropriate:
Each of the three arrows is a strand of execution. Each strand gets its own view of x. The strand with "k=0" gets the original view. The strand with "k=2" gets a default-initialized view. At the join point, two views reduce to a single view that is used by the strand with "k=4". When that strand executes the iteration with "k=4", it should be using the value of x updated by "x=next(x) for k=3, not the value of x after "x=next(x)" for k=1. Thus the right view should be propagated and the left one thrown away. That's what a right holder does. When I wrote the TBB primes example that uses the aforementioned pattern, I mistakenly used x op y → x for the reduction operation in tbb::parallel_reduce. The error went unnoticed until recently because executions where the reduction value was used were rare.
Pattern 2: Scratch Object
Sometimes in serial loops this pattern arises:
for( int k=0; k<n; ++k ) { ExpensiveToConstructObject x; ...use x... }
If it does not matter in the ... whether the object is freshly constructed, a programmer will often optimize by hoisting construction/destruction of the object, like this:
{ ExpensiveToConstructObject x; for( int k=0; k<n; ++k ) { ...use x... } }
This scenario often arises when ExpensiveToConstructObject is a heap-allocated array that is used for scratch space. Though good for faster serial optimization, the transform prevents parallelization using cilk_for, because concurrent iterations will interfere with each other. What we want is to create a ExpensiveToConstructObjectonly when necessary to prevent interference. Making x into a holder does the trick:
{ LeftHolder<ExpensiveToConstructObject> x; for( int k=0; k<n; ++k ) { ...use x... } }
Each time a strand starts ab initio, it gets a freshly constructed ExpensiveToConstruct object as its view. The view will be carried across subsequent iterations on the same strand. At join points, one of the incoming strands will donate its view for use by the outgoing strand. It does not matter whether it is a left or right holder, because it does not matter what value is carried between iterations or returned by the reduction. However, the reason for choosing a LeftHolder over RightHolder is that RightHolder requires a swap operation that LeftHolder does not. ExpensiveToConstructObjectmight not support a swap operation, or the swap operation might be expensive.
Pattern 3: Detecting a Steal
My blog on detecting theft covered this application of a holder. There I used a left holder for simplicity, but it really does not matter if the holder is a right holder in that blog's example. The reduction is always over "true op true", so it doe not matter which argument op returns. However, Pablo Halpern pointed out to me that a right holder should be used in the following scenario. Suppose that a function spawns work, and after a cilk_sync you want to detect whether there were anysteals. Then a right holder should be used, like this:
void f() { RightHolder<bool> x; x.get_view() = true; cilk_spawn g(); cilk_spawn h(); cilk_sync; if( !x.get_view() ) printf("continuation of g() or h() was stolen\n"; }
If a continuation after g() or h() is stolen, it gets a fresh view of x, default initialized to false. When execution reaches the cilk_sync, the views merge. Using a right holder ensures that the final view will be one of the fresh views, if any were generated. Thus x will be false after the cilk_syncunless no stealing occured.
Summary
Holders come in left and right forms. Right holders can be useful for exploiting optional loop-carried dependences in parallel code. Both left and right holders are useful for optimizing temporary objects used in loops when it does not matter what value is carried between iterations, though left holders have a slight advantage in that case. Though the concepts directly map to Cilk Plus, they also apply to tbb::parallel_reduce. | https://software.intel.com/es-es/articles/left-versus-right-holders-in-intel-cilk-plus | CC-MAIN-2017-17 | refinedweb | 1,495 | 54.63 |
Build Light: Continuous Delivery Meets Reengineering a USB Driver
The DevOps Zone is brought to you in partnership with Librato. Check out Librato's whitepaper on Selecting a Cloud Monitoring Solution.
Continuous Delivery is a pattern language used in software development to automate and improve the process of software delivery. Techniques such as automated testing, continuous integration and continuous deployment allow software to be developed to a high standard, easily packaged and deployed to test environments.
Continuous delivery treats the commonplace notion of a deployment pipeline: a set of validations through which a piece of software must pass on its way to release. Code is compiled if necessary and then packaged by build servers like Jenkins or Bamboo every time a change is committed to a source control repository, then tested by a number of different techniques before it can be marked as releasable.
As a developer you have to monitor the build server after each commit, in order to see if your work has impacts on the upcomming release. The article Using a Raspberry PI to control an extreme feedback device has inspired us to buy a traffic light in the Cleware Shop. We find the idea cool to visualize the results of our commits with a traffic light and see it as addition to the cS Jenkins Bell. The traffic light is a simple USB device that has a green, a yellow and a red led.
Unfortunately, the original driver of the traffic light only support Microsoft Windows and Linux. But many people at comSysto use Apple PowerBooks.That is why we decided to reengieer the driver and put it in an Java API. We monitored the linux driver on an Ubuntu virtual machine with the usbmon facility of the Linux kernel. Usbmon can be used to dump information on the raw packet that is sent during the USB communication of the computer and the USB device, which is in our case the Cleware traffic light.
sudo modprobe usbmon
If you do not want to watch the whole communication between a computer and USB device, a tool called Usbdump helps to view only the communication to a defined USB device. Usbdump is a simple frontend for the Linux kernel’s usbmon facility. Every USB device is identified by a vendor and product ID. In case of the Cleware traffic light, the vendor ID is 0D50 and the product ID is 0008.
usbdump -d 0D50:0008 -u 1
Once the usbdump is started, you can switch on and off the traffic light with the original driver and you will get a similar dump as result of the observation. The dump is compressed a little bit. It only shows the switch on and off sequence of the yellow led of the traffic light.
3.680370 1<-- 6: 8a00 0000 0000 3.686056 -->2 3: 0011 01 11.649153 1<-- 6: 8e00 0000 0000 11.675358 -->2 3: 0011 00 11.681172 1<-- 6: 8e00 0000 0000
As you can see, the switch-on sequence of the yellow LED is 0011 01, and the switch-off sequence is 0011 00. Now, all information is available to implement a driver. The HID-API provides a simple Java API for devices such as USB Devices on Mac, Linux and Windows. It is a very simple API. As you can see in the class diagram below, it only consists of four classes. The ClassPathLibraryLoader initializes the native driver, and with the HIDManager you can access a specific device or list all devices. The HIDDeviceInfo delivers information about the USB device and HIDDevice is responsible for the write operations. The write method of the HIDDevice must be used to write to the USB device. In our case that means, if you want to switch on the yellow light of the traffic light, you have to create a byte array for the sequence 0011 01 using the write method. After the data is written, the yellow light will flash.
We are able to create a very simple Java API for the Cleware traffic light with the help of the HID-API. As you can see in the class diagram below, there is a TrafficLightFactory that creates a TrafficLightImpl instance, which is used to perform operations like switching on and off the LEDs of the traffic light USB device.
You can easily use this API in your own application, you only have to put the following dependency in your Maven POM.xml:
<dependency> <groupId>com.comsysto.buildlight</groupId> <artifactId>cleware-driver</artifactId> <version>1.0</version> </dependency>
If you are using a modern build system like Gradle, you can put the following dependency in your build.gradle:
compile "com.comsysto.buildlight:cleware-driver:1.0"
Here is a code example of how to use the Cleware Traffic Light Java Driver with the above mentioned dependency:
public class TrafficLightFactoryTest { public static void main(String[] args) { TrafficLight light = TrafficLightFactory.createNewInstance(); light.switchOn(Led.RED); light.switchOffAllLeds(); light.close(); } }
Now, let’s come back to continous delivery. We created a small application on top of the Cleware Traffic Light Java Driver, which is called Build Light. It is a watchdog for Jenkins and Bamboo that switches the green LED on the traffic light on when a build succeeds, blinks the yellow light when a build is running and flashes the red light when a build has failed. You can see how it looks like in the following videos:
You can get the Build Light source code from comSysto’s GitHUB repository. The only thing you have to do is visit the link below and unzip the compressed file. It is available for Windows, Mac OS X, Linux and the Raspberry Pi.
Download Build Light artifacts and source
The following Shell commands show how you can install Build Light on Mac OS X:
bzuther@MacBook ~/Downloads$ tar xvf buildlight-0.1-DEV.zip bzuther@MacBook ~/Downloads$ cd buildlight-0.1-DEV/bin bzuther@MacBook ~/Downloads$ ./buildlight
You have to create a buildlight.properties file in the bin directory after you have unzipped Build Light. You define the build you want to watch in this file. Here is an example for Jenkins and Bamboo:
#Jenkins example: build.server=Jenkins jenkins.server.url= jenkins.build.name=Build-Light-Test-Build #Bamboo example: build.server=Bamboo bamboo.server.url= bamboo.build.key=BUILDLIGHT_JOB bamboo.username=zutherb bamboo.password=t0ps3cr3t
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}{{ parent.urlSource.name }} | https://dzone.com/articles/build-light-continuous?mz=38541-devops | CC-MAIN-2015-48 | refinedweb | 1,077 | 54.02 |
Carriage Returning?
Got the app a few days ago and was amazed at how Beautiful Soup was a part of one of the libraries. Decided to import some code I was writing on my computer that downloads some stuff from a certain website, and when my program comes to a line to print out the status of something that's downloading, it keeps updating itself with each new line instead of on a single line like so on my laptop. Is this just a problem with the app itself, iOS, or my program? If it helps, the line is basically this:
sys.stdout.write("\r ...%d%%, %d MB, %d KB/s, %d seconds have passed" %(percent, progress_size / (1024 * 1024), speed, duration)) sys.stdout.flush()
Other than that, this program's great and with my free time, I'm starting to play around with changing some of my programs to work with the UI stuff.
Pythonista's console doesn't support using the carriage return like that. You can clear the current output like this however:
import console console.clear()
ah ok. Thanks! | https://forum.omz-software.com/topic/805/carriage-returning | CC-MAIN-2018-30 | refinedweb | 182 | 69.21 |
I've been waiting for the standard to finalize for quite some time now. Sadly concepts did not make it until the end, but better so as having another broken feature like export.
Most compilers already implement part of C++2011, so there is already the possibility to play around with some of the new language features.
Here are two links that I googled a few weeks ago.
MSVC only:...
Halfway through in most cases, support in gcc is seems to be the most complete.
I read a story about concepts. It took long and still wasn't ready. So maybe we will see it in the future. Also a header-less C++ (like Java) would be a nice feature.
All together, it seems as a bunch of very useful and "right" extensions.
Clang is also progressing fast:
This is not up to date, someone just submitted a patch that implements for range loops.
Also, clang's implementation of the standard c++ library implements almost all of c++0x, whereas gcc's libstdc++ is still missing things such as regexps:
I expect clang to catch up with gcc's implementation of c++0x by its next release cycle (ie the next release after 2.9 which is imminent). I just hope they'll sort the platform dependent bits of libc++ soon, because on linux it still requires to be linked with gcc's libsupc++ to provide exception handling stuff.
I read a story about concepts. It took long and still wasn't ready. So maybe we will see it in the future. Also a header-less C++ (like Java) would be a nice feature.
It is planned for a TR (technical release), please see
They just did not managed to have it as part of the newly released standard.
Page 2?!?
Anyway, here's what I'm looking forward to in rough order:
Auto
(yay, finally! 'var' from C#)
Lambda
(nice for those used to 'scripting' languages like Python; I use closures all the time, much handier than classes)
Initializer lists
Rvalue references)."
Brings to mind the British Member of Parliament who was allotted time to ask a minister about "the decline in the export of merkins?" .... in the debating chamber.
After much research he discovered that a merkin was a 16th century word for a wig ... for the other place humans grow hair!
Similarly puerile ... and charming!
Can someone please explain C++ popularity?
I've worked with a number of languages and I just don't get where C++ sits in the problem space. It's not close to the hardware like assembler. It's not a representation of human concepts like lists. It's not a designed to minimise the jump from human idea to computer language. It's not designed to be a declarative (descriptive) language.. Probability of error and readability in C++ seem to be very poor.
I would even go so far as to say that you could most easily obfuscate code with C++. It effectively allows you to totally hide both the low-level effects and also the semantics of what you're doing really easily.
So why the principle of "simplest language, least error" not given much weight in C++, are the benefits so great? What are they?
The popularity of C++ is easier to explain than the popularity of Objective-C…
Both languages allow you to optimize for speed when you need it. That's why C++ is popular, that and OOP + operator-overloading which allows you to create your own efficient ADTs, for say 3D engines.
Two main reasons:
1) Good compatibility with C. This is important when you want to do systems programming. Most operating systems and system libraries are written in C, so for example, if I want to program in Ada and I need to have the ability to call system library functions, etc., I need Ada bindings. With C++ you can use all C constructs directly.
2) Object-oriented programming model. You can do OO programming in C, but it's a bit more effort and requires discipline and experience. Certain programming constructs are expressed better with OO paradigm. I mainly write C code, however when needed I tend to write C code that uses abstract data types, inheritance and polymorphism. If you have a large team of programmers C++ makes OO programming more formal, this makes it easier for inexperienced programmers to write conforming interfaces.
Personally I'm not keen on C++, I find it too messy and wacky. The language as a whole has too many holes, i.e. it allows you to do things which result in undefined behavior and are hard to debug. I would really like to switch to Ada 2005, however until major Unix platforms (Linux, BSD, Solaris) decide to fully support Ada and provide complete Ada bindings for all their system libraries, I will stick with C.
Thank you for your response - I appreciate it. I am still not convinced.
(1) You can bind to C using lots of other languages. If you're primarily doing high level programming - you shouldn't need to do this often. So I still don't see why we pay the price of C++ just for this reason. Binding to C is done rarely and therefore the effort can be done there .. eg Python to C bindings. The majority of time is spent doing high level coding in a nicer language.
(2) There are lots of other much less hazardous OO languages. Again why use something like C++ to gain the safety and convenience benefits of C++ when the language itself has so many pitfalls that negate these benefits?
I can only conclude that C++ is a macho choice. Like driving manual cars whenin fact automatic or even driver-less cars would be safer, more convenient, but just wouldn't be seen as macho.
I'm still open to ideas ... keep them coming.
C++ was just at the right place/ right time.
It capitalised on C syntax popularity (java, c# in turn capitalised on C++ syntax ) and delivered good natural integration with existing C code / libs.
Other languages / runtimes provide some support for C ABI but none of them can consume C headers directly. This made C++ a natural "upgrade" path for projects that were moving up abstraction ladder.
Current popularity is mostly outcome of that reinforced by excellent tool support (hundreds manyears of optimization compiler research) and availability of libs of all kind (both low and high level).
Actually, when used dilligently it delivers.
It's biggest advantage is that the progammer has a big freedom in deciding how highlevel his/her code is going to be. From the C/asm level to almost java levels with a good library (ask QT devs). And all of this in a single codeset! Most advanced / dangerous features are for use of libs developers, usuall code cruchers will get by by using only a small subset of the language and sticking to usage patterns mandated by the standard lib of choice.
Edited 2011-03-29 23:44 UTC
(2) There are lots of other much less hazardous OO languages. Again why use something like C++ to gain the safety and convenience benefits of C++ when the language itself has so many pitfalls that negate these benefits?
C++ is an industry standard, cross platform, vendor neutral language without a fat runtime (i.e. runs on metal). It will be around long after C# and Java (both vendor specific languages, to varying extent) are gone. C++ is not a lot "worse" than those languages, esp. after C++11, and it will always be faster and have leaner memory profile in practice.
With Qt being LGPL and C++11 coming, C++ is more relevant than ever.
The pitfalls of the language are not really a problem unless you want to make it a problem, i.e. write contorted code. Libraries like Qt mostly eliminate the memory management headaches, which has been the main gripe against C++.
Didn't try yet, but my current assumption is there will be no problems with any of the features.
I would expect Qt to gain some new goodies like initializer lists for containers as the standard gets deployed. Qt can also deprecate some features that are now provided by the language itself (foreach).
Yeh, kind of how they've adopted std::string instead of QString and std::vector instead of QList and std::map instead of QDict???
Why use something standard when you can roll your own.
3. C++ was around when Microsoft was deciding the language to write most of their software in.
Just like Obj-C, which unless picked by Apple would be a yet another language used only by enthusiasts.
To me, C++ is lacking only one feature - a garbage collector. GC isn't only for convenience, it allows more abstract data structures be used in the API. In C++ a function/method may take objects as parameters and return objects but someone has to specify who is responsible for their allocation and, more importantly, for cleaning them. Often, if the object is a part of a larger data collection, or if is being passed between object many times it is simply impossible to decide who should clean it up.
This is why most of frameworks written in C++ still feel like a set of C functions (operating on primitive data) conveniently grouped into classes.
You're right, they are. But that brings another issue to the table:
Many C++ features are not standardized or were standardized late. This led to proliferation of alternative incompatible implementations. That's OK for application code an single libraries but not good for frameworks.
Say, you want to use some imaginary Qt and Boost at same time. But then you find out that one of them requires GC #1 to handle the memory, while the second has standardized on GC #2. Oops!
This is not just about GC, same thing happens when you want to reuse any abstraction in two different frameworks, although here you may have some luck with wrapping or monkey patching.
Regarding garbage collection and objects ownership, shared_ptr and weak_ptr help a ton (and you can have them using boost in pre c++0x compilers).
There's the downside compared to GC that you have to be careful to avoid cycles, but on the other hand the deterministic aspect of it (objects are finalized as soon as no one needs them anymore and not some indefinite time later on) make some things easier than with GC.
I invested several full-time years into Ada 83, and moved some of the code to Ada 95. In my experience, Ada had the pleasant property of minimal debug - if we could get our code to compile, because of the explicitness, it would probably work pretty well.
I rather miss that.
I can't find a reference now (and my memory may be off - if you have a reference pro or con, I'd be much obliged), but I recall that in the twilight of the Ada Mandate, a commission studied what was required to launch Ada as a successful commercial language. The commission recommended that the government invest either $15 million (which would make Ada a success) or $0 million (which would allow Ada to fail), because anything less than $15 million wouldn't achieve widespread success anyway.
Naturally, the government "saved" money by investing $10 million.
The US fiscal crisis distilled.
I don't (have a reference)... but I love Ada. My favorite language but no one uses it. I love the rigid explicitness, even with "pointers", and then there is the surprising power of attributes... just a great language!
Because PL/SQL is loosely based on Ada it's the only thing that makes working with an Oracle database bearable.
My second favorite language is very different in many ways from Ada: euphoria. Again, not an oft-used language. Ah well. For work it's all Java with a smattering of Ruby and Php.
I'll join the OsNews Ada fan-club. I had to use Ada for a project a year ago, and I really loved the language. It managed to include a lot of the higher-level features that C++ added to C -- like an exception mechanism, implementation-hiding, classes and polymorphism -- in a much more predictable and consistent fashion.
The biggest thing that keeps me from actively using it is how verbose and picky it is -- I can't be as rapidly productive in Ada as I can in C++. A great example is string handling. IIRC, strings of different lengths are considered to be different sub-types, and their ranges are considered to be different sub-types. This makes operating on groups of strings More Work than it Should Be -- your code gets bogged-down with lots of specific type conversions (to map the range of one string onto the range of another), any one of which could potentially raise a range error.
In the TIOBE index Ada has been steadily rising since early 2010.
No idea how to explain it..
With C++0x that's definitely no longer true. "constexpr" alone makes C++ a better C. The new strongly typed enums are less error-prone than C enums, templates are less error-prone than function-style macros (IF you use them only like function-style macros - not talking about advanced template voodoo here). Etc.
I only do C-style programming (no OOP, no template voodoo, no STL), and C++0x is clearly superior to C99 for that IMO.
I would even go so far as to say that you could most easily obfuscate code with C++. It effectively allows you to totally hide both the low-level effects and also the semantics of what you're doing really easily.
Yes, it's possible to write code in C++ where you have to look all over the source base to parse a single line of code. However, nobody forces you to write code like this. You can write utterly hard to parse code in plain C, too. The preprocessor alone is worse than anything C++ added.
C++ tends to fill the space of high performance application that still want the syntax niceties so RSI doesn't set in for the developer team. Think any large multimedia production suite or game development kit and its almost always going to be C++ in some form or another. C++ is really different languages to different groups and individuals.
While C is ok for large programs at some point you want your inheritance and virtual functions without the cost of a hash table lookup (like in a higher level language such as python) and well, C++ adds that just-enough syntax goodies to make it worth the added pain of readability sometimes.
But most of the time I'd agree, C is overall the better easier to read language, if only humans never got RSI and man hours were infinite.
Sometimes I think too, C++ can do some clever things that would be arduous to accomplish in C (though always possible). Think the Eigen matrix library for example. Its only competitor is intel's mkl at this point, both C++ template libraries that do lots of compile time optimizations using templates, yet the syntax still looks something like using a statically typed numpy.
Its really quite an amazing library and doing the same in C would require lots of macro magic that would surely turn your code in to a very difficult pile to figure out.
Take a look at how OO in C looks like:...
Or something like this:
#include "utc_date_clock.h"
#include <stdio.h>
/*
Object inheritance hierarchy:
simple_clock (Current time)
|
+-date_clock (Current time + date)
|
+-utc_date_clock (Current date + UTC time)
*/
int main(void)
{
/* Clock object */
utc_date_clock_t uc;
/* Constructor */
utc_date_clock_init(&uc);
/* Calls simple_clock set_time() function */
utc_date_clock_set_time(&uc);
/* Calls date_clock set_date() function */
utc_date_clock_set_date(&uc);
/* Calls utc_date_clock set_utc_time() function */
utc_date_clock_set_utc_time(&uc);
/* Cast to (simple_clock_t *) object pointer */
printf("\n");
/* Calls virtual display() function */
simple_clock_display_rtb((simple_clock_t *)&uc);
/* Calls non-virtual display() function */
simple_clock_display((simple_clock_t *)&uc);
/* Cast to (date_clock_t *) object pointer */
printf("\n");
/* Calls virtual display() function */
date_clock_display_rtb((date_clock_t *)&uc);
/* Calls non-virtual display() function */
date_clock_display((date_clock_t *)&uc);
/* Cast to (utc_date_clock_t *) object pointer */
printf("\n");
/* Calls virtual display() function */
utc_date_clock_display_rtb((utc_date_clock_t *)&uc);
/* Calls non-virtual display() function */
utc_date_clock_display((utc_date_clock_t *)&uc);
printf("\n");
/* Virtual destructor */
simple_clock_free_rtb((simple_clock_t *)&uc);
return 0;
}
atom$ gcc -O -Wall simple_clock.c date_clock.c utc_date_clock.c clocks_main.c
atom$ ./a.out
simple_clock_init() returning
date_clock_init() returning
utc_date_clock_init() returning
30/03/2011 (UTC 12:37:51)
12:37:51
30/03/2011 (UTC 12:37:51)
12:37:51 30/03/2011
30/03/2011 (UTC 12:37:51)
30/03/2011 (UTC 12:37:51)
simple_clock_free() returning
date_clock_free() returning
utc_date_clock_free() returning...
Frankly, I can't see the forest for the trees in that code.
C++ is as close to the hardware as C. One of the core principles of the language is that you don't pay for features you don't use, and you know the cost of the features you do use.
I used C++ in gameboy advance projects.
C++ offers a lot of features over C that improve readability and maintainability, IF used properly. I've noticed that C++ is most often misused by people trying to be too clever instead of just doing the simplest, most obvious thing.
Look up for instance the RAII pattern and think about how much redundant (and error prone) code writing is saves you compared to C.
I also disagree that C is a very good language. For instance, people work around limitations in C by constructing lots of clever things above it, for instance using a lot of clever macros, which are an awful thing to have to rely upon. You don't end up with very clear or even standardized code.
You also have to do everything by hand, such as containers, and everyone does it differently. What's the standard way to make a linked list in C? What's the standard way to emulate object oriented programming? What's the standard way to implement a sorted container?
I could come up with such questions all day.
Another huge advantage of C++ is that a lot of incorrect constructs simply won't compile, instead of resulting into a runtime bug. The weak type system in C just doesn't cut it.
Humbly, I think that's backward. I would argue that writing elegant C is at least as hard as writing elegant C++.
The worst C++-learning disaster I've seen was a Java developer who essentially assumed that all similar constructs in C++ must work like the roughly-equivalent Java features. In particular, he didn't get how constructors and destructors worked, and wasn't interested in learning.
I expect stories like that one are at the root of a lot of terrible C++ learning experiences -- people coming from newer, cleaner languages who aren't prepared for a language with the subtleties and rough edges that C++ has.
No it isn't. There are many C++ concepts that simply do not exist in C. You can code all your life in C, without knowing anything about generic programming, meta-programming, object orientation, functional programming, for example.
The use these paradigms properly requires good developer skills.
Yep, I do agree.
C may not be the best language ever designed, however compared to C++ I don't think C is any worse.
All the things you mentioned about C not having standard containers and algorithms is not a big issue. What people tend to do is write their own libraries, or use libraries provided by third parties.
In fact I can say the same thing about C++, until recently there was no standard way in C++ to use hash tables, or do multi-threaded programming. You had to rely on libraries from third parties. A lot of C++ programmers rely on STL, however quite a few people dislike STL for various reason. So if you tend not to use STL because you think it's flawed and not designed properly, then there is really no good reason to use C++ in the first place.
Yeah, so until recently STL was missing a couple things. It's still a far cry compare dto not having anything at all.
And I would submit that people who dislike the STL are bad programmers prone to reinvent the wheel anyway. There is pretty much no valid reason not to use the STL. There is a lot of bad excuses, though.
Right, so when the speed of linked lists in C vs C++ is the same, however the code bloat due to STL is 200K extra (and grows in proportion to the number of linked list objects in use), you call this a bad excuse not to use STL?
Now take this code size overhead and multiple by the number of different containers in use and the number of container instances and you end up with a hefty bloat.
You're not stating on which compiler, with which compilation options (debug builds don't count) or even how you measure this 200k difference (if you don't strip symbols from the binary it's obviously going to be a lot bigger, but it doesn't count either).
You don't have 200k of container code implementation, that's simply wrong. And don't tell me "prove it" when you didn't even provide any detail as to the origin of that "200k" overhead claim.
Also, either it depends on the number of different container types (non-inline code) or the number of times containers are used (inline code).
Interestingly, a plain C container implementation would either involve inline code, or functions and their overhead would scale similarly.
Bad excuse? You betcha.
Use STL linked list for storing and traversing struct01{int n1, int n2;} data type, note executable size. Then create 10 linked lists, storing struct01{int n1; int n2;}, struct02{int n1; int n2;}, ... struct10{int n1; int n2;} and note executable size.
Done.
Here is the first test as I compiled it, on a 32 bits kubuntu linux using gcc 4.4:
#include <list>
struct struct01{ int n1; int n2; };
int main( int a, char** b )
{
std::list< struct01 > list01 { {1,2}, {2,3}, {2,3}, {2,3} };
for( auto it = list01.begin(); it != list01.end(); ++it )
std::cout << "derp\n";
return 0;
}
I've initialized the list with stuff and printed out something in the loop to make sure it's not optimized away for having no side effect. This gives additional overhead but still a far cry from what you claim, so I don't care.
Compiled with gcc 4.4.1 in i386 code, with optimization:
g++ derp.cpp -o derp -O3 -std=c++0x
The binary weights a whopping 7816 bytes. After striping (with strip -s), it's 5608 bytes.
And now for the second test:
#include <list>
struct struct01 { int n1; int n2; };
struct struct02 { int n1; int n2; };
struct struct03 { int n1; int n2; };
struct struct04 { int n1; int n2; };
struct struct05 { int n1; int n2; };
struct struct06 { int n1; int n2; };
struct struct07 { int n1; int n2; };
struct struct08 { int n1; int n2; };
struct struct09 { int n1; int n2; };
struct struct10 { int n1; int n2; };
int main( int a, char** b )
{
std::list< struct01 > list01 { {1,2}, {2,3}, {2,3}, {2,3} };
std::list< struct02 > list02 { {1,2}, {2,3}, {2,3}, {2,3} };
std::list< struct03 > list03 { {1,2}, {2,3}, {2,3}, {2,3} };
std::list< struct04 > list04 { {1,2}, {2,3}, {2,3}, {2,3} };
std::list< struct05 > list05 { {1,2}, {2,3}, {2,3}, {2,3} };
std::list< struct06 > list06 { {1,2}, {2,3}, {2,3}, {2,3} };
std::list< struct07 > list07 { {1,2}, {2,3}, {2,3}, {2,3} };
std::list< struct08 > list08 { {1,2}, {2,3}, {2,3}, {2,3} };
std::list< struct09 > list09 { {1,2}, {2,3}, {2,3}, {2,3} };
std::list< struct10 > list10 { {1,2}, {2,3}, {2,3}, {2,3} };
for( auto it = list01.begin(); it != list01.end(); ++it )
std::cout << "derp\n";
for( auto it = list02.begin(); it != list02.end(); ++it )
std::cout << "derp\n";
for( auto it = list03.begin(); it != list03.end(); ++it )
std::cout << "derp\n";
for( auto it = list04.begin(); it != list04.end(); ++it )
std::cout << "derp\n";
for( auto it = list05.begin(); it != list05.end(); ++it )
std::cout << "derp\n";
for( auto it = list06.begin(); it != list06.end(); ++it )
std::cout << "derp\n";
for( auto it = list07.begin(); it != list07.end(); ++it )
std::cout << "derp\n";
for( auto it = list08.begin(); it != list08.end(); ++it )
std::cout << "derp\n";
for( auto it = list09.begin(); it != list09.end(); ++it )
std::cout << "derp\n";
for( auto it = list10.begin(); it != list10.end(); ++it )
std::cout << "derp\n";
return 0;
}
It compiles to a vastly bloated binary of 11913 bytes. After striping, it's 9704 bytes.
Horror error messages (at least on GCC) would be one reason to make.
If I can recall properly I managed to generate error messages that were literally half screen size, 80% of which were the typedefs for some obscure implementation specific stuff I saw first time in my life.
Thats my biggest complaint for template libs. They fail to hide implementation details the moment you put a character in a wrong place.
I even recall some tool that user perl magic to turn those error messages into something at least mercifull.
That was few years back though, I don't know what does it look now.
You've got that exactly backwards.
Most C++ features are tools designed to solve specific, recurring problems in C. STL containers save you the trouble of implementing the same container types over and over again ad infinitum. Classes and polymorphism save you having to use nested unions-and-structs with macros to cobble together trees with heterogeneously-typed nodes. Classes, ctors, dtors, new, delete and references also give the developer powerful techniques for minimizing the amount of explicit memory management they have to do. Exceptions provide the developer much more elegant error-handling and state clean-up than return-value checking coupled with explicit in-code clean up.
All of these tools help a programmer to generate more robust code much more quickly than is possible in plain C. They allow the programmer to sometimes defer common grunt-work to the language, which saves time, reduces errors and improves readability. (Well, when those tools are used correctly; then again, sloppy C can have consequences that are just as catastrophic as sloppy C++.)
If you don't believe me, try hacking together a trivial GTK application in C, then do a Qt version in C++ (or if you feel like it, for more accurate results, use Gtkmm and C++). If your results are like mine, you'll notice that one takes a lot longer than the other.
Because C++ is not a single, integrated language. It's C with a bunch of extra tools. | http://www.osnews.com/comments/24578 | CC-MAIN-2016-07 | refinedweb | 4,528 | 62.38 |
*******************************
:mod:`usocket` -- socket module
.. module:: usocket
:synopsis: socket module
This module provides access to the BSD socket interface.
See corresponding `CPython module <>`_ for
comparison.
Socket address format
---------
.. function:: socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP)
Create a new socket using the given address family, socket type and protocol number.
.. only:: port_wipy
.. note::
SSL sockets need to be created the following way before wrapping them with
``ssl.wrap_socket``::
import socket
import ssl
s = socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_SEC)
ss = ssl.wrap_socket(s)
.. function:: socket.getaddrinfo(host, port)])
.. only:: port_wipy
Exceptions
----------
.. data:: socket.error
.. data:: socket.timeout
Constants
---------
.. data:: socket.AF_INET
family types
.. data:: socket.SOCK_STREAM
.. data:: socket.SOCK_DGRAM
socket types
.. data:: socket.IPPROTO_UDP
.. data:: socket.IPPROTO_TCP
.. only:: port_wipy
.. data:: socket.IPPROTO_SEC
protocol numbers
class socket
============
Methods
-------
.. method:: socket.close
Mark the socket.
.. method:: socket.bind(address)
Bind the socket to address. The socket must not already be bound.
.. method:: socket.listen([backlog])
Enable a server to accept connections. If backlog is specified, it must be at least 0
(if it's lower, it will be set to 0); and specifies the number of unaccepted connections
tha the system will allow before refusing new connections. If not specified, a default
reasonable value is chosen.
.. method:: socket.
.. method:: socket.connect(address)
Connect to a remote socket at address.
.. method:: socket.send(bytes)
Send data to the socket. The socket must be connected to a remote socket.
.. method:: socket.sendall(bytes)
Send data to the socket. The socket must be connected to a remote socket.
.. method:: socket.recv(bufsize)
Receive data from the socket. The return value is a bytes object representing the data
received. The maximum amount of data to be received at once is specified by bufsize.
.. method:: socket.sendto(bytes, address)
Send data to the socket. The socket should not be connected to a remote socket, since the
destination socket is specified by `address`.
.. method:: socket.recvfrom(bufsize)
Receive data from the socket. The return value is a pair (bytes, address) where bytes is a
bytes object representing the data received and address is the address of the socket sending
the data.
.. method:: socket.setsockopt(level, optname, value)
Set the value of the given socket option. The needed symbolic constants are defined in the
socket module (SO_* etc.). The value can be an integer or a bytes-like object representing
a buffer.
.. method:: socket.settimeout(value).
.. method:: socket.setblocking(flag).0)
.. method:: socket.makefile(mode='rb')
Return a file object associated with the socket. The exact returned type depends on the arguments
given to makefile(). The support is limited to binary modes only ('rb' and 'wb').
CPython's arguments: ``encoding``, ``errors`` and ``newline`` are not supported.
The socket must be in blocking mode; it can have a timeout, but the file object’s internal buffer
may end up in a inconsistent state if a timeout occurs.
.. admonition:: Difference to CPython
:class: attention
Closing the file object returned by makefile() WILL close the
original socket as well.
.. method:: socket.read(size)
Read up to size bytes from the socket. Return a bytes object. If ``size`` is not given, it
behaves just like ``socket.readall()``, see below.
.. method:: socket.readall()
Read all data available from the socket until ``EOF``. This function will not return until
the socket is closed.
.. method:: socket.readinto(buf[, nbytes])
Read bytes into the ``buf``. If ``nbytes`` is specified then read at most
that many bytes. Otherwise, read at most ``len(buf)`` bytes.
Return value: number of bytes read and stored into ``buf``.
.. method:: socket.readline()
Read a line, ending in a newline character.
Return value: the line read.
.. method:: socket.write(buf)
Write the buffer of bytes to the socket.
Return value: number of bytes written. | https://gitrepos.estec.esa.int/taste/uPython-mirror/-/blame/9b18811951a8a9fff712b300fb481a16c8e61ac4/docs/library/usocket.rst?page=1 | CC-MAIN-2022-40 | refinedweb | 622 | 52.36 |
The name of a constructor method is the same as the name of the class. For example, if we have a class named Dragon its constructor will be named Dragon as well:
public class Dragon{
public Dragon(){
super();
}
}
There are a couple of things to notice here. One is that, unlike a regular method, the first character is upper-case, just like the class name. The constructor name must exactly match the class name. While it is only a convention that classes (and therefore, their constructor methods) start with a capital letter, it is an iron-clad requirement that the constructor name match the class name.
The other thing you'll want to notice is that there's no type given in the method declaration. A normal method (called an instance method, if we want to get formal) has a type provided in its declaration, just as a variable has a type in its declaration:
public void dragon(){ } // Instance Method.
public int dragonCount; // Instance Variable.
public class Dragon{ } // Class.
public Dragon(){ } // Constructor.In the constructor's declaration, there's a scope called out (public) but no type. This is because, as a constructor for the object, it will be returning an object of the type it is a constructor for. OK, that sounds worse than it is. Let's try again...
A Dragon constructor returns a Dragon object. A String constructor returns a String object. That's what it constructs, so that's what it returns. Declaring a type would be redundant:
public Dragon Dragon(){ } // This is NOT correct code, just an example of silliness!
A Subtle Error
If you accidentally have a typo in your program that results in your class and constructor having different names, the compiler will complain that you've got a method without a type declaration. You'll look at the code and say "Hey! That's a constructor. It doesn't need a type declaration! What is my compiler smoking?"
public class Dragon{
public Dragin(){
super();
}
}
Dragon.java:3: invalid method declaration; return type required
public Dragin(){
^
1 error
What's happening here is that the compiler sees that the name of the method is different from the name of the class. Aha, it says, this isn't a constructor since it doesn't have the same name as the class. So it must be an instance method. Hey, instance methods need a type! There's no type! Then it prints the error message.
Note that spelling errors include capitalization. So having a class named Dragon with a constructor called dragon() would cause the same error.
For more about constructor methods, see Multiple Constructor Methods. | http://beginwithjava.blogspot.com/2008/07/constructor-methods.html | CC-MAIN-2020-40 | refinedweb | 441 | 66.94 |
WiPy 2.0 Captive Portal Network Config
- soulkiller last edited by
Hello,
I was trying to implement a captive portal for the initial configuration of the device. I've been found some implementations on ESP8266 and ESP32 boards on the internet and decided to go with the below:
which uses DNS redirection method.
I've faced some issues regarding network library in Pycom ( using firmware 1.15.1 ).
- Ap mode is successfully initializes below code, but I've seen the IP of the board remains 0.0.0.0
- When I connect my android phone to the board, WiFi details in android as -> IP: 1.2.3.5 / Gateway: 1.2.3.4 / DNS: 1.2.3.4 Subnet: 255.255.255.0 , so it is correct I believe.
- On the android chrome when I enter the mock website address (asd.net), the redirection isn't happening.
How it's possible to make automatic redirection to the captive portal, when a client connects to the board, am I missing something ?
import network import usocket as socket import ure ap = network.WLAN(mode=network.WLAN.AP, ssid="wipy" ) ap.ifconfig(id=1, config=('1.2.3.4', '255.255.255.0', '1.2.3.4', '0.0.0.0')) ip = ap.ifconfig()[0] print("DNS Server: dom.query. 60 in A {:s}".format(ip)) # Prints- DNS Server: dom.query. 60 in A 0.0.0.0 udps = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) udps.setblocking(False) udps.bind(('',53)) s = socket.socket() addr = (ip, 80) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(addr) s.listen(1) s.settimeout(2) print("Web Server: Listening http://{}:80/".format(ip)) # Prints- Web Server: Listening regex = ure.compile("network\?ssid=(.*?)&password=(.*?)\sHTTP") set_connection = False while set_connection is False: try: data, addr = udps.recvfrom(4096) print("Incoming data, from : ", addr) DNS = DNSQuery(data) udps.sendto(DNS.response(ip), addr) print("Replying: {:s} -> {:s}".format(DNS.domain, ip)) # Prints- Replying: beacons2.gvt2.com. -> 0.0.0.0 except: print("No DNS") # Web server accepting connections try: res = s.accept() client_sock = res[0] client_addr = res[1] req = client_sock.recv(4096) print("Request:") print(req) client_sock.send(CONTENT) client_sock.close() print() search_result = regex.search(req) if search_result: incoming_network_name = search_result.group(1) incoming_network_pass = search_result.group(2) con = connection(incoming_network_name, incoming_network_pass) if con is True: d = {"network_name": incoming_network_name, "network_password": incoming_network_pass} f = open("config.json", "w") f.write(ujson.dumps(d)) f.close() set_connection = True except: print("Timeout") time.sleep_ms(1000) udps.close()
Thanks in advance
-Baris
Hello,
I released a fully new version (v2.0) of my web server here :.
Open source MIT, fully asynchronous, more robust, more fast and more efficient on Pycom modules.
It is delivered with a good documentation.
For captive portal, you can use a simple DNS server here (see readme) :
Thank you for your support and feedback. ☺️
- Panometric last edited by
@soulkiller , did you get this working? Can you share an example? Thanks.
- soulkiller last edited by
Hello @paul-thornton , thank you for the reply. I've upgraded the firmware to 1.18.2, but still I get the same outputs.
- Paul Thornton last edited by
@soulkiller said in WiPy 2.0 Captive Portal Network Config:
1.15.1
Hello @soulkiller,
That firmware version is rather old now. a ton has been fixed in the networking area in later builds. Try giving this a go under 1.18. (latest stable). Hopefully you'll see better results. | https://forum.pycom.io/topic/4392/wipy-2-0-captive-portal-network-config/?page=1 | CC-MAIN-2020-05 | refinedweb | 572 | 54.9 |
Markception
Go figure. Based upon these instructions from Codeholics, I started to convert MPR using the Python powered Pelican. Pelican did a good job of cleanly processing my WordPress export, and extracting my posts and other content. It looked like I was on my way.
Except my posts are written in Markdown and stored that way in the WordPress database. Which Pelican’s
import function conveniently escapes when it generates Markdown. Sigh.
It may not be the most elegant way, but I think I can work around this with a custom fork of the Pelican source code. At worst, I’ll be flexing some atrophying Git muscles. | https://crossjam.net/wp/mpr/2019/05/markception/ | CC-MAIN-2019-51 | refinedweb | 107 | 66.64 |
Java SE 7: Reviewing JVM Performance Command Line Tools
Overview
Purpose
Java includes a number of tools you can use to monitor your Java Virtual Machine (JVM). This tutorial covers some of the command line tools available to you in JDK 7.
Time to Complete
Approximately 45 minutes
Introduction
Have you ever wanted to get information about a JVM that is already running? Find out things like what command line parameters were used to start the JVM or what was the
main method used to start the JVM?
Java SE 7 includes a number of tools you can use to monitor your Java Virtual Machine (JVM). In this tutorial, learn to use the
jps command and the new
jcmd command to get information about currently running JVMs on a system. Then, use the process information with
jstat to monitor JVM garbage collection activity locally and remotely.
Hardware and Software Requirements
The following is a list of hardware and software requirements:
- Windows XP or Windows 7 32 bit or 64 bit
- Java 7 Update 4 or later
- JEdit 4.5.1 or later
- NetBeans 7.1.2 later
- GlassFish 3.1.2 or later (Included with NetBeans)
- Java DB 10.8.1.2 or later (Included with NetBeans)
Note from the Author: At the time of this writing,
jcmd is not available on all platforms. The OBE was created using Windows 7 64 bit.
Prerequisites
Before starting this tutorial, you should do the following:
- Install JDK 7 update 4
- Install JEdit
- Install NetBeans for Java EE 7.1.2 which includes Glassfish and Java DB.
- Make sure the JDK 7
bindirectory is included in the PATH for the system.
- Click Start > Computer to open the Windows that displays information about this computer.
- From the menu choose System Properties
- From the menu on the left choose Advanced System Settings
- From the Advanced tab, choose Environment Variables
- From system variables, choose the Path variable.
- Add the following to the path:
C:\Program Files\Java\jdk1.7.0_04\bin;
- Start JEdit
- Start NetBeans
- From the NetBeans Services tab start GlassFish. This will start GlassFish and JavaDB.
Using
jps
What is
jps?
The
jps tool queries running JVMs on a system. By default, executing the command lists the JVMs running on your local system. The
jps command reports the local VM identifier (lvmid) for each instrumented JVM.
The examples that follow are taken from a Windows 7 64 bit system running the following programs:
- JEdit - A Java programming editor
- NetBeans - A Java IDE
- GlassFish - A Java application server
- JavaDB - A database Server included with NetBeans
Note: The screenshots used in the examples were not all taken from the same session. Therefore, the process IDs may change from one screenshot to the next.
To start, run the jps command with no parameters.
So based on the earlier discussion we should see 4 JVMs. But why are 5 shown? Because a JVM is created for the
jps command. Note that the lvmid is listed along with a short name for the main method that started the JVM.
The
jps -l command lists full package name along with the main method for that JVM. For a jar file, the path to the jar file is displayed instead
On Windows, the path name for the jar file names can be truncated. See the next option to correct this.
The
jps -m command displays the same information as
jps -l but adds the arguments passed to the main method.
The command fixes the truncation issue and shows the full path to the jar file.
To see the arguments passed to the JVM use the
jps -v option.
Finally, if you don't want to see all that path and class data, use the
jps -q option.
That covers most of the
jps options. You can use
jps to remotely connect to a system. The required configuration and steps are covered later in this OBE.
Using the
jcmd Command
The
jcmd command is new in JDK 7 and provides many of the features of
jps plus some additional information as well. The
jcmd command allows you to query various aspects of specific virtual machines. Examples of some of these options are included below.
Enter the
jcmd with no options.
So the default command returns results very similar to the
jps -m command. The lvmid or process ID (pid), the class name or jar name, and the command line parameters are shown in the output.
Note: Since the
jcmd documentation refers to the process ID as (pid) consider pid to be interchangeable with lvmid for the purposes of this OBE.
If the
-l option is added, the output is the same.
So it appears
jps -l is the default option.
To find out what kind of information
jcmd can display about a JVM, pass the pid along with
help to the command. For example:
jcmd 10672 help
So information about the VM or the garbage collector (GC) can be queried and the results returned to the command prompt window.
To view the version of the VM for the JVM with a pid of 10672:
jcmd 10672 VM.version
Both the Hotspot and JDK versions are displayed.
To view the system properties for pid 10672, use the following command:
jcmd 10672 VM.system_properties
All the system properties set for this VM are displayed. As the example shows, there can be several hundred lines of information displayed.
To view the GC related flags that were applied to a JVM use the
VM.flags option. For example:
jcmd 10672 VM.flags
All the flags used for your VM are shown.
To view the VM's uptime use the following command:
jcmd 10672 VM.uptime
The uptime is shown in seconds. In this example, the VM has been up for 23 hrs.
An example of GC information that can be displayed with
jcmd is the class histogram. The histogram shows which classes are taking up the most memory in the VM. For example, a sample command line might look like this:
jcmd 10672 GC.class_histogram > temp.txt
The results can be rather verbose, so you can redirect the output to a file. Both internal and application specific classes are included in the list. Classes taking the most memory are listed at the top, and classes are listed in a descending order.
10672: num #instances #bytes class name ---------------------------------------------- 1: 54231 7425056 [C 2: 43483 6266344
3: 43483 5924120 4: 4151 4633416 5: 100011 3200352 java.lang.String 6: 4151 3018096 7: 3436 2575680 8: 51021 1632672 java.util.HashMap$Entry 9: 23238 1607400 [Ljava.util.HashMap$Entry; 10: 7913 1412552 [B 11: 17554 966592 [Ljava.lang.Object; 12: 20134 966432 java.util.HashMap 13: 1157 626064 14: 15258 610320 java.util.TreeMap$Entry 15: 18788 601216 java.util.Collections$UnmodifiableMap 16: 4405 533376 java.lang.Class 17: 13295 531800 java.util.LinkedHashMap$Entry 18: 5628 428896 [I 19: 16207 388968 java.util.ArrayList 20: 6121 387432 [S ...
Finally, there is an option to view all the performance related counters on a VM. This example uses the PerfCounters.print option to display all the PerfCounters for a JVM Running GlassFish:
jcmd 7140 PerfCounter.print
Once again the output can be quite verbose so generally you should filter the results.
On Windows, you can use the
find command to filter results. For example:
jcmd 7140 PerfCounter.print | find "java.property.java.vm"
Using the
find filter, only counters in the
java.property.java.vm namespace are shown.
Using the
jstat Utility
There are other command-line tools that can use the pid information generated from
jps and
jcmd. The
jstat command-line tool displays detailed performance statistics for a local or remote HotSpot VM. The
–gctuil option is used most frequently to display garbage collection information.
Note: When using the Concurrent Mark Sweep (CMS) collector (also known as concurrent collector),
jstat reports two full GC events per CMS cycle, which is obviously misleading. However, young generation stats are accurate with the CMS collector.
Before we can use
jstat, we need to get the list of JVM pids on the system. For example:
jcmd
We can use the GlassFish server with the pid of
7140 for
jstat monitoring.
With a pid, the
jstat command with the
-gcutil option can be used to monitor the garbage collector. For example, to display gc information every five seconds use:
jstat -gcutil 7140 5000
From the output, you can see between the third and fourth sample a minor garbage collection takes place. Here is an explanation of columns shown in the output:
P: Permanent space utilization as a percentage of the space's current capacity
YGC: Number of young generation GC events
YGCT: Young generation garbage collection time
FGC: Number of full GC events
FGCT: Full garbage collection time
GCT: Total garbage collection time
The
-gcutil option is only one of many options available for
jstat. For more information, check out the
jstat documentation.
Using the
jstat Utility Remotely
The
jstat command can also run remotely using the
jstatd utility. Note that
jstatd should not be run in a production environment and if security is a concern, running the command locally is preferred.
The first step to use the utility is to setup a policy file in the directory you run
jstatd from. Open a text editor in your home directory.
Name the file
jstatd.policy. Enter the following text into the file.
grant codebase "file:${java.home}/../lib/tools.jar"{ permission java.security.AllPermission; };
Save the file.
Note:The example policy file allows
jstatd to run without any security exceptions. This policy is less liberal then granting all permissions to all codebases, but it is more liberal than a policy that grants the minimal permissions to run the
jstatd server. More restrictive security can be specified in a policy to further limit access than this example provides. However, if security concerns cannot be addressed with a policy file, the safest approach is not to run jstatd and instead use the monitoring tools locally rather than connecting remotely.
Open a Command Prompt window.
To start
jstatd run the utility with the following parameters.
jstatd –J-Djava.security.policy=<path to policy
file>/jstatd.policy
If you are in your home directory and the
jstatd.policy file is located there your command line would be:
jstatd –J-Djava.security.policy=jstatd.policy
The
jstatd server should start. However, no information is displayed to the console.
Now connect to your machine from another machine. For example:
jstat -gcutil 2874@remotehost 5000
You should see output that is the same when the command is run locally.
The picture shows the command run on the same VM using a remote machine running Mac OS X.
Summary
In this tutorial, you have learned how to:
- Query a system for running JVMs using
jps
- Query a system for running JVMs using
jcmd
- Query various performance aspects of a JVM using
jcmd
- Perform command line performance monitoring locally and remotely using the
jstatutility.
Resources
For additional information please visit the following links:
- jps Documentation
- jcmd Documentation
- jstat Documentation
- Java Performance Tuning and Optimization Course
Credits
- Curriculum Developer: Michael William. | http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/JavaJCMD/index.html | CC-MAIN-2018-05 | refinedweb | 1,858 | 65.62 |
Hello Makers,
This Instructable is part of a series of Instructables with the NodeMCU, my previous Instructables shows you how to Interfacing Servo with NodeMCU and lots more. So make sure, you check that first before trying out this. So, let's get started !!
Step 1: Components Needed
All that you need is:
Hardware Required
- NodeMCU
- 10K POT
- Servo Motor
- Bread Board
- Male Header pins
- Micro USB cable
- Connecting Wires
Software Required
- Arduino IDE (with ESP8266 Library installed)
Step 2: Description
About Potentiometer
- A potentiometer is a three-terminal resistor with a sliding or rotating contact that forms an adjustable voltage divider.
- Potentiometers are commonly used to control electrical devices such as volume controls on audio equipment.
- Potentiometers operated by a mechanism can be used as position transducers, For example: In a joystick
Generally Potentiometer is called as variable resistors that change its resistance value (in ohms) when the rotating contact is turned/adjusted.
Therefore, using NodeMCU, we can control the servo arm to a specified position by turning the potentiometer.
As simple as that!
Step 3: Soldering
Solder Male Header pins to the Potentiometer, so it makes the connection to bread board easy.
Step 4: Circuit Wiring
Servo connections:
The Orange wire connects to Digital pinD4.
The Brown wire connects to GNDpin.
The red wire connects to 3v3 pin.
Pot connections:
The first pin is connected to the 3v3 pin.
The second pin is connected to Analog input A0 pin.
The third pin is connected to GND pin.
Step 5: Coding Time
Make sure you include the ArduinoServo library.
CODE:
#include <Servo.h>
Servo servo; // create servo object to control a servo
int pot = 0; // analog pin used to connect the potentiometer<p>int temp; // temporary variable to read the value from the analog pin</p>
void setup() {<p> Serial.begin(9600);</p><p> servo.attach(4); // D2</p><p> servo.write(0);</p><p>}</p>
void loop() {<p> temp = analogRead(pot); // reads the value of the potentiometer (value between 0 and 1023)</p><p> Serial.println(temp);</p><p> temp = map(temp, 0, 1023, 0, 180); // scale it to use it with the servo (value between 0 and 180)</p><p> servo.write(temp); // sets the servo position according to the scaled value delay(50); // waits for the servo to get there }</p>
Download the "POT_NodeMCU.ino" file and open it up in the Arduino IDE.
Then Create a new sketch and paste the code below in the Arduino IDE and hit Upload.
You can tinker with it if you like based on the application, or just use it as it is.
Step 6: Output
Using Serial monitor you can check the output from the analog pin connected to POT.
As you turn the rotating contact the servo arm is turned.
That's all makers!
I hope you liked this, Stay Tuned for more Projects!
Discussions | https://www.instructables.com/id/Control-Servo-Motor-Using-Potentiometer/ | CC-MAIN-2019-13 | refinedweb | 478 | 64.41 |
:
from name in assemblyNames
select Assembly.LoadWithPartialName(name)
One at a time, put the reflection objects representing these assemblies into a, and for each assembly a run through the types c defined in there:
from c in a.GetTypes()
Filter through, keeping each type only if it
a) IsPublic
b) has Any constructor that IsPublic
c) implements ICollection<T> for some T:
where c.IsPublic &&
c.GetConstructors().Any(m => m.IsPublic) &&
GetInterfaceTypes(c).Contains(typeof(ICollection<>))
For those that pass this test, select out their full name:
select c.FullName;.
The C# team needs your help debugging the new Visual Studio 2005 Service Pack 1 Beta . I’ve written about
You’ve been kicked (a good thing) – Trackback from DotNetKicks.com
>> A collection is a type that implements IEnumerable and has a public Add method.
Hmmm!
What if the type derives from ICollection<T> but has a non-public Add method, which is also an explicit interface method.
In such cases, the type might actually use a differently named Add method or require an explicit interface cast. (Eg, priority queue or stack can have enqueue or push, for example.)
Another advantage to examining the interface method if possible is the ability for non-English developers to construct friendlier native language methods for their objects.
Welcome to the eighth installment of Community Convergence . This week let’s focus on two C# Wikis available
>> If an entry in the list consists of multiple arguments to an Add method, these are enclosed in { curly braces }.
To me, curly brackets have always said one of two things in c#: array contents and code blocks.
So it’s a bit confusing to me why you chose curly brackets to indicate parameter tuples being sent to a method, when clearly the logical choice would have been the simple parenthesis:
Plurals myPlurals = new Plurals { “collection”, ( “query”, “queries” ), new KeyValuePair(“child”, “children”) };
Thank you for these comments. A comment related to Wesner’s was also given to me offline: since we have syntax for calling with multiple arguments we could have special support not only for ICollection<T> but also for IDictionary<K,T>. It adds to the complexity but may capture some good scenarios. We’ll certainly revisit it in the design group.
As for the curly syntax for multiple arguments, let it be no secret that parentheses and curlies were both strong candidates. Both are also already overloaded. Omer’s comment outlines that clearly for curlies; however, parentheses are also already heavily used; for grouping, invoking, casting etc. Curlies have the advantage of not falsely suggesting that we have tuples in the language.
Which tools I need to play with LINQ?
You could make it a lot cleaner by implementing a KeyValuePair operator, that creates a KeyValuePair-instance, like in Smalltalk:
var pair = key -> value;
// same as: var pair = new KeyValuePair(key, value);
Then you can remove the curly braces from your initializer:
var p = new Plurals { "mouse" -> "mice", "child" -> "children", "fish" -> "fish" };
>> parentheses are also already heavily used; for grouping, invoking, casting etc.
You mention invoking and this is exactly the situation here – you’re invoking an overload. You can say that the pure mathematical definition of a function dictates that the above pair is a tuple and that the language doesn’t have them, but the fact remains that this is a method call and not a type initialization (I’m talking about only the query/queries part) which would make the use of curly brackets inconsistent with the rest of the language (which uses curly brackets for initialization: anonymous types, collection initializers, array initializers, anonymous methods, etc.).
When implenting ICollection<T> I have also been adding AddNew(T t). This takes the passed item and makes a new copy to put in the array. It would seem this is preferable for a constuction call as I would assume the braced items could be changed later. If the litorals were added with the normal Add() then the complier should complain when the program attemps to change a read only value.
Curious, why not just inherit your collection class (or the abstract version of your collection, if so inclined) from List<T> – and get all this IEnumerable related cool stuff for basically free?
When you identified the ‘collections’ in your framework that did not implement ICollection<T>… why didn’t you fix that?
Is it because inheriting and implementing ICollection<T> is too costly/breaking?
Interesting article.
[syntax niggle]
[question w obvious answer]
Hope this comment proved my cleverness!
Mads Torgersen (have I got it right? you never wrote your full name) wrote last month in his weblogabout
Mads Torgersen (have I got it right? you never wrote your full name) wrote last month in his weblog about
I hate to be negative, but this is a terrible idea. Has Microsoft been looking for community feedback on this?
I can understand now wanting to limit the application of this feature to ICollection<T>, since that interface requires a Remove method, which may not always be appropriate. But, as has already been mentioned, what if I don’t want to use Add as the name of the method to add new items? For example, the Queue<T> class does not implement ICollection<T>, presumably because the Remove method as defined in that interface has no meaning for a queue. And its "Add" method is called Enqueue. But clearly a Queue has the ability to be initialized from a list of items. But since you are only looking for ICollection (and maybe IDictionary), the Queue class will completely miss out on this functionality.
Also, what if I have an IEnumerable class which implements an Add method for another purpose? Imagine if the string class had methods "string Add(char)" and "string Add(string)", that functioned like the + operator. Based on that, the compiler would allow syntax like
new string {"a", ‘b’, "cde"}
But the result would be an empty string. The same would be true for any class which was designed to be immutable but wanted to use an Add method to return combined objects (think something similar to MulticastDelegate). Talk about non-intuitive!
This article indicates that the reason this approach is necessary is because many collection classes don’t implement ICollection<T>. Queue is a good example. It seems to me that the real problem here is that there is an entire set of logical types, such as Queue, to which items can be arbitrarily added but not removed. These types should also be able to participate in this pattern, since there’s nothing about the pattern that requires the ability to arbitrarily remove items. However, these types are missing interface representation in the framework, resulting in the need for the approach described in this article. Instead of hacking up some behind-the-scenes signature binding, shouldn’t this be fixed? You’re already admitted that ICollection was a mistake; can you go a little farther and fix the real hole in this scenario, instead of trying to mask it?
It seems to me that the core of the problem is that the compiler is attempting to assign semantic meaning to a particular member name. C-style programming has never included this concept; the GetEnumerator example cited in this article is the only other example I can think of (the fact that the author notes that most developers don’t even know about this is evidence of how foreign the concept is to most C-style developers). Even the using keyword insists on the IDisposable interface; it doesn’t go looking for a Dispose method all on its own.
This is not simply resistence to change; semantics of member names should remain soley at the discretion of the developer, to determine the best name to use in a particular context (such as Queue.Enqueue). Microsoft should seek community feedback on this issue, and seriously reconsider whether this is the best thing for the future of the C# language.
As a side note, while I don’t feel as strongly about it, I tend to agree with Omer, that parentheses make more sense in context than braces.
Why not create a new interfaces ICollector<T> and ICollector defining only a Add Method. Existing collection interfaces (including ICollection<T>)and classes (including Queue) implementing some kind of add-functionality could be changed to implement ICollector<T> or ICollector. This would not break existing code.
What is a collection? The answered could be: It is a class implementing ICollector<T> or ICollector.
An IPairCollector<T> interface could be used in the same way.
This Is really nice But Need More Examples
Are you sure that GetInterfaceTypes walks up the inheritance tree? Because if it doesn’t and I implement IList<T>, then even though IList<T> implements ICollection<T>, my class won’t show in that query.
I can tell you that we EXTENSIVELY use generic collections here.
Here some examples to my prevoius e-mail:
namespace Test.Normal {
// Sample interfaces and classes without special handling of add-functionality
interface ICollection<T> {
void Add(T item);
bool Remove(T item);
}
class NomalCollection<T> : ICollection<T> {
public void Add(T item) { }
public bool Remove(T item) { return true; }
}
class NormalQueue<T> {
public void Enqueue(T item) { }
public T Dequeue() { return default(T); }
}
}
namespace Test.Enhanced {
// Sample interfaces and classes with special handling of add-functionality intoducing ICollector<T>
interface ICollector<T> {
void Add(T item);
}
interface ICollection<T> : ICollector<T> {
bool Remove(T item);
}
class EnhancedCollection<T> : ICollection<T> {
public void Add(T item) { }
public bool Remove(T item) { return true; }
}
class EnhancedQueue<T> : ICollector<T> {
public void Enqueue(T item) { }
public T Dequeue() { return default(T); }
void ICollector<T>.Add(T item) { Enqueue(item); }
}
}
————————————
using System;
namespace Test {
class Program {
static bool IsICollector(object o)
{ // The test "o is ICollector<>" with empty generic type parameter is not possible.
// This method does it using Reflection.
Type[] interfaces;
Type iCollectorType;
if (o == null)
return false;
interfaces=o.GetType().GetInterfaces();
iCollectorType = typeof(Enhanced.ICollector<>);
foreach (Type t in interfaces){
if (t.IsGenericType && t.GetGenericTypeDefinition() == iCollectorType)
return true;
}
return false;
}
static void Main(string[] args)
{
Normal.ICollection<int> normColl1 = new Normal.NomalCollection<int>();
Normal.NomalCollection<int> normColl2 = new Normal.NomalCollection<int>();
Enhanced.ICollection<int> enhColl1 = new Enhanced.EnhancedCollection<int>();
Enhanced.EnhancedCollection<int> enhColl2 = new Enhanced.EnhancedCollection<int>();
normColl1.Add(1); normColl2.Add(2);
enhColl1.Add(3); enhColl2.Add(4);
Console.WriteLine("normColl1 IS ICollector: {0}", IsICollector(normColl1)); // ==> false
Console.WriteLine("normColl2 IS ICollector: {0}", IsICollector(normColl2)); // ==> false
Console.WriteLine("enhColl1 IS ICollector: {0}", IsICollector(enhColl1)); // ==> true
Console.WriteLine("enhColl2 IS ICollector: {0}", IsICollector(enhColl2)); // ==> true
Normal.NormalQueue<int> normQueue = new Normal.NormalQueue<int>();
Enhanced.ICollector<int> enhQueue1 = new Enhanced.EnhancedQueue<int>();
Enhanced.EnhancedQueue<int> enhQueue2 = new Enhanced.EnhancedQueue<int>();
normQueue.Enqueue(1);
((Enhanced.EnhancedQueue<int>)enhQueue1).Enqueue(2); enhQueue1.Add(3);
enhQueue2.Enqueue(4); ((Enhanced.ICollector<int>)enhQueue2).Add(5);
Console.WriteLine("normQueue IS ICollector: {0}", IsICollector(normQueue)); // ==> false
Console.WriteLine("enhQueue1 IS ICollector: {0}", IsICollector(enhQueue1)); // ==> true
Console.WriteLine("enhQueue2 IS ICollector: {0}", IsICollector(enhQueue2)); // ==> true
Console.ReadLine();
}
}
}
How about using attributes for this? Then you could use an [CollectionAddMethod] and [CollectionRemoveMethod] for example instead of looking for an actual implementation of an ICollection…
Would an Add extension method (new feature in C# 3.0) that was in scope also be accepted by the compiler for collection initialization?
For example (bear with me – I’m new to this stuff), assume there exists a Queue<> class which is IEnumerable<> but not ICollection<> and has an Enqueue method but no Add method. If the following extension method was defined:
public static void Add<T>(this Queue<T> queue, T item)
{
queue.Enqueue(item);
}
would that work? I know in this case it seems an unnecessary method call because Add just wraps Enqueue, but taking it further, it would allow any number of custom Add methods to be added to any collection type and participate in the collection initialization syntax.
Nu ştiu câţi dintre voi au păstrat setarea standard a Visual Studio, şi anume aceea de a-ţi deschide
I like Andres Cartin’s suggestion for Attributes. Feels more flexible.
With curly braces…hmmm looks like PERL!
About the collection initializer: Couldn’t the same thing be accomplished with a constructor like this:
public Collection(params T[] items)
and not have to introduce new syntax?
Collection<String> myStrings =
new Collection<String>("One", "Two", "Three");
Andres Cartin’s suggestion is great !
It looks like Microsoft has taken a big step backwards with LINQ. The syntax/semantics are counter-intuitive and makes readability a great challenge.
Querying function names for the correct funciton to call is a bad idea. I think you should just fix the collections you have found with this query with one of the suggested methods above. What this artical does do is show the power of LINQ, and how its power can be used with reflection for analysis of source code. I think developers are more interested in this power then saving a few lines of code when initializing a collection.
–Falooley
there might be a bit of stupidity in every revolutionary thing but I as a database freak for the last 10-12 years am thinking that LINQ is the worst I’ve seen from MS. it is refering to object data (fields) as if they are relational data(columns). this comes to confuse the already confused c# developer about everything he is supposed to do with a database. well, their RELATIONAL database. we’ve got tons of rubbish sql from our web developers anyway and this now will make things even worse!
Recently I came across a blog post by Mads Torgersen , the project manager for the C# language team at
Thanks again for all your comments. Many of you suggest that we introduce some mechanism (new interface, attributes, special methods etc) to better mark the fact that something "is a collection" and how it should be initialized with a collection initializer.
This does not address the problem we set out to solve, which is to make collection initialization possible on a number of existing classes without modification. The only suggestion I’ve seen that does that is the one about allowing colleciton initializers to make use of Add methods added as extension methods.
We will look at that, but as it is, we are currently finishing up the last bits of coding for Orcas, and can hardly fit any more changes in. Heck we gotta ship at some point. Luckily this is the kind of limitations that we can lift in the next version if the need is there; we are not designing ourselves out of it.
Welcome to the nineteenth Community Convergence. I’m Charlie Calvert, the C# Community PM, and this is
Why do you microsft guys go public with your language design issues just as you go into lockdown. Surely it would be more meaningful to engage the community at a point where their input can make a difference.
LINQ and C# 3.0 have been public since PDC in september 2005, with active forums, blogs, website etc. We got a ton of useful input from the community which has made quite a difference. Welcome to the game 🙂
Sorry for being late.
My personal experience has been that ICollection and the like are not fine-granular enough. The interfaces should be more fine-granular. My rule of thumb is: every interface in the system should have at most one member. Works amazingly since 2003.
Interfaces should more use interface inheritance to provide more flexibility in distilling out certain facets of the functionality.
I totally agree with Oli that a special interface is needed, with the only Add(T item) method.
I don’t really like the proposal of Andres Cartin about attributes, this should be solved with interfaces – interfaces are there and can handle it well.
My own little library includes the IFillable<T> interface with the only method Add(T item). The name (Fillable) isn’t probably the best, ICollector might be an option, but the idea served me very well all the time. There are a lot of scenarios where the only thing that we want to do with a parameter is to add an item to it. Almost everywhere, where we use yield return to return a number of items, we can use a parameter of type IFillable. The only difference is that it won’t be lazy anymore.
Some examples from my own "base class library":
public interface IFillable<T>
{
void Add(T item);
}
public interface ISet<T>
{
bool Contains(T item);
}
public interface IClearable
{
void Clear();
}
public class ListSet<T> : List<T>,
ISet<T>,
IFillable<T>,
IClearable
{
}
public class Set<T> :
Dictionary<T, Object>,
IEnumerable<T>,
ISet<T>,
IFillable<T>,
IClearable
{
…
}
How sad it is that Microsoft doesn’t consider an XML document a collection! For example, it is not possible to us a For/Each block to iterate through each element in an XML document using VB or C#. It is possible to do with XSL.
I’ve submitted a case (SRZ070705000503) about Microsoft’s misconception that everything between the start and end tags of an element is a single element when it is not. That is only true for elements with text content; not xml content (descendants). This case has been escalated for weeks now so I assume that there is some validity to my claim.
XML would be SO MUCH MORE USEFUL if each element (node) could be dealt with individually without affecting the descendants of the element. A good example would be to delete or move an element leaving the descendants as descendants of the deleted or moved element.
Consider an XML document with elements that have an attribute called Approved which can be True or False and you want to end up with an XML document that consists only of the elements with Approved=True using an XPath predicate. Currently, this can only be done by converting the XML to a NodeList which loses the hierarchical structure.
I’ve recommended that the XMLNode object in the MSXMLDOM get a new property called ExcludeDescendants. That property would be False by default in existing applications that don’t have the ExcludeDescendants property so that existing applications would work as they do now. New instances of controls that would be affected such as the XMLDataSource control would have the ability to set that property to True so that individual elements could be manipulated the same way that they can be using XSL.
If Microsoft were to include an XML document as a collection, that would open up many new potential uses for XML which currently can’t be done or require dozens of lines of code to do.
There are plenty of name/value pair collections, now it’s time to provide developers with hierarchical collections!
David
I couldn’t find GetInterfaceTypes, but GetInterfaces seems to do the trick:
from name in assemblyNames
select Assembly.LoadWithPartialName(name) into a
from c in a.GetTypes()
where c.IsPublic &&
c.GetConstructors().Any(m => m.IsPublic) &&
c.GetInterfaces().Contains(typeof(ICollection<>))
select c.FullName
However, it’s interesting that
typeof(Dictionary<,>.KeyCollection).GetInterfaces().Contains(typeof(ICollection<>))
returns False, even though KeyCollection implements ICollection<>. Why would that be?
File this in my learn something new every day bucket. I received an email from Steve Maine after he read
Ultracet and coumadin. Ultracet. | https://blogs.msdn.microsoft.com/madst/2006/10/10/what-is-a-collection/ | CC-MAIN-2018-43 | refinedweb | 3,239 | 53.41 |
Windows 2000 Has 65,000+ Bugs 596
According to a story on ZDNET, Sm@rt Reseller got an internal MS memo that says Windows 2000?
Re:bugtracking and product release (Score:1)
Actually, I've used Microsoft's internal bug tracking system, and it's basically just a cheezy little database comments type frontend they wrote themselves, much like Bugzilla. Of course, it's windoze software, not a scalable, web based thing like Bugzilla.
Bugzilla actually is somewhat better IMO, though the two are about equivalent in most respects. Actually, they're nearly identical in practice. Bugzilla has far superior bug dependency tracking, with the dependency graphs and such, which puts it on top.
Microsoft's "advanced statistical analysis tools" for their bug database are also pretty much describable as "a cheesy excel spreadsheet with the database link business." Nothing fancy or anything.
Re:come on guys (Score:1)
You are the Sys. admin of a big company, and you decide to install Linux with kernel 2.3.42 in a production server (note: this is a development kernel!). Now go ahead and tell that to the upper management. You'll be fired in 60 seconds...
Unlike your example with Mozilla (or in my example - Linux) - those bugs are NOT being published. MS doesn't tells you "ahh, with IIS 5.0 we got this error and that error" - you'll find that when you have BSOD or your system won't work well..
In Mozilla or Linux - you got a bug list (in the Linux example - check Alan Cox TODO list to see what I mean) - so you know whats right and whats wrong. With MS Win 2k - nada.
And this, my friend, is the difference..
Re:Windows 2000 has over 63,000 bugs (corrected) (Score:1)
From my past experience, I know that MS underestimate bugs, so I really think that "potential issues" are bugs. Maybe not a serious ones, but still - its bugs..
Re:In fairness (Score:2)
There is an extra name given to anything that is actually serious (such as any form of broken functionality, security related or crashes) called showstopper. The stuff that goes into the bug database can refer to anything from , "there is a mispelling in this spec" or "overactive assert in the debug build" to the showstopper class bugs. On shipping, there were no showstopper bugs, which was the criteria.
In the end, I suggest people use the product for a change, and see for themselves that it is quite stable.
Re: bugs in OS not dangerous ???!!! (Score:2)
And still the everything works quite well... I get my salary every month even though my bank is using MS products.
Don't be too sure about it -- banks don't run any of their actual operations on Windows. If they will switch to Windows in some "upgrade", handled by the next generation of managers, we will all start having a lot of questions, where are our money.
Re:Spelling. (Score:2)
I'm a linux user
No, you are not...
- it's great for me as a SysAdmin, wonderful server platform for internet applications, and so on. But desktops? Bullshit. Come back when you've got a productivity suite HALF as good as MS Office, or even WordPerfect.
^^And that was the proof -- WordPerfect runs on Linux, troll.
The appropriate place to run Win 2000... (Score:2)
New XFMail home page [slappy.org]
Re:In fairness (Score:2)
On the "betatest" newsgroups, there are literally thousands of posts with testers posting what they consider "bugs" which, in my opinion, are nothing but "niggly" things that doesn't deserve any attention.
I think this is a really good example of where open source has some advantages. Little "niggly" things get fixed by the person they're "niggling".
;-)
Re:In fairness (Score:2)
--Chris
If you are going to be pedantic (Score:2)
--
I agree but... (Score:2)
--
difference (Score:2)
--
Re:Spelling. (Score:2)
Re:Good poll? (Score:2)
Re:for every bug you find (Score:2)
6,535,000 cockroaces ain't all that bad. They're crunchy, full of protien, and just add milk!
Fool. (Score:2)
(Note: hit the link on the comment ID number and you can see it's moderation history.)
why am I not surprised? (Score:2)
___
Re:Not shocked (Score:2)
windows 2000 hasn't even been released, redhat's bugzilla tracks bugs through about 6 releases.
i know the pundits refer to linux as "new and untested," but a significant percentage of w2k code is completely new and unproven in a production level environment.
What will they say next? (Score:2)
Only three weeks ago, I attended a seminar hosted by a company selling "fireware solution" which runs on NT. The speaker was telling us that their "solutions" will run on W2K.
In the Q & A session, I asked the speaker if the company has any plan to port their wares into Linux, and you know what that guy said to me?
"We have no plan to port any of our product to Linux, and we will never do so, because Linux is too buggy."
Yeah, this is exactly what the guy (supposingly the CEO of the company) said, and his company was supposed to be one of the "biggest NT supporter" in Asia.
With W2K having over 28,000 "features" that may give them "real problems", I truly wonder what the guy will say next.
On the relatively 'bright side' (Score:2)
However, there are an estimated 28,000 Real Problems (TM) still in the software. This, is still quite disheartening. I for one am delaying deployment of Windows 2000 Professional on workstations until it's reported that the final version (give or take 4 service packs) is relatively stable.
And for all you IT managers out there, make sure you develop a stable method of deployment before updating all your NT 4.0 boxen, unless you want to deal with a huge heap of problems. Use common sense.
--
Please note (Score:2)
Also Microsoft has a history of saying that things anyone else would call a bug is not a bug.
Glad I am not planning to use this...
Cheers,
Ben
Re:How many bugs are in Linux? (Score:2)
When you say linux, what do you mean? Is linux just the kernel, the GNU binaries as well, or the entire distrobution?
See it's hard to say what linux IS. Some distrobutions have more bugs than others, and some kernels have more bugs than others. Also add to the fact that linux is being developed and debugged 24/7 worldwide. Look at the developer map on and see what I mean.
I can assure you from working on many projects, some open source some closed source - that linux's development cycle can't be held to the same pattern as MS windows, HP UNIX, etc. Linux is a distributed and large development effort with massive talent and harsh peer review. I wrote a small piece of code that was bug free. ( Very small i.e. near useless code is the only code that can bug free. ) And I still got email about a possible buffer overflow that could happen when the library was used with 'application X'.
Don't try and see releases as linux as a finished product, instead view it as a work of art - always adapting, always changing, always improving...
Re:Debian appears to have 10,000 (Score:2)
The current list of "release-critical" bugs (that is, bugs that must be fixed before release, is available from here [debian.org].
Of course, there is a huge fluff factor here. Debian uses the bug-tracking system to track things that aren't really bugs, there are bugs that weren't really bugs, and so on.
Re:Debian appears to have 10,000 (Score:2)
True, but a very high proportion of the bugs in Debian are with "non-core" parts of the distribution (things that wouldn't be distributed with a Microsoft OS). Many bugs are just users being "niggly" as well. A significant number of "bugs" are in fact proposals for policy changes. Not much difference in fact (except that Debian doesn't hide the problems).
Also, Windows 2000 has some HUGE features that debian doesn't have, like Active Directory.
Debian has some huge features that Win2000 doesn't have, including a complete development environment, full server functionality, lots of powerful applications, etc. etc. etc. The upcoming Debian release will span 4 CD's of binaries. Big as Win2000 is, if you take all the code that Debian distributes, Debian is far bigger.
But these comparisons wouldn't be possible except a memo happened to fall into ZDNet's hands. Wouldn't it be nice if Microsoft made its bug tracking database public?
Re:In fairness (Score:2)
I really really doubt this is actually true in the large sense. First, there are non-programmer users who simply can't fix the bugs (yes, they must be eliminated like the worthless deadweight they are, because knowledge of C is the only skill worth having). Secondly, there are technical users like me who simply don't care about having their own little private code fork that has to be maintained separately (if the original source was kept around at all) who have a very much accurately-formed impression that a diff from Joe Random Luser will be ignored, and generally don't feel like going through the bureacracy of whatever ad hoc QA system, if any, there might have been set up. KDE's bug reporting system is illustrative here: you must send an email that you must hand-format, with a module name that you must guess at, and you get a nastygram if it doesn't fit the formatting criteria. God forbid you get an actual response.
Yes it's possible to fix it yourself. It just hasn't become any less of an irksome chore.
Re:A suggestion to Microsoft-emulate commercial Un (Score:2)
Was NT ever ported to SPARC? I can't imagine anything would ever make Sun happier than a working port of NT to SPARC hardware. Sun considers Solaris as a loss-leader, it just continues to flog it because NT's scalability has always ben too laughable for the big servers Sun wants to sell. That and McNealy's ego.
Re:No thanks. (Score:2)
Microsoft's Bugtracking System... (Score:2)
Re:Microsoft's Bugtracking System... (Score:2)
Re:Oh, stop being so predictable (Score:2)
I hope you are not confusing it with the "Slashdot Community." I would dare say that a large number of real linux hackers have great disdain for slashdot, for a long list of reasons including those you mention.
Make sure you are disgusted with the right people for the right reasons.
Re:Spelling. (Score:2)
I don't want to pick on Linux but I hate being on the receiving end of this sort of thing.
Q: Your software breaks when I do X.
A: We never do X. You are weird. Don't do X. Now go away.
There were many deficiencies in early UNIX kernels, mostly in error checking/recovery and algorithms that scaled poorly. At the time, there were legitimate reasons for it. It was a research operating system that had restricted resources, keeping things simple was important. That was 25 years ago.
Today, I can think of no good reason why a modern operating system should not be able to handle very large numbers of threads/processes/sockets/files without crashing or exhibiting pathological behaviour. Fast and small is nice but not at the expense of reliability and scalability.
Nothing against you... (Score:2)
Hah (Score:2)
That being said, I might argue that some of the recent pressures behind Linux's (and other Open Sourceish products) recent popularity is symptomic of a reversal process (just a hint of it). Though Open Source is not the answer per se (and I doubt it ever will be), it indicates that at least some customers and businesses are growing tired of MS's (et. al) antics, considering alternative solutions, and "Open source" software is, unfortunately, one of the few alternatives that still stands. It has little to do with the fact that Linux is "free"; many have come to realize that software isn't an end unto itself--it is a means to an end, merely a tool to be used. It is a tool that doesn't wear out, and hence doesn't need to be upgraded every year. As a result, software can, and should, become more STABLE and CONSISTENT. This allows companies to cut down in costs in many ways. Not only do they not need to buy new software and licenses, but they don't need to upgrade computers so frequently either. In addition, this kind of stability allows the employee to become more familiar with his OS/Applications, further cutting support costs and improving efficiency. Likewise, a more stable feature set would allow the software the time to develop such that it actually performs as it is supposed to (every tried embedding documents often? mail merge? Connecting to a windows network (netbios) over dialup and TCP/IP...)
Most companies care little about how much MS (et. al) sells their software and licenses for (even though they're overpriced by most any measure). Nor do they care if the software is propietary (not "free"), for its own sake. It is the secondary and tertiary costs (e.g., support, HW upgrade, employee efficiency, etc.), some of which I mentioned earlier, that cost them dearly. Though most companies have not yet reached the point where they refuse to buy MS, there is definetly significant discontent emerging. Maybe not this year....maybe not next year, but Microsoft can't keep pumping out their same shit indefinetly...
Fixing all bugs? (Score:2)
----
Re:Oh, stop being so predictable (Score:2)
Just because it's "beta" doesn't mean it doesn't work. Just because something has "bugs" doesn't mean they affect you and your configuration. Windows 2000 is very stable by any standard.
----
Re:Customer report == real bug until proven otherw (Score:2)
* Customer reports bug.
* Technician/Developer tries to duplicate bug, and fails.
Besides, not all bugs are "debugged" by fixing the software. Some bugs are marked for workarounds, others become warnings (don't use this with that), and so forth. Unless you have unlimited funds and unlimited time, you can never "fix" all bugs.
(By the way, the "infamous" Chevy Nova actually sold just fine in Latin America. The urban legend that it didn't arose later.)
----
Re:No thanks. (Score:2)
Windows 2000 is the most stable "dot zero" Microsoft release I've ever seen. This report of 65,000 bugs is completely divorced from any reality.
Windows 2000 isn't for the home desktop user anyway. Windows 2000 is for corporate networks, and with some exceptions, only makes sense when it's networked together with other Windows 2000 machines.
----
Re:Showstopper is a flexible term... (Score:2)
----
Ok... (Score:2)
Is that an improvement though? (Score:2)
How does it compare to win98? how about to win98SE?
They're all buggy, and we all know that.
So is it getting much worse withW2k, or is it getting a little better, or is it about the same as the others?
--
grappler
Re:Good poll? (Score:2)
Pope
Another nail in thier coffin. (Score:2)
Micro$erf: So, when are you upgrading to Windows 2000?
Me: When you get the 65K or so of bugs out of the code.
Micro$erf: First service pack will take care of that - a month at the outside. Upgrading then?
Me: Um, no. I'd have to get rid of all the Alphas we rolled out for NT4 first.
Micro$erf: Ouch, tough luck. Want me to call Dell for you? $25K gets you the equivelent -
Me: -of a $10K Alpha.
Micro$erf: Heh, um yeah. But Windows 2000 has Active Directory!!! Dynamic DNS!!! We'll reduce your TCO to new lows, especially for your workstations!!!
Me: Even the Macs?
Micro$erf: Macs? Why would you want a dead architecture?
Me: 'cause we're in publishing.
Micro$erf: Oh well, Macs can get files, and they can print, that's all they need.
Me: K. If you say so. I read in the initial stages of Win2K that it would do MacIP - where is it?
Micro$erf: Upcoming feature. It'll probrably only be $49 or so per client, too. Isn't that wonderful!!!
Me: Beautiful. Really. Y'know, lately I've been playing with Linux, and-
Micro$erf: OH GOOOOOD! We've got another add on for unix-type machines, since we're supporting choice these days.
Me: So they get to participate in Active Directory?
Micro$erf: No, but it helps you migrate NIS into AD. You get to use all the familliar Unix utilities, and you can migrate to NT at your leisure from those nasty old legacy systems. For 149$ a server, you can't go wrong.
Me: Sure, what ever you say.
Micro$erf: See we figured it out and you'l only have to spend umm.... $75K to upgrade. Of course, we didn't include all the new Servers, network switches, WAN upgrades and wasted hardware in that price, but why worry about that?
So when can we expect you to order?
Me: (puts on red fadora, picks up stuffed penguin)When you get out of the psyciatric ward.
Re:HAHAHAHA!! (Score:2)
Gee.. where have I heard that before?
Don't be silly (Score:2)
Only 25000 bugs? (Score:2)
Unsurprised (Score:2)
Programming a system, without Engineering it, works well for certain types of evolving systems. Linux, web sites and prototypes change to quickly to Engineer, but trying to "just type in the code" for a major, static system like the autopilot for a aircraft is murder.
So what I'm saying is, as long as we Program a system and then expect to "freeze" it there will always be orders of magnitudes more bugs than we would like. If we keep insisting on not Engineering software there are only two solutions to making Programmed software more robust:
1) Fix it yourself, as in the Open Source model
2) Pay someone else to fix it, which usually means bying the next "upgrade" cleverly disguised as N-3 bug fixes and 3 new features.
Engineered software costs more to build but costs far less in the longer term. Just look as far as the nearest book on software engineering.
So the question is, why do we tolerate 65,000 bugs? Do we feel responsibly for not paying them enough to fix it? Do we feel bad we can't edit the source for them? Or are we just ashamed we keep buying their crap even if it isn't what we, as Consumers, want?
Re:In fairness (Score:2)
Sure, that's fair, and I'm glad to see this post is being moderated up. On the other hand:
As a coder, I'm not going to go liberally sprinkling my code with "BugBug" comments. That's reserved for something somewhat serious and important. Maybe Microsoft policy is different however. Still, 27,000 things Microsoft's coders think is important enough to mark as a bug, yet Microsoft feels the product is ready for release?? Wow!
oh! I see! (Score:2)
Bugs only get fixed if people care enough to fix them, non-critical bugs might not get fixed.
[ c h a d o k e r e ] [dhs.org]
Never mind (Score:2)
[ c h a d o k e r e ] [dhs.org]
wow (Score:2)
[ c h a d o k e r e ] [dhs.org]
Re:Bogus article (Score:2)
I'll name one of them! (Since I entered at least 3 bugs into that database once-upon-a-time... I've been there...)
It goes something like this:
Title: License Plates out of Date.
Description:
Car has out-of-state plates. Get new ones.
Repro: Look at front and rear of car.
Status:
Resolved - won't fix
Reopened
Postponed
Closed as fixed
Reopened - Assigned to new team member from out of state...
Postponed.
...
Etc etc etc... so on and so forth
(As for the other 62999, I have no idea... but a large number of them are most likely bugs that can't be fixed, because fixing them would break existing applications - such as the "Tab control when positioned with tabs running vertically will not return correct dimensions of space remaining" one that I filed about a year ago...
The thing is, it can't be fixed... apparently (though I never got one of the NT team to tell me how the info could be used), the values it returns are deterministic, and as such, someone could have come up with a calculation to work around the problem, and as such, fixing it would break existing apps.
This is the way it goes, folks - a lot of bugs get entered and can't be fixed because they'd break compatibility with some olde Win3.1 app or something.
Shame really.)
Simon
The Tao of Programming (Score:2)
From The Tao of Programming by Geoffrey James [demon.nl]:
Re:In fairness (Score:2)
65000 bugs is nothing compared to public mentality (Score:2)
The way mass merchandised software is produced today, the public just swallows it, because it's NEW!
"Windows 2000, I have to have it"
I remember back several years ago, when this new revolutionary Windows 95 was being released, people were floccking to the stores getting in line so they could have it FIRST.
Do THESE people care how many bugs there are?
I've always had a beef for commercial software. It was ORIGINALLY designed to be a shortcut for those who didn't know how to code the application themselves.
Now it's the norm...
Now, I can sit in a Technical Support Cubicle in the Cubicle Jungles of a not-so-small software organization based in San Diego [intuit.com] and listen to people whine and complain about what this Software [quickbooks.com] can or can't do.
The only think I can think of, but cannot say, is "Well, this is software that you bought, of course it is not going to do what you want, because YOU didn't create it."
(That was probably off-topic, but I digress)
Back to WIN2K. Like some of the above write-ups are stating, the public will not care if there are PUBLISHED bugs, defects, etc.
There will STILL be people lining the malls, shopping centers, and Software Outlets just to get this defective, bug filled Operating System on their machine.
Just because, the computer public is the computer public. They eat this stuff up and complain about it later.
Bill Gates.... he's a genius, he has marketed to the Lowest Common Denominator.
*Carlos: Exit Stage Right*
"Geeks, Where would you be without them?"
Debian appears to have 10,000 (Score:2)
65,000 outstanding items for W2K seems high, but it's not outrageously high - it's two or three times higher than I would have expected, but that could simply indicate very enthusiastic testers.
I'm *far* more concerned by the hints that suggests the bugs are no longer seem to be orthogonal - service packs are introducing as many bugs as they fix. *That* suggests that the code is on the brink of becoming totally unmaintainable, a very real possibility with a large code base that pretends to be tightly integrated.
Re:I was in "QA" too... (Score:2)
Actually, I didn't read it as a bash, nor was I trying to bash Microsoft myself. Mine was comments based on some time I spent working at Microsoft (actually, DreamWorks Interactive, who is 50% owned by Microsoft--but the work was done at the Microsoft campus).
The two don't mix. While you can have a project that has elements of both, you can't call a system that relies heavily on ad-hoc testing a formal system.
That's not what I was trying to describe. What I was trying to describe was a process which has a formal test plan and formal testers who run through a formal script, combined with automation which can perform certain elements of a formal test plan in an automated environment, combined with testers who were also encouraged to "bang on it" within certain parameters. (Read: "Charles, you're in charge of banging on the ODBC Control Panel as well as performing pages 303-306 of the scripted test plan.")
That is, they use a formal test plan written at the start based on the formal specification of the product, but they also encourage their testers to "play with the project" as well as executing the formal test plan.
As to "beta testers", Microsoft calls them "customers." (Okay, I know--cheap shot...)
Integration has nothing to do with it. Complete specifications with the time to execute tests based on them is the whole issue -- it always has been.
Normally I'd agree. However, it seems to me that once a project reaches a certain level of complexity, due to the O(N**2) nature of certain types of interactions inside a "black box", the amount of time required to execute tests based on a complete test specification may grow to be in the dozens or even hundreds of years.
With Microsoft's Windows 2000 product, a number of the "modules" inside the black box are coded as
So integration *does* have something to do with it: it defines how complex the product's possible behaviors will be, and that ultimately defines how complex the test plan will have to be to completely test the product.
Now if they built this thing in a fault-tolerant fashion, in the way firmware is built for an airplane, they'd build it as a collection of independant modules which use well-defined protocols to communicate with each other. Then the testing reduces to an O(N) problem of testing each module and testing to make sure it communicates correctly with the established protocol.
My guess: Most of the formal group gets dragged into ad-hoc testing --or-- they have incomplete tests based on incomplete specifications that they 'sign off' on when marketing, production, upper-management-in-other-areas, decides that there has been enough testing.
Based on my experience, it'll likely be the latter: an incomplete specification (that is incomplete because of the nature of the product), combined with testers who will close bugs more on pressure from management than anything else.
I'm not disagreeing with you about the nature of the ad-hoc element of all of this. I just wanted to clarify my comments, to make sure that folks here understood that I'm not denouncing Microsoft for not having a formal test plan--I'm quite sure they have one.
I just believe that, due to the way Microsoft elected to build the Windows 2000 product, that the specification and test plan is necessarly incomplete due to how huge the entire product is.
Re:In fairness (Score:2)
I have to concur about this. Realize that any company, such as Microsoft, who uses a formal Q/A program which uses a formal bug tracking system is going to eventually fill that bug log with a lot of niggly little things which frankly don't matter.
For example, one project I worked (a children's game) contained about 50 bugs from one tester who didn't like the color of the eyes of one of the characters. (He claimed they were too brown, and should be bluer.) Each bug report corrisponded to each scene in which the character appeared.
Eventually we scanned all of the art to make sure the eye color was the same, and closed out all of the bugs over the tester's protests.
I still have bug reports in my own bug tracking system covering similar non-issues, "helpful" suggestions, and things like "on-line help manual contains run-on sentence in 3rd paragraph." It's quite possible that the large bulk of the bugs relate to similar on-line content.
What's especially frustrating about such Q/A processes such as the one Microsoft uses is often they will report the easy to spot items, such as run-on sentences in on-line help. But at the same time, fatal, hard to detect crashing bugs will go by unnoticed because the Q/A test plan didn't include a situation which would stress the software in unexpected ways. And with the huge complexity of Microsoft's Windows 2000 product, that's the one that worries me the most: not that the product will ship with 65,000 content bugs, but that the crashing fatal bug which wipes out my hard disk wasn't even detected by their test plan.
Re:I was in "QA" too... (Score:2)
If there is one thing that Microsoft does right, by the way, it's this: Microsoft has separate career paths for programmers, testers, management, and content authors. Unlike other companies, which after 5 years of programming, you're expected to be bumped into management and never program again, Microsoft gives you the option to continue up the pay scale as a programmer instead.
What that means is that the head of the testing team for a large and important product such as Win2000 probably has a hell of a lot of Q/A experience.
Microsoft will also use a formal, specifications driven testing plan that included both a bunch of testers who do more "free-form exploration" of the product, and who do a formal testing which is driven by a script. They'll also be using testing automation.
The only problem with the Windows 2000 product is that it's an integrated operating system--that is, unlike Linux development which uses a Unix-like development philosophy of keeping each of the pieces small and managable, Windows 2000 attempts to put a hell of a lot into one large, monolithic black box. This plays hell on any formal testing plan in that you now have to test every possible interaction of every component of that black box. (Linux, on the other hand, can be tested more easily by testing each component separately, and making sure each component interacts with the standard Unix API correctly.)
The monolithic nature of Windows 2000 means that it will be near impossible to create a complete and full test plan, simply because of the huge number of component interactions within the black box. There's probably just too many conditions to test adequately.
Re:Unscientific comparison (Score:2)
So just because there are about 20,000 BUGBUG lines doesn't really mean much.
Except for the stuff in the service pack ... (Score:2)
Re:Windows and non-x86 platforms (Score:2)
NT was proclaimed to be architecture-independent when it first came out, but one by one all the ports to things like MIPS dropped away - leaving only the Alpha port (until now?)
Re:65,000+, huh? (Score:2)
MS Buyers are truly drones (Score:2)
Obviously there is a significant number of people that are compelled to lap up whatever MS spews out. I had thought the failure of MS Bob was an indication that the public was starting to change its thinking, but it's clear this isn't yet complete.
Maybe someone could forward this on to the DoJ Anti-trust division for use in the trial.
Four Bugs in the release that I know about (Score:2)
A couple bugs in the OS/2 console app emulation used to run older Microsoft console Apps and most importantly, to run the Brief editor. The OS/2 --version of Brief supports long filenames, runs great under WinNT.
One, The Ctrl-S and Ctrl-C keys are trapped and don't get through (this works in WinNT, the OS/2 support DLLs are unchanged in Win2000, it's a bug in Win2000).
Two, The file create function does not work on FAT32 volumes, just gives an error. Open works fine. (So for instance you cannot use Brief to edit a file on FAT32).
The most serious bug I know of it IDE driver doesn't work on Micronics 440FX based motherboards (and maybe others). Very popular in Dual Pentium Pro servers.
Bad metrics (Score:2)
One developer, informed of Microsoft's bug estimates, said all new software ships with lots of bugs but few software vendors are willing to acknowledge this reality. "The fact that Microsoft found that many bugs indicates to me just how thorough their testing processes are," said the Windows developer, who requested anonymity.
It could mean that they have done a really good job of finding the bugs, or it could mean that there are a lot of bugs to be found. It depends on a number of factors. What's the arrival rate of new bug reports? How are the known bugs distributed? How does that distribution compare to the distribution of new code in the system since the last release? How does the bug distribution compare to the distribution of testing effort? We don't know enough here other than to say that if this memo really is from within MS, we have no reason to dispute that they know about this many bugs.
How many bugs are in Linux? (Score:2)
Bug Count != Quality (Score:2)
In short, a hypothetical future statement that w2k has 65k "bugs" and w2k-sp1 has only 33k "bugs" would be a completely meaningless comparison, and says absolutely nothing about the quality of either code.
There is no accurate measure of the "bugginess" of the code, particularly one as complex as w2k. For a very simple code, I may measure bugginess by testing all possible inputs (for example, consider a code with two bits of input, bit A and bit B, whose assigned task is to return (A OR B). If the code returns 0 for A=0,B=0 and 1 otherwise, the code is 0% buggy. If the code always returns 0, it got 3 test cases wrong out of four and is 75% buggy).
We often rely on anecdotal evidence to evaluate software ("We have fixed the problem in the PPP script") and compare different pieces of software but should take numerical measurements (such as this bug count) with a grain of salt.
Re:Oh, stop being so predictable (Score:2)
You might have meant something like
if (Liunx_community & (creationism | fundamentalism))
Re:Is that an improvement though? (Score:2)
Yeah, funny you should say that cause bugs like that do get submitted to microsoft and processed.
I think many of the bugs are more like compatability issues to various hardware and software combinations that "could" arise.
Windows 2000 is inherently more stable because of it's underlying WNT/VMS architecture, so apps won't take down the OS as easily as they could on 9x.
Re:My W2K uptime shows no problems yet (Score:2)
Re:Oh, stop being so predictable (Score:2)
Re:Oh, stop being so predictable (Score:2)
if Linux_community is anything but NULL then your if block is evaluated.
Anyway, I was saying that the knee-jerk reactions everyone has is reminicent of creationists.
Re:65,000 defects - BS (Score:2)
I mean, it would make sense, since heaps of applications leave their COM signatures in the registry after the dll is deleted.
Re:Debian appears to have 10,000 (Score:2)
Also, Windows 2000 has some HUGE features that debian doesn't have, like Active Directory.
Re:Oh, stop being so predictable (Score:2)
65K . . . (Score:2)
_________________________
Not shocked (Score:2)
I think not.
_________________________
Re:Win2k not so bad, Site Server not so good (Score:2)
In all seriousness though, I have found NT4 (SP5) to be more reliable than Win2k RTM, at least with Exchange Server. I get no end of bluescreens and Exception Faults on a Win2k testing box. I don't think there is any garuntee that win2k is more stable until enough people use it to prove it.
Re:Not shocked (Score:2)
Re:How many bugs are in Linux? (Score:2)
Just for the sake of argument, I'll use RedHat 6.1. After a little bit of research, I've found that since it's release, no more than 10,000 complaints have been logged. The number is actually more around 9700, and this certainly counts 'non-bugs' as well.
Just a note, since I'm on topic, is that even though RH has SIGNIFICANTLY fewer bugs, it still releases patch after patch after patch, trying to get as close to PERFECT as it can be.
65,000 bugs on the wall, 65,000 bugs.... (Score:2)
Patch it around
65,000... Hey! The keyboard isn't working! What's wrong with this darn....
Re:Windows 2000's slogan (Score:2)
Might be. It can't get much worse.... Right now, my machines running Windows 98 are as unresponsive as if I'd already poured hot grits down the keyboards. And... darn... I have to run it because I support so many poor schlubs who do not have a choice. If I had my druthers, I'd put them all on one of the BSDs. My BSD systems never go down.
--Brett Glass
Re:In fairness (Score:2)
Still 65000 is a huge number...
As a comparison, Red Hat's bugzilla is currently at about 9700 bugs, about 95% of which are resolved, and some of the non-resolved bugs being non-reproducable; and Red Hat's bugzilla contains the whole system (and powertools). I don't think the 65000 bugs in Windows 2000 include bugs in, for example, Visual C++ (Red Hat's include gcc).
Even if only 20% of the bugs are real, that's way more than any bug ever reported in Red Hat Linux.
I think it's pretty much the same situation if you look at the number of bugs in the bug tracking systems for other Linux distributions, or the various BSDs.
Re:Spelling. (Score:2)
Nowhere in my post did I assert that Linux does not have a lot of bugs. I didn't talk about Linux at all. In fact, I said that I accept the fact that bugs are inherrent in computer science, just like the spokesperson for Microsoft said. I further said that it surprises me that people are far more tolerant of defects in computer software than they are in any other type of product. You should probably pay attention to posts before you reply to them.
My post had nothing to do with Windows vs. Linux or any other OS, it was merely an observation about the state of the software market.
talk about being a troll.
Perhaps you should apply that to yourself.
For comparison (Score:2)
Now you might say that Debian is worse at tracking bugs than MS (ie a smaller ratio of Debian's bugs are known than of Windows's bugs) due to the number of full-time MS employees etc, or you might say that the bug tracking system in Debian is at least as good because of its openness to anyone who would submit.. But those are the numbers for anyone interested.
Also important to note is that this does not include kernel bugs. I would have included them, but I don't know where to find those... Someone please reply if you have them.
News Release from Microsoft. (Score:2)
Windows 2004, to be released in Q3 2005, will have a new and improved core. This core has been heavily tested. Our acquisitions department has been looking at the proper target [linuxone.net] and we feel the time is right to change our market focus.
In related news, Microsoft is looking for a new graphic artist who can properly draw a pentagram [linuxone.net].
-----
W2K will soon have zero bugs! (Score:2)
unsigned short bugs_r_us;
the bug counter will soon go from 65535 to 0.
Marketing? Deadlines? Pah... (Score:3)
So instead of correcting the problem and pushing back the release date, Microsoft is going to release Windows 2000 upon thousands of unsuspecting retailers, and millions of unsuspecting users JUST to meet the deadline. "That's okay, we'll fix it in service pack 1."
The only problem with that is, Service pack 1 is a good 6 months away. In the meantime, what do the users do?
"Our goal for the next release of Windows 2000 is to have zero bugs."
WHO do these people think they're KIDDING? The next release? Okay, we're at Service pack 6 for NT 4. Several of those service packs actually BROKE more stuff than they fixed, and the goal for Windows 2000 OSR2 is zero bugs? Sure, I'll hand it to them - They have the right idea, but:
A) it's more than likely just marketspeak: "This one may have 63,000 problems, but the NEXT one will have zero, enabling you to have fun, and be more productive than ever! Blah Blah..."
B) How about attainable goals? How many people believe in their hearts that Microsoft will put out a Bug-free operating system? There is no such thing. Also, Microsoft is so concerned about market share that they could care less about present problems. "Fix it later."
Market researchers have repeated warnings to their clients against upgrading immediately to Win2000.
Go back about 5 years, replace "Win2000" with "Windows 95", and we have the SAME EXACT situation all over again. (Those who do not learn from history are doomed to repeat it.)
Several outfits have advised customers to wait until Microsoft issues its first or second service pack before deploying Win2000.
*Ahem* - Replace "Win2000" with NT 4.0. Wash, Rinse, Repeat.
-- Give him Head? Be a Beacon?
Irresponsible Slashdot article posters. (Score:3)
?
(By the way, when is the Extrans going to work again? Taco? Taco? Bueller?)
This "HeUnique" goombah needs a) a little computer science education, b) to read more carefully, c) to sit down and take a deep breath before posting.
First, the ZDNet article refers to 63,000 "defects", but not all defects are bugs. As reading it makes clear, some defects are simply usability issues, some are shortfalls in meeting intended functionality, others are simply things that cause end-user confusion. To equate all these with software bugs that make the product unusable indicates many things, starting with a lack of real-world experience delivering software to end-users, and obviously including no exposure to the product in question.
Of course Microsoft suggests putting this in a production environment. That's what a piece of software achieving release MEANS. Release does not mean the software works perfectly. It means it meets customer or client expectations, which in a properly managed relationship, are equal to the deliverable. If you've led the client to believe they'll get platinum and you deliver brass, that says more about you than the client. But if you say by X we can deliver brass, or we can wait until Y if you insist on silver, Z for gold
I hope that HeUnique doesn't continue to help Slashdot slide into the abyss of adolescent BBS flammage.
----
bugtracking and product release (Score:3)
O.k. the issue I'd like to highlight is the fact that Microsoft has very thorough configuration management software. I don't know what they use, but you can bet your sweet ass it beats the pants off Bugzilla (which I love, don't get me wrong) -- they can afford it and they need it. That being said, it is certain that they have now and have had for years bug tracking resources in their development teams.
The fact that there are 21,000 or 63,000 "bugs" -- for the sake of some degree of objectivity let's assume there are 20,000 actual "bugs" in Window 2000, as tracked by Microsoft's internal bug tracking systems -- that are being announced now implies that there were (let's say again) very close to 20,000 (or more -- this is assuming they've been busting ass to fix them since they went "gold") bugs that were in the bug tracking system when the product was shipped to manufacturers.
This is in spite off the resources they are claiming they have used to beta test the product! [ I should note that beta testing is rarely testing in a production-load environment, so it is not as useful for finding bugs likely to emerge in Real Use (this is not an indictment of Microsoft, it's just the unfortunate truth) ] I can only imagine how much of a piece of shit Win2k was when it went out for beta testing...
We know why they ship buggy product (two primary reasons -- to meet shipping deadlines, and because a "perfect" product has no need for upgrades
:-) ). That they ship buggy product for exhorbitant prices is unforgiveable (ignoring even the marketing that claims otherwise as I'm trying hard to do). That they spend as much as they do on testing and still release shitware is an indictment of their development process -- though what they're doing wrong is open for holy war ("talk amongst yourselves...").
Bottom line: a large number (~20,000) bugs were most likely known, IN THE SOURCE CONTROL SYSTEM, at the time the product was shipped to manufacturers.
Draw your own conclusions.
Unscientific comparison (Score:3)
In the Linux kernel source (2.2.12), I found "XXX" 1,561 times out of approximately 2,000,000 lines of code.
Now, Win2k supposedly has 35,000,000 lines of code, or 17.5 times what is in the linux kernel. Therefore, to compare, 1,561 * 17.5 = 27,318.
Looks like the kernel source is right in line with Win2k as far as BugBug or XXX comments go.
In addition, as a coder, I do liberally sprinkle with XXX. Everytime I hit something that I realize I could do better or stub something out for now, I XXX. The code will work and be considered bug free (depending on the stub), but there remain XXX's to remind myself that I wanted to do something better there. In other words, a lot of my XXX's are for rainy days when I have time to improve code instead of just chugging to the next deadline.
Biased poll? (Score:3)
Though, Microsoft has spread enough FUD that maybe it's time for some Anti-FUD like this. In that case, could it maybe be a little less obvious?
--
A list of few of the bugs: (Score:3)
But on the plus side: Notepad is unbundled from the OS, and now availble for only $99 from local retailers.
Re:A suggestion to Microsoft-emulate commercial Un (Score:3)
2) Microsoft already has a kick ass debugger - not free though. And the debug symbols for Windows 2000 are readily downloadable my MSDN subscribers or Beta testers. Core dumps (or any crash in windows) again can be debugged. You have many options. One is if you have VC++ installed, it'll bring up a window asking you if you want to debug, then you can do step-step debugging. ALso Dr Watson can collect information like your "core" dump files and store them. BSOD are also documented on MSDN and MS Support, including information for how to connect to a machine during a 'bugcheck/bsod' and debug the BSOD.
Windows 2000's DDK (Driver Development Kit) comes with several 'build' enviroments for creating and testing drivers. Including the 64bit build enviroments for Win64.
3. NT is theorectically hardware independent, very little has to be rewritten because of the HAL. However the market wasn't very good for MIPS, ALPHA, SPARC or PPC and those ports kind of died.
A suggestion to Microsoft-emulate commercial Unix! (Score:3)
1. Run a bugtraq-style mailing list. Even without the source, there are a lot of people with extensive enough knowledge of Windows OS internals to provide at least some outside insight as to why a particular bug might be occurring.
2. Make a really kick-a#! debugger readily and freely available in the tradition of gdb. Make things like core dumps and other Unix diagnostic niceties standard, to allow people the ability to pull something useful out of the rubble for a postmortem. Obviously, within a closed-source paradigm, some method would be needed to ensure that only Microsoft programmers could dissassemble the cores; encryption, maybe? (and yes, I know there's a joke in there somewhere about a user's disk filling up with core dumps within five seconds, but I'm leaving it alone!)
3. Two words: architechture independence. While I have no hard facts to back this up, I would imagine that, because Microsoft is concentrating on a single hardware architechture, quite a bit of assembley code is sneaking its way in. Assembley code is good for speed, but (although there will be doubtlessly much debate about this) the fact remains that the more architechture-independent code is in a product, the more stable it is. For further proof, look at early OSs (such as MSDOS 1.0) that are coded significantly in assembley, and something like BSD Unix, which is about 80% architechture independent - the only assmbley routines are device I/O, memory mapping, and other such things. If Microsoft went to an architechture-independent approach, it could make its debugging job a lot easier.
I know that many people here will probably flame me for giving honest suggestions to Microsoft, but politics aside I think that if Microsoft were to take up the practices I outlined above, along with similar practices common in the Unix world, it would make all our lives a lot easier. After all, Microsoft is going to be here for quite a while, and the less pain that existence inflicts on us, the better.
Re:Spelling. (Score:3)
It's so bad, in fact, that people expect the products they're buying to be defective. I use both Windows and MacOS, and am not at all phased when the box locks up and I have to hit the reset switch. But now that I think about it, shouldn't I be?
Re:Not shocked (Score:4)
Consider also RedHat [redhat.com], which has been around for a much shorter period of time. Their Bug reporting system [redhat.com] reports a total of about 1640 new, reopened, and assigned bugs with 140 bugs new this week. If Redhat had the same user base as windows, their bug system would likely report similar numbers.
Time and experience with the new OS will be the true test of its stability. Just think of how the bug counts will grow once it's been released to the rampaging mobs!
65,000+, huh? (Score:4)
(Please don't moderate this if you're not a programmer.
Oh, stop being so predictable (Score:4)
These bugs aren't show stoppers, gee 65K ooh that is heaps, the damn thing won't even boot! Not.
These bugs are more like, on this system with X hardware when running along side with this hardware and when running X's software package called Y, windows 2000 will have a pixel out of place.
A majority of bugs in the 65K are very much like this. Bugs that cause potential problems with people not having HCL hardware. In fact I wouldn't even call most of them 'bugs' as such, since in the traditional sense they aren't - unless like Microsoft you want to make sure Windows 2000 works on the billions of hardware and software configurations out there.
And this statement "Is this what MS suggests putting on people's workstations and installing on production servers? What do you think?" is just so typical of what everyone's reaction around here would be. So blind, arrogant and ignorant, and very predictable. It's the type of knee jerk reaction which has made me so bitter with the Linux community over the past 3 years.
In many ways the Linux community acts too much like creationists/fundamentalists, no matter what science comes up with there's a knee jerk "oh we're not all monkeys you devil worshipping bastards" reaction.
Windows 2000 is by far the most stable and featured operating system Microsoft has written to date. I have NEVER seen a BSOD on any of our production machines at work.
I admit, on a 3 year old K6200 at home, I have seen around 6 BSOD during the beta testing phase, around the same amount of kernel panics I get on the machine as it seems, so i suspect my hardware is stuffed.
In the last few months of the beta, Microsoft was only paying attention BSOD (bug check) bug reports, even though other bug reports (like cosmetic or hardware compatabilty reports were still being sent in). This isn't incompetance, it's good management.
There's a point in a product's life cycle when it has to ship or never gets shipped. I mean, how many bugs has Redhat 6.1 had since it's releast, heck how many security problems has it had since it's released?
Microsoft at least plan these out, and while they're working on Windows 2000, they also have very good ideas of what the next service pack will do, and even what the next version of Windows 2000 will do. An example of one of these 'feature' bugs is load balancing COM+ services, this was a feature that never got finished in time, but has been moved into the service pack. It's by was by means essential, so it'll get updated later.
Microsoft has tried to do everything they can in Windows 2000, and it's no suprise that they'll be problems and things they don't get done, but that's software! Things that don't get done, get done later in a service pack (or option pack), and bug fixes are the same.
Despite these 65K bugs, Windows 2000 is still stable and will work for most people.
Anyway look at it the other way round, 75% of people _won't_ have compatability problems according to this article. That's not bad for an OS upgrade as HUGE as Windows 2000.
In fairness (Score:5).
-matthew Priestley
mpriest@microsoft.com
-konstant
Yes! We are all individuals! I'm not! | https://slashdot.org/story/00/02/11/1840225/windows-2000-has-65000-bugs | CC-MAIN-2017-04 | refinedweb | 9,171 | 71.24 |
Hello guys, today we will learn some ways to store data with java, we will talk about these following ways :
- Storing through vector
- Storing with file
- Storing with database
First we will discuss how we may store data using Vectors
Listing 1: Storing data with Vectors
import java.util.Vector; public class Storage { Vector a=new Vector(); Person p=new Person(); public static void main(String args[]) { Storage s=new Storage(); for(int i=0;i<5;i++) s.start("ID"+i); s.show(); } public void start(String id) { p.setId(id); p.setName("Anurag"); a.add(p); } public void show() { for(int i=0;i<a.size();i++) { Person per=(Person)a.get(i); System.out.println("ID:"+per.getId()+" and Name:"+per.getName()); } } } class Person { String name; String id; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getId() { return id; } public void setId(String id) { this.id = id; } }
Here:
- java.util.Vector is used to implement the vector class
- Now we define a class and within it we define vector and also an object of another class called Person
- Now the Person object is made to store basic info like name and id. And we use vector to store this information in easy manner
- We define a loop and call the start method 5 times passing a new id to start method each time as an argument
- In start method we are setting information on person object and storing this information in vector a using the add method of vector
- Since the loop run 5 time so the vector will record the 5 records and save them which you may use for future purpose
- We can use the show method to show all the data inside the vector
- In show method we run a loop from 0 to vector size so that each element in vector gets processed. In next step we display the information
- After that we defined a class called Person which will define the variable name and id within it. We have defined setters and getters for these.
Now we move forward to 2nd method which is saving to file
Listing 2: Storing data with files
import java.io.BufferedWriter; import java.io.FileWriter; public class Storage2 { Person2 p=new Person2(); public static void main(String args[]) { Storage2 s=new Storage2(); for(int i=0;i<5;i++) s.start("ID"+i); System.out.print("Done"); } public void start(String id) { p.setId(id); p.setName("Anurag"); try { FileWriter fw=new FileWriter("out.txt",true); BufferedWriter bw=new BufferedWriter(fw); bw.write(p.msg()); bw.newLine(); bw.close(); } catch(Exception e) { e.printStackTrace(); System.out.println("error"+e.getMessage()); } } } class Person2 { String name; String id; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String msg() { return this.id+" "+this.name; } }
Here:
- We include FileWriter and BufferedWriter to include functionality to write to file
- First we make a class named Storage2
- We make a object of class person2 which contain info about person like id and name
- We define the main method and define the object of Storage2 class.
- Now we call the start method of this class which will write data to file.This will be done 5 times
- Now we define the start object and then we make objects for File Writer and BufferedWriter.Now they are used to write the name and id using the msg function of Person2
- After writing to file we close the stream.Remember in FileWriter we gave 2 argument which are file path and the other argument that is true tell that we want to append in the file
- We capture all exception which may occur
- We define the Person2 class which define name and id.We also define setter and getter for the same.We also define a msg function which will return the id and name for current object
The third way of storage is Database. We have already discussed this in our previous posts about How to connect with MySQL database using Java. You may use this as reference.
Remember that you use file when you have some linear data where you don’t involve search operations since here database would be much more effective.
This is all for this article. See you next time with some more exciting article | http://mrbool.com/how-to-store-data-with-java/25483 | CC-MAIN-2017-09 | refinedweb | 741 | 69.72 |
Post your Comment
Aggregating Actions In Struts Revisited
Aggregating Actions In Struts Revisited... Aggregating Actions in Struts , I have given a brief idea of how to create action... these new actions as ?Event Aggregating Actions? and the ones in Part I as ?Non Built-In Actions
Struts Built-In Actions
... actions shipped with Struts APIs. These
built-in utility actions provide different...;
Actions
Struts 2 Actions
Struts 2 Actions
In this section we will learn about Struts 2 Actions, which is a fundamental
concept in most of the web... request.
About Struts Action Interface
In Struts 2 all actions may implement
Struts2 Actions
.
However with struts 2 actions you can get different return types other than...Struts2 Actions
When... generated by a Struts
Tag. The action tag (within the struts root node of 2 Actions
Struts2 Actions
Struts2 Actions... is usually generated by a Struts
Tag.
Struts 2 Redirect Action
In this section, you will get familiar with struts 2 Redirect action
Configuring Actions in Struts application
Configuring Actions in Struts Application
To Configure an action in struts... it is enabled the struts becomes much
friendlier and provide significant speed ...;struts-default"> </package>
defines the name of the package. Here
Implementing Actions in Struts 2
Implementing Actions in Struts 2
Package com.opensymphony.xwork2 contains.... Actions the contains the
execute() method. All the business logic is present....
login.jsp
<%@ taglib prefix="s" uri="/struts-tags" %>
Test Actions
Test Actions
An example of Testing a struts Action is given below using...;
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts...;default" namespace="/" extends="struts-default">
<default
struts how to make one jsp page with two actions..ie i need to provide two buttons in one jsp page with two different actions without redirecting to any other page
|
AGGREGATING ACTIONS IN STRUTS |
Aggregating Actions In Struts Revisited... |
Struts
Built-In Actions |
Struts
Dispatch Action |
Struts
Forward...
configuration file |
Struts
2 Actions |
Struts 2 Redirect Action
Struts Tutorial
, Architecture of Struts, download and install struts,
struts actions, Struts Logic Tags... :
Struts provides the POJO based actions.
Thread safe.
Struts has support... of Struts and download.
Struts Built-In Actions
Struts provide the built-in actions 1 Tutorial and example programs
;
Aggregating Actions In Struts Revisited -
In my previous article Aggregating Actions in Struts , I have given a brief idea of how....
- STRUTS ACTION - AGGREGATING ACTIONS IN STRUTS
Struts Forward Action Example
about Struts
ForwardAction (org.apache.struts.actions.ForwardAction). The ForwardAction is one of the Built-in Actions
that is shipped with struts framework... Struts Forward Action Example
Struts LookupDispatchAction Example
Struts LookupDispatchAction Example
Struts LookupDispatch Action (org.apache.struts.actions.LookupDispatchAction) is one of the Built-in Actions provided along (org.apache.struts.actions.MappingDispatchAction)
is one of the Built-in Actions
Struts Dispatch Action Example
Struts Dispatch Action Example
Struts Dispatch Action (org.apache.struts.actions.DispatchAction)
is one of the Built-in Actions provided along
Action in Struts 2 Framework
Actions
Actions are the core basic unit of work in Struts2 framework. Each.... Actions are mostly associated with a HTTP request of User.
The action class... actions configuration matches
with a specific result that will be rendered
Post your Comment | http://www.roseindia.net/discussion/23981-Aggregating-Actions-In-Struts-Revisited.html | CC-MAIN-2014-10 | refinedweb | 529 | 50.53 |
import IndexPage from 'flarum/components/IndexPage.js'
IndexPage
Extends:
The
IndexPage component displays the index page, including the welcome
hero, the sidebar, and the discussion list.
Member Summary
Method Summary
Public Methods
public actionItems(): ItemList source
Build an item list for the part of the toolbar which is about taking action on the results. By default this is just a "mark all as read" button.
Return:
public changeSort(sort: String) source
Redirect to the index page using the given sort parameter.
Params:
public clearSearch() source
Redirect to the index page without a search filter. This is called when the 'x' is clicked in the search box in the header.
public composeNewDiscussion(deferred: Deferred): Promise source
Initialize the composer for a new discussion.
Params:
Return:
public navItems(): ItemList source
Build an item list for the navigation in the sidebar of the index page. By default this is just the 'All Discussions' link.
Return:
public newDiscussion(): Promise source
Log the user in and then open the composer for a new discussion.
Return:
public searching(): String source
Return the current search query, if any. This is implemented to activate the search box in the header.
Return:
public sidebarItems(): ItemList source
Build an item list for the sidebar of the index page. By default this is a "New Discussion" button, and then a DropdownSelect component containing a list of navigation items. | https://api.flarum.dev/js/v0.1.0-beta.5/class/js/forum/src/components/IndexPage.js~IndexPage.html | CC-MAIN-2020-29 | refinedweb | 227 | 56.45 |
I think i'm having issues with the loading sequence of the javascripts and these iframes. Will report more details once i'm done fixing the issue.
Thanks for your response, David! -Sumit On Dec 9, 2:36 am, david <david.brill...@gmail.com> wrote: > Hi sumit, > > Just a though, I didn't test it. > you don't use custom event it has the form "namespace:eventName". > > What you could do ?? is to define in frame A: > document.observe("FrameB:message", function(e){ > console.log("11"+e); > > }); > > And send from Frame B: > Event.fire(document,'FrameB:message','message to send',true); > > It could work, but my question is about frame and crossdomain ?? > > -- > david > > On 8 déc, 20:31, Sumit <skbrnwl-...@yahoo.com> wrote: > > > Hi, > > > I've certain iframes loaded on my page (same domain) and i want to > > fire custom events from one of them to the other for which those > > iframes are already listening. Somehow the following implementation > > doesn't work (sadly the firebug console doesn't show anything): > > > In the iframe A, i'm doing-> > > document.observe("message", function(e){ > > console.log("11"+e); > > > }); > > > In the iframe B (same as domain A), i'm doing-> > > Event.fire(parent.frames["frame11"],"message","frame12", true); > > > Any idea what i might be doing wrong? > > Thanks in advance. > > -Sum. | https://www.mail-archive.com/prototype-scriptaculous@googlegroups.com/msg09520.html | CC-MAIN-2017-34 | refinedweb | 217 | 70.09 |
NAMEbeet - music tagger and library organizer
SYNOPSIS
beet [args...] command [args...] beet help command
COMMANDS
import
beet import [-CWAPRqst] [-l LOGPATH] PATH... beet import [options] -L QUERY
Add music to your library, attempting to get correct tags for it from MusicBrainz.
Point the command at some music: directories, single files, or compressed archives. The music will be copied to a configurable directory structure and added to a library database. The command is interactive and will try to get you to verify MusicBrainz tags that it thinks are suspect. See the autotagging guide for detail on how to use the interactive tag-correction flow.
Directories passed to the import command can contain either a single album or many, in which case the leaf directories will be considered albums (the latter case is true of typical Artist/Album organizations and many people's "downloads" folders). The path can also be a single song or an archive. Beets supports zip and tar archives out of the box. To extract rar files, install the rarfile package and the unrar command.
Optional command flags:
- By default, the command copies files your the library directory and updates the ID3 tags on your music. In order to move the files, instead of copying, use the -m (move) option. If you'd like to leave your music files untouched, try the -C (don't copy) and -W (don't write tags) options. You can also disable this behavior by default in the configuration file (below).
- Also, you can disable the autotagging behavior entirely using -A (don't autotag)---then your music will be imported with its existing metadata.
- During a long tagging import, it can be useful to keep track of albums that weren't tagged successfully---either because they're not in the MusicBrainz database or because something's wrong with the files. Use the -l option to specify a filename to log every time you skip an album or import it "as-is" or an album gets skipped as a duplicate.
- Relatedly, the -q (quiet) option can help with large imports by autotagging without ever bothering to ask for user input. Whenever the normal autotagger mode would ask for confirmation, the quiet mode pessimistically skips the album. The quiet mode also disables the tagger's ability to resume interrupted imports.
- Speaking of resuming interrupted imports, the tagger will prompt you if it seems like the last import of the directory was interrupted (by you or by a crash). If you want to skip this prompt, you can say "yes" automatically by providing -p or "no" using -P. The resuming feature can be disabled by default using a configuration option (see below).
- If you want to import only the new stuff from a directory, use the -i option to run an incremental import. With this flag, beets will keep track of every directory it ever imports and avoid importing them again. This is useful if you have an "incoming" directory that you periodically add things to. To get this to work correctly, you'll need to use an incremental import every time you run an import on the directory in question---including the first time, when no subdirectories will be skipped. So consider enabling the incremental.
- By default, beets will proceed without asking if it finds a very close metadata match. To disable this and have the importer ask you every time, use the -t (for timid) option.
- The importer typically works in a whole-album-at-a-time mode. If you instead want to import individual, non-album tracks, use the singleton mode by supplying the -s option.
- If you have an album that's split across several directories under a common top directory, use the --flat option. This takes all the music files under the directory (recursively) and treats them as a single large album instead of as one album per directory. This can help with your more stubborn multi-disc albums.
- Similarly, if you have one directory that contains multiple albums, use the --group-albums option to split the files based on their metadata before matching them as separate albums.
- If you want to preview which files would be imported, use the --pretend option. If set, beets will just print a list of files that it would otherwise import.
- If you already have a metadata backend ID that matches the items to be imported, you can instruct beets to restrict the search to that ID instead of searching for other candidates by using the --search-id SEARCH_ID
beet list [-apf] QUERY
Queries the database for music.
Want to search for "Gronlandic Edit" by of Montreal? Try beet list gronlandic. Maybe you want to see everything released in 2009 with "vegetables" in the title? Try beet list year:2009 title:vegetables. You can also specify the sort order. (Read more in query.)
You can use the -a switch to search for albums instead of individual items. In this case, the queries you use are restricted to album-level fields: for example, you can search for year:1969 but query parts for item-level fields like title:foo will be ignored. Remember that artist is an item-level field; albumartist is the corresponding album field.
The -p option makes beets print out filenames of matched items, which might be useful for piping into other Unix commands (such as xargs). Similarly, the -f option lets you specify a specific format with which to print every album or track. This uses the same template syntax as beets' path formats. For example, the command beet ls -af '$album: $tracktotal' beatles prints out the number of tracks on each Beatles album. In Unix shells, remember to enclose the template argument in single quotes to avoid environment variable expansion.
remove
beet remove [-adf] QUERY
Remove music from your library.
This command uses the same query syntax as the list command. You'll be shown a list of the files that will be removed and asked to confirm. By default, this just removes entries from the library database; it doesn't touch the files on disk. To actually delete the files, use beet remove -d. If you do not want to be prompted to remove the files, use beet remove -f.
modify
beet modify [-MWay] [-f FORMAT] QUERY [FIELD=VALUE...] [FIELD!...]
Change the metadata for items or albums in the database.
Supply a query matching the things you want to change and a series of field=value pairs. For example, beet modify genius of love artist="Tom Tom Club" will change the artist for the track "Genius of Love." To remove fields (which is only possible for flexible attributes), follow a field name with an exclamation point: field!.
The -a switch operates on albums instead of individual tracks..
Items will automatically be moved around when necessary if they're in your library directory, but you can disable that with -M. Tags will be written to the files according to the settings you have for imports, but these can be overridden with -w (write tags, the default) and -W (don't write tags). to apply the changes, n to discard them or q to exit and apply the selected changes. This option lets you choose precisely which data to change without spending too much time to carefully craft a query. To skip the prompts entirely, use the -y option.
move
beet move [-capt] [-d DIR] QUERY
Move or copy items in your library.
This command, by default, acts as a library consolidator: items matching the query are renamed into your library directory structure. By specifying a destination directory with -d manually, you can move items matching a query anywhere in your filesystem. The -c option copies files instead of moving them. As with other commands, the -a option matches albums instead of items. The -e flag (for "export") copies files without changing the database.
To perform a "dry run", just use the -p (for "pretend") flag. This will show you a list of files that would be moved but won't actually change anything on disk. The -t option sets the timid mode which will ask again before really moving or copying the files.
update
beet update [-F] FIELD [-aM] QUERY
Update the library (and, optionally, move files) to reflect out-of-band metadata changes and file deletions.
This will scan all the matched files and read their tags, populating the database with the new values. By default, files will be renamed according to their new metadata; disable this with -M. Beets will skip files if their modification times have not changed, so any out-of-band metadata changes must also update these for beet update to recognise that the files have been edited.
To perform a "dry run" of an update, just use the -p (for "pretend") flag. This will show you all the proposed changes but won't actually change anything on disk.
By default, all the changed metadata will be populated back to the database. If you only want certain fields to be written, specify them with the `-F` flags (which can be used multiple times). For the list of supported fields, please see `beet fields`.
When an updated track is part of an album, the album-level fields of all tracks from the album are also updated. (Specifically, the command copies album-level data from the first track on the album and applies it to the rest of the tracks.) This means that, if album-level fields aren't identical within an album, some changes shown by the update command may be overridden by data from other tracks on the same album. This means that running the update command multiple times may show the same changes being applied.
write
beet write [-pf] [QUERY]
Write metadata from the database into files' tags.
When you make changes to the metadata stored in beets' library database (during import or with the modify command, for example), you often have the option of storing changes only in the database, leaving your files untouched. The write command lets you later change your mind and write the contents of the database into the files. By default, this writes the changes only if there is a difference between the database and the tags in the file.
You can think of this command as the opposite of update.
The -p option previews metadata changes without actually applying them.
The -f option forces a write to the file, even if the file tags match the database. This is useful for making sure that enabled plugins that run on write (e.g., the Scrub and Zero plugins) are run on the file.
stats
beet stats [-e] [QUERY]
Show some statistics on your entire library (if you don't provide a query) or the matched items (if you do).
By default, the command calculates file sizes using their bitrate and duration. The -e (--exact) option reads the exact sizes of each file (but is slower). The exact mode also outputs the exact duration in seconds.Beets has a few "global" flags that affect all commands. These must appear between the executable name (beet) and the command---for example, beet -v import ....
- -l LIBPATH: specify the library database file to use.
- -d DIRECTORY: specify the library root directory.
- -v: verbose mode; prints out a deluge of debugging information. Please use this flag when reporting bugs. You can use it twice, as in -vv, to make beets even more verbose.
- -c FILE: read a specified YAML configuration file.Beets includes support for shell command completion. The command beet completion prints out a bash 3.2 script; to enable completion put a line like this into your .bashrc or similar file:
eval "$(beet completion)"
Or, to avoid slowing down your shell startup time, you can pipe the beet completion output to a file and source that instead.
You will also need to source the bash-completion script, which is probably available via your package manager. On OS X, you can install it via Homebrew with brew install bash-completion; Homebrew will give you instructions for sourcing the script.
The completion script suggests names of subcommands and (after typing -) options of the given command. If you are using a command that accepts a query, the script will also complete field names.
beet list ar[TAB] # artist: artist_credit: artist_sort: artpath: beet list artp[TAB] beet list artpath\:
(Don't worry about the slash in front of the colon: this is a escape sequence for the shell and won't be seen by beets.)
Completion of plugin commands only works for those plugins that were enabled when running beet completion. If you add a plugin later on you will want to re-generate the script.
zshIf you use zsh, take a look at the included completion script. The script should be placed in a directory that is part of your fpath, and not sourced in your .zshrc. Running echo $fpath will give you a list of valid directories.
Another approach is to use zsh's bash completion compatibility. This snippet defines some bash-specific functions to make this work without errors:
autoload bashcompinit bashcompinit _get_comp_words_by_ref() { :; } compopt() { :; } _filedir() { :; } eval "$(beet completion)"
SEE ALSO
beetsconfig(5) | https://jlk.fjfi.cvut.cz/arch/manpages/man/beet.1.en | CC-MAIN-2019-47 | refinedweb | 2,197 | 63.29 |
Hello,
I'm using Vue with TypeScript, and I am declaring some variables on the Vue instance (namely the store) in a file called `vue.d.ts` using module augmentation:
// noinspection ES6UnusedImports
import Vue from "vue";
import Router, {Route} from "vue-router";
import {Store} from "../store";
declare module "vue/types/vue" {
interface Vue {
store: Store;
$router: Router;
$route: Route;
$q: any;
}
}
This is to let TypeScript know that the instance does have those variables.
After upgrading to WebStorm 2018.3, I'm getting a errors about "unresolved variables" when trying to access them from within my code:
import Vue from 'vue'
// ...
@Component
export default class Person extends Vue {
// ...
async mounted() {
this.result = await getResult(this.store); // here "this.store" is apparently not declared
}
}
Identical code showed no errors in the previous version of WebStorm (2018.2?), and the code still compiles with no errors or warnings w/ TS compiler v3.1.3.
Any help is appreciated.
Ah! This is correct and fixed my issue.
Thank you! :)
Works fine for me using similar code:
Did you try invalidating caches? If it doesn't help, please share a sample projecrt that can be used to recreate the issue
Hmm, you are correct, when I create a new project it works fine also.
I did 'Invalidate Caches / Restart' already, is there anything else in the settings that could affect where does WebStorm load its types from?
Anything - other project files, libraries, installed modules, project roots setup, etc.
One clue I found is that in 2018.3, when I open the vue.d.ts file in the project that works correctly, I see the green I symbols indicating Implementations of the interface; when I open the vue.d.ts file in my (now broken) project, I see no such symbols. (In 2018.2, they are there in both cases.)
Deleting the file and creating it elsewhere in the directory structure doesn't make the I symbols show up either; it simply does not seem to register as a module augmentation; but WebStorm is aware of the definition, as when I created a duplicate file with different definitions, it complained of TS2717.
Nevertheless, I think I was able to isolate the minimal set of files that trigger this? If you would try it yourself, I would be really glad, thank you!
Thanks, reproduced!
the problem is that you have `vue` module excluded from indexing, as it's not listed as a dependency in package.json; marking node_modules/vue as not excluded (Mark Directory As/Not Excluded) should solve the issue: | https://intellij-support.jetbrains.com/hc/en-us/community/posts/360001792619-2018-3-broke-TypeScript-Module-Augmentation-?sort_by=votes | CC-MAIN-2019-30 | refinedweb | 425 | 65.01 |
After.
try
catch
You have written a cool application server... But as is the case with most servers, it runs in background, either as a Windows Service or may be with a hidden window. Now, how are you going to notify the System Administrator, in case some failures or important events occur? All big-shot server products use the Windows Event log for this purpose.
And so should you, with the simple function given below: (Use the relevant EventLogEntryType for your application)
EventLogEntryType
using System.Diagnostics;
public void WriteEventLog(string sCallerName, string sLogLine)
{
if (!System.Diagnostics.EventLog.SourceExists(sCallerName))
System.Diagnostics.EventLog.CreateEventSource(sCallerName, "Application");
EventLog EventLog1 = new EventLog();
EventLog1.Source = sCallerName;
EventLog1.WriteEntry (sLogLine, EventLogEntryType.Warning);
}
Sometimes, users (or QA people) can get really nasty and try to run multiple instances of your beloved little application on a single machine. Now, in case that makes you uncomfortable, just pop in the following code in your Main().
Main()
Yes, it is utilizing a Mutex object to make sure the users don’t get too smart.
Mutex
using System.Threading;
static void Main()
{
bool bAppFirstInstance;
oMutex = new Mutex(true, "Global\\" + “YOUR_APP_NAME”, out bAppFirstInstance);
if(bAppFirstInstance)
Application.Run(new formYOURAPP() or classYOURAPP());
else
MessageBox.Show("The threatening message you want to go for…",
"Startup warning",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation,
MessageBoxDefaultButton.Button1);
}
A techie note from Adam: The '\\Global' thingie ensures that the app should be a single instance on the machine, not just for this user's session.
'\\Global'
Well, what can impress users more than a neat little mail from your cute server? The task is pretty easy with .NET, do have a look at the following function. Please don’t forget to provide the correct sender account for Message.From and a valid SMTP server for SmtpMail.SmtpServer. (Then prepare to receive hugs and flying kisses from elated users.)
Message.From
SmtpMail.SmtpServer
If you want to get one step ahead of others, here are some more tricks:
MailFormat.Html
MailFormat.Text
using System.Web.Mail;
private bool SendEmail(string sFrom, string sTo, string sCC,
string sBCC, string sSubject, string sMessage, int iMailType)
{
try
{
MailMessage Message = new MailMessage();
// If sFrom is blank, system mail id is assumed as the sender.
if(sFrom=="")
Message.From = "default@myserver.com";
else
Message.From = sFrom;
// If sTo is blank, return false
if(sTo=="")
return false;
else
Message.To = sTo;
Message.Cc = sCC;
Message.Bcc = sBCC;
Message.Subject = sSubject;
Message.Body = sMessage;
Message.BodyFormat = MailFormat.Text;
SmtpMail.SmtpServer = "Put a valid smtp server IP";
SmtpMail.Send(Message);
return true;
}
catch(System.Web.HttpException ehttp)
{
// Your exception handling code here...
return false;
}
catch(Exception e)
{
// Your exception handling code here...
return false;
}
catch
{
// Your exception handling code here...
return false;
}
};
}
To get the IP of the local machine, use the following method before invoking GetIPAddress():
GetIPAddress()
string sHostName = Dns.GetHostName();
Well, you can always dump a few strings into a file and call it a log file. What’s the big deal? The thing is - it does not look, ahem, techie. Here is a sample which creates a log file (one per day & instance) and puts in time-stamped log entries into it. The file names are such that sorting them in Windows File Explorer is very easy for the SysAd.
Also note that logging functions will require multithreading support, so I am using the lock thingie here; you can either get rid of it (for ST apps) or use something that suits you better. Kudos to Adam for help with this trick.
using System.IO;
public void WriteLogLine(string sCallerName, string sLogFolder,
long lCallerInstance, string sLogLine)
{
lock(this)
{
string sFileName;
sFileName = String.Format("{0}_{1:yyyy.MM.dd}_{2:00}.log",
sCallerName, DateTime.Now, lCallerInstance);
StreamWriter swServerLog =
new StreamWriter(sLogFolder + sFileName, true);
swServerLog.WriteLine(
String.Format("[{0:T}] {1}", DateTime.Now, sLogLine));
swServerLog.Close();
}
}
Windows has given you a great provision to store configuration tidbits and stuff like that… The registry. Why not use it, instead of using custom configuration files?
Below are the functions to create a registry key, and set and get a string value. You can extend the get/set couple for long values and so on. Please note that for defensive programming purpose, I am putting in the supplied default value, in case a registry value is missing. I like this approach better than crying out with an exception. If you are of the other opinion, please feel free to do what you like.
Also note that, many people prefer storing the configuration information in easily modifiable and self-maintainable XML files these days. Be sure about your and your clients' preference and then choose the best suitable option.
using Microsoft.Win32;
using System.IO;
using System.Security;
/// <summary>
/// Tries to read the registry key, if is does not exist,
/// it gets created automatically
/// </summary>
public void CheckRegistryKey(string sKeyname)
{
RegistryKey oRegistryKey =
Registry.LocalMachine.OpenSubKey("SOFTWARE\\" + sKeyname, true);
if(oRegistryKey==null)
{
oRegistryKey =
Microsoft.Win32.Registry.LocalMachine.OpenSubKey("SOFTWARE", true);
oRegistryKey.CreateSubKey(sKeyname);
}
}
/// <summary>
/// Checks for a string value in given path,
/// if not found adds provided default value
/// </summary>
public string GetStringValue(string sKeyname,
string sValueName, string sDefault);
}
if(oRegistryKey.GetValue(sValueName)==null)
{
oRegistryKey.SetValue(sValueName, sDefaultValue);
return sDefaultValue;
}
else
return (string)oRegistryKey.GetValue(sValueName);
}
/// <summary>
/// Sets a string value for given key
/// </summary>
public void SetStringValue(string sKeyname, string sValueName,
string s);
}
oRegistryKey.SetValue(sValueName, sValue);
}
If you are not yet environment conscious, it's time to be. First, thank God. This is something we always need to look up. Now with .NET, we have a single class which lets us access all this wealth of information. What are you looking for? The OS version, CLR version, user name, values of system variables such as the temp folder, physical memory mapped to your app?
All this valuable information can be extracted with the Environment class as illustrated below:
Environment
using System;
public static void GetEnvironmentInfo()
{
// Fully qualified path of the current directory
Console.WriteLine("CurrentDirectory: {0}", Environment.CurrentDirectory);
// Gets the NetBIOS name of this local computer
Console.WriteLine("MachineName: {0}", Environment.MachineName);
// Version number of the OS
Console.WriteLine("OSVersion: {0}", Environment.OSVersion.ToString());
// Fully qualified path of the system directory
Console.WriteLine("SystemDirectory: {0}", Environment.SystemDirectory);
// Network domain name associated with the current user
Console.WriteLine("UserDomainName: {0}", Environment.UserDomainName);
// Whether the current process is running in user interactive mode
Console.WriteLine("UserInteractive: {0}", Environment.UserInteractive);
// User name of the person who started the current thread
Console.WriteLine("UserName: {0}", Environment.UserName);
// Major, minor, build, and revision numbers of the CLR
Console.WriteLine("CLRVersion: {0}", Environment.Version.ToString());
// Amount of physical memory mapped to the process context
Console.WriteLine("WorkingSet: {0}", Environment.WorkingSet);
// Returns values of Environment variables enclosed in %%
Console.WriteLine("ExpandEnvironmentVariables: {0}",
Environment.ExpandEnvironmentVariables("System drive: " +
"%SystemDrive% System root: %SystemRoot%"));
// Array of string containing the names of the logical drives
Console.WriteLine("GetLogicalDrives: {0}", String.Join(", ",
Environment.GetLogicalDrives()));
}
The above function will work with console applications only (as it has Console.Writelines). For your use, modify it the way you need.
Console.Writeline
Watching user activities inside a folder is often a task for application servers. For example, I have a server which needs to wait until user uploads an XML file into a special folder. Once user drops the file there, the server does some processing according to the file contents.
Once you know how to do this thing, I am sure you will find thousands of applications to utilize this trick. And it is not just limited to file creation events, you can watch on virtually all the activities users can do in there...
using System.IO;
// Watches the C:\Temp folder and notifies creation of new text files
public static void WatchTempFolder()
{
// Create the FileSystemoFileSystemWatcher object and set its properties
FileSystemWatcher oFileSystemWatcher = new FileSystemWatcher();
oFileSystemWatcher.Path = "C:\\Temp";
oFileSystemWatcher.NotifyFilter = NotifyFilters.LastAccess
| NotifyFilters.LastWrite | NotifyFilters.FileName |
NotifyFilters.DirectoryName;
oFileSystemWatcher.Filter = "*.txt";
// Add event handlers.
oFileSystemWatcher.Created += new FileSystemEventHandler(OnCreated);
// Begin watching.
oFileSystemWatcher.EnableRaisingEvents = true;
// Wait for the user to quit the program.
Console.WriteLine("Press \'q\' to quit the sample.");
while(Console.Read()!='q');
}
// The event handler
private static void OnCreated(object source, FileSystemEventArgs e)
{
Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType);
}
Please note: The Created event does not guarantee that the other app or user has finished writing the file. For example, many times a server needs to wait for a user to upload a file in a specific folder. The Created event is raised as soon as the user starts uploading the file, but the server needs to wait until the copy/upload process completes. There is no ideal method I am aware of to ensure the transfer completion. A work-around is to wait until an open operation on that file can succeed. While the copy/upload is in progress, open will fail.
Created
I don't know about you, but I had always starved to give my app users an extra helping hand if they need one. Microsoft provides a really neat COM component called MS Agent for this purpose. It can show a friendly cartoonish character with our app - to read text, do animations and add some life to your otherwise boring app!
(1) Add the MS Agent COM component in your VS.NET toolbox by clicking Visual Studio menu Tools > Add/remove toolbox items > COM Components. Check ‘Microsoft Agent Control 2.0’ and click ok.
(2) The agent control will now be shown under the ‘components’ tab in the VS toolbox. In your Windows Form based application, drag and drop it on your form. The component will get added to the form and you will see the following member in your form
public class Form1 : System.Windows.Forms.Form
{
private AxAgentObjects.AxAgent axAgent1;
Now manually add the following member just after the above code.
private AgentObjects.IAgentCtlCharacter speaker;
(3) Now you have the agent infrastructure in place and you also have the speaker object. On a suitable event like form_load or button_click Add the following code:
try
{
this.axAgent1.Characters.Load("merlin" , "merlin.acs");
this.speaker = this.axAgent1.Characters["merlin"];
this.speaker.Show(null);
this.speaker.MoveTo(800, 600, null);
this.speaker.Play("Explain");
this.speaker.Speak("Give some text here for me to talk...", null);
}
catch
{
MessageBox.Show("Invalid charater");
}
Note that it is better to load the agent once, typically when your form loads. And then use it on various events as you want.
(4) That’s it, you are done. Execute the program and see the agent in action. In case you do not have the agent files installed, visit the following link to download agent files and if required TTS engines for desired languages:[^]
Please note that using the Agents makes sense only in the right apps and if utilized correctly. If used in a wrong app or in a wrong way, it can be very irritating to users.
Sometimes executing a batch file or a utility program with command line arguments is so handy than to write your own code. For example suppose your program generates an report in MS Excel format, you can use the code given below to launch the freshly generated file in Excel…
System.Diagnostics.Process.Start(
@"c:\program files\microsoft office\excel.exe", @"c:\myFile.xls");
I have deliberately not attached code samples and project files. Because the idea is to keep the code as concise and task-specific as possible. All you need to do is, copy-paste the example functions directly into your code and start using them.
If I receive reasonable responses from users asking for downloadable code files, I will plan to upload a ToolBox class DLL which will encapsulate all this functionality so that it can be used as a component in your projects.
I have compiled this list while working on a C# .NET server product for the first time, so minor inconsistencies ought to exist. Please correct me if you have better solutions.
I hope you enjoyed this article and will be using some ideas from this in your projects... Best of luck and thanks a lot!
This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.
A list of licenses authors might use can be found here
((System.ComponentModel.ISupportInitialize)(this.axAgent1)).EndInit();
Console.WriteLine()
System.Diagnostics
EventLog
System.Web.Mail
System.Web
System.Net
Resolve
GetHostByName
mxmissile
System.Web.Mail.SmtpMail
General News Suggestion Question Bug Answer Joke Praise Rant Admin
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages. | http://www.codeproject.com/Articles/8210/Top-10-tips-and-tricks-to-jazz-up-your-Csharp-busi | CC-MAIN-2015-48 | refinedweb | 2,119 | 50.94 |
Xinput GamePad Controller (v2.5)
Slightly better version of the xinput implementation for unity based on the amazing work done by speps (), allows to control four gamepads with a very simple to use API and easily map computer inputs to gamepad button using a custom inspector.
##How to use : Simply drag the “LaunchGamePadController” script in on any object in your scene (preferably an empty). Then in your character controller script for instance, add the following :
GamePadController.Controller gamePad; //Declaring a variable for our gamepad void Start() { gamePad = GamePadController.GamePadOne; //GamePadOne for first controller GamePadTwo for the second one, and so on... }
And then to use the buttons just write :
gamePad.A.Pressed (if you want to check that the button A has been pressed [one frame]) gamePad.A.Held (if you want to check that the button A is held) gamePad.A.Released (if you want to check that the button A has been released [one frame]) gamePad.A.Zero (is the default state)
To get the axis inputs just use :
gamePad.LeftStick.X (for the x axis of the leftstick).
Thanks to speps’ work you can also use vibrations :
gamePad.SetVibration(100,100) //for 100% intensity on both motors gamePad.StopVibration() //to stop the vibration gamePad.SetVibration(100,100,5) //to have the gamepad vibrate for 5 seconds then stop
You can also very easily map computer inputs to the gamepad inputs, that way the ‘v’ key of your keyboard will represent the A button of your gamePad :
if(gamePad.A.Pressed) Debug.Log("Pressed")
that way this code will allow you to have both inputs (computer and gamepad) working at the same time or only one at a time (if the gamePad is not connected) with a single line of code.
//--> Additional Objectives //add dualstick for 2d games //add deadzone function //add more than 4 controllers to gamepadcontroller //change gamepad number classes to enum, ex : GamePad.One //-->Computer Inputs //check all existing unity assets (case insensitive serach), auto-correct axis if incorrect case //First controllers values get copied in all other controllers (so as not to rewrite them) //allow change of key or button or axis at runtime (public class and variables plus custom functions) //Check if button is axis and transform axis values to button //make some deafult parameters (Ex : Right Stick is always axis, if button is axis, then only one direction) //Add other default Parameters (Ex : LeftStick X&Y already have Horizontal and Vertical written, etc...) //Add smart autocomplete //Use custom editor for "enable controller" //Use structs (same as GamePadController) for computer inputs //Save/Load preconfigured inputs in a file | https://unitylist.com/p/18u/Xinput-Game-Pad-Controller | CC-MAIN-2019-35 | refinedweb | 435 | 59.33 |
It's not the same without you
Join the community to find out what other Atlassian users are discussing, debating and creating.
OK here is my issues. I have a situation where I want to make a field required when a user checks a check box. For this discussion my checkbox field is checkBoxField with a single choice of Yes. The field I want to make required is requiredTextField. I am using the Behaviours add-on of Scriptrunner wit the following Configuration:
The behavior is mapped to ProjectA:Story
Validation Script attached to checkBoxField
Here is my script.
def description = getFieldByName("requiredTextField")
def checkBox = getFieldById(getFieldChanged())
def selectedOption = checkBox.getValue() as String
def isYesSelected = selectedOption == "Yes"
description.setRequired(isYesSelected)
I've done this before with select lists but for some reason the checkbox is kicking my butt. Any help and/or advice would be appreciated. Thanks in advance. .pd
Hi Peter,
What is the exact problem you are experiencing? Is the text field not correctly getting set as required? I've tried reproducing your setup on my local Jira instance and it's working correctly, but it may be that my configuration is different to yours in some important respect.
Thanks,
Jake
To reproduce on my system (not that it will be the same as yours)
1. navigate to the correct project.
2. Open an existing Story.
3. Click the Edit Issue button.
4. Click the correct tab.
5. Scroll down and check the checkbox.
the requiredTextField is not required.
@Joanna Choules [Adaptavist], thanks for the confirmation that the script works. I found a typo in the field name. Fixing this fixed the problem.
. | https://community.atlassian.com/t5/Adaptavist-questions/Scripting-Checkbox-Behaviour-using-Scriptrunner/qaq-p/692800 | CC-MAIN-2019-09 | refinedweb | 274 | 60.41 |
On Sat, 21 Feb 2009, Diego Biurrun wrote: > On Sat, Feb 14, 2009 at 03:09:16AM +0100, Diego Biurrun wrote: >> >> Ooops, I indeed forgot about that. After putting r5962 of fft_3dn2.c in >> place I tried compiling with gcc 4.1, 3.4, 3.3 and 2.95. After changing >> asm to __asm__ and adjusting the function declaratin in dsputil.h it >> compiles fine with gcc 4.1, 3.4 and 3.3. Only 2.95 fails and outputs >> the following error message: >> >> libavcodec/x86/fft_3dn2.c: In function `ff_imdct_calc_3dn2': >> libavcodec/x86/fft_3dn2.c:214: Invalid `asm' statement: >> libavcodec/x86/fft_3dn2.c:214: fixed or forbidden register 7 (sp) was spilled for class GENERAL_REGS. >> >> I'm sure we could add a check for this to configure. > > Loren, what do you think? Since it's not a lack of a feature but rather a failure of optimization, I guess you'd have to paste exactly the same asm constraints into configure and hope the context doesn't affect it. > Also note that merging back the code from r5964 is nontrivial for me > since I know zilch about x86 asm while you can probably do it in two > minutes or so... attached --Loren Merritt -------------- next part -------------- Index: libavcodec/x86/fft_3dn2.c =================================================================== --- libavcodec/x86/fft_3dn2.c (revision 17512) +++ libavcodec/x86/fft_3dn2.c (working copy) @@ -72,12 +72,11 @@ __asm__ volatile("movd %0, %%mm7" ::"r"(1<<31)); #endif for(k = 0; k < n4; k++) { - // FIXME a single block is faster, but gcc 2.95 and 3.4.x on 32bit can't compile it __asm__ volatile( - "movd %0, %%mm0 \n" - "movd %2, %%mm1 \n" - "punpckldq %1, %%mm0 \n" - "punpckldq %3, %%mm1 \n" + "movd %1, %%mm0 \n" + "movd %3, %%mm1 \n" + "punpckldq %2, %%mm0 \n" + "punpckldq %4, %%mm1 \n" "movq %%mm0, %%mm2 \n" PSWAPD( %%mm1, %%mm3 ) "pfmul %%mm1, %%mm0 \n" @@ -91,12 +90,10 @@ #else "pfpnacc %%mm2, %%mm0 \n" #endif - ::"m"(in2[-2*k]), "m"(in1[2*k]), - "m"(tcos[k]), "m"(tsin[k]) - ); - __asm__ volatile( - "movq %%mm0, %0 \n\t" + "movq %%mm0, %0 \n" :"=m"(z[revtab[k]]) + :"m"(in2[-2*k]), "m"(in1[2*k]), + "m"(tcos[k]), "m"(tsin[k]) ); } | http://ffmpeg.org/pipermail/ffmpeg-devel/2009-February/065803.html | CC-MAIN-2016-26 | refinedweb | 359 | 82.24 |
Install Minecraft
If Minecraft: Pi edition isn't already installed on your Pi, head over to and follow the instructions.
The API
The API allows you to write programs which control, alter and interact with the minecraft world, unlocking a whole load of minecraft hacking. How about creating massive structures at the click of a button or a bridge which automatically appears under your feet allowing you to walk across massive chasms or a game of minesweeper, a huge real time clock, a programmable directional cannon, turn blocks into bombs or the game snake?
Minecraft is a world of cubes or blocks, all with a relative size of 1m x 1m x 1m, and every block has a position in the world of x, y, z; x and z being the horizontal positions and y being the vertical.
The API works by changing the ‘server’, which runs underneath the game, allowing you to interact with these blocks and the player, such as:
- Get the player’s position
- Change (or set) the player’s position
- Get the type of block
- Change a block
- Change the camera angle
- Post messages to the player
Libraries
You can interact with the server directly by sending a message to it, but the nice people at Mojang also provide libraries for python and java which simplify and standardise using the API.
The libraries are installed along with the game in the /opt/minecraft-pi/api/java and api/python directories.
The following example is written in Python and uses Mojang’s python api library.
API Example
Create Directory
We need to create a directory to put our program into.
mkdir ~/minecraft-magpi
Create program
Open the Python 2 editor Idle (or your favourite editor) and create a program file called minecraft-magpi.py in the ~/minecraft-magpi directory
We are going to need 3 modules, the minecraft.py and block.py modules from the minecraft directory containing the library we just copied and the standard time module so we can introduce delays into our program.
import mcpi.minecraft as minecraft
import mcpi.block as block
import time
Next, we need to use the Minecraft class in the python library to create a connection to the game’s server, this object will also be how we interact with the game and will provide access to all the functions. When your program runs this statement, Minecraft will have to be running and you will need to be in a game, otherwise you will get errors.
mc = minecraft.Minecraft.create()
Using our minecraft object, mc, we can then interact with the game and send the player a message. We will also put a delay in using the time.sleep() function otherwise the whole program will run too fast for us to see what’s going on.
mc.postToChat("Hello Minecraft World")
time.sleep(5)
Using the program built so far, you can test to make sure everything is working. Load up minecraft and create a (or enter an existing) world then if you’re using Idle pick 'Run, Run Module' from the menu. If all has been setup correctly you will see the “Hello Minecraft World” message in the game.
Interacting with the player is done through the player class of the mc object allowing us to find the position and change the position of the player. The next block of code finds the players position using the getPos() command, which returns an object of x,y and z coordinates, the setPos() command is then used to move the player 50 blocks up, by adding 50 to the player’s y coordinate. We then add a delay, so there is enough time for your player to fall down to the ground!
playerPos = mc.player.getPos()
mc.player.setPos(playerPos.x, playerPos.y + 50, playerPos.z)
mc.postToChat("Dont look down")
time.sleep(5)
You can use the position of the player as a starting point for interacting blocks, this way you can find out what block the player is standing on or place blocks around the player, there is however a challenge, the x, y and z coordinates returned by the getPos() function are decimals (aka floats), as your player can be in the middle of a block, but to interact with blocks we need to use whole numbers (aka integers), so we need to use the function getTilePos(), which returns the block (or tile) he’s standing on.
The code below gets the players tile position, it then calls the minecraft API’s getBlock() function to find out the type of block the player is standing on (by minusing 1 from the y co-ordinate) before using setBlock() to create blocks of the same type the player is standing on around him. So if your player is standing on DIRT, he will end up with DIRT surrounding him, however if he is standing on STONE, STONE will appear.
playerTilePos = mc.player.getTilePos()
blockBelowPlayerType = mc.getBlock(playerTilePos.x, playerTilePos.y - 1, playerTilePos.z)
mc.setBlock(playerTilePos.x + 1, playerTilePos.y + 1, playerTilePos.z, blockBelowPlayerType)
mc.setBlock(playerTilePos.x, playerTilePos.y + 1, playerTilePos.z + 1, blockBelowPlayerType)
mc.setBlock(playerTilePos.x - 1, playerTilePos.y + 1, playerTilePos.z, blockBelowPlayerType)
mc.setBlock(playerTilePos.x, playerTilePos.y + 1, playerTilePos.z - 1, blockBelowPlayerType)
mc.postToChat("Trapped you")
time.sleep(5)
We have now trapped our player within 4 blocks (providing he doesn’t break out!), in order to set him free we need to remove a block. Removing blocks is done using setBlock(), but rather than making the block solid like WOOD or STONE we set it to AIR.
mc.setBlock(playerTilePos.x + 1, playerTilePos.y + 1, playerTilePos.z, block.AIR)
mc.postToChat("Be free")
time.sleep(5)
A full list of all the available blocks can be found in either the minecraft api specification or in the block.py module in the python api library ~/mcpi/api/python/mcpi/block.py.
The API also allows you to set many blocks at a time, allowing you to create cuboids very quickly using the setBlocks() command. It works by specifying 2 sets of x,y,z coordinates which it then fills the gap between the 2 coordinates with a certain block you pass as the final parameter. The code below will create a diamond floor underneath our player 50 blocks (across) x 1 block (up) x 50 blocks (along), with our player in the middle (i.e. 25 behind and to the left, 25 in front and to the right).
mc.setBlocks(playerTilePos.x - 25, playerTilePos.y - 1, playerTilePos.z - 25, playerTilePos.x + 25, playerTilePos.y -1, playerTilePos.z + 25, block.DIAMOND_BLOCK)
mc.postToChat("Now thats a big diamond floor!")
To recap on the functions covered in this article:
- postToChat(message) - communicate with the player(s) in the game
- getBlock(x, y, z) - get a block type for a specific position
- setBlock(x, y, z, blockType, blockData) - set (change) a block to a specific blockType
- setBlocks(x1, y1, z1, x2, y2, z2, blockType, blockData) - set lots of blocks all at the same time by providing 2 sets of co-ordinates (x, y, z) and fill the gap between with a blockType
- player.getPos() - get the precise position of a player
- player.setPos(x, y, z) - set (change) the players position
- player.getTilePos() - get the position of the block where the player current is
There are a few other functions available in the api which should be explored but using only the small number discussed in this article, its possible, with some imagination and a small amount of programming knowledge to create some quite fantastic constructions, tools and utilities.
I love minecraft, its a tremendously creative game and with the Pi edition’s API it opens up new level of creativity and will hopefully encourage more people to try their hand at programming.
If you want to see more examples of what I have done with Minecraft: Pi edition (e.g. a massive analogue clock, the game of snake, an auto bridge which appears under your feet or the whole of Manhattan) head over to my Minecraft page.
I love this blog!! I've always wanted to know how to mod Minecraft Pi. But can you make it a little clearer?
What are you struggling with? Is there something specific you want clearer?
Well, I had trouble at first. I was thinking that maybe you can put in which files you are editing, etc.
I was thinking about modding the minecraft files so I can add in new blocks or change how the world generates
Is this possible?
This comment has been removed by the author.
WHAT IS mkdir ~/minecraft-magpi AND WHERE CAN I FIND IT??? I CHECKED THROUGH MY COMPUTER, PORPERTIES OF EVERUTHING... AND STILL COULDN'T FIND IT... WHEN YOU SAY; We need to create a directory to put our program and api library into mkdir ~/minecraft-magpi. I GET TOTALLY COFUSED BECAUSE I DON'T KNOW WHERE ALL THIS STUFF IS... :/
AS I SAID BEFORE, I AM WORKING ON A PROJECT THAT WILL ME MASSIVE!!! SO PLEASE HELP AND REPLY FAST!
PS: GREAT JOB WIHT CREATING THIS PROGRAM
Hi
mkdir is the command to create a directory. mkdir ~/minecraft-magpi creates a directory called minecraft-magpi in the /home/pi directory. You would run these commands in the terminal.
You mention your computer. Are you using a raspberry pi?
Have you thought about starting with some linux usage tutorials before embarking on your big project, it would give you some useful knowledge.
Best of luck
Mart
yes, i meant my raspberry pi. i understand that the stuff should run in something, but where? i am new to raspberry pi and dont really know how it works... Thank you for the reply!
If you are using the desktop. You can run this commands in a terminal, double click LX Terminal on the desktop to open up the command window.
THNX Martin!!! it is working great! you dont know where i could find a program like this one (that builds things for you) for computer?
A program like what one?
a program that builds stuff for you on minecraft.
I have built several programs that automatically build things in minecraft, check out my minecraft projects here -
Also take a look at my program which converts 3d models into minecraft, it might give you some inspiration.
Thanks! This got me started with the API so now I know roughly how to make something of my own!
ImportError: no module named connection
Are you by any chance using Idle 3 (and therefore Python 3)? The API doesnt work with python 3 (without doing some fiddling).
I have an error, when I hit F5 this is what comes up in the Python Shell...
Traceback (most recent call last):
File "/home/pi/minecraft-magpi/minecraft-magpi.py", line 1, in
import minecraft.minecraft as minecraft
File "/home/pi/minecraft-magpi/minecraft/minecraft.py", line 1, in
from connection import Connection
Import Error: No module named connection
Can you help me?
Are you by chance using IDLE3 (and therefore Python 3?). If so switch to IDLE Python 2.x). The api modules arent python 3.
Um.. How would I do that? I'm not very good with the Pi.
When you double click on IDLE on the desktop, pick IDLE and not IDLE3
I'm of the C64 and Amiga generation (wonderful wonderful times for all of us fortunate enough), and now have the absolute privilege to meet people like yourself doing what we did for fun way back in the day.. It swells me with pride to see what you are doing, and now I can share the basics with my 13 yo son in his favourite game .. A truly magical time for us old guys to pass on... It is a privilege to meet you Martin, and continued good fortune to you for establishing this wonderful project
Thanks a lot for the encouraging words... Im not quite so pleased with being an "old guy" tho ;)
This comment has been removed by the author.
when i run the.program it says
importerror no module named minecraft
please help
Did you copy the minecraft python library to your program's folder, this line:
cp -r ~/mcpi/api/python/mcpi ~/minecraft-magpi/minecraft
yes
could i just copy the code from minecraft.py and block.py and just put it in there???
If its setup correctly you should have a folder called minecraft in the same folder as your minecraft-magpi.py program which has got all the api py files including minecraft.py, block.py, connection.py, vec3.py, etc
I got that /home/pi/minecraft-magpi/minecraft is not a directory
Sorry its difficult to offer any advice other than start at the top and try again. You should have copied the minecraft python api library to the /home/pi/minecraft-magpi/minecraft directory when you did this step:
cp -r ~/mcpi/api/python/mcpi ~/minecraft-magpi/minecraft
This comment has been removed by a blog administrator.
I had no trouble with the hello world one, but the next two are making this show up when I run them:
Traceback (most recent call last):
File "/home/pi/minecraft-magpi/TrappedYou.py", line 1, in
playerTilePos = mc.player.getTilePos()
NameError: name 'mc' is not defined
I think you have taken my code instructions to literally, the 2nd portion of code:
playerPos = mc.player.getPos()
mc.player.setPos(playerPos.x, playerPos.y + 50, playerPos.z)
mc.postToChat("Dont look down")
time.sleep(5)
should be added to the bottom of the first code
import minecraft.minecraft as minecraft
import minecraft.block as block
import time
mc = minecraft.Minecraft.create()
mc.postToChat("Hello Minecraft World")
time.sleep(5)
Through the tutorial you are meant to build up 1 program not many programs. I hope that makes sense.
The reason you are getting the error is because your program is create "mc", because you program is missing the code
mc = minecraft.Minecraft.create()
Thanks so much! Also, did you know that the current version of NOOBS (raspberrypi.org/downloads) has Minecraft Pi Edition pre installed? I didn't like it that way, because I Like going inside and changing the names of worlds and things like that. :) I went ahead and uninstalled the pre-installed package, then did it the way your tutorial shows, then I played around until I got a nice grass block icon for it on the desktop. Just wondering, if I follow your tutorial for making a Minecraft server on my Raspberrry Pi, does it run a PC Minecraft server, or a Pi Edition one? Keep up the good work!
I did. I'll update the post at some point...
Hi, at the Raspberry Jam at PyConUK Coventry, Sept 2014, you handed out a neat four-page (4xA5) version of this article, which would be ideal for schools. Is that available as a freely distributable PDF, please, and if so from where? Looking forward to your book.
i am getting an error : cp -r ~/mcpi/api/python/mcpi ~/minecraft-magpi/minecraft
when i do the: cp -r ~/mcpi/api/python/mcpi ~/minecraft-magpi/minecraft command in the LX terminal
hi I am new to the raspberry pi and I am using the IDLE to code. I have got an error coming up on the screen when I run it saying. in
import minecraft.Minecraft ImportError: No module named. when you reply could you break it down so that I could understand the code a bit better. and what does it mean by module.
Minecraft comes installed with raspbian as default now so my tutorial is a little out of date. Change your import to be import mcpi.minecraft as minecraft.
I have updated the tutorial to reflect the latest changes in Raspbian. Hopefully it should work for you now.
Hi.
I wondered if you can help.
I'm trying to set minecraft up as a coding tool for primary school kids.
I've bought your book and followed your instructions, but the first program won't work.
I've installed the AIMStarterKitPi.tar.gz onto the pi (minecraft Pi was already installed) and extracted this as per your instructions in the book.
I've then followed you instructions and entered the code into IDLE (not IDLE3) and triple checked it for accuracy.
But when I run it I get the following error in line 1 from connection import connection:
ImportError: No module named connection.
How do I fix this? I don't understand what's gone wrong?
Hi,
The usual problem if you get the "no module named connection" error is because the code is being run in python 3 not python 2. This might not be your issue because you seem pretty clear that you are using IDLE (and not IDLE 3), but I would double check that the python shell shows you are running Python 2.x.x.
If you submit a post in the forum along with your code I will do my best to help you.
You might also find the videos on the companion website, they take you through adventure 1 step by step.
Mart
Hi mart,
Thanks for the help!
I feel a bit daft now, i'd opened both IDLE and IDLE3 by accident and ended up in the IDLE3 window so all is resolved now!
Thanks again for your help!
Chris
No problem. We have all been there. Im glad you are up and running.
#!/bin/sh
# /etc/init.d/tightvncserver
# Set the VNCUSER variable to
the name of the user to start
tightvncserver under
VNCUSER=’pi’
case “$1” in
start)
su $VNCUSER -c ‘/usr/bin/
tightvncserver :1’
echo “Starting TightVNC
server for $VNCUSER”
;;
stop)
pkill Xtightvnc
echo “Tightvncserver stopped”
;;
*)
echo “Usage: /etc/init.d/
tightvncserver
{start|stop}”
exit 1
;;
esac
exit 0
Do you have a point to make?
###=pi
HOME=/home/pi
export USER HOME
case "$1" in
start)
echo "Starting VNC Server"
#Insert your favoured settings for a VNC session
su - pi -c "/usr/bin/vncserver :0 -geometry 1280x800 -depth 16 -pixelformat rgb565"
;;
stop)
echo "Stopping VNC Server"
/usr/bin/vncserver -kill :0
;;
*)
echo "Usage: /etc/init.d/vncboot {start|stop}"
exit 1
;;
esac
exit 0
Its an init.d script for starting a VNC server... Well done. Are you just posting obscure spam?
Good morning, I've got a question about interacting with multiple players. My son and I are doing some programming and connecting to the same world. While we can see the blocks each other is creating we are having problems with interacting with each other's programs. Specifically we created transporters and it leverages a while loop uses the getTilePos () to determine the location of a player but only seems to recognize the player associated to the computer the script is running on. Is there something I can do to make it functional for all players. Also is there a solution for renaming players? Thanks this blog is a huge help for my 9 year old programmer
Hi Michael,
In order to interact with multi players in the same game you need to use the 'entity' functions in the api. Have a look at "MInecraft Entity" in the Python API Reference
For info - when you use mc.player.getTilePos() it only returns data for the 'host' player, you can use mc.entity.getTilePos(entityid) to return the position for any player.
If you are running 2 programs on 2 different Pi's, you will need to use the IP address when creating the connection to the Pi which is hosting the Minecraft game. e.g. mc = minecraft.Minecraft.create("192.168.1.1")
I hope this helps.
Martin
Martin, thanks using entity worked like a charm. We have printed out your api reference it is awesome companion to the adventures book. Really let's us expand the options and complexity of the solutions. Tons of fun, thanks for putting that together.
Quick follow up question do know how to change a players name or where that is stored?
Good news. Unfortunately the Pi edition doesn't allow you to change the players name.
Martin,
I've got a Raspberry Pi with Minedraft installed with it and I have your 'Adventures in Minecraft' book, but I am stuck at adventure 1!
I have written down all of the code to say "Hello Minecraft World" , (CAREFULLY(with no mistakes)) but when I press 'Run' it switches to Python Shell and says, "ImportError: No module named mcpi.minecraft"
What should I do?!
Have you downloaded the starter kit and saved your program to the 'MyAdventures' folder? The error is saying it can't find the minecraft api module which is in the MyAdventures/mcpi directory.
Create a new post in our forum, it'll be easier to help you there, following the Adventures in Minecraft tab at the top of the page.
I don't have the starter pack,
I didn't know where to get it.
From
Wiley.com/go/adventuresinminecraft
Follow Adventure 1 it'll talk you through download and install
This comment has been removed by a blog administrator.
I have downloaded the starter pack for my Pi and it came up with an Xarchiver window and it showed the API and just some Licenses.
What do I do now? I tried the "Hello Minecraft World" command again but again it said, "ImportError: No module named mcpi.minecraft"!
Well that sounds positive. Did you extract the files to the /home/pi directory?
There is a video on the wiley.com/go/adventuresinminecraft website which shows you how to setup your raspberry pi and get hello minecraft world working. Perhaps that might help?
It would be great if you could create a post in the forum if you need more help, that way others can help and we can share links, pictures, videos, etc.
Thanks for your help Martin!
I like the adventures you have made. :)
Hi Martin, it is kind of annoying when i want to run obsidz_teleport in minecraft pi cos i have to type it in lxterminal. Do you know any way to make it so that it runs the code automatically when i open one of my worlds. Please help!
Martrin, great job you are doing - I am a teacher and Minecraft is a super motivator for teaching Python. I few months or more back I bought some B+ Pis. Downloaded and installed the then latest Raspian image.
The new Minecrat tutorials refer to IDLE 3 now but I get errors when running Python 3 scripts for Minecraft. I ran apt-get to download and install updates but this has not fixed the probelm - what do you suggest? If I download the latest image onto my micro SD card will this fix the problem? Many thanks. Hastklass.
Do you think I can download pi minecraft on a chromebook?
you can download it from pi.minecraft.net using any browser, I doubt it would run though.
Also, I don't have internet on my pi. Do you think I can download your programs on another computer, and then copy them to my SD card?
Yes.
Do you know anything about the Koding app on google chrome? If so, is it possible to, throught the terminal on the app, download the files and minecraft and play them inside the app on a chromebook?
Sorry Im not familiar with the Koding app.
OK. I saw that there is a version of raspbian that is newer than Wheezy. Is there a way to update my version of raspbian without loosing all my files?
sudo apt-get update
sudo apt-get dist-upgrade
The above commands will do it and won't affect any of your Minecraft Python files stored under /home/pi.
HOWEVER, you should always make sure that you have backups of ALL critical files. Copy them onto a USB stick, "scp" them someplace, anything...
Hi Martin!
It's me again. :/
I have extracted the MyAdventures folder and it has worked! (small accomplishment)
But,(not again!), this time I ran the module, after extracting the file, and instead of the "no module named: mcpi.minecraft", I got a new message saying "ImportError: No module named connection"!
What do I do?
Use Python 2 not Python 3
ok, thanks!
Hi Martin. New to this, and I have an issue. When I run the module, I get NameError: name 'player' is not defined. Please tell me what stupid mistake I am making!
Are you doing mc.player... ?
(mc is a vriable holding the Minecraft client reference).
The player.getDirection(), player.getPitch(), etc functions are failing for me (vanilla Raspian install). The "old" player functions (getTilePos(), etc) work. What do I need to do to enable them ?
I have created a small lisp package that implements the python api for minecraft, if anyone wants to test it is at
Hello Martin, from Paris France.
Just got your Adventures in Minecraft, I'm pretty enthusiast about it.
A few days before I succeeded setting up Minecraft on a Raspberry Pi 3, thanks to Daniel Lemire's tutorial :
Playing with my seven year old daughter on this Minecraft server, I was wondering if by any chance there was a way to enable / apply the Python scripts your refering to ?
Thanks for any help. All the best.
Hi Martin,I really like your book,
I was just wondering why it looks impossible to type Command Lines into the chat ?
I tried to type into the bukkit server terminal :
>op
The server answered : >Opped
But I still get error messages telling Commands are not recognised.
Thank you Martin.
Hmm some text is missing because I used greater and lesser signs.
I typed op username
and got Opped username :)
Hi Martin
I teach children programming. I wanted to use Python and Minecraft. All are logged into the same server. On computers where there is no server Minecraft does not respond to commands with Python. Does not display any error. What is wrong?
In order to use python to control Minecraft, you need to connect to an API, this API is either Minecraft: Pi Edition or for the full version of Minecraft, a plugin, usually RaspberryJuice, which runs on a server.
Without a plugin providing the API you cant connect. Simple as that really!
hi martin i have a problem i want to change the wooden door into a iron dooor but it won't change
Are you using Minecraft: Pi edition or the RaspberryJuice and full fat minecraft?
If your using the Pi edition, I dont think there are any iron doors. | https://www.stuffaboutcode.com/2013/04/minecraft-pi-edition-api-tutorial.html?showComment=1421254521244 | CC-MAIN-2019-35 | refinedweb | 4,450 | 73.37 |
Read Excel XLS spreadsheets with Python
Someone mailed out information to a club I'm in as an .XLS file. Another Excel spreadsheet. Sigh.
I do know one way to read them. Fire up OpenOffice, listen to my CPU fan spin as I wait forever for the app to start up, open the xls file, then click in one cell after another as I deal with the fact that spreadsheet programs only show you a tiny part of the text in each cell. I'm not against spreadsheets per se -- they're great for calculating tables of interconnected numbers -- but they're a terrible way to read tabular data.
Over the years, lots of open-source programs like word2x and catdoc have sprung up to read the text in MS Word .doc files. Surely by now there must be something like that for XLS files?
Well, I didn't find any ready-made programs, but I found something better: Python's xlrd module, as well as a nice clear example at ScienceOSS of how to Read Excel files from Python.
Following that example, in six lines I had a simple program to print the spreadsheet's contents:
import xlrd for filename in sys.argv[1:] : wb = xlrd.open_workbook(filename) for sheetname in wb.sheet_names() : sh = wb.sheet_by_name(sheetname) for rownum in range(sh.nrows) : print sh.row_values(rownum)
Of course, having gotten that far, I wanted better formatting so I could compare the values in the spreadsheet. Didn't take long to write, and the whole thing still came out under 40 lines: xlsrd. And I was able to read that XLS file that was mailed to the club, easily and without hassle.
I'm forever amazed at all the wonderful, easy-to-use modules there are for Python.
[ 09:58 Aug 31, 2011 More programming | permalink to this entry | comments ] | http://shallowsky.com/blog/programming/read-xls-with-python.html | CC-MAIN-2015-14 | refinedweb | 311 | 73.07 |
PHP Gets Namespace Separators, With a Twist
Soulskill posted more than 5 years ago | from the or-maybe-more-of-a-slant dept.
."
Going back to DOS style... (5, Funny)
joaommp (685612) | more than 5 years ago | (#25518371)
... and comming full circle.
Re:Going back to DOS style... (0, Troll)
Dogtanian (588974) | more than 5 years ago | (#25518459)
Going back to DOS style...
No; DOS used the backslash as a directory separator (since- apparently- someone had permitted forward slash to be a legal filename character before subdirectories had been introduced).
AFAIK PHP uses the forward slash for that purpose (or does this depend upon the server/OS it's running under?) Either way, namespaces have nothing to do with the infamous DOS usage.
Re:Going back to DOS style... (4, Informative)
Anonymous Coward | more than 5 years ago | (#25518491)
Uhm no. Because the DOS commands used '/' for indicating options as opposed to the '-' of the UNIX world.
Re:Going back to DOS style... (2, Informative)
larry bagina (561269) | more than 5 years ago | (#25518507)
which was based on CPM and VMS.
Re:Going back to DOS style... (5, Funny)
joaommp (685612) | more than 5 years ago | (#25518509)
Jeez, take a joke as it is, will you?
Re:Going back to DOS style... (0)
Anonymous Coward | more than 5 years ago | (#25519093)
It isn't much of a stretch to consider a subdirectory as a namespace for file names. It's hard to believe now, but back then we had plenty of systems with no directory support - all files had to have a unique name. In this context, a subdirectory was a wonderful new feature, with much the same advantages as a namespace has in programming.
Re:Going back to DOS style... (-1, Troll)
Pikiwedia.net (1392595) | more than 5 years ago | (#25518523)
Re:Going back to DOS style... (1)
lysergic.acid (845423) | more than 5 years ago | (#25518911) Answers.com adds additional content/features (dictionary results & pronounciation audio clips) to the Wikipedia articles--and they also have a search feature. frankly, i don't see what value Pikiwedia has aside from being yet another Wikipedia mirror.
Re:Going back to DOS style... (1)
NemosomeN (670035) | more than 5 years ago | (#25518977)
Re:Going back to DOS style... (2, Insightful)
The Bender (801382) | more than 5 years ago | (#25518955)
FRIST PSOT (-1, Troll)
Anonymous Coward | more than 5 years ago | (#25518381)
where is it?
what wrong with (0, Offtopic)
netdur (816698) | more than 5 years ago | (#25518385)
dot?
php now is anti-slash dot?
Re:what wrong with (2, Funny)
FooAtWFU (699187) | more than 5 years ago | (#25518499)
[sic]
Re:what wrong with (4, Insightful)
anotherone (132088) | more than 5 years ago | (#25518501)
PHP uses the . as the concatenation operator. PHP does not support operator overloading...
Re:what wrong with (2, Informative)
mysidia (191772) | more than 5 years ago | (#25518853) interpreted as a concatenation.
I.e. $X = $A . $B
Is a concatenation
$X = $A.$B
Is a parse error
$X = $A.B
Is an assignment of 'X' to the 'B' variable within the 'A' namespace
Re:what wrong with (4, Insightful)
moderatorrater (1095745) | more than 5 years ago | (#25519017).
Another fashionable addition for PHP: (4, Insightful)
Anonymous Coward | more than 5 years ago | (#25518387)
PHP 5.3 also adds support for local GOTOs. This langauge is so up with the times.
Can\'t read summary (5, Funny)
jspenguin1 (883588) | more than 5 years ago | (#25518391)
WTF? (1, Insightful)
Anonymous Coward | more than 5 years ago | (#25518403)
Being different to be different, aren't we?
Re:WTF? (4, Interesting)
ThePhilips (752041) | more than 5 years ago | (#25518723)? (5, Insightful)
caluml (551744) | more than 5 years ago | (#25518819)
I think their decision to use '\' is very very dumb one.
You've summed up my opinion concisely. That is *truly* retarded to use the (almost?) universal escape character for another reason. Almost as retarded as Microsoft going with \ for a directory separator.
Re:WTF? (1)
dascritch (808772) | more than 5 years ago | (#25519043):WTF? (2, Funny)
moderatorrater (1095745) | more than 5 years ago | (#25519055)
That's because.. (1, Insightful)
Anonymous Coward | more than 5 years ago | (#25518405)
There's obvious drawbacks for using a period (.) as a string concatenator, it's easy to put strings together since typing a period is a lot easier than a plus (+), but this means you can't use a period for namespaces as many OO coders are used to..
Re:That's because.. (4, Insightful)
SoapBox17 (1020345) | more than 5 years ago | (#25518883):That's because.. (1)
Tablizer (95088) | more than 5 years ago | (#25518939)
What about VB-style "&" for concatenation?
Re:That's because.. (1)
moderatorrater (1095745) | more than 5 years ago | (#25519107)
Re:That's because.. (1)
coryking (104614) | more than 5 years ago | (#25518957) the result of this bit of javascript?
var myInt = 1.0;
var myStr = "hello"
alert(myStr + myInt);
What should that return?
I dunno, maybe I'm full of it, but I just dont like when dynamic languages use "+" for both addition and concatenation.
Re:That's because.. (1)
Fweeky (41046) | more than 5 years ago | (#25519119)
Python: TypeError: cannot concatenate 'str' and 'float' objects
Ruby: TypeError: can't convert Float into String
Weak typing is the problem, not dynamic typing.
But in PHP for Windows (5, Funny)
Anonymous Coward | more than 5 years ago | (#25518409)
It'll be
/, just to keep things interesting.
Re:But in PHP for Windows (1, Funny)
Anonymous Coward | more than 5 years ago | (#25518969)
I thought they chose \ to make windows users feel like at home..
HOLY FUCKING SHIT!?!?! (-1, Redundant)
Anonymous Coward | more than 5 years ago | (#25518419)
/ not
::??? What the fuck were they on?!?!
Re:HOLY FUCKING SHIT!?!?! (-1, Redundant)
Anonymous Coward | more than 5 years ago | (#25518751)
How the FUCK did you get modded insightful?
Re:HOLY FUCKING SHIT!?!?! (1, Funny)
mweather (1089505) | more than 5 years ago | (#25518979)
Re:HOLY FUCKING SHIT!?!?! (4, Informative)
coryking (104614) | more than 5 years ago | (#25518825).
I have to say they are working really hard.... (5, Insightful)
A beautiful mind (821714) | more than 5 years ago | (#25518443)
Re:I have to say they are working really hard.... (5, Informative)
FooAtWFU (699187) | more than 5 years ago | (#25518457)
Re:I have to say they are working really hard.... (1)
ThePhilips (752041) | more than 5 years ago | (#25518831) PHP.
It seems that the PHP developers had chosen path of M$VB.
Re:I have to say they are working really hard.... (1)
Just Some Guy (3352) | more than 5 years ago | (#25519111):I have to say they are working really hard.... (1)
-noefordeg- (697342) | more than 5 years ago | (#25518987)...
The BASIC of the 21st century (5, Insightful)
mangu (126918) | more than 5 years ago | (#25518505):The BASIC of the 21st century (1)
rawg (23000) | more than 5 years ago | (#25518575)
and I'm migrating them over to Ruby on Rails or Merb. PHP is lame.
Re:The BASIC of the 21st century (5, Funny)
Dragonslicer (991472) | more than 5 years ago | (#25518627)
Then I see people suggesting \ for a namespace separator, and I wonder what happened to all the people that put so much work into making PHP5 good, and why we can't get them back.
Re:The BASIC of the 21st century (2, Insightful)
mangu (126918) | more than 5 years ago | (#25518703)
The last one was seen downloading a Ruby On Rails development environment.
Re:The BASIC of the 21st century (0)
Anonymous Coward | more than 5 years ago | (#25518755)
Well, it's apparent that they rejected double-colon ("::") because they didn't want folks to be confused with DECnet node names.
And Python is better? (0, Troll)
Anonymous Coward | more than 5 years ago | (#25518699)
OK, yes Python is better than PHP but they're both a pain in the ass for the web/text based world of web development. I mean really, both PHP and Python are not that much easier to use than just writing a program in C/C++. Things like regular expressions are stupidly annoying to use (compare to Perl or Lua+LPeg). I don't even get the point of Python because it's a slow scripting language with almost all the verbose complexity of a compiled language. Just weird.
Unfortunately there aren't a lot of options. Perl isn't all that great because while it's awesome at the usability and text processing part it's not so good from a structured design point of view. It's difficult to design complicated software in Perl. Plus Perl is basically dead since they decided to start that idiotic Perl 6 project that will never be finished (and even if it is I'm sure it will suck).
My personal choice would be something like Lua with LPeg and a nice large supporting library. I know the Kepler project does work in this space but their stuff isn't anywhere near as nice as what is available in PHP and Perl API's. Their designs are just odd because they approach things from a Lua point of view instead of a web developer point of view.
Re:And Python is better? (1)
eric2hill (33085) | more than 5 years ago | (#25518815)
You could write your web application in C++ [tntnet.org] but I'm not sure if anyone other than you would be able to understand it in 5 years...
:)
Re:The BASIC of the 21st century (0)
bjtuna (70129) | more than 5 years ago | (#25518707)
So, when people ask you for minor upgrades on their existing PHP websites, you rewrite the whole thing in Python. Do you really? I'm not buying it.
Re:The BASIC of the 21st century (0, Flamebait)
Anonymous Coward | more than 5 years ago | (#25518767)
Notice how he said "when people ask me", meaning he's just yet another college guy who has done a few pages for some club or whatnot and therefore thinks he's hot shit. He has obviously never worked in a professional development environment, where the technology used to create the web front end is largely totally irrelevant as that layer is given so little control that anything will work. I get happy just thinking about this guy then he leaves his college with his worthless degree, getting hit right in the face when he comes out and realizes that web developers are the IT world's equivalence to fluffers in porn.
Re:The BASIC of the 21st century (1)
mangu (126918) | more than 5 years ago | (#25518777)
I don't do minor upgrades, there are other people for that. When a major upgrade is needed, let's say from version "2.7" to "3.0" they call me.
Re:The BASIC of the 21st century (2, Funny)
faraway (174370) | more than 5 years ago | (#25519059) (2, Interesting)
mweather (1089505) | more than 5 years ago | (#25519085)
Re:The BASIC of the 21st century (0)
Anonymous Coward | more than 5 years ago | (#25519005)
Since PHP is so widely spread:
I'm just waiting for some nutcase to develop a "sensible programming language to PHP" compiler.
That would make things even more interesting. =)
Re:I have to say they are working really hard.... (1)
thc4k (951561) | more than 5 years ago | (#25518927)
... on collecting every bad design choice in one place, to serve as a warning to others. Php has beem the prime source for how-not-to's for ages now, and still manage to come up with new stuff
.. respect!
While at it... (1)
Shados (741919) | more than 5 years ago | (#25518477)
While at it, they should have picked a page from the W3C and made namespaces full, compliant URIs.
That would have been epic!
/sarcasm.
.NET / WPF is going this way (2, Interesting)
coryking (104614) | more than 5 years ago | (#25518909)Param"
</UserControl>
You can even get multiple
.NET namespaces to map into a single XML namespace.
yet another wtf (3, Interesting)
larry bagina (561269) | more than 5 years ago | (#25518489)
The rfc [php.net] claims that typing "**" is easier than typing "%%" or "^^".
Re:yet another wtf (1, Insightful)
Anonymous Coward | more than 5 years ago | (#25518557)
All I can say is that "\" is a key combination of a right hand key with AltGr on a German keyboard. How is that easy to type? "::" is Shift-. on all keyboards that I know of.
Re:yet another wtf (2, Funny)
Mental Maelstrom (1268890) | more than 5 years ago | (#25518659)
AltGr + Plus [the key right of number 0] on Estonian layout also. This is so discriminatory!
:P
We should use a character present on most keyboard layouts. I propose the use of the Space-key for this purpose.
Re:yet another wtf (1)
Televiper2000 (1145415) | more than 5 years ago | (#25518735)
Re:yet another wtf (1)
e4g4 (533831) | more than 5 years ago | (#25518869)
The rfc [php.net] claims that typing "**" is easier than typing "%%" or "^^".
But it is!
... if your right shift key is broken...
A long overdue addition (2, Insightful)
DontLickJesus (1141027) | more than 5 years ago | (#25518495)
Just my 2 cents.
Re:A long overdue addition (5, Funny)
FooAtWFU (699187) | more than 5 years ago | (#25518533)
While you're livin' it up at your stately manor, I'm coding PHP out of my garage, you insensitive clod!
Re:A long overdue addition (4, Insightful)
Shados (741919) | more than 5 years ago | (#25518617)
Thats all good. I personally feel its just easier to avoid PHP altogether and not have to adjust to all of the language's quirks for little to no benefits from other offerings. Simpler that way.
Backslash! (3, Funny)
SEWilco (27983) | more than 5 years ago | (#25518537)
Well now we all know what trouble this is going .. (4, Funny)
3seas (184403) | more than 5 years ago | (#25518561)
... to cause for windows servers...
imagine what directories will be deleted due to a typo!
F\ck (1)
vawarayer (1035638) | more than 5 years ago | (#25518567)
F\ck
:P
Well, That Does It! (0, Flamebait)
maz2331 (1104901) | more than 5 years ago | (#25518573)
OMFG - this addition is just so horrid that everyone's going to give up on PHP and start coding Web apps in C++ through CGI interfaces again.
/Sarcasm
Seriously, who cares what charater they are using? Developers are smart enough to adapt.
Re:Well, That Does It! (0)
Anonymous Coward | more than 5 years ago | (#25518667)
OMFG - this addition is just so horrid that everyone's going to give up on PHP and start coding Web apps in C++ through CGI interfaces again.
/Sarcasm
Seriously, who cares what charater they are using? Developers are smart enough to adapt.
I would love to agree with you and formerly would have done but judging by some of these comments... *shudders*
Re:Well, That Does It! (3, Insightful)
Zontar The Mindless (9002) | more than 5 years ago | (#25518695):Well, That Does It! (1, Funny)
TheRaven64 (641858) | more than 5 years ago | (#25518745)
Re:Well, That Does It! (2, Interesting)
larry bagina (561269) | more than 5 years ago | (#25518803)
This isn't the first (or last) time PHP developers have implemented a stupid workaround rather than fixing problems with the language/runtime/interpreter/parser/scanner.
Re:Well, That Does It! (1, Funny)
Anonymous Coward | more than 5 years ago | (#25518945)
\ instead of :: ? (1)
AdmiralXyz (1378985) | more than 5 years ago | (#25518599)
other issues (4, Insightful)
adamruck (638131) | more than 5 years ago | (#25518613)
Maybe they could starting fixing the noun-verb vs verb-noun problems instead.
Re:other issues (1)
mdmkolbe (944892) | more than 5 years ago | (#25519087)
Re:other issues (1)
dascritch (808772) | more than 5 years ago | (#25519091) (5, Funny)
redink1 (519766) | more than 5 years ago | (#25518689)
Thank you, PHP.
Re:Today is a Wonderful Day (3, Interesting)
siride (974284) | more than 5 years ago | (#25518967)
so what's the problem here? (1)
Tumbleweed (3706) | more than 5 years ago | (#25518693)? (5, Informative)
mysidia (191772) | more than 5 years ago | (#25518959)? (3, Funny)
coryking (104614) | more than 5 years ago | (#25519121)?
oh my... (-1, Flamebait)
Anonymous Coward | more than 5 years ago | (#25518709)
oh my....
what's the problem with php, it seems to me a quintessential "just another language", without interesting features, and disposable by design. they keep it that way intentionally, it seems.
recently i saw several performance comparisons and it seems at least useless even by that point of view.
of course it's one of the most used languages in the web world.
i hope it dies, horribly and SOON.
All languages (1)
symbolset (646467) | more than 5 years ago | (#25518791)
...?
Phalanger (1)
shutdown -p now (807394) | more than 5 years ago | (#25518725) for several large language families now (all curly-braces family languages - C/C++/Java/C#/EcmaScript, and almost all modern popular scripting languages - Python, Ruby, Lua...). It's even used as the same in PHP, given that it is also a curly-braces language. Reusing it outside string literals in an entirely different capacity is not a good idea (especially when other languages of the family have already applied different meaning to backslash outside string literals - in C# and Java it's used to escape Unicode characters in identifiers).
Re:Phalanger (1)
mysidia (191772) | more than 5 years ago | (#25519037)
C# and Java it's used to escape Unicode characters in identifiers
Ok.. I was wrong there IS something worse than using the ESCAPE character to delineate namespaces.
Allowing unicode characters in identifiers is SICK and not to be encouraged by any programming language or any compiler for any reason, as the issues are even more widespread than with this PHP issue.
The need to ever escape the unicode character in identifier name should be ample evidence to that effect.
#irc.trooltalk.com (-1, Offtopic)
Anonymous Coward | more than 5 years ago | (#25518759)
Easier on which keyboard layout? (5, Insightful)
Anonymous Coward | more than 5 years ago | (#25518761).
Gripe Moan Bitch and Holler! (-1, Troll)
FlyingGuy (989135) | more than 5 years ago | (#25518807)
Seriously, I mean WTF! It is a scripting language for fucks sake, why does it matter to you what they use? If you use the language, thats the deal, if you don't then use whatever C clone you like, there are plenty of them out there, or better yet, just program in C, why screw around with all the intermediate shite? You can write smaller, more compact & light weight server side programs in C then you can for just about anything else.
Scripting languages are for convenience, nothing more nothing less. Anything you can do in ANY scripting language be it Perl, Python, PHP, Rails or whatever, pick any of them, you can build faster, smaller and better programs in C.
Native binary languages for *nix system have all the same goodies in them just written at lower levels and you have to do a little work, or god forbid, some memory management, a horrific thought I know, but what do you think all this stuff is written in? Uhmm mostly C or its bastard stepchild, C++
Scripting languages are for those of a weak mind and poor technical skills and the singular lack of the ability to plan a system out before you write one line of code.
Re:Gripe Moan Bitch and Holler! (3, Insightful)
SUB7IME (604466) | more than 5 years ago | (#25518899)
Scripting languages are for those of a weak mind and poor technical skills and the singular lack of the ability to plan a system out before you write one line of code.
Or for projects that need to be compiled at runtime. But, nice magnanimity.
Re:Gripe Moan Bitch and Holler! (1)
aftk2 (556992) | more than 5 years ago | (#25518903)
Re:Gripe Moan Bitch and Holler! (1)
maxume (22995) | more than 5 years ago | (#25519139)
I took it as an extremely well crafted troll.
Re:Gripe Moan Bitch and Holler! (0)
Anonymous Coward | more than 5 years ago | (#25518915)
Sure, why not, right? Let's reinvent the wheel EVERY FUCKING TIME we write the specs for a language. We don't want anyone getting comfortable now. Shit, let's make sure we use EBCDIC encoding for PHP7, too -- hey, don't complain, it's a scripting language! That's the deal!
You are a narrow-minded BUFFOON, sir.
Re:Gripe Moan Bitch and Holler! (0, Flamebait)
siride (974284) | more than 5 years ago | (#25519053)
Classes, namespaces, and subnamespaces (4, Informative)
janwedekind (778872) | more than 5 years ago | (#25518833)
Other suggestions (3, Interesting)
lepidosteus (1102443) | more than 5 years ago | (#25519029) !
Well... (1)
Tablizer (95088) | more than 5 years ago | (#25519047)
You know what they say:
If you don't like it, you can go fork yourself.
\ vs / (1)
fahrbot-bot (874524) | more than 5 years ago | (#25519069)...
The real question is (0)
Anonymous Coward | more than 5 years ago | (#25519131)
The real question is: will they admit their mistake and correct it before it destroys the community?
The linked blog showing the example: spl_autoload_register(array("Foo\tBar", "loader")); highlights the fact that this is an epic blunder that will fracture the community.
The language designers who spent only "hours" debating the solution need to swallow their pride and admit they made a mistake. Then they should take public comments on how to solve the problem, and put it to a popular vote among the user community.
yuck (1)
ColoBikerDude (947706) | more than 5 years ago | (#25519165)
Stupid choice. I guess I will just endeavor to avoid namespaces altogether.
Does this mean that writing "eval" statements in regular expressions would have to be triple-escaped then?
preg_replace("/oldtext/e", "ns\\\pick_new_text()");
That makes my head hurt. | http://beta.slashdot.org/story/109147 | CC-MAIN-2014-42 | refinedweb | 3,615 | 72.16 |
HSFFIG/Tutorial.0 (release date 07/30/2005).
2 Getting HSFFIG
2.1 Downloading
The project homepage is located at. Hsffig source code may be downloaded from the "File Releases" section of the web page. Source tarball file name is hsffig-1.0.tar.gz. Darcs users may check out from the repos at:
- darcs get ("stable" snapshot)
- darcs get ("unstable" snapshot)
2.2 Building from Program Input
Hsffig acts as a filter (in Unix sense) which means that it consumes all its input information on its standard input (stdin), and produces its output on standard output (stdout). No other files are involved.
The hsffig program is invoked as follows:
gcc -E -dD header.h | hsffig > HEADER_H.hsc
The -E option instructs gcc only to preprocess (no compilation) its input file, and the -dD option instructs it to emit #define preprocessor statements along with the preprocessed header (without -dD, autogenerated binding module will not contain import statements for constants defined this way).
3.1 Preprocessor Requirements
It is assumed that majority of hsffig users will use tools from the GNU Compiler Collection (GCC), whose preprocessor complies with the hsffig requirements. For other preprocessors from other vendors, the following is expected:
- The very first line of preprocessor output will contain the following construct:
# 1 header.h
where header.h is the name of the "toplevel" header file; number following after the hash sign does not matter.
Since hsffig does not take any command line arguments, the only way to determine the name of the module is the preprocessor output itself. When hsffig encounters a line like shown above (starting with hash sign and number), it derives the autogenerated Haskell module name by stripping the directory part from the header file name (as in basename(1)), uppercasing all characters (therefore the header file name cannot start with a digit), and replacing dots with underscores. Therefore, for a header file header.h, the autogenerated module will be named HEADER_H.
If compilant preprocessor is not available, and control lines like discussed above cannot appear in the preprocessor output (with gcc, this may be simulated with -P option), a special token @@MODULENAME@@ will be used in the Module statement. Later, it may be substituted with anything desirable with a program like sed(1). Also, if hsffig is unable to determine the header file name from its input, constants defined via #define will not be imported.
4 Program Output
Hsffig outputs hsc code on its standard output, to be redirected to a file or (possibly) to some other filter program. The output is ready for processing by hsc2hs. Description of hsc2hs input file format may be found here:
The output file will contain the following sections:
- Special Definitions for hsc2hs
- Module header
- Constants defined with #define
- For each structure/union imported, an instance of the above mentioned class to access each member
- Constants defined via enumerations
- Import declarations for each function/extern variable declared
The preprocessor outputs preprocessed contents of not only the header file specified on its command line, but also of all other header files included within. This results in importing of some extra stuff (for instance, if a header file has #include <stdio.h> inside, everything defined in stdio.h will be imported as well). This merely gives the Haskell compiler which "connects" the library to an application written in Haskell the same look as the C compiler would have if it were "connecting" the library to an application written in C.
In first lines of generated hsc code, an #include statement is present to include the same header file that was consumed by hsffig. If hsffig is unable to determine header file name from its input (see Preprocessor Requirements), a special token @@INCLUDEFILE@@ will be placed with the #include statement instead. Similarly to the module name substitute, it may be later converted into a real header file name with a program like sed.
4.1 Special Definitions for Hsc2hs
In generated hsc code, the following hsc2hs macros are used to access members of structures/unions:
- #peek
- #poke
- #ptr
These macros take type declaration of the structure whose members are being accessed, as its first argument.
Consider the following structure declaration (a slightly modified fragment of BerkeleyDB's db.h):
struct __dbc { DB *dbp; /* Related DB access method. */ DB_TXN *txn; /* Associated transaction. */ struct { DBC *tqe_next, **tqe_prev; } links; /* . . . other members . . . */ }
To access members of the {{{struct ___dbc}}}, e. g. to peek a value of dbp, the following hsc2hs macro will be used:
(#peek struct __dbc, dbp)
But links is declared "anonymously", i. e. its structure type is not named. The only way to construct a #peek/#poke/#ptr macro is to put the whole structure declaration as its first argument:
(#peek struct {DBC *tqe_next, **tqe_prev;}, tqe_next)
This will cause an error because the C preprocessor macro that hsc2hs converts the above construct into, takes only two arguments, but comma in the structure declaration will be recognized as argument separator, i. e. there will be three arguments.
To work this around, hsffig makes the following declaration at the beginning of generated hsc code:
#ifndef __quote__ #define __quote__(x...) x #endif
This is a gcc feature called "macro varargs". The only thing this macro does is to represent its arguments whatever is their number, as a single token for the preprocessor.
So the macros from the example above will look:
(#peek __quote__(struct __dbc), dbp) (#peek __quote__(struct {DBC *tqe_next, **tqe_prev;}), tqe_next)
Additionally, the template file that hsc2hs needs to convert hsc to Haskell code needs to be modified. It uses the offsetof macro which also takes two arguments, but passing anonymously declared structure type containing commas will cause the same problems. So in the modified template file, the same __quote__ macro is used with offsetof:
#define hsc_peek(t, f) \ printf ("(\\hsc_ptr -> peekByteOff hsc_ptr %ld)", (long) offsetof (__quote__(t), f));
These special definitions are placed in the very beginning of every file that hsffig generates. A separate template file for hsc2hs is no longer needed. So, to generate importable Haskell code, a command like one below needs to be issued:
hsc2hs -t /dev/null HEADER_H.hsc -o HEADER_H.hs
Specifyiing /dev/null as template file name causes hsc2hs not to use any template file.
4.2 Splitting Large Modules
Considering that hsffig generates import statements for everything it encounters in all header files included within the toplevel header file, amount of generated Haskell code may be quite large, so it cannot be compiled by ghc at once due to memory limitations. To overcome this, a special utility, splitter is included with hsffig. In generated hsc code, the following comments are inserted:
-- Split begin/DB_H {-# OPTIONS -fglasgow-exts -ffi #-} #include "db.h" #ifndef __quote__ #define __quote__(x...) x #endif module DB_H( module DB_H, {-- #SPLIT# module DB_H_C, module DB_H_S, module DB_H_F, module DB_H_E, module DB_H_S_cnt, #SPLIT# --} module Foreign, module Foreign.C.String, module Foreign.C.Types) where import Foreign import Foreign.Ptr import Foreign.C.Types import Foreign.C.String {-- #SPLIT# import DB_H_C import DB_H_S import DB_H_F import DB_H_E import DB_H_S_cnt #SPLIT# --} -- Split end
This example is found in the very begining of generated hsc code. The splitter program reads its input file line by line. Comments like {{{-- Split begin/DB_H}}} redirect all subsequent lines in a file whose name is composed of characters following after '/' with '.hs' appended. Comments like {{{-- Split end}}} close output file: input lines are lost until another Split begin comment is met. Lines {{{ {-- #SPLIT# }}} and {{{ #SPLIT# --} }}} are removed from output, so enclosed pieces of Haskell code are uncommented.
As a result, one large module is split into many parts:
- The "Root" module to be imported into an application: name derived from the header file name, see above, e. g. DB_H
- A separate module containing import statements for constants declared with #define: name is derived from the header file name and postfixed with "_C", e. g. DB_H_C
- A separate module containing import statements for constants declared via enumerations: name is postfixed with "_E", e. g. DB_H_E
- A separate module containing import statements for variables and functions: name is postfixed with "_F", e. g. DB_H_F
- A separate module containing declaration of a multiparameter class and datatypes necessary to access members of structures/unions: name is postfixed with "_S_cnt", e. g. DB_H_S_cnt (Note: as of the patchlevel 2, instead of a single module postfixed with "_S_cnt", three separated modules are created, positixed with: "_S_n" for newtype declarations, "_S_t" for type aliases, and "_S_d" for declarations of structure member selector datatypes (V_..., X_..., D_...).
- A separate module for each structure/union defined in the header file and files included within: name is postfixed with "_S_" and followed by the structure type identifier derived by hsffig, e. g. DB_H_S_S{{{___}}}db_dbt for {{{struct __db_dbt}}}, or module DB_H_S_S_1142 for a structure declared anonymously (hsffig assigns unique numeric identifiers to such structures).
However, application developers do not need to know all these module names: all they still need to know is name of the "root" module (DB_H in our example) to be imported.
It is recommended to use ghc with --make option: this forces the compiler to chase all module dependencies automatically. Since all the modules created by splitter contain correct import statements, no module will be left behind.
5 FFI Import Details
5.1 Naming Conventions
A significant difference between C and Haskell is that C does not force starting character of its variable, function, or type identifiers to be of certain case while Haskell has requirements of this kind. To resolve this problem, the following rules apply when an identifier declared in a C library is imported in a Haskell application.
All identifiers imported from a C library, or created to make import easier, are prefixed as shown in the table below:
The table summarizes all prefixes hsffig adds to imported identifiers, and corresponding types of import. Flags Yes and No show whether given prefix and import purpose is suitable for each sort of imported entity.
5.2 Typedefs
C types declared with the typedef statement are imported as type aliases prefixed with "T_". These type aliases may be more convenient to use in certain situations.
The following C declaration:
{{{ typedef union {
struct { int a:1; int b:1; int c:1; int d:1; } x; int y;
} *PBF; }}}
imports as:
{{{ type T_PBF = Ptr (U_9)
newtype S_5 = S_5 () newtype U_9 = U_9 ()
-- instances to access S_5 and U_9 members follow
}}}
In the following Haskell program:
{{{ module Main where
import BF_H
main = do
putStrLn $ "Test of Bit Fields"
alloca $ \(bfu :: T_PBF) -> do x <- (bfu --> V_x) (x, V_a) <-- fromIntegral 1 (x, V_b) <-- fromIntegral 0 (x, V_c) <-- fromIntegral 0 (x, V_d) <-- fromIntegral 1 y <- (bfu --> V_y) putStrLn $ "y = " ++ (show y)
}}}
it is necessary to declare the type of bfu because there is no foreign import declaration that would drive the type inference mechanism. Since the union is declared anonymously, the type derived by hsffig contains a numeric identifier that is hard to remember. Imported typedef helps because it may be used instead, and is controlled by a developer (Ptr U_9 couls be used with the same effect).
Per FFI Addendum, the following typedefs are imported as they are (the Addendum defines names of Haskell types equivalent to them):
* {{{ptrdiff_t}}} * {{{size_t}}} * {{{wchar_t}}} * {{{sig_atomic_t}}} * {{{clock_t}}} * {{{time_t}}} * {{{FILE}}} * {{{fpos_t}}} * {{{jmp_buf}}}
5.3 Constants (#define)
For each constant declared with #define, generated hsc code looks as follows:
{{{
- define BIG_ENDIAN __BIG_ENDIAN
- define PDP_ENDIAN __PDP_ENDIAN
- define BYTE_ORDER __BYTE_ORDER
- define S_IREAD S_IRUSR
- define S_IRGRP (S_IRUSR >> 3)
- define S_IROTH (S_IRGRP >> 3)
}}}
becomes
{{{ c_BIG_ENDIAN = #const BIG_ENDIAN c_PDP_ENDIAN = #const PDP_ENDIAN c_BYTE_ORDER = #const BYTE_ORDER c_S_IREAD = #const S_IREAD c_S_IRGRP = #const S_IRGRP c_S_IROTH = #const S_IROTH }}}
that is, hsffig does not deal with actual value of the constant: it is left to hsc2hs.
However, arbitrary #define cannot be imported this way. Some preprocessor macros have parameters, or contain C statements, or otherwise cannot be assignment expression's RHS. To rule such preprocessor macros out, for each #define hsffig encounters on its input, a short C program is created, like this:
{{{
- include "header.h"
static int a = BIG_ENDIAN; }}}
for {{{#define BIG_ENDIAN __BIG_ENDIAN}}}. The command line for gcc is:
{{{ gcc -pipe -x c -q -fsyntax-only - 2>/dev/null }}}
If this program passes syntax check, the constant is imported, otherwise not imported.
This explains why without being able to determine the header file name from its input, hsffig is unable to import #define 'd constants. This also shows that processing time for a header will be rougly linear to the number of #define preprocessor statements in the header.
Constants are not in the IO monad, and may be used in any function. Bit operations (from Foreign.C.Bits) may be applied to them:
. c_S_IWUSR .
may be used to specify file permissions {{{rw-rw-r--}}}
5.4 Constants (enum)
Enumerations are imported similarly to preprocessor-defined constants, but identifiers are prefixed with "e_".
An example showing usage of both #define and enumeration constants:
{{{
dbop <- dbp --> V_open ret <- withCString "access.db" $ \dbname -> do r <- dbop dbp nullPtr dbname nullPtr (fromIntegral e_DB_BTREE) (fromIntegral c_DB_CREATE) (fromIntegral dbperm) return r
}}}
fromIntegral may be necessary to apply to constants when calling foreign functions because the Haskell compiler infers the type for the following sort of expressions:
{{{ c_DB_CREATE = 1 e_DB_BTREE = 1 }}}
as Integer while the function referred to by dbop in the example above requires CInt, CUInt, CInt for its last three arguments.
5.5 Variables
5.5.1 Regular Variables
Regular variables contain either values or pointers to other variables (not functions). For this sort of imports, the following identifiers are created:
* a pointer to the variable itself: prefix is "p_" * a nullary function returning variable's value in the IO monad: prefix is "v_" * a unary function taking a value and assigning it to the variable (in the IO monad): prefix is "s_"
So, for a variable declared as
{{{ extern int a; }}}
FFI import declarations will be as follows:
{{{ foreign import ccall "header.h &a"
___2___ :: Ptr (CInt)
p_a = ___2___ v_a = peek ___2___ s_a = poke ___2___ }}}
where ___2___ is one of internal unique names that hsffig assigns to all identifiers it encounters in the header file.
So, to retrieve value from a variable, v_a is used:
{{{ x <- v_a -- equivalent to peek p_a }}}
To update the variable value, s_a is used:
{{{ s_a 4 -- equivalent to poke p_a 4 }}}
If a variable contains pointer to a value, e. g
{{{ extern int *ap; }}}
then it is imported as follows:
{{{ foreign import ccall "header.h &ap"
___3___ :: Ptr (Ptr (CInt))
p_ap = ___3___ v_ap = peek ___3___ s_ap = poke ___3___ }}}
so to dereference the pointer, additional peek is needed:
{{{ c <- v_ap >>= peek }}}
and s_ap will update the variable itself with new address, rather than the value it points to.
5.5.2 Function Pointers
Function pointers contain pointers to executable code.
For this sort of imports, the following identifiers are created:
* pointer to the variable itself: prefix is "p_" * a function the variable points to (with proper arity and type signature): prefix is "x_" * a nullary function returning the function pointed to by the variable (in the IO monad): prefix is "v_" * a unary function updating the variable with new function reference: prefix is "s_" * optionally: wrapper functions for arguments taking function references: prefix is "w_"
A variable declared as:
{{{ int (*c)(long,int); }}}
is imported as follows:
{{{ foreign import ccall "header.h &c"
___8___ :: Ptr (FunPtr (CLong -> CInt -> IO CInt))
p_c = ___8___ foreign import ccall "dynamic"
___8___mk___ :: FunPtr (CLong -> CInt -> IO CInt) -> (CLong -> CInt -> IO CInt)
foreign import ccall "wrapper"
___8___wr___ :: (CLong -> CInt -> IO CInt) -> IO (FunPtr (CLong -> CInt -> IO CInt))
x_c _1 _2 = peek ___8___ >>= \s -> ___8___mk___ s _1 _2 v_c = peek ___8___ >>= (return . ___8___mk___) s_c = \s -> ___8___wr___ s >>= poke ___8___ }}}
Note that the function referred to by c returns IO CInt. It is assumed that all functions imported from a C library are unsafe, and therefore forced to be monadic. Based on the same assumption, all calls are considered "safe": this also allows calling Haskell functions from C code.
A variable declared as a function pointer in C', from the Haskell point of view contains a Fun'Ptr i. e. virtual address of some foreign function's entry point. This cannot be used by a Haskell application directly, so a special dynamic import function needs to be declared. Such a pseudo-function (only its name and type signature need to be declared: the Haskell compiler does the rest) converts a Fun'Ptr into a function usable by Haskell applications. Another pseudo-function, wrapper import dose the opposite: converts a Haskell function into a monadic value containing a Fun'Ptr i. e. a virtual address of an entry point usable by foreign functions (useful for callbacks).
For the variable - function pointer c, p_c returns pointer to the variable, just like for a regular variable. However, v_c returns the variable value passed through the dynamic import pseudo-function, so it may be used directly in Haskell applications. The setter function, s_c takes a Haskell function with proper type signature and updates the c variable value with new function address. The function x_c is the foreign function c points to.
The difference between v_c and x_c is illustrated below:
{{{ pc1 <- v_c r1 <- pc1 33::CLong 21::CInt
-- but
r2 <- x_c 33::CLong 21::CInt
}}}
v_c is a monadic value; x_c is not.
Optionally additional wrapper imports are created if a function pointed to by a variable takes other functions as arguments.
Consider the following:
{{{ typedef int (*F2) (long); typedef float (*X2) (double); F2 (*ee) (X2); }}}
The variable ee is a pointer to a function taking a function from double to float, and returning a function from long to int.
The import looks as follows:
{{{ foreign import ccall "header.h &ee"
___40___ :: Ptr (FunPtr (FunPtr (CDouble -> IO CFloat) -> IO (FunPtr (CLong -> IO CInt))))
p_ee = ___40___ foreign import ccall "dynamic"
___40___mk___ :: FunPtr (FunPtr (CDouble -> IO CFloat) -> IO (FunPtr (CLong -> IO CInt))) -> (FunPtr (CDouble -> IO CFloat) -> IO (FunPtr (CLong -> IO CInt)))
foreign import ccall "wrapper"
___40___wr___ :: (FunPtr (CDouble -> IO CFloat) -> IO (FunPtr (CLong -> IO CInt))) -> IO (FunPtr (FunPtr (CDouble -> IO CFloat) -> IO (FunPtr (CLong -> IO CInt))))
x_ee _1 = peek ___40___ >>= \s -> ___40___mk___ s _1 v_ee = peek ___40___ >>= (return . ___40___mk___) s_ee = \s -> ___40___wr___ s >>= poke ___40___ foreign import ccall "wrapper"
w_ee_1 :: (CDouble -> IO CFloat) -> IO (FunPtr (CDouble -> IO CFloat))
}}}
An additional import declaration, w_ee_1 has been created. It may be used if ee is called, and some Haskell function is passed as a parameter:
{{{ mydoublefloat :: CDouble -> IO CFloat mydoublefloat = {-- function body here --}
mydoublefloat_wrapped <- w_ee_1 mydoublefloat
foo <- x_ee mydoublefloat_wrapped
-- or
foo <- w_ee_1 mydoublefloat >>= x_ee }}}
Note that in the current version, hsffig' does not create a dynamic import when a function imported returns a Fun'Ptr.
Name of autogenerated wrapper import for function arguments ends with "_1". If a function takes more than one argument - function then more than one wrapper import will be created (one per function type). For example:
{{{ void (*psetpdf)(double (*df)(double,double),int,long,void(*)(int)); }}}
imports as:
{{{ foreign import ccall "header.h &psetpdf"
___6___ :: Ptr (FunPtr (FunPtr (CDouble -> CDouble -> IO CDouble) -> CInt -> CLong -> FunPtr (CInt -> IO ()) -> IO ()))
p_psetpdf = ___6___ foreign import ccall "dynamic"
___6___mk___ :: FunPtr (FunPtr (CDouble -> CDouble -> IO CDouble) -> CInt -> CLong -> FunPtr (CInt -> IO ()) -> IO ()) -> (FunPtr (CDouble -> CDouble -> IO CDouble) -> CInt -> CLong -> FunPtr (CInt -> IO ()) -> IO ())
foreign import ccall "wrapper"
___6___wr___ :: (FunPtr (CDouble -> CDouble -> IO CDouble) -> CInt -> CLong -> FunPtr (CInt -> IO ()) -> IO ()) -> IO (FunPtr (FunPtr (CDouble -> CDouble -> IO CDouble) -> CInt -> CLong -> FunPtr (CInt -> IO ()) -> IO ()))
x_psetpdf _1 _2 _3 _4 = peek ___6___ >>= \s -> ___6___mk___ s _1 _2 _3 _4 v_psetpdf = peek ___6___ >>= (return . ___6___mk___) s_psetpdf = \s -> ___6___wr___ s >>= poke ___6___ foreign import ccall "wrapper"
w_psetpdf_1 :: (CDouble -> CDouble -> IO CDouble) -> IO (FunPtr (CDouble -> CDouble -> IO CDouble))
foreign import ccall "wrapper"
w_psetpdf_2 :: (CInt -> IO ()) -> IO (FunPtr (CInt -> IO ()))
}}}
The function pointed to by setpdf takes two arguments-functions of different types, therefore two wrapper imports have been created.
Enumeration of wrappers created for arguments does not correspond to positional numbers of arguments.
5.6 Functions
Functions are imported under their own names prefixed by "f_". Similarly to the situation described above (variables holding function pointers), additional wrappers will be created for arguments representing other functions. Examples of import:
{{{ double dplus(double,double); }}}
imports as:
{{{ foreign import ccall "static header.h dplus"
f_dplus :: CDouble -> CDouble -> IO CDouble
}}}
A function taking another function as argument:
{{{ int db_env_set_func_yield (int (*)(void)) ; }}}
imports as:
{{{ foreign import ccall "static header.h db_env_set_func_yield"
f_db_env_set_func_yield :: FunPtr (IO CInt) -> IO CInt
foreign import ccall "wrapper"
w_db_env_set_func_yield_1 :: (IO CInt) -> IO (FunPtr (IO CInt))
}}}
Rules for creation and naming of wrapper imports are the same as defined for variables containing function pointers.
5.7 Structures and Unions
5.7.1 Basic Information
C structures/unions are different from Haskell records with labeled fields: different structure types may contain members with same names. Therefore direct mapping of C structures to Haskell records is not possible.
Some structures are declared with struct statement:
{{{ struct foo {
int bar; long baz;
}; }}}
Some structures are declared with typedef statement:
{{{ typedef struct foo {
int bar; long baz;
} foo_t; }}}
In some cases, structure name in the typedef statement may be omitted:
{{{ typedef struct {
int bar; long baz;
} foo_t; }}}
There also may be structures/unions declared within another structures/unions without explicit structure type name declaration:
{{{ typedef struct {
int bar; long baz; struct { float faa; size_t taa; } str_anon;
} foo_t; }}}
5.7.2 Datatypes and Combinators for Structure Members Access
Structure types are imported using the newtype Haskell statement. Type name is prefixed with "S_" for structures and "U_" for unions. If a structure was declared as struct foo, Haskell type name will be S_foo. If a structure was declared anonymously (struct without identifier), a unique numeric identifier will be used as structure type name, e. g. S_65.
A imported structure type declaration looks like: {{{newtype S_foo = S_foo ()}}}. Indeed, this type name serves only identification purpose.
In practice, Haskell application developers using hsffig do not need to memorize these clumsy type identifiers: Haskell type inference system carries most of the burden.
To access imported structure members, two algebraic data types are declared for each member identifier hsffig encounters in its input:
* V_member_id: to get/set value of a structure member member_id * X_member_id: if a member holds function pointer, to invoke the function member_id points to
Unlike variables, there is no "S_" prefixed item.
A multi-parameter class with functional dependencies is declared to enable access to structures/unions members. Because of this, Haskell-98 extensions must be enabled in the compiler processing output of hsffig'. The definition of this class is placed in the HSFFIG.Field'Access module of the Haskell library coming with the package.
a c -> b where (==>) :: Ptr a -> c -> b (-->) :: Ptr a -> c -> IO b (<--) :: (Ptr a, c) -> b -> IO () (==>) _ _ = error " illegal context for ==>" (-->) _ _ = error " illegal context for -->" (<--) _ _ = error " illegal context for <--"
The functional dependencies a c -> b specify that type of b depends entirely on the types a and c, and there may be only one type of b for every possible combination of a and c.
Indeed, a is the type of an imported structure/union. The type c is the data type associated with a structure/union member identifier. The type b is type of the member as represented to a Haskell program. In a C structure/union cannot be more than one member with same name (and different types). That's what the functional dependencies mean in this case. This information is sufficient for the Haskell compiler to infer the type of a value retrieved from a structure/union member.
The multiparameter class mentioned above is not used by Haskell applications directly. All imported types of structures/unions are instances of this class.
So, for a simple structure (note that the structure type and one of its members have the same name):
{{{ struct abc {
int abc;
}; }}}
the datatypes are:
{{{ newtype S_abc = S_abc () -- for the structure itself data V_abc = V_abc deriving (Show) -- for the member `abc' data X_abc = X_abc deriving (Show) -- not used }}}
To get/set the member abc of the structure abc, the following instance is defined:
{{{ instance FieldAccess S_abc (CInt) V_abc where
z --> V_abc = (#peek __quote__(struct abc), abc) z (z, V_abc) <-- v = (#poke __quote__(struct abc), abc) z v
}}}
So, for this instance, a = {{{S_abc}}}, b = {{{CInt}}}, and c = {{{V_abc}}}. Which is semantically equivalent to the above declaration of the member abc of the struct abc.
The {{{-->}}} combinator retrieves value of the given member from the structure pointed to by the given pointer. Thus, to access the value of abc, a Haskell application contains:
{{{ r <- z --> V_abc }}}
Because of the multiparameter class and the instance declaration, the compiler is able to determine the type of the {{{z --> V_abc}}} expression correctly.
Assume another structure declaration:
{{{ struct def {
void (*abc)(char *,int);
}; }}}
perfectly legal from the C standpoint. Not only do the two different structures have a member with the same name abc, but these members have different types: one is a scalar integer value; another is a function pointer.
The import for struct def is (its part of the interest):
{{{ newtype S_def = S_def () instance FieldAccess S_def ((Ptr (CChar) -> CInt -> IO ())) V_abc where
z --> V_abc = (#peek __quote__(struct def), abc) z >>= (return . ___60___S_def___mk) (z, V_abc) <-- v = (___60___S_def___wr v) >>= (#poke __quote__(struct def), abc) z
}}}
For this instance, a = {{{S_def}}}, b = {{{Ptr (CChar) -> CInt -> IO ()}}}, and c = {{{V_abc}}} i. e. the same as for abc in struct abc.
So, in
{{{ r <- z --> abc t <- x --> abc }}}
if x and z point to structures abc and def respectively, types of values bound to r and t will be different.
The {{{<--}}} combinator is used for updating structure/union members with new values. This is a "real" update, not simulated by Haskell state mechanisms.
The code
{{{ (z,V_abc) <-- 4 -- fixme: is fromIntegral needed for a constant? }}}
is equivalent to C code:
{{{ z -> abc = 4; }}}
The {{{==>}}} combinator is used to call functions pointed to by structre/union members. While {{{-->}}} may be applied only to "V_" prefixed identifiers, the {{{==>}}} combinator may be applied only to "X_" prefixed identifiers.
The difference between "V_" and "X_" prefixed structure member identifiers is similar to that for imported variables holding function pointers:
{{{
fclose <- dbp --> V_close ret <- fclose dbp 0
-- but
ret <- (dbp ==> X_close) dbp 0
}}}
The following is complete set of import statements that hsffig generates for struct def:
{{{ instance FieldAccess S_def ((Ptr (CChar) -> CInt -> IO ())) V_abc where
z --> V_abc = (#peek __quote__(struct def), abc) z >>= (return . ___62___S_def___mk) (z, V_abc) <-- v = (___62___S_def___wr v) >>= (#poke __quote__(struct def), abc) z
foreign import ccall "dynamic"
___62___S_def___mk :: (FunPtr (Ptr (CChar) -> CInt -> IO ())) -> ((Ptr (CChar) -> CInt -> IO ()))
foreign import ccall "wrapper"
___62___S_def___wr :: ((Ptr (CChar) -> CInt -> IO ())) -> IO (FunPtr (Ptr (CChar) -> CInt -> IO ())
instance FieldAccess S_def ((Ptr (CChar) -> CInt -> IO ())) X_abc where
z ==> X_abc = \_1 _2 -> do x <- z --> V_abc r <- x _1 _2 return r
}}}
So, {{{z ==> X_abc}}} returns a function with type {{{Ptr (CChar) -> CInt -> IO ()}}}. Because instance with V_abc is defined with only {{{-->}}} combinator, and instance with X_abc is defined with only {{{==>}}} combinator, and instance with X_abc is declared only for members holding pointers to functions, attempt to use wrong combinator-member combination will result in compilation or runtime error.
Members of structures/unions which are structures/unions themselves are imported so that {{{-->}}} combinator returns a Ptr to the member, and {{{<--}}} combinator is not allowed. Example (from bfd.h):
{{{ typedef struct lineno_cache_entry {
unsigned int line_number; /* Linenumber from start of function*/ union { struct symbol_cache_entry *sym; /* Function name */ unsigned long offset; /* Offset into section */ } u;
} alent; }}}
imports as:
{{{ newtype S_lineno_cache_entry = S_lineno_cache_entry () newtype U_40 = U_40 ()
instance FieldAccess S_lineno_cache_entry (Ptr U_40) V_u where
z --> V_u = return $ (#ptr __quote__(struct lineno_cache_entry), u) z (z, V_u) <-- v = error $ "field u is a structure: cannot be set"
instance FieldAccess S_lineno_cache_entry (CUInt) V_line_number where
z --> V_line_number = (#peek __quote__(struct lineno_cache_entry), line_number) z (z, V_line_number) <-- v = (#poke __quote__(struct lineno_cache_entry), line_number) z v
instance FieldAccess S_lineno_cache_entry (CInt) V_sizeof where
z --> V_sizeof = return $ (#size __quote__(struct lineno_cache_entry))
--
instance FieldAccess U_40 (CULong) V_offset where
z --> V_offset = (#peek __quote__(union {struct symbol_cache_entry *sym; unsigned long offset; }), offset) z (z, V_offset) <-- v = (#poke __quote__(union {struct symbol_cache_entry *sym; unsigned long offset; }), offset) z v
instance FieldAccess U_40 (Ptr (S_symbol_cache_entry)) V_sym where
z --> V_sym = (#peek __quote__(union {struct symbol_cache_entry *sym; unsigned long offset; }), sym) z (z, V_sym) <-- v = (#poke __quote__(union {struct symbol_cache_entry *sym; unsigned long offset; }), sym) z v
instance FieldAccess U_40 (CInt) V_sizeof where
z --> V_sizeof = return $ (#size __quote__(union {struct symbol_cache_entry *sym; unsigned long offset; }))
}}}
So, to achieve the same as C code below does:
{{{ alent *pal;
/* ... */
off = pal -> u.offset }}}
a Haskell program would contain:
{{{ pal <- -- whatever returns IO (Ptr S_lineno_cache_entry)
off <- (pal --> V_u) >>= \u -> (u --> V_offset) }}}
5.7.3 Bit Fields
Bit fields (declared as {{{int somefield:n}}}) are supported by hsffig, but there are some additional things that need attention.
There is no such thing as offsetof for bit fields. To implement the {{{-->}}} and {{{<--}}} combinators, special inline C functions are embedded in the hsc code hsffig generates. This is achieved with the #def macro that hsc2hs recognizes.
These functions are placed in a special C file. This file must be compiled and linked to the final executable. Consider the following C header (bf.h):
{{{ union bitfields {
struct { int a:1; int b:1; int c:1; int d:1; } x; int y;
}; }}}
and the Haskell program (bftest.hs):
{{{ -- Test for bit fields.
module Main where
import BF_H
main = do
putStrLn $ "Test of Bit Fields"
alloca $ \(bfu :: Ptr U_bitfields) -> do x <- (bfu --> V_x) (x, V_a) <-- fromIntegral 1 (x, V_b) <-- fromIntegral 0 (x, V_c) <-- fromIntegral 0 (x, V_d) <-- fromIntegral 1 y <- (bfu --> V_y) putStrLn $ "y = " ++ (show y)
}}}
When hsffig processes bf.h it creates BF_H.hsc. When hsc2hs processes BF_H.hsc it creates BF_H.hs, and additionally BF_H_hsc.h and BF_H_hsc.c. The latter is recommended to compile with ghc:
{{{ ghc -c BF_H_hsc.c }}}
which provides correct compilation environment, so necessary paths for the runtime header files will be passed to gcc properly.
After all, the executable may be compiled and linked:
{{{ ghc -ffi -fglasgow-exts -package HSFFIG --make bftest.hs BF_H_hsc.o -o bftest }}}
If bftest is run, it prints "9", as one might expect (at least on the x86 architecture).
5.7.4 Foreign Structures/Unions as Storables and Alloca
It is often necessary to pre-allocate a foreign (C) structure/union, so a foreign function can use it. The alloca and malloc functions are defined in Haskell FFI for this purpose. They require an argument belonging to the class Storable.
So, for every structure type imported by hsffig, iinstance of Storable is declared (for struct abc used in the example above):
{{{ instance Storable S_abc where
sizeOf _ = (#size __quote__(struct abc)) alignment _ = 1 peek _ = error $ "peek and poke cannot be used with struct abc" poke _ = error $ "peek and poke cannot be used with struct abc"
}}}
These four methods are minimally required implementation of Storable per the FFI Addendum.
Actually, only sizeOf plays a role here, returning the same value as C expression {{{sizeof (struct abc)}}} would return.
An example below (retrieval of data from Berkeley DB) shows the use of everything discussed above:
{{{
(ret, ks, vs) <- alloca $ \dbkey -> -- dbkey = alloca (sizeof (DBT)) alloca $ \dbdata -> -- dbdata = alloca (sizeof (DBT)) withCStringLen "fruit" $ \fruit -> do -- (address, length) (dbkey,V_data) <-- fst fruit -- dbkey -> data set to the string address (dbkey,V_size) <-- (fromIntegral $ snd fruit) -- dbkey -> size set to the string length r <- (dbp ==> X_get) dbp nullPtr dbkey dbdata 0 -- r = dbp -> get (dbp, NULL, dbkey, dbdata, 0) ksc <- (dbkey --> V_data) :: IO CString -- ksc = dbkey -> data kss <- dbkey --> V_size -- kss = dbkey -> size if (r == 0) then do dsc <- (dbdata --> V_data) :: IO CString -- dsc = dbdata -> data dss <- dbdata --> V_size -- dss = dbdata -> size ks <- peekCStringLen (ksc, fromIntegral kss) vs <- peekCStringLen (dsc, fromIntegral dss) return (r, ks, vs) else return (r, undefined, undefined)
}}}
It may be noted again that a Haskell application developer does not need to remember type identifiers of foreign structures involved. The compiler, using FFI import statements and the multiparameter class' functional dependencies, correctly infers all necessary type information. In fact, type of dbkey and dbdata in the example above should be Ptr S_'_'_db_dbt (as defined in the header: {{{typedef struct __db_dbt { ... } DBT;}}}). But this type is not mentioned explicitly in the code.
6 Compilation of Applications Using Bindings Created with HSFFIG
Applications using bindings created with hsffig must be compiled/linked with the option -package HSFFIG passed to ghc. In the example below, the application consists of a single module containing the main funstion: main.hs, and the C library header file is header.h. The library file name is library.a.
The main.hs file must contain an import statement:
{{{
import HEADER_H
}}}
When hsffig processes header.h it creates HEADER_H.hsc. When hsc2hs processes HEADER_H.hsc it creates HEADER_H.hs, and additionally HEADER_H_hsc.h and HEADER_H_hsc.c. The latter is recommended to compile with ghc:
{{{ ghc -c HEADER_H_hsc.c }}}
which provides correct compilation environment, so necessary paths for the runtime header files will be passed to gcc properly.
After all, the executable may be compiled and linked:
{{{ ghc -ffi -fglasgow-exts -package HSFFIG --make main.hs HEADER_H_hsc.o library.a -o main }}}
The library of the package HSFFIG contains definition of the multiparameter class (HSFFIG.Field'Access.Field'Access) and the combinators necessary to access members of C structures/unions (see above). It is not necessary to directly import the hsffig modules in the application modules because the binding module re-exports them. It is however necessary to use the -fglasgow-exts options of ghc.
So, in the simplest case, the following steps are necessary:
hsffig > HEADER_H.hsc
hsc2hs -t /dev/null HEADER_H.hsc -o HEADER_H.hs
ghc -c HEADER_H_hsc.c
ghc -ffi -fglasgow-exts -package HSFFIG --make main.hs HEADER_HSC.o library.a -o main
In some cases, size of the autogenerated Haskell code of the binding module is too large so it cannot be compiled due to lack of system resources. In this case, the binding module has to be split (see above, Splitting Large Modules). Steps to compile and build an executable now are:
hsffig > HEADER_H.hsc
hsc2hs -t /dev/null HEADER_H.hsc -o HEADER_H.hs_unsplit
splitter HEADER_H.hs_unsplit
ghc -c HEADER_H_hsc.c
ghc -ffi -fglasgow-exts -package HSFFIG --make main.hs HEADER_HSC.o library.a -o main
The only one step added is running splitter over the Haskell source code generated by hsc2hs. The way the final executable is linked does not change.
7 Known Problems and Workarounds
7.1 Variadic Functions
C functions whose argument list ends with an ellipsis (...) in other words taking variable number of arguments cannot be imported by hsffig. A common example is printf. If hsffig encounters such a function, it places a comment in its output explaining why the function could not be imported. However if a variable or a structure/union member is defined as a pointer to a variadic function is imported as a pointer to a function with type IO () i. e. {{{void (*p)(void)}}}. This preserves the ability to query/set function pointer from a Haskell program.
So:
{{{ int (*pvard)(int,int,...);
int vard (int,int,...); }}}
imports as:
{{{ foreign import ccall "header.h &pvard"
___58___ :: Ptr (FunPtr (IO ()))
p_pvard = ___58___ foreign import ccall "dynamic"
___58___mk___ :: FunPtr (IO ()) -> (IO ())
foreign import ccall "wrapper"
___58___wr___ :: (IO ()) -> IO (FunPtr (IO ()))
x_pvard = peek ___58___ >>= \s -> ___58___mk___ s v_pvard = peek ___58___ >>= (return . ___58___mk___) s_pvard = \s -> ___58___wr___ s >>= poke ___58___
--
-- -- import of function/variable/structure member(s) vard :: WrongVariadicFunction is not possible -- because of the following reason(s): -- function is variadic }}}
7.2 Functions/Variables of Structure Type
If a function or a variable has a structure (not structure pointer) type, hsffig cannot import it. If hsffig encounters such a function, it places a comment in its output explaining why the function could not be imported. However, if a structure/union member is itself a structure/union, it is imported so that the {{{-->}}} combinator returns a Ptr to that member. However the {{{<--}}} combinator is not defined for such members.
So:
{{{ struct {int a,b,c,d;} *allocs(int,int,int,int);
struct {int a,b,c,d;} directs(int,int,int,int); }}}
imports as:
{{{ foreign import ccall "static header.h allocs"
f_allocs :: CInt -> CInt -> CInt -> CInt -> IO (Ptr (S_56))
--
-- -- import of function/variable/structure member(s) directs :: CInt -> CInt -> CInt -> CInt -> @S_58 is not possible -- because of the following reason(s): -- function takes/returns structure(s) directly -- }}}
Note that while these two functions have return types looking the same, they are not the same from the C compiler standpoint, nor are they the same from the hsffig standpoint.
7.3 Unresolved Symbols When Linking
As mentioned above, hsffig generates FFI import declarations for every function it finds a prototype for. It may rarely happen, the header file has prototypes for functions not defined by the library the header is related to. As an example, consider the following short program printing "Hello World" using the low-level write function of the standard C POSIX library:
{{{ module Main where
import UNISTD_H
main = withCStringLen "Hello World\n" $ \hello -> do
f_write (fromIntegral 0) (fst hello) (fromIntegral $ snd hello)
}}}
The prototype for write is contained in the unistd.h include file usually located in /usr/include. However if the program above is compiled and linked the "usual" way, two symbols remain unresolved by the linker: {{{__}}}ftruncate, and pthread_atfork *. As a result, the linker fails to create the executable file.
The possible workarounds are:
* To find the library where missing symbols are defined, and specify it on the ghc command line to link the executable. * To tell the linker to ignore the unresolved symbols and build the executable no matter what. * To use the -split-objs option that ghc provides (Note: See also HsffigLinkageOptimization for more detailed discussion of object file splitting possibilities).
The first option provides the best consistency, but it may be hard sometimes to find the correct library, especially for such low-level functions perhaps not assumed to be called directly.
The second option is a "short-cut" indeed: it leaves the problem open. If the developer is cofident that none of the unresolved symbols will be used for a whole life cycle of the apllication being developed, this may be acceptable, but this should not be considered an universal solution.
The third option is kind of a compromise: it leads to creation of consistent executable (and even the file size may be reduced significantly), but it also complicates the compliation/linkage process.
When given an option, -split-objs, ghc invokes a special script on the assembly files generated during compilation which cuts them into large number of small pieces. For this example program, UNISTD_H.hs was split into more than 700 object files.
These object files are placed in the special subdirectory whose name is derived from the module name: e. g. UNISTD_H_split for UNISTD_H. This directory is not autocreated: explicit mkdir command is necessary. The next step is to create a static library containing all those object files (ar -cq). The library must be specified later on the ghc command line to link the executable.
To tell more, this applies to the situation when splitter is not invoked, and there remains only one Haskell module with FFI declarations. If the module is split (this is "source split", not "object split, one not to be confused with another), then it makes sense to apply -split-objs only to the submodule containing FFI import declarations for functions (i. e. whose name is postfixed with "_F", UNISTD_H_F in this example): structures/unions, constants, and enumerations are compile-time items not dealt with by the linker.
The bottom line: uniform processing of object files with ghc --make is no longer available. Even worse, --make does not recognize libraries as compilation targets: if the module Main imports UNISTD_H, and there is UNISTD_H.hs, and libUNISTD_H.a, but no UNISTD_H.o, ghc --make will try to compile UNISTD_H to UNISTD_H.o and will ignore existence of the library.
The Makefile for this example program is shown below. It features the second and the third ways to work around the unresolved symbols problem.
$(HSFFIG) > UNISTD_H.hsc
UNISTD_H.hs: UNISTD_H.hsc
$(HSC2HS) UNISTD_H.hsc -o UNISTD_H.hs
- The target to build the split-objects library:
libUNISTD_H.a: UNISTD_H.hs
-mkdir UNISTD_H_split $(GHC) -c -split-objs -package HSFFIG UNISTD_H.hs ar cq libUNISTD_H.a UNISTD_H_split/*.o
syscall: syscall.hs libUNISTD_H.a UNISTD_H_hsc.o
$(GHC) -c UNISTD_H_hsc.c
- The second workaround: ignore unresolved symbols. The linker option to do this may depend on the version
- of binutils used. In this example, it is --noinhibit-exec. Note how -optl and -Wl are combined.
$(GHC) -ffi -package HSFFIG -fglasgow-exts --make syscall.hs UNISTD_H_hsc.o \ -optl -Wl,--warn-once -optl -Wl,--noinhibit-exec -o syscall-1
- The third workaround: link against the library. The --make option of ghc is not available.
$(GHC) -package HSFFIG -fglasgow-exts syscall.hs UNISTD_H_hsc.o libUNISTD_H.a -o syscall-2
clean:
rm -rf syscall-1 syscall-2 libUNISTD_H.a UNISTD_H* UNISTD_H_split *.o *.hi
- Note: This is of course OS-dependent situation: the situation described was observed on Linux with glibc 2.1.x. This example is provided here to illustrate how unresolved symbols problem may be worked around.
[DimitryGolubovsky]
[CategoryTutorial], [CategoryTools] | http://www.haskell.org/haskellwiki/index.php?title=HSFFIG/Tutorial&oldid=6295 | CC-MAIN-2014-41 | refinedweb | 6,859 | 59.33 |
19 October 2012 15:13 [Source: ICIS news]
HOUSTON (ICIS)--Archer Daniels Midland (ADM) has increased its stake in ?xml:namespace>
ADM said that the acquisition of GrainCorp would be in line with its strategy to expand its agricultural services and oil seeds businesses.
ADM holds a 14.9% interest in the Sydney-based grain handling, oils and agricultural company, after acquiring an additional 10%, at Australian dollar (A$) 11.75/share ($12.11/share), on Thursday, it said.
GrainCorp confirmed that ADM approached it “concerning a potential transaction.” However, GrainCorp has not yet received a formal proposal from ADM, it said.
($1 = | http://www.icis.com/Articles/2012/10/19/9605718/us-archer-daniels-midland-plans-to-acquire-australias-graincorp.html | CC-MAIN-2015-22 | refinedweb | 103 | 57.87 |
View all headers
Path: senator-bedfellow.mit.edu!faqserv
From: fleck@informatik.uni-bonn.de (Markus Fleck)
Newsgroups: comp.lang.python.announce,comp.lang.python,comp.answers,news.answers
Subject: [comp.lang.python.*] Posting guidelines -- bi-weekly posting
Supersedes: <python-faq/python-newsgroup-faq_939904504@rtfm.mit.edu>
Followup-To: comp.lang.python
Date: 30 Oct 1999 10:34:53 GMT
Organization: none
Lines: 223
Approved: news-answers-request@mit.edu
Expires: 28 Nov 1999 10:27:26 GMT
Message-ID: <python-faq/python-newsgroup-faq_941279246@rtfm.mit.edu>
NNTP-Posting-Host: penguin-lust.mit.edu
Summary: Python language info and comp.lang.python.announce posting guidelines
X-Last-Updated: 1998/09/23
Originator: faqserv@penguin-lust.MIT.EDU
Xref: senator-bedfellow.mit.edu comp.lang.python.announce:708 comp.lang.python:61607 comp.answers:38275 news.answers:169978
View main headers
Changes in 1.4: - now also cross-posting to comp.answers and news.answers
> HOW TO post to comp.lang.python[.announce] <
------------------------------------------------
posted bi-weekly to comp.lang.python.announce,
comp.lang.python, comp.answers, news.answers
About Python
------------
From.
To find out more, the best thing to do is to start reading the tutorial
from the documentation set at <>."
Example: "Hello World" in Python
--------------------------------
The original task can be accomplished by a one-liner:
print "Hello World!"
Here is a longer example, a function that returns a string
containing a series of multiple "Hello World!" greetings:
def my_hello(how_often):
retval = how_often * "Hello World! " # "multiply" string
return retval[:-1] # strip off trailing space
Usage:
>>> my_hello(5)
'Hello World! Hello World! Hello World! Hello World! Hello World!'
Note that block structure in Python is defined by indentation, rather than
block delimiters (as used in many other programming languages such as Perl,
Java and C/C++).
comp.lang.python
----------------
comp.lang.python (or c.l.py for short) is the general discussion newsgroup
for users of the Python language. It is also available as a mailing list;
see below for instructions on subscribing to c.l.py through the mailing list.
If you have questions regarding the use of Python, please take the time to
consult the Python "Frequently Asked Questions" (FAQ) list first before
posting to comp.lang.python: it's at <>.:
1. It is often very helpful to INCLUDE SOME BACKGROUND INFORMATION if
you are announcing a very specialized package or event. Submissions
will be rejected by the moderators if a casual c.l.py.a reader
cannot understand the utility or context of your announcement.
2. INCLUDE A URL (web address) for your announcement. Hint: a "real"
web page often looks better than a mere FTP address and offers more
possibilites to present your package "at a glance".
3. GIVE YOUR PACKAGE A VERSION NUMBER. If you give your package a version
number from the start, it will be easier to identify different releases
in the future. Even "small" packages should have version numbers.
4. Clarify the LICENSE that you release your package under. If you want to
release something as free software, you might want to have a look at
the "Open Source Definition", <>,
and pick one of the licenses mentioned there under "Example Licenses".
5. You should INCLUDE YOUR E-MAIL ADDRESS in the body text of your
posting or in the trailing .signature block. Please do *not* sign
your announcement with PGP; most people would not know your public
PGP key anyway and would get a warning message.
6. Avoid excessive cross-posting. Messages that are cross-posted to
several moderated news groups will usually be approved by the
moderator of the first group in the list.
7..
8. Format your posting so that all lines are at most 78 characters
wide. (Exception: Internet resource addresses (cf. 7. above) should
not be line-wrapped, if possible.)
You can upload your program or module to <>,
or become a PSA member and create a web page at the "Starship Python" server
(see below). The Python main FTP site is being mirrored at serveral sites
all around the world. Don't forget to send a short e-mail notification to
<mailto:ftpmaster@python.org> and upload a corresponding <package>.README
file together with your announcement.
Mailing list gateways
---------------------
* comp.lang.python:
There is a two-way gateway between the comp.lang.python news group and
the "python-list" mailing list. You can subscribe to this list by sending
an e-mail message to the following address:
<mailto:python-list-request@python.org>
with the text "subscribe" in the e-mail body. You can unsubscribe by
sending an e-mail message to the same address with the text "unsubscribe"
in the e-mail body.
There is a web archive of past comp.lang.python postings at FindMail,
<>.
* comp.lang.python.announce:
There is also a mailing list gateway for comp.lang.python.announce.
To subscribe or unsubscribe, send an e-mail to
<mailto:python-announce-list-request@python.org>
with a body content of "subscribe" or "unsubscribe", respectively.
Please note that comp.lang.python.announce is moderated; you cannot
just post to this list. Please e-mail any announcements to the
c.l.py.a submission address:
<mailto:python-announce@python.org>
or use your news reader to post to comp.lang.python.announce.
In the latter case, your posting should be forwarded to the
c.l.py.a moderators automatically by the news server software.
A web archive of c.l.py.a postings is currently being prepared.
Until it becomes available, you can look for c.l.py and c.l.py.a
postings with DejaNews, <>, or FindMail,
<>.
Further Python Resources
------------------------
WWW: <> - Python Language Home Page
<> - Python Language FAQ
<> - Python Quick Help Index Page
<> - Starship Python: User Pages
Usenet: <news:comp.lang.python> - Python Discussion Newsgroup
<news:comp.lang.python.announce> - Python Announcements Newsgroup
The PSA
-------
About the "Python Software Activity" (PSA), cf. <>:
"The continued, free existence of Python is promoted by the contributed
efforts of many people. The Python Software Activity (PSA) supports those
efforts by helping to coordinate them. The PSA operates web, ftp, and
that benefit the Python user community. In order to continue, the PSA
needs the membership of people who value Python." Have a look at the PSA
web pages for further information about the PSA and membership benefits.
--
----------- comp.lang.python.announce (moderated) ----------
Article Submission Address: python-announce@python.org
Python Language Home Page:
Python Quick Help Index:
------------------------------------------------------------ | http://www.faqs.org/faqs/python-faq/python-newsgroup-faq/ | CC-MAIN-2014-23 | refinedweb | 1,067 | 52.56 |
0
import java.util.Scanner; public class EventFrequency { /** * main method: * ask the user for the average number of events per time interval * (lambda) and the number of time intervals to observe * draw a horizontal and vertical histogram of the number of heads */ public static void main(String[] args) { // set up to get user input Scanner scan = new Scanner(System.in); // ask user for the average number of events per time interval System.out.println("What average number of events per time interval do you want?"); int lambda = scan.nextInt(); // ask user for the number of time intervals to observe System.out.println("How many time intervals do you want to observe?"); int times = scan.nextInt(); // instantiate a Poisson object named myDist with average number of events Poisson myDist = new Poisson(lambda); // step 1: // declare an int array named "counts" to count coin flip occurences // make its size one larger than 3 * lambda // step 2: // initialize all of the values in the counts array to 0 // step 3: // count the number of events occurring in each time interval observed // step 4: // print out the estimated probabilities of zero events and lambda events // step 5: // instantiate an object of the Histogram class with // the array to be drawn, the indices of valid data, // and the maximum length of the bars in the histogram // // call its draw methods to draw the two histograms } }
Edited 4 Years Ago by Ezzaral: Formatted code. Now you just need to post specific questions, because no one is going to finish the assignment for you. | https://www.daniweb.com/programming/software-development/threads/418569/eventfrequency-prog-please-help-urgent | CC-MAIN-2017-04 | refinedweb | 257 | 55.27 |
#include <statement.h>
Detailed Description
An RDF statement, consisting of a triple (subject, predicate, object).
Definition at line 43 of file statement.h.
Constructor & Destructor Documentation
creates a null statement
Definition at line 56 of file statement.cpp.
creates a copy of another statement
- Parameters
-
Definition at line 63 of file statement.cpp.
creates a statement Do not call this in your code, use Model::createStatement() instead.
- Parameters
-
Definition at line 68 of file statement.cpp.
destructor
Definition at line 77 of file statement.cpp.
Member Function Documentation
returns the object of this statement as resource, if possible.
Definition at line 119 of file statement.cpp.
returns the object of this statement as string, if possible.
Definition at line 130 of file statement.cpp.
returns whether this statement is a null statement (i.e.
was created using Statement())
Definition at line 96 of file statement.cpp.
the object of the statement
Definition at line 113 of file statement.cpp.
assigns another statement
- Parameters
-
Definition at line 81 of file statement.cpp.
returns whether two statements are equal.
Currently statements are equal, if they are from the same model (!) and subject, predicate and object are equal.
- Parameters
-
Definition at line 87 of file statement.cpp.
the predicate of the statement
Definition at line 107 of file statement.cpp.
the subject of the statement.
Definition at line 101 of file statement. | https://api.kde.org/frameworks/syndication/html/classSyndication_1_1RDF_1_1Statement.html | CC-MAIN-2020-16 | refinedweb | 229 | 53.17 |
Despite.
C++ Notes
Language notes — C++
Compiled by Jeremy Kelly
These are my personal C++ notes. They document C++03, plus some features from C++11-17, which is generically labeled modern C++. The notes do not provide an exhaustive description of the language. Concepts that seem obvious to me often go unmentioned. Conversely, some of these items are interesting without being particularly useful.
The notes are here for my convenience, but you are welcome to use them, subject to the terms of the Creative Commons Attribution-ShareAlike 4.0 International License. If you find a mistake, please let me know.
All example code follows the Split Notation.
This page includes a two-column print style. For best results, print in landscape, apply narrow margins, and change the Scale setting in your browser's print options to 60%.
char represents one element from a single character set, usually (but not necessarily) ASCII. It is one byte in size.
wchar_t represents one element out of all character sets in all locales supported by the implementation. It is usually two bytes in size. Wide character literals are prefixed with
L:
wchar_t o = L'A';
Character types are usually signed by default.
Escape sequences allow special characters to be represented within character and string literals:
Arbitrary characters can be specified with a single backslash, followed by up to three octal digits:
char o = '\101';
or a backslash and an
x, followed by any number of hex digits:
o = '\x0041';
Integers are signed by default:
Integer literals can be prefixed to specify their number base, or suffixed to specify their size or signedness:
Floats are always signed:
Visual Studio treats
long double as
double.
Float literals can be specified with scientific notation, the exponent being marked with
E or
e:
const double oTol = 1E-3;
When an integer and a float are passed to an operator, the integer is automatically converted to a float.
In general, an l-value is an object that can be addressed through a variable or pointer. Parameters are always l-values, even when they reference r-values. An r-value is typically a temporary object. In many cases, the content of an r-value can be moved rather than copied, since the r-value will not be used again.
When not otherwise specified, a reference in C++ is an l-value reference, declared with a single ampersand. This is generally made to reference an l-value, and if the reference is non-
const, it must be initialized that way:
static int eCtFull = 0; static int eCtDef = 16; void gReady(bool aCkFull) { int& orCt = (aCkFull ? eCtFull : eCtDef); ...
However, if the reference is
const, the reference can be initialized with a temporary object. When this is done, the temporary persists until the reference goes out of scope:
const tPt& oPtCtr = aCkOrig ? tPt() : tPt(aX, aY);
After initialization, a reference cannot be made to target a different object.
Just as non-
const l-value references must target l-values, r-value references must target r-values. If an r-value reference is initialized with an l-value, a build error will result, just as if a non-
const l-value reference were initialized with an r-value.
The r-value reference is declared with two ampersands. It can be used to define move constructors and move assignment operators that swap instance content without copying:
class tAct { public: tAct(tAct&& arAct) { Swap(arAct); } tAct& operator=(tAct&& arAct) { Swap(arAct); return *this; } void Swap(tAct& arAct) { tDataAct* opData = epData; epData = arAct.epData; arAct.epData = opData; } ...
The source instance is modified, so it cannot be
const, as it would in copy operations. The source should be left in a destructible state, and it should be assignable, if the type supports assignment. Move operations should not throw.
Defining copy and move operations allows a type to copy from l-values and move from r-values. Additionally, the
move template function in the Standard Library casts an l-value to an r-value reference, allowing a move to be performed on l-values:
class tPlan { public: tPlan(tPlan&& arPlan): eActDef(move(arPlan.eActDef)) { } tPlan& operator=(tPlan&& arPlan) { eActDef = move(arPlan.eActDef); return *this; } void Swap_Def(tAct&& arAct) { eActDef = move(arAct); } ...
If
move is applied to a type that does not implement move operations, the instance will be copied.
Note that swap operations can be implemented with any non-
const reference, whether l-value or r-value. Defining a swap parameter as an r-value reference ensures that the argument is a temporary object, or an instance explicitly wrapped with
move.
While it can be useful to
move a parameter representing an r-value to a function's return value:
tAct gAdv(tAct&& arAct) { tDataAct oData = gDataAdv(); arAct.Upd(oData); return move(arAct); }
it is not necessary to move a local variable to the return:
tAct gWait() { tAct oAct; ... return oAct; }
This return value optimization is performed automatically by the compiler.
Applying two ampersands to a deduced type can produce a forwarding reference, also known as a universal reference, rather than a true r-value reference. Specifically, given type parameter
z in a template function, the parameter type
z&& produces a forwarding reference if it is not qualified with
const or
volatile:
template<typename z> void gExec(z&& ar) { ...
auto&& also produces a forwarding reference:
auto&& orLot = aLot;
Unlike r-value references, which must be initialized with r-values, forwarding references can be initialized with r-values or l-values. They can also target
const or
volatile instances. When that happens, the qualifiers are subsumed by the type parameter, so the forwarding reference cannot be used to bypass their effects, even though it does not list the qualifiers.
The
forward function casts a reference to an r-value if it represents an r-value argument. This allows the argument to be perfect-forwarded to other functions as an r-value or as an l-value, with qualifiers:
void gPrep(const tAct& aAct) { ... } void gPrep(tAct& arAct) { ... } void gPrep(tAct&& arAct) { ... } template<typename zAct> void gRun(zAct&& aAct) { gPrep(forward<zAct>(aAct)); ...
It is dangerous to
move a forwarding reference, because
move unconditionally casts to an r-value reference, even if the reference happens to represent an l-value.
The type referenced by a pointer is the base type of that pointer. A
void pointer can store the address of any object, but
it cannot be dereferenced or participate in pointer arithmetic without first being cast.
In modern C++, a pointer can be set to reference no object by assigning
nullptr. Unlike common implementations of
NULL, this value is not implicitly converted to an integer.
A pointer can be made to reference a variable within a class type. Such a pointer does not reference a particular variable instance, as other variable pointers do. Instead, it references one member within any instance of the containing type. It is like an object-relative offset rather than an absolute memory address:
struct tEnv { tEnv(int aWth, int aHgt): Wth(aWth), Hgt(aHgt) {} int Wth; int Hgt; }; int tEnv::* opSize;
The declaration is similar to that of an ordinary value pointer, but the indirection operator is prefixed by the class type. Since class variable pointers do not reference specific instances, no instance is needed to set such a pointer. Only the type is specified:
opSize = &tEnv::Hgt;
An instance is needed to dereference the pointer. The dereferenced pointer is applied to the instance, and read or written just as the variable would be:
tEnv oEnvSm(6, 4); int oSize = oEnv.*opSize;
A function pointer can reference any function with a matching signature:
short gCt(int aID); short (* odCt)(int) = &gCt;
The pointer is declared like a function, with the indirection operator and pointer name replacing the function name. Parameter names can be specified or not. When setting the pointer, the address of operator can be applied to the function, or it can be omitted:
odCt = gCt;
Once initialized, function pointers can be invoked directly:
short oCt = odCt(100);
or they can be explicitly dereferenced:
oCt = (*odCt)(100);
Where function pointers are concerned,
static class functions and non-class functions are identical. The same pointers can reference functions of either type, if the signatures match:
struct tCat { static short sCt(int aID); }; odCt = &tCat::sCt;
Pointers can also reference non-
static class functions. Much like class variable pointers, these reference a specific class type as well as a function signature:
struct tIt { short WgtMin(int aCt) const; }; short (tIt::* odWgt)(int) const = &tIt::WgtMin;
As with non-class function pointers, the indirection operator and pointer name replace the function name in the declaration. As with class variable pointers, the indirection operator is prefixed with the class type. Unlike ordinary function pointers, the address of operator is required when assigning to the pointer. The class is specified when setting the pointer, but no instance is needed.
odWgt = &tIt::WgtMin;
An instance is needed to dereference the pointer, however. The dereferenced pointer is applied to the instance and invoked as the class function itself would be:
tIt oIt; short oWgt = (oIt.*odWgt)(10); tIt* opIt = new tIt; oWgt = (opIt->*odWgt)(20);
Multidimensional arrays are implemented as arrays of arrays:
int oGrid[gXMax][gYMax];
Elements are accessed by dereferencing each array in turn:
int o = oGrid[oX][oY];
This is equivalent to:
int o = *(*(oGrid + oX) + oY);
The rightmost dimension is the only one providing a continuous linear mapping of memory to array values.
When declaring arrays as function parameters, the size of all dimensions but the first must be specified:
void gScan(int aGrid[][gYMax]);
This allows the offsets to be calculated when dereferencing the array.
Like other aggregates, arrays can be initialized with initializer lists:
int oOff[] = { 5, 10, oX + 10 };
List elements need not be constant. Such lists can be used only during initialization.
If the array size is not specified, it will be inferred from the initializer list. If it is specified, and if initializers are not provided for all elements, the remaining elements will be default-initialized.
When initializing multidimensional arrays, the innermost list levels correspond to the rightmost array dimensions:
int oGrid[2][3] = { { 11, 12, 13 }, { 21, 22, 23 } };
When initializing character arrays with string literals, the compiler adds and initializes one element for the zero-terminator, even when the string is empty:
char oText[] = "";
String literals separated by whitespace are joined into continuous arrays by the compiler:
char oText[] = "ABC" "DEF" "GHI";
All string literal data is allocated for the lifetime of the program, even when defined within a block.
An enumeration associates a set of named integral values with a new type:
enum tSt { gStReady, gStAct = 100, gStDone };
The elements are called enumerators. These often have the size of an
int, but the standard allows them to be larger if their values are outside that range. Visual Studio warns and then truncates values when this happens.
Unless a value is specified, each enumerator takes the value of its predecessor, plus one. If no value is specified for the first enumerator, it is set to zero. Multiple enumerators can have the same value.
Enumerations can be defined anonymously. They can have namespace, class, or local scope:
void gOut() { enum { oOpen = 10, oClosed = 20 }; ...
Ordinary enumerations produce unscoped enumerators, which have the same scope as the enumeration itself. These enumerators are automatically converted to integral types, which in turn are converted to floats. Integral types cannot be converted to enumerators without a cast.
In modern C++, placing the
class keyword after
enum produces an enumeration class:
Enumeration classes create scoped enumerators that differ from unscoped enumerators in two ways:Enumeration classes create scoped enumerators that differ from unscoped enumerators in two ways:
enum class tSt { Ready, Act = 100, Done };
They do not appear in the scope containing the enumeration. To reference one, it is necessary to prefix with the enumeration name, like a
static class member:
tSt oSt = tSt::Ready;
In modern C++, it is possible to specify the underlying integral type by listing it after the enumeration name, much like the base class in a class type definition:
enum tSlot: char { ...
It is also possible to forward-declare an enumeration, allowing the definition to be moved to a CPP file:
enum tSlot: char;
Enumeration classes can be forward-declared without specifying an integral type. According to the standard, traditional enumerations must specify a type when they are forward-declared, but Visual Studio ignores this requirement.
Class types include classes, structures, and unions. Though they are usually defined with file or namespace scope, they can be defined locally, as long as all functions are defined within the class definition:
void gExec() { class tNode { public: int Cd; void Send() { gSend(Cd); Cd = 0; } }; tNode oNode; ...
A constructor is called when storage is allocated. If no constructor is accessible at some point in the code, no instance can be allocated there, dynamically or otherwise. The constructor initializes class variables in the order of their definition within the class, not their order within the member initializer list.
Class types that implement destructors cannot be automatically or statically allocated if their destructors are inaccessible. They can be dynamically allocated in this situation, but not deleted.
A default constructor is one with no parameters, or one for which all parameters have defaults. The function call operator is not required when invoking a default constructor:
tEl* opEl = new tEl;
However, using the operator causes the instance to be zero-initialized in some cases, particularly when it is a POD type:
tEl* opElZero = new tEl();
If no constructor is explicitly defined for some class type, the compiler will create a default constructor for it, as long as all the type's members can themselves be default-constructed. All constructors call the default constructors of member variables that are not explicitly constructed in their initializer lists.
If an array is not completely initialized when it is defined, the base type of that array must provide an accessible default constructor, whether explicitly defined or otherwise.
A copy constructor accepts a reference to an instance of the same type. Other parameters can be defined if default values are provided for them. When a class type variable is initialized with an instance of the same type, the copy constructor is called, not the assignment operator:
tIt oItTemp = oIt;
If no copy constructor is explicitly defined, the compiler will create one that calls the copy constructor of each member, as long as each has an accessible copy constructor.
When a derived class is instantiated, constructors in the least-derived base classes are invoked first. When it is destroyed, destructors in the most-derived classes are invoked first.
If a base class has a default constructor, it need not be explicitly initialized by the derived class. If it does not, a base class initializer must be specified in the initializer list:
struct tCtl { tCtl(int ahWin): hWin(ahWin) {} int hWin; }; struct tBtn: public tCtl { tBtn(int ahWin): tCtl(ahWin) {} };
There is no way for a derived class to initialize base class variables directly.
Declaring a base class destructor
virtual makes destructor calls polymorphic. This ensures that derived destructors are called even if the instance is deleted through a base class pointer.
By default, the compiler implements a number of special member functions for class types, if such functions are invoked when the class is used:
To implement the default constructor automatically, it must be possible to default-construct every variable in the class type. Similarly, to implement the copy constructor, every variable must itself provide an accessible copy constructor. The same holds for the assignment operator.
The Rule of Three recommends that, if either the copy constructor, copy assignment operator, or destructor is explicitly defined, all three should be defined, since custom resource management in one function entails a similar obligation in the others.
In modern C++, the compiler also defines a move constructor and a move assignment operator. Unlike the original special member functions, defining either of these prevents the other from being implemented automatically. Additionally, defining a copy constructor, a copy assignment operator, or a destructor prevents either move function from being implemented by the compiler. Conversely, the original copy functions are not implemented if either move function is defined.
If the default implementation for any special function is disabled, it can be recalled by applying the
default keyword to its declaration:
class tLot { public: virtual ~tLot(); tLot(tLot&& aLot) = default; tLot& operator=(tLot&& aPt) = default; ...
Non-
static
const class variables must be initialized with member initializers:
struct tLine { tLine(unsigned int aCode): Code(aCode) {} const unsigned int Code; };
static class variables are not associated with specific instances of the containing type; instead, a single instance is shared by the entire class. These variables are initialized before
main executes. Their relative initialization and deinitialization order is undefined.
Declaring a non-
static class variable also defines the variable. By contrast,
static class variable declarations do not serve as definitions, so the variables must be defined outside the class definition. Technically, even
static
const integer variables require explicit definition, even when these are initialized inline:
struct tEl { static const int sIdxMax = 255; }; const int tEl::sIdxMax;
Visual Studio does not enforce this requirement.
Bit fields allow the memory used by an integral type to be split between several class variables. The bit size of each variable is specified after the variable name. Omitting the variable name creates an anonymous field, which is typically used for padding. The implementation may also insert padding to preserve type boundaries:
struct tMsg { unsigned char X: 2; unsigned char Y: 2; char: 3; bool Set: 1; };
The size assigned to a given field cannot exceed that of the field's type. Only integral types and enumerations can be used as fields.
It is impossible to obtain the address of a field. Fields can be used in any class type, and, like other variables, fields defined in unions share memory with other union variables.
static class functions are not associated with a particular instance of the
class, so
this is not defined within them, and they cannot call other class functions unless they are also
static, or unless the non-
static functions are invoked through an instance.
const functions cannot invoke non-
const functions in the same instance, and they cannot modify variables in that instance unless those variables are
mutable. They are allowed to modify
static class data.
When applied to a class function, the
volatile qualifier indicates that the function is thread-safe.
volatile class functions cannot invoke non-
volatile functions on the same instance. They can modify non-
volatile class data, however.
Class elements are
private by default. Structure and union elements are
public by default.
Namespaces, enumerations, typedefs, and other class types can be defined within classes, just like variables and functions. Such elements have class scope, plus the specified access level.
The friends of a class gain access to all class elements accessible to the class itself, including
protected elements inherited from parents. Because
private parent elements are inaccessible to the class, they are inaccessible to its friends.
The friends of a base class have access to the base class members of all derived classes, even when the derived classes do not. No other friend obligations are inherited by derived classes.
Class types and functions can be declared friends. Neither need be defined at the time of the friend declaration.
Classes, structures, and unions must be identified as such when declared as friends:
struct tBatch { friend class tList; friend struct tItr; friend union thIdx; ...
Friend privileges are not inherited by types derived from friend types.
Function friends are declared with a complete function prototype:
class tSet { friend void gSort(tList& arList); friend void tStore::Write(); ...
If a derived class defines a function with the same name and signature as one in a base class, and if the base class function is not
virtual, the base function will be hidden by the derived function within the derived class. Base class variables are also hidden by derived class variables with the same name. Hidden base members can be accessed from derived classes by using the scope resolution operator, which prefixes the identifier with the name of the targeted class type, and two colons:
struct tCont { bool Avail; void Sort(); }; struct tList: public tCont { int Avail; void Sort() { tCont::Sort(); } };
Scope resolution can also be performed from outside the class:
tList oList; bool oAvail = oList.tCont::Avail;
It is often desirable to prevent the compiler from defining its own copy constructor and assignment operator for a particular class type. Traditionally, this is done by declaring the functions
private and omitting their definitions.
In modern C++, this intention can be made explicit by applying the
delete keyword to the declarations:
class tMgrRsc { public: tMgrRsc(const tMgrRsc&) = delete; tMgrRsc& operator=(const tMgrRsc&) = delete; ...
By itself, each declaration prevents the compiler from defining the function. Additionally, the
delete keyword produces a compiler error if it is called, rather than a linker error, as would occur if the definitions were simply omitted.
In other respects, the
delete syntax produces an ordinary declaration. In particular, it is not possible to
delete functions that have already been declared or defined.
delete can be applied to different signatures, however. If a function accepts a type like
int, to which many other types are automatically converted:
int gNextID(int aID) { ...
the unwanted conversions can be avoided by targeting alternative signatures with
delete:
int gNextID(char) = delete;
The compiler recognizes the deleted function as an overload, so it does not even consider the conversion.
delete can also be applied to unwanted template signatures or specializations:
template <typename z> void gStore(z a) { ... } template <typename z> void gStore(z* a) = delete;
Declaring a class function
virtual:
class tWin { public: virtual void Inval(thRend ahRend); ...
allows derived classes to override it:
class tView: public tWin { public: void Inval(thRend ahRend); ...
When this is done, the new implementation is used wherever the function is called, even in the base class. By contrast, non-
virtual functions can only be hidden, which causes the new implementation to be invoked from the derived class, but not from the base. Class types with at least one
virtual function are said to be polymorphic. Because the correct implementations are not known until run time, virtual functions cannot be inlined by the compiler.
Though it remains inaccessible, a
private base class function can be overridden, causing the derived implementation to be called when invoked by the base. The base implementation remains inaccessible to the child.
To override successfully, the base function must be
virtual, and the new function must match its name and signature exactly. If these requirements are not met, the result is typically a new function that perhaps hides or overloads the original. Compilers seldom warn when this happens.
In modern C++, functions can be marked
override, in the same way they are marked
const or
volatile:
class tEd: public tWin { public: void Inval(thRend ahRend) override; ...
Such a function is meant to override a function in the parent. If it fails to do so, a compiler error results.
Where
virtual allows a function to be overridden, in modern C++,
final prevents a function from being overridden any further:
class tEdNum: public tEd { public: void Inval(thRend ahRend) override final; ...
A class type can also be made
final by placing the keyword after the class name, and before the inheritance list:
class tEdNumCust final: public tEdNum { ...
Such a class cannot be inherited from at all.
After declaring one or more pure virtual or abstract functions:
struct tPerson { virtual void vRep() = 0; };
a class cannot be instantiated. Neither can its descendents, unless all such functions have been overridden somewhere in the inheritance chain. In other respects, pure virtual functions are like other class functions. They can even be defined in the abstract class, and invoked:
void tPerson::vRep() { cout << "Person" << endl; } struct tCust: public tPerson { void vRep() {} }; void gExec() { tCust o; o.tPerson::vRep(); }
In particular, pure virtual destructors, which are sometimes use to make classes abstract, must be defined if derived classes are to be instantiated.
When a class type specifies a base class in its constructor, it can prefix the base with an inheritance access level that limits the accessibility of base class members outside the derived class. In particular,
protected inheritance renders
public base members
protected in the derived class,
private inheritance renders all base members
private, and
public inheritance leaves base members unchanged.
public and
protected base members remain accessible in the derived class and its friends:
class tFig { public: int Wth; }; class tSq: private tFig { public: tSq() { Wth = 10; } };
To prevent non-
public base classes from being accessed indirectly, derived classes cannot be upcast to
protected or
private base classes without an explicit cast:
tFig* opFig = (tFig*)&oSq;
By default, if a class derives from multiple base classes, and if two or more of the base classes share a common ancestor, multiple instances of that ancestor will be defined in the derived class. To avoid ambiguity, it is necessary to specify one of the intermediate classes when referencing a duplicated variable or function.
To prevent duplication, the common ancestor can be inherited as a virtual base class by prefixing it in the intermediate class constructors with
virtual:
struct tVehi { const string Model; tSpanTime Age() const; }; struct tBoat: virtual public tVehi { }; struct tCar: virtual public tVehi { }; struct tBoatCar: public tBoat, public tCar { };
All members of a union share the same location in memory. When one member is assigned, the content of the other members becomes undefined.
A union cannot contain any variable that implements a constructor or a
destructor, or that overloads the assignment operator. Although they are class types, unions cannot participate in inheritance, or declare
virtual
functions.
Unions defined within other class types can be anonymous:
struct tVal { union { int uX; int uY; }; };
Variables within these unions are accessible as though they were members of
the containing type. Unions with file scope can be made anonymous, but they
must be declared
static:
static union { int uID; int uIDEx; };
Anonymous unions cannot define functions or non-
public
variables.
Aggregate types include arrays, and any class type that:
privateor
protecteddata, unless that data is
static;
virtualfunctions.
Aggregates can be initialized with initializer lists. The list values can include other classes or structures:
struct tOpt { tOpt(int aLenMax): LenMax(aLenMax) {} int LenMax; }; struct tConn { int ID; string Name; tOpt Opt; }; tConn oConn = { 100, "Test", tOpt(10) };
The values must be specified in the order of their declaration within the type. As with arrays, elements for which no value is provided will be default-initialized. Initializer lists cannot be used to assign, only to initialize.
Other types can use initializer lists in modern C++, but aggregates can use them in all versions.
A POD type is an aggregate that:
static;
POD types can be serialized and deserialized with block memory transfers.
The
template keyword introduces a template parameter list. Like a function parameter list, this construction identifies parameters to be used in the definition:
template <typename xType, int xSize> struct tArr { tArr(int aVal); xType Els[xSize]; };
In template classes, the class name is followed by a template argument list, which identifies the specialization to be defined:
template <typename xType, int xSize> inline tArr<xType, xSize>::tArr(int aVal) { for (int o = 0; o < xSize; ++o) Els[o] = aVal; }
Often this reiterates the parameter list, but in partial or explicit specializations, some or all parameters will be replaced with specific types.
Template functions are defined much as template classes are, but no argument list is needed for the general specialization:
template <typename xType> void gExch(xType& arVal0, xType& arVal1) { xType oVal(arVal0); arVal0 = arVal1; arVal1 = oVal; }
Nor is the argument list always needed to invoke the function:
gExch(oX, oY);
It can be used to select a particular specialization, however:
gOut<string>("Ready");
It is also used to pass non-type parameters:
gExec<256>(od, 1000);
Template functions can be defined in class types that are not themselves template classes:
struct tFile { template <typename xData> void Write(xData& arData); }; template <typename xData> inline void tFile::Write(xData& arData) { eWrite(arData.Read()); }
Templates can be parameterized with type or non-type parameters. Default arguments can be specified for either:
template <typename xType = short, int xDim = 3> struct tPt { static const int sDim = xDim; xType Disp[xDim]; };
Parameters that follow the first default argument also require defaults. The argument list braces must be applied to a template class, even if all the defaults are accepted:
tPt<> oPt;
Type parameters must be preceded by
typename or
class. These are equivalent.
Class types with local scope cannot be used as type arguments.
Non-type parameters are defined with a type and a parameter name, much like function parameters, though they do not pass arguments in the same way. Template arguments must be constant.
Non-type parameters can be:
String literals are not valid template arguments.
Explicit specialization allows distinct implementations to be defined for specific parameter combinations. Explicitly-specialized template classes can define different variables and functions; they need share nothing, in fact, but their names and template parameter signatures.
To distinguish an explicit specialization from other specializations of the same template, the entire argument list must be populated with specific types. Since every template parameter has been specified in the argument list, the class definition is preceded by an empty parameter list:
template <> struct tArr<bool, 1> { tArr(int aVal); bool El; };
The same is done for non-class function specializations:
template <> void gExch<int>(int& arVal0, int& arVal1) { arVal0 ^= arVal1; arVal1 ^= arVal0; arVal0 ^= arVal1; }
No parameter list is needed for class function specializations:
inline tArr<bool, 1>::tArr(int aVal) { El = (aVal != 0); }
Partial specialization supports distinct implementations for certain template parameter choices, while leaving other parameters open.
The open parameters remain in the template parameter and argument lists. The constrained parameters are removed from the parameter list, and their entries in the argument list are replaced with specific types:
template <int xSize> struct tArr<bool, xSize> { tArr(int aVal); bool Els[xSize]; }; template <int xSize> inline tArr<bool, xSize>::tArr(int aVal) { for (int o = 0; o < xSize; ++o) Els[o] = (aVal != 0); }
typename is most often found in a template parameter list, but it can also be used in the template definition, where it explicitly marks some element as a type:
template <typename xType> void gNext() { typename xType::tData oData; gExec(oData); }
The compiler knows nothing about a given parameter type until the template is specialized, so it may not otherwise be able to parse the definition. Visual Studio does not require
typename in this particular case, however.
A type alias is an alternative name for a type. It can created as a typedef or as a
using alias.
A typedef is defined by placing the typedef name where the variable or function name would be found, and then prefixing with the
typedef keyword:
typedef vector<int> tSeq;
Thereafter, the typedef name can be used in place of the original type:
tSeq::size_type oIdx = 1;
The same syntax is used for more complex types. If a non-
static class function pointer is declared this way:
short (tIt::* odWgt)(int) const = nullptr;
an equivalent typedef can be defined with:
typdef short (tIt::* tdWgt)(int) const;
Typedefs can have namespace, class, or local scope.
In modern C++, type aliases can also be created with the
using keyword. Instead of placing the alias name where the variable or function name would be found, it appears on the left side of an assignment. The notional variable or function name is simply removed:
using tSeq = vector<int>;
The same syntax applies to more complex declarations:
using tdWgt = short (tIt::*)(int) const;
Unlike typedefs,
using aliases can be templatized:
template <typename zEl> using tSeqsByCd = map<string, vector<zEl>>;
The resulting alias template is specialized like any other template:
tSeqsByCd<int> oSeqsByCd;
Like typedefs,
using aliases can have namespace, class, or local scope, unless they are templatized, in which case they cannot be local.
Many basic types are automatically converted to other types, even when precision would be lost. Compilers generally warn when this is done. Some automatic conversions can be performed without losing precision. These are called type promotions.
A conversion from a user type to another type is implemented with a conversion operator, which returns an instance of the new type. A conversion from another type is implemented with a constructor that accepts the original type as a parameter.
The conversion operator declaration is unlike other operators: no parameter is accepted, and no return type is specified, not even
void. Instead, the conversion type is specified after the
operator keyword, and it is followed by the function call operator:
struct tOrd { operator int() const { return 100; } };
Conversion operators allow user-defined types to be implicitly converted to other types:
tOrd oOrd; int oID = oOrd;
When defined, conversion operators are also invoked during explicit conversions:
cout << (int)oOrd;
By default, if a constructor can be invoked with a single parameter, it will be used by the compiler to perform implicit conversions from the parameter type to the constructed type:
struct tCust { tCust(int aID = 0, float aBal = 0.0); }; tCust oCust = 1;
It is usually preferable to mark these constructors
explicit. When this is done, the conversion can be performed only with a cast.
Upcasting converts a derived class reference to a base reference. Downcasting converts a base reference to a derived reference. Crosscasting converts a base class reference to another base reference, which is possible only when the instance derives from both.
dynamic_cast uses RTTI to convert pointers and references within a class family:
tCtl* opCtl = dynamic_cast<tCtl*>(opBtn); tCtl& orCtl = dynamic_cast<tCtl&>(orBtn);
When
dynamic_cast succeeds, the converted pointer or reference is returned. When a pointer cast fails, or when the source pointer is zero, zero is returned. When a reference cast fails,
bad_cast is thrown. Because they provide no type information,
void pointers cannot be passed to
dynamic_cast.
A given upcast will succeed if the destination is a unique, accessible base class of the instance type. If the instance uses multiple inheritance, and if multiple matching base instances are found, the cast will fail. It will also fail if the destination is a
private or
protected base class.
A given downcast will succeed if the source pointer or reference type is polymorphic, if the destination type is accessible, and if the instance type matches or derives from the destination type.
A crosscast will succeed if the source pointer or reference type is polymorphic, if the destination type is accessible, and if the instance type derives from both the source and the destination types. The destination type need not be polymorphic.
Any cast will succeed if the destination type matches the instance type.
static_cast does not use RTTI, never requires a polymorphic source type, and performs no run-time check, so it cannot return zero or throw. It is used to perform upcasts and downcasts. It also converts between 'related' types, like integers and floating-point types:
bool oVal = true; int oIdx = static_cast<int>(oVal);
const_cast is used to remove
const or
volatile qualifiers:
struct tCurs { int Idx; void Skip() const; }; void tCurs::Skip() const { ++(const_cast<tCurs*>(this)->Idx); }
This is safe only if the value to be cast was not originally declared with such qualifiers.
reinterpret_cast converts 'unrelated' types. It generally produces a value with the same bit pattern as its argument. It converts between all pointer types, and between all pointer and integral types.
The traditional C-style cast can perform any conversion expressible with a combination of
static_cast,
reinterpret_cast, and
const_cast.
Aliasing occurs when a memory location is referenced by two or more l-values, whether these are variables, pointers, or references. When this happens, the compiler must ensure that changes to one alias are reflected in the others. C and C++ enforce strict aliasing rules that limit the number of aliases. For an l-value to be valid in C++, one of the following must be true:
charor
unsigned char.
If none of these criteria are met, the alias produces undefined behavior.
Identifiers can contain letters, numbers, and underscores, but they cannot begin with numbers. Many identifiers beginning with underscores are reserved for use by the environment.
A declaration provides basic information about an identifier to a translation unit, so that it can be referenced. Some declarations also define elements, allowing them to be used in other ways. An element can have multiple declarations, but it must have only one definition, or a linker error will result. Function declarations are also known as prototypes.
A variable declaration serves as a definition if storage is allocated, which happens unless:
static;
externwithout being initialized.
A function declaration serves as a definition if the function body is inlined.
A forward declaration allows a variable, function, or type to be referenced before it is defined. In particular, a forward-declared type can be referenced as long as its members are not accessed, and its size not calculated:
struct tNode; class tGraph { public: void Add(const tNode& aNode); ...
Objects can be initialized with the assignment operator:
int oIdx = 1;
or with constructor syntax:
int oMax(12);
These techniques allow type narrowing, where an argument is automatically converted to a smaller compatible type, even if information would be lost. Most compilers warn when this is done.
In modern C++, an object can also be initialized by assigning with one or more arguments surrounded by curly braces:
int oMask = {0x0000FFFF};
In the past, this syntax was allowed only when initializing aggregates. If the object has a constructor that accepts an
initializer_list, the braces and their content will be interpreted as an instance of that type, unless the braces are empty, in which case the default constructor will be invoked, if possible. To specify an empty list, place empty braces inside parentheses:
tQueueAct oQueue({});
or inside a second set of braces.
If there is no
initializer_list constructor, the brace elements will be matched against the constructors that are defined, as though the traditional constructor syntax had been used:
tPt oCtr = {0.0, 0.0};
If the object has no constructors, the brace content will be used for memberwise initialization. The values will be assigned to the object's members in the order the members were defined within the class type. The braces can contain elements with different types.
Curly braces can also be used in place of parentheses, in something like the constructor syntax:
tPt oStart{0.0, 1.0};
This is sometimes called universal or uniform initialization. If a constructor can be matched with the arguments, it will be invoked, otherwise the brace content will be used for memberwise initialization.
In all cases, curly braces prevent narrowing. They can also be used to avoid vexing parse problems.
The scope of an identifier determines the parts of a translation unit from which the identifier is accessible.
An identifier declared within a named namespace has namespace scope. It is usable anywhere after its declaration.
The global namespace is defined automatically. It is unnamed, and it contains all other namespaces. An identifier in this namespace has file scope, and it is also usable after its declaration.
Every label has function scope, making it usable throughout the function that defines it, even before it is declared. This allows
goto to jump into or out of blocks. No other identifier has this scope.
If it is not a label, an identifier declared within a function has local scope. It is usable within the containing block, after the declaration.
If it is outside of a function definition, an identifier declared within a class type has class scope. It also has a
public,
protected, or
private access level, but this is not a scope per se. An identifier with class scope is usable anywhere its access level permits.
For the most part, a variable's storage class determines when and how it is allocated and deallocated. Some storage classes can also be applied to functions.
Local
static variables are initialized the first time they are encountered. In this they differ from class-
static variables, which are not initialized in a predictable order. In both cases, the variables are allocated on the heap, and a single instance is shared by all function invocations, or by the entire class.
static variables persist for the lifetime of the program, and, in all cases, their relative deinitialization order is undefined.
The
extern storage class affects linkage, but it does not change the way a variable is stored. It does determine whether storage is allocated for variables. In most cases, storage is allocated automatically when a variable is declared. However, an
extern variable declaration that does not initialize the variable does not allocate storage. This allows a single variable instance to be declared and referenced by multiple translation units.
Non-class functions have
extern storage by default. Where functions are concerned, this only affects linkage.
An
auto variable is allocated on the stack when the program reaches its declaration, and it is deallocated when the program leaves the containing block. Local variables have
auto storage by default.
register requests that the variable be stored in a register. This request may be ignored by the compiler.
mutable class variables can be modified by functions declared
const. Unlike other storage classes,
mutable does not affect linkage or variable lifetimes.
Storage class and scope combine to define an element's linkage. This determines whether declarations that use the same identifier are understood to reference the same element, or different ones.
const file-scope variables always have internal linkage. For non-
const variables, and for those without file scope, the linkage is:
The linkage for functions:
Because external linkage is the default, there is never a need to declare functions
extern. If a function is declared
static and then
extern in the same translation unit, it will continue to have internal linkage.
Elements with no linkage cannot be referenced from outside the containing scope. Same-name identifiers therefore reference different entities when used in different scopes. Local variables have no linkage.
Elements with internal linkage can be accessed from other scopes, but not from other translation units. Such identifiers therefore reference different entities when used in different translation units.
static file-scope variables and functions have internal linkage.
Elements with external linkage can be referenced from other scopes and other translation units. Such identifiers therefore reference the same entities at all times. Among others, file-scope functions and
extern file-scope variables have external linkage, unless already given internal linkage in the same translation unit.
The two qualifiers,
const and
volatile, are sometimes known as cv-qualifiers. They can both be applied to the same element.
Variables marked
const cannot be changed after they are initialized.
const can appear in two locations within a pointer declaration. Placing it before the type prevents the referenced instance from being modified through the pointer:
const int* op;
Placing it before the variable prevents the pointer itself from being modified:
int* const op = 0;
Placing it in both locations prevents either modification:
const int* const op = 0;
When a class function is marked
const, it is prevented from modifying variables in the instance from which it is called, unless those variables are
mutable. It is also prevented from calling other functions in the same instance, unless they are
const. Non-
const class functions cannot be invoked from
const instances.
When applied to a variable or parameter,
volatile warns that the value can be read or written without the compiler's knowledge. The compiler is expected to avoid certain optimizations, such as placing the value in a register.
If a class function is declared
volatile, that function cannot invoke non-
volatile functions on the same instance. Similarly, if a class type instance is declared
volatile, non-
volatile functions cannot be invoked on that instance, and its variables are considered
volatile as well.
volatile functions can modify non-
volatile variables.
When applied to a variable,
constexpr indicates that its value can be known at compile time.
constexpr variables are implicitly
const, but
const variables are not
constexpr because they can be assigned with values that are not known until run time.
Similarly, when applied to a function,
constexpr indicates that it can be evaluated at compile time, if its arguments are themselves
constexpr. Such functions can also be called at run time, like any other function. Both class and non-class functions can be
constexpr. Note that
constexpr appears at the beginning of the declaration, not the end, as
const does:
struct tPos { constexpr tPos(double aR, double aI); constexpr double Dist() const; ...
Implementing a
constexpr constructor produces a literal type, which can be instantiated at compile time, like built-in types.
Only pure functions can be
constexpr. These are functions that have no side effects, and that return values dependent only on the function's inputs. In C++11,
constexpr functions must consist of a single
return statement. In C++14, functions can contain multiple statements, but they cannot contain
try blocks,
goto statements, or
static variables, and all variables must be literal types that are initialized where they are defined. In all cases, the parameters and return type must also be literal.
constexpr class functions are implicitly
const in C++11, but not in C++14, even though side effects are disallowed. These must be explicity marked both
constexpr and
const.
constexpr values can be used in places that are normally reserved for compile-time constants, like array sizes and enumerator values.
In general, any statement that can be interpreted as a declaration must interpreted that way. This is known as the most vexing parse. For example, if a class has a default constructor:
class tCacheMem { public: tCacheMem(); tCacheMem(int aCap); ...
it may seem appropriate to invoke that constructor when initializing another class:
class tMgrPath { public: tMgrPath(const tCacheMem& aCache); ... int main(int aCtArg, char* apArgs[]) { tMgrPath oMgr(tCacheMem()); oMgr.Exec(); ...
In this case, the vexing parse requires that
oMgr be interpreted not as an instance of
tMgrPath, but as an undefined function that returns an instance of
tMgrPath, with
tCacheMem() being read as an unnamed parameter for a function with no arguments that returns a
tCacheMem. When this happens,
oMgr.Exec() will fail with a message that
oMgr is not a class type.
The problem can also arise when variables are passed to non-default constructors. In this example, the parentheses around
oCap are assumed to be superfluous, so that
oMgr is read as a function accepting a
tCacheMem parameter named
oCap:
int oCap = 128; tMgrPath oMgr(tCacheMem(oCap));
In both cases, the intent can be clarified by surrounding the constructor invocation with parentheses:
tMgrPath oMgr((tCacheMem(oCap)));
An argument is a value that is passed to a function. A parameter is the representation of that value within the function. Arguments can be r-values or l-values, but parameters are always l-values.
Overloading allows the same name to be associated with different functions in the same scope. When the overloaded function is invoked, the compiler chooses one definition by comparing the provided arguments with available signatures. If no exact match is found, a near match is chosen, by applying, in order:
If no match is found, a compiler error results.
Note that a child class defines its own scope relative to the base type from which it inherits. When a function is invoked through the child class, the compiler will attempt to match the call to a function in the child scope before it looks outside to functions in the parent. Therefore, if a name in the parent is overloaded in the child:
class tScroll { public: ... void Add(float a); }; class tScrollFast: public tScroll { public: ... void Add(int a); };
calls through the child could be routed to functions that match the arguments less well than functions in the parent:
tScrollFast oScroll; // Truncates to int and calls tScrollFast::Add: oScroll.Add(1.1F);
Functions in the parent can be brought into the child scope by
using them in the child definition:
class tScrollFast: public tScroll { public: ... using tScroll::Add; void Add(int a); };
When a binary operator is defined as a class function, the left operand is represented in the definition by
this.
Operator overloads in class types can be declared
virtual. All overloads are inherited except the assignment operator.
If the assignment operator is not overloaded for a given class type, ordinary memberwise assignment will be performed. Overloaded assignment operators are not inherited by subclasses, but the assignment overload in a base class will be called when that part of the derived class is assigned. When overloading the assignment operator, it is best to implement a copy constructor as well.
When overloading a postfix increment or decrement operator, it is necessary to introduce a dummy
int parameter to distinguish the signature from that of the prefix operator. The parameter is not used:
struct ti { // Prefix increment: ti& operator++() { ++Idx; return *this; } // Postfix increment: ti operator++(int) { ti oi(*this); ++Idx; return oi; } int Idx; };
Postfix operators are also distinguished by the fact that they return copies, not references.
Like the binary arithmetic operators,
new and
delete can be overloaded as class or non-class functions. If they are overloaded as class functions, those overloads will be called in preference to any non-class overloads. The class function overloads are implicitly
static. Variations like array
new and
delete, placement
new and
delete, and
nothrow new count as separate operators with distinct overloads.
When an object is allocated, its size is passed automatically to operator
new. Similarly, the size of the entire array is passed to operator
new[]. When an object is deallocated, the pointer is passed to operator
delete:
struct tMgr { void* operator new(size_t aSize); void operator delete(void* ap) {} }; void* tMgr::operator new(size_t aSize) { if (aSize > sizeof(tMgr)) terminate(); static tMgr osInst; return &osInst; }
Any number of parameters can be added to
new or
delete. Operators with extra parameters are known as placement
new and
delete:
struct tMgr { tMgr() {} tMgr(const string& aID): ID(aID) {} string ID; void* operator new(size_t aSize, int aIdx); void operator delete(void* ap, int aIdx) {} void operator delete(void* ap) {} }; void* tMgr::operator new(size_t aSize, int aIdx) { if ((aIdx < 0) || (aIdx >= 4)) terminate(); static tMgr osInsts[4]; return &osInsts[aIdx]; }
If an exception is thrown during initialization, the placement
delete overload with the same additional parameters will be called. If such an overload is not defined,
delete will not be called, and a leak may result. The placement
delete overload is not called when memory is explicitly deleted.
To invoke placement
new, pass the additional arguments to the
new operator itself. The allocation size will be passed automatically:
tMgr* opMgr = new(0) tMgr("A1");
Applying the scope resolution operator without a name specifies the global namespace:
char gChEsc; namespace n { char oCh = ::gChEsc; };
Applying the operator with a base class name allows base members to be accessed from derived instances:
struct tProd { int Code; } struct tBook: public tProd { int Code; } tBook oBook; cout << oBook.tProd::Code << endl;
The
sizeof operator can be applied to instances or types. When applied to an array instance, the size of the entire allocation is returned, this being the size of the array type multiplied by the element count.
It is safe to delete null pointers, but it is not safe to delete dangling pointers, which reference already-deleted memory.
To ensure that the correct destructor is called, a pointer that is being deleted must have the same type as the referenced instance, or its type must be a base class of that type with a
virtual destructor.
Types allocated with
new[] must provide accessible default constructors. Having been allocated with
new[], arrays must be deallocated with
delete[]. This causes the destructor to be invoked on each element:
tEl* opEls = new tEl[4]; delete[] opEls;
The standard
new operators throw
bad_alloc if an allocation fails. The
nothrow placement
new overloads return zero instead:
char* opBuff = new(nothrow) char[256];
By passing a callback to
set_new_handler, it is also possible to have a function invoked when allocation fails.
The conditional or ternary operator evaluates a boolean expression, and returns the second operand if it is true, or the third if it is false. The result can be used as an l-value:
((aAxis == gAxisX) ? cX : cY) = oVal;
Alternatively, if it returns a function pointer, it can be invoked:
((oCt < 1) ? cRun_Front : cRun_Back)(oData);
Bitwise XOR is performed with
operator^. There is no logical XOR operator, but
operator!= is equivalent if both operands are booleans.
The unary sign operators
+ and
- promote their operands to
int.
The sequence operator evaluates both operands, then returns the result of the right one. Because this operator has the lowest possible precedence, a sequence expression must be parenthesized when its result is assigned:
int oYOrig = (oX++, oY++);
break jumps out of the enclosing
for,
while,
do-while, or
break statement. Only one such statement is terminated.
continue effectively jumps to the end of the enclosing
for,
while, or
do-while statement, not the beginning. This distinction is important for
do-while loops, as
continue does cause the loop condition to be retested.
goto jumps to a label in the current function. Labels have function scope, not local scope, so
goto can jump into blocks as well as out of them:
if (oDone) goto X; do { ... X: cout << "Done" << endl; } while (false);
Every label must be followed by a statement or another label.
goto cannot be used to skip a variable definition unless that variable is a POD type.
All standard exceptions derive from
exception, but any type can be thrown.
If an exception is thrown within a
try block, the first
catch block that matches the exception type will be executed, even if a succeeding block matches more closely. If no block in the call stack matches the exception,
terminate will be called. By default,
terminate ends the program, but a custom handler can be set by passing a callback to
set_terminate.
Caught exceptions can be re-thrown by invoking
throw without an argument.
If the stack is being unwound to handle one exception when a second is thrown, the runtime will be unable to choose which of the exceptions to propagate, and
terminate will be called. For this reason, destructors should not throw exceptions.
A function may be designed to meet one of the three exception guarantees, which characterize its effects if it cannot complete its task:
A function that makes no guarantee may leave the program in an unusable state.
A function try block replaces the body of a function with
try and
catch blocks, so that the entire function is covered by the
catch:
void gExec() try { ... } catch (const tExcept& aExcept) { gLog.Add(aExcept); }
This is the only way to catch exceptions thrown from a constructor's initializer list.
An exception specification limits the types that can be thrown from a given function. The same specification must be applied to the function's declaration:
void gVeri() throw(bad_alloc, bad_typeid);
and its definition:
void gVeri() throw(bad_alloc, bad_typeid) { ...
If an exception is thrown from such a function, and if its type is neither specified nor derived from a specified type,
unexpected will be called. By default,
unexpected ends the program, but a custom handler can be set by passing a callback to
set_unexpected. The specification is checked only when exceptions are thrown out of the function. Any type can be safely thrown and caught within it.
If the function is overridden, it must provide the same specification that was declared in the base class, or a more restrictive one.
If no type is listed in the specification, no exception can be thrown from the function:
void gSort() throw();
Traditional exception specifications are deprecated in modern C++. They have been replaced by
noexcept, which merely indicates whether exceptions can be thrown. This allows compiler and library implementers to optimize code without breaking exception guarantees. When applied without arguments,
noexcept claims that a function does not throw:
void gVeri() noexcept;
As before, the same specification must be applied to the function's declaration and its definition.
noexcept can also accept a constant expression argument. If the expressions is true, no exceptions are meant to be thrown:
template <typename x> void gStore(x aVal) noexcept(is_pointer(x)) { ...
By default, all destructors and
delete operators are implicitly
noexcept.
The
noexcept operator is often used inside the
noexcept specification. This operator accepts a single expression argument, and returns true if the compiler can verify that the expression does not throw:
class tSigFast { public: void Exec() const noexcept; ... template <typename xSig> void gForw(xSig aSig) noexcept(noexcept(aSig.Exec())) { ...
If a
noexcept function does throw,
terminate will be called.
Namespaces define distinct scopes, named or otherwise. They are defined at file scope, or within other namespaces.
Declaring an element in a namespace block places it in that namespace. The element can be defined outside the block, but doing this entails that all namespace members be prefixed with the namespace:
namespace nChain { struct tLink; tLink gHead(); } struct nChain::tLink { string ID; }; nChain::tLink nChain::gHead() { return nChain::tLink(); }
Distinct namespace blocks with the same name contribute to the same namespace:
namespace nStr { string gUp(const string& aText); } namespace nStr { string gLow(const string& aText); }
Defining an unnamed namespace issues an implicit
using directive. Because such a namespace cannot be referenced anywhere else, its content effectively has file scope:
namespace { short gLenMax; } gLenMax = 0xFFFF;
Namespace aliasing allows long namespace paths to be abbreviated:
namespace nTransL = nMath::nTrans::nLaplace;
A
using declaration brings a specific identifier into scope, allowing it to be referenced without specifying its namespace:
using nStr::gUp;
A compilation error results if the identifier is already declared in the current scope. If the identifier is declared in an enclosing scope, that element is hidden.
A
using directive makes an entire namespaces accessible without bringing identifiers into the current scope:
using namespace nStr;
If the same identifier is declared locally and in an accessible namespace, the namespace declaration is hidden. If the same identifier is declared in an enclosing local scope and within an accessible namespace, the declaration in the enclosing scope is hidden. If the same identifier is declared in multiple accessible namespaces (including possibly the global namespace) a namespace must be specified whenever the identifier is used.
The global namespace is always accessible.
After preprocessing, source files are known as translation units or compilation units. The compiler transforms these into object files.
Generally, the pound sign in a preprocessor directive must be the first non-whitespace character in its line. Visual Studio does not enforce this requirement.
Preprocessor directives can be made to span multiple lines by appending a backslash to the end of each continued line.
#define can be used to create a macro, which associates a name with the text that follows it:
#define mLvlOpt 4
The preprocessor will replace the name with the text wherever it is found. Even keywords can be used as names.
The name can be followed by an untyped parameter list. These parameters can then be referenced within the text, much like a function:
#define mMaskComb(z) (~(z) & 0x0F0F)
It is customary to parenthesize parameters within the definition to avoid operator precedence problems when expressions are passed to the macro. Unlike ordinary function calls, macro parameters are evaluated every time they appear in the text, so expressions with side effects must be avoided.
If no value follows the name, the name will be defined, but it will be replaced with the empty string during preprocessing:
#define mBuildFast
#undef cancels the effect of a
#define directive.
#ifdef and
#ifndef test whether a preprocessor identifier has been defined.
#if and
#elif test whether a constant expression evaluates to true. Any of these can be followed by
#else, and all must be followed at some point by
#endif.
Included files are always located in an implementation-specific manner. Generally, files in angle brackets are located by searching a user-defined path:
#include <iostream>
Filenames in double quotes are typically sought in the folder containing the file performing the include:
#include "Test.h"
Visual Studio then searches folders containing files that themselves include the file performing the include. Most implementations finally locate the file as though its name were enclosed in angle brackets.
Compilation is aborted if the preprocessor encounters an
#error directive. If a string follows
#error, it will be displayed by the compiler.
#pragma provides access to implementation-specific compiler features.
#line is used to reset the preprocessor's record of the line number:
#line 1
or its record of the line number and file name:
#line 1 "Test.h"
The
# operator wraps a macro argument with double quotes:
#define mOut(zText) cout << "~ " #zText << endl;
The
## operator concatenates two macro arguments into a single word:
#define mJoin(z0, z1) z0##z1
A number of macros are defined by the environment:
auto_ptr is the original Standard Library smart pointer. It overloads
operator* and
operator-> so that instances can be dereferenced like regular pointers:
auto_ptr<tCase> oCase(new tCase()); tCase oCaseOrig(*oCase); oCase->Adv();
Copying one
auto_ptr to another causes the source instance to release ownership of the allocation, leaving the source to reference nothing. As a result, it is unsafe to store
auto_ptr instances in most containers, and
const instances cannot be copied.
auto_ptr is deprecated in modern C++. It is replaced by
unique_ptr,
shared_ptr, and
weak_ptr.
unique_ptr ensures that a single smart pointer owns the allocation at any moment. Instances cannot be copied; ownership is instead transferred when an instance is moved. Unlike
auto_ptr,
unique_ptr provides a boolean conversion that returns true if the pointer is set. This allows instances to be checked in boolean expressions like raw pointers:
void gAttach(const unique_ptr<tPack>& abPack) { if (!abPack) ...
The specialization for array allocations implements
operator[], so elements can be dereferenced as normal:
unique_ptr<tPt[]> obPts(new tPt[oCt]); for (int o = 0; o < oCt; ++o) { tPt& orPt = obPts[o]; ...
C++14 provides the
make_unique function that produces
unique_ptr instances without calling
new directly:
const tPt oPtDef(oX, oY); unique_ptr<tPt> obPt = make_unique<tPt>(oPtDef);
shared_ptr is a reference-counting smart pointer, which allows a single allocation to be shared among multiple instances. The reference count is set to one when the raw pointer is first stored in a
shared_ptr. The count is incremented whenever an instance is copy-constructed or copy-assigned, and decremented when an instance is destroyed. The allocation is deleted when the count reaches zero. Reference cycles must be avoided, or the allocation will not be freed. It is also important that the original raw pointer not be passed to more than one
shared_ptr, except by copying or assigning smart pointer instances. If this happens, one group of instances will delete the allocation while the others are still active, causing them to dangle.
Unlike
unique_ptr,
shared_ptr cannot be used with array allocations.
C++11 provides the
make_shared function that produces
shared_ptr instances without calling
new directly.
weak_ptr can be used to reference a
shared_ptr allocation without incrementing the reference count. This allows references to cycle without blocking deallocation. In particular, when implementing the Observer pattern, the publisher can be made to reference subscribers with
weak_ptr instances. Subscribers can then be deleted without explicitly unsubscribing.
A
weak_ptr instance is created by passing a
shared_ptr to the
weak_ptr constructor.
weak_ptr provides no way to access the allocation, so another
shared_ptr must be created. This can be done by:
lockmethod, which returns a
shared_ptrthat references the original allocation, or null if the allocation has been deleted;
weak_ptrto a
shared_ptrconstructor, which throws if the allocation has been deleted.
When enabled, Run-time Type Information or RTTI allows very basic type information to be retrieved while the program runs.
The
typeid operator returns a
const reference to a
type_info instance:
#include <typeinfo> const type_info& oInfo = typeid(string);
The
type_info class identifies types. It supports type comparisons with
operator== and
operator!=, and it provides a
name function that returns a
char array containing the type name. The exact
name output is implementation-defined.
The
main function accepts zero:
int main()
or two arguments:
int main(int argc, char* argv[])
argv[0] stores the name of the executable, with or without its path.
argv[argc] is set to zero.
The value returned from
main becomes the return value of the executable. In Visual Studio, failing to return from
main does not generate a warning, unlike other functions, and doing this causes zero to be returned from the executable. Programs can also be terminated with
exit, which accepts a return value.
C++ Pocket Reference
Kyle Louden
2003, O'Reilly Media
Effective Modern C++
Scott Meyers
2014, O'Reilly Media
The C++ Programming Reference, Third Edition
Bjarne Stroustrup
1998, Addison-Wesley
The C++ Programming Reference, Fourth Edition
Bjarne Stroustrup
2013, Addison-Wesley
Scope Regions in C and C++
Dan Saks
Retrieved November 2008,
Linkage in C and C++
Dan Saks
Retrieved November 2008,
volatile - Multithreaded Programmer's Best Friend
Andrei Alexandrescu
Retrieved November 2008,
Stack Overflow question 'Hidden Features of C++?'
Retrieved July 2015, stackoverflow.com
Exception Safety and Exception Specifications: Are They Worth It?
Herb Sutter
Retrieved June 2018,
"constexpr" function is not "const"
Andrzej Krzemieński
Retrieved July 2018, akrzemi1.wordpress.com | http://anthemion.org/cpp_notes.html | CC-MAIN-2018-39 | refinedweb | 10,899 | 51.68 |
import "acln.ro/zerocopy"
zerocopy.go zerocopy_linux.go
Transfer is like io.Copy, but moves data through a pipe rather than through a userspace buffer. Given a pipe p, Transfer operates equivalently to p.ReadFrom(src) and p.WriteTo(dst), but in lock-step, and with no need to create additional goroutines.
Conceptually:
Transfer(upstream, downstream)
is equivalent to
p, _ := NewPipe() go p.ReadFrom(downstream) p.WriteTo(upstream)
but in more compact form, and slightly more resource-efficient.
A Pipe is a buffered, unidirectional data channel.
NewPipe creates a new pipe.
BufferSize returns the buffer size of the pipe.
Close closes both sides of the pipe.
CloseRead closes the read side of the pipe.
CloseWrite closes the write side of the pipe.
Read reads data from the pipe.
ReadFrom transfers data from src to the pipe.
If src implements syscall.Conn, ReadFrom tries to use splice(2) for the data transfer from the source file descriptor to the pipe. If that is not possible, ReadFrom falls back to a generic copy.
SetBufferSize sets the pipe's buffer size to n.
Tee arranges for data in the read side of the pipe to be mirrored to the specified writer. There is no internal buffering: writes must complete before the associated read completes.
If the argument is of concrete type *Pipe, the tee(2) system call is used when mirroring data from the read side of the pipe.
Tee must not be called concurrently with I/O methods, and must be called only once, and before any calls to Read or WriteTo.
Write writes data to the pipe.
WriteTo transfers data from the pipe to dst.
If dst implements syscall.Conn, WriteTo tries to use splice(2) for the data transfer from the pipe to the destination file descriptor. If that is not possible, WriteTo falls back to a generic copy.
Package zerocopy imports 4 packages (graph) and is imported by 1 packages. Updated 2019-04-11. Refresh now. Tools for package owners. | https://godoc.org/acln.ro/zerocopy | CC-MAIN-2020-34 | refinedweb | 332 | 69.58 |
A simple, end-to-end encrypted and easy to use push service for messages.
Project description
Lightweight Push Library
Lightweight Push is a simple and easy to use push service. It lets you send end-to-end encrypted push messages to your Android mobile devices without hosting your own services or building your own App. The library uses the AlertR Push Notification Service which is build atop of Google Firebase. You only have to install the official AlertR Android App from Google Play to receive the messages and create an account at alertr.de. After that you can directly use the Lightweight Push library.
Unlike some other push service providers, Lightweight Push offers you real end-to-end encryption. The message is encrypted in the Lightweight Push directly before sending and decrypted on your Android devices. Neither the AlertR Push Notification Service nor Google can read the messages. Some other providers use the term "end-to-end encryption" only as marketing and do not have it. For example, some providers use a web api where the message is sent via a HTTPS request to the server of the provider. To state the simplicity of their service, they show commands with curl and the like that will make such a request and send you a push notification. However, the message in the shown requests is unencrypted and the encryption is done by the server of the provider before it is sent to your devices. So even though they use HTTPS, the message can still be read by the provider and therefore it is no end-to-end encryption.
Lightweight Push uses channels to send your messages to different Android devices. The Android devices subscribe to the channels they want to receive the messages from. This allows you to send messages triggered by specific events to different devices. For example in a server context, a failed HDD is only interesting for people responsible for hardware issues, but a failed server is also interesting for people working on this server.
Due to technical reasons, the subject and message size is at the moment limited to 1400 characters. However, if you send a message that is larger than 1400 characters, it will be truncated and send to you. In the near future this will change and a bigger size will be allowed.
You do not want to use some service on the Internet for this but host everything yourself? No problem, each component needed to send push messages is Open Source.
Installation and Usage
Lightweight Push is written for Python 2 and 3. For the encryption, it needs the
pycrypto package. To make the installation of the Lightweight Push library as easy as possible, you can install it with pip via the following command:
pip --user install lightweight-push
Afterwards, all prerequisites are installed.
After you created and activated your alertr.de account, the library is very easy to use. The following small script will send a push notification message to your mobile devices:
import lightweightpush push_service = lightweightpush.LightweightPush("my_email@alertr.de", "super_secret_password", "shared_secret_to_encrypt_msg") push_service.send_msg("Subject of Message", "Message text", "MyChannel")
In order to receive the messages on your Android devices, you have to install the AlertR Android App. The App settings screen looks like the following:
In the Channel setting, a comma separated list of channels you want to receive with this device has to be set. As setting for our example configuration, we set only the following channel:
MyChannel
The E-Mail Address setting is the used alertr.de username.
my_email@alertr.de
The Shared Secret setting is used to decrypt the received messages. It has to be the same as the one configured in the Lightweight Push script.
shared_secret_to_encrypt_msg
Infrastructure
The following image shows the used infrastructure:
Lightweight Push will encrypt your message with your shared secret and send it to the alertR Push Notification Service. The end-to-end encryption ensures that neither the alertR Push Notification Service nor the Google Firebase service is able to read your message. The message will be sent on a channel that you choose. The channel is used to be able to receive the same message on multiple devices you own or want to be able to receive the message. In order to prevent multiple uses of the same channel by different users and therefore collisions, the channel is linked to your alertr.de account. In the unlikely event that an attacker is able to deduce your used channel, only devices that know your used secret are able to decrypt the message. This is shown in the infrastructure image as an example. An attacker subscribes for the channel "MyAlarm" that is used by another user. The message is encrypted with the secret "MySecret". But only the device using this secret is able to decrypt the message.
Support
If you like this project you can help to support it by contributing to it. You can contribute by writing tutorials, creating and documenting exciting new ideas to use it, writing code for it, and so on.
If you do not know how to do any of it or do not have the time, you can support me on Patreon. Since services such as the push notification service have a monthly upkeep, the donation helps to keep these services free for everyone.
Bugs and Feedback
For questions, bugs and discussion please use the Github Issues.
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/lightweightpush/0.0.3/ | CC-MAIN-2021-10 | refinedweb | 922 | 62.48 |
Created on 2019-12-26.17:48:35 by jeff.allen, last changed 2019-12-26.17:48:35 by jeff.allen.
I noticed when tracing through the statement:
from javax.swing.text.Utilities import *
that once having found (created) the module (a PyJavaType) for "javax.swing.text.Utilities" the thread dives into org.python.core.imp.importAll(PyObject, PyFrame) to populate the locals of the frame with the attributes of the module. So far, so good.
A couple of things are worthy of question:
1. module.__dir__() involves (what seems to be) an inordinately repetitive traversal through the bases (and bases of bases) of the class to collect the names: why not just the MRO?
2. For every name collected in step 1, and not starting "_", we call module.__findattr__(sname), which may return null. (How often?) The first example is attribute "class" (a bean accessor from java.lang.Object.getClass()). __findattr__("class") returns null, and this triggers a call to __builtin__.__import__(), here to look for a module called "Utilities.class" with default (level=-1) semantics. This involves looking in quite a few places, twice.
Parking my suspicions here for later investigation.
Hosted on DigitalOcean,
Supported by Python Software Foundation, | https://bugs.jython.org/issue2854 | CC-MAIN-2022-21 | refinedweb | 203 | 62.85 |
A daemon for asynchronous job processing
Hades is an multithreaded asynchronous job processing class. It allows you to register different job types and associate processor functions or classes with those job types.
Job processor function needs to expect job data as input. If a job processor is a class, it needs to have run() method that expects job data as input.
Jobs are discovered by watching a folder on the file system for new files. If a file is correctly formated it is parsed and processed passing the parsed data to the registered processor.
A file needs to be a json document with a ‘type’ key matching one of the registered job types.
When the class is initialized it expects a path to the folder to watch. The folder needs to have three subfolders: ‘in’ for incoming jobs, ‘cur’ for storing successfully processed jobs (this can be disabled by passing save_successful=False to the class), and ‘err’ for storing failed jobs (this can be disabled by passing save_failed=False to the class).
By default a pool of 5 processing threads will be started. This can be tuned by passing threads=N to the class.
If a job processing fails, it will be reprocessed few more times as defined by retries attribute (default is 3). If this is not desired it can be disabled by passing retries=0 to the class.
The usage is very simple. You need to define processors, initialize Hades with the path to the folder to watch, register processors with Hades and call start() method to start all the threads. By default Hades runs in interactive mode. If you want to run it in a daemon mode, just pass ‘daemon=True’ to the start() method.
import hades class Download: def run(self, task): print("Downloading page: {0}".format(task['url'])) return True def send_email(task): print("Email for: {0}".format(task['rcpt'])) return True if __name__ == '__main__': hades = hades.Hades('/tmp/jobs') hades.register({'email': send_email}) hades.register({'download': Download}) hades.start(daemon=True)
To send jobs, just deserialize a json object containing the data for your jobs and save them into the defined folder. Hades will pick it up from there.
import json email = {'type': 'email', 'from': 'no@mail.com', 'rcpt': 'test@example.com', 'subject': 'Test email', 'body': 'Hi there!'} download = {'type': 'download', 'url': '', 'file': '/tmp/miljan.org.html'} json.dump(email, open("/tmp/jobs/in/email", "w")) json.dump(download, open("/tmp/jobs/in/download", "w"))
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/hades/ | CC-MAIN-2017-26 | refinedweb | 430 | 67.35 |
I have a vector int a[100], initialised with values such as 9726745. How do I set them all to a specific value x without a for statement?
Printable View
I have a vector int a[100], initialised with values such as 9726745. How do I set them all to a specific value x without a for statement?
I don't think you can do it without looping (at least indirectly).
>without a for statement?
With a while statement :D
You can use memset() to do this.
Edited: Irrelevant.
Never mind the fact that there are no vectors in C.Never mind the fact that there are no vectors in C.Quote:
Originally posted by XSquared
It's not safe to use memset( ) with a vector.
Quzah.
Are we talking about an array here or a vector class? For an array, my example will most certainly work. For a vector class it won't, but this is the C programming board not C++.
Heh. Oops.
As soon as I saw vector my mind snapped into C++ mode.
Proper handling of memset is save with an array.
It is always save to set all bits to zero in an array of char (signed or unsigned),but thats all.C allows every single
data type except {signed,unsigned} char to have padding bits, that are not part
of the representation of the value. It is possible that improper
combinations of these padding bits can generate what is called a trap
representation.
So,for example memseting an array of ints to zero is not save (nonportable).
[OT]
The memory of std::vector is continous,memseting a std::vector of {unsigned,signed} chars is save too.
[/OT]
Please, just take the easy obvious way:
Code:
int a[100];
for (int i=0;i<100;i++)
{
a[i]=0;
}
One way to assign to an array without a loop is to wrap the array in a structure.Code:
#include <stdio.h>
struct sType
{
int a[10];
};
const struct sType Default = {{56,7,8,1,27,13,54,82,23,16}};
void show(const int *array, size_t size)
{
size_t i;
for ( i = 0; i < size; ++i )
{
printf("%2d%c", *array++, i % 10 == 9 ? '\n' : ',');
}
}
int main(void)
{
struct sType object = {{83,6,71/*remaining elements are 0*/}};
fputs("Before: ", stdout);
show(object.a, sizeof(object.a)/sizeof(*object.a));
object = Default;
fputs("After: ", stdout);
show(object.a, sizeof(object.a)/sizeof(*object.a));
return 0;
}
/* my output
Before: 83, 6,71, 0, 0, 0, 0, 0, 0, 0
After: 56, 7, 8, 1,27,13,54,82,23,16
*/
Here's an obvious answer: at the time of declaration:
int foo[5] = { 1, 1, 1, 1, 1 };
Of course, you could always use recursion:
There's a few missed ways. That'll suffice for now.There's a few missed ways. That'll suffice for now.Code:
void fill( int array[], size_t size, int value )
{
if( size > -1 )
{
fill( array, size-1, value );
array[size] = value;
}
}
Quzah. | http://cboard.cprogramming.com/c-programming/41369-how-do-i-set-vectors-values-one-value-printable-thread.html | CC-MAIN-2015-48 | refinedweb | 501 | 73.98 |
First of all, how to import the module.
howToImport.py
from ctypes import *
Next, how to use C library dynamic linking and functions.
howToLoadLib.py
msvcrt=CDLL("C\\WINDOWS\\System32\\msvcrt.dll") str="On Python!!" msvcrt.printf("Hello World : %s",str)
By the way, there are several methods of dynamic linking, such as CDLL (), windll (), oledll, etc. I'm a complete beginner, so it's a bit confusing, but maybe I'll use it properly depending on the OS ...?
By the way, input functions such as gets () can also be used normally. Also, for dynamic linking,
howToLoad_2.py
msvcrt=cdll.msvcrt
But it seems that it can be done. (I wonder if this is more common ...?)
I don't know this in detail either, but maybe it can be used if it is environment-dependent and is in the standard library directory ...? You can do it normally without writing an absolute path here.
In Python, you generally don't have to specify a type for a variable, but in C you have to specify a type for a variable. And since there is no C type in Python, ctypes has it for you! For example
howToHensu.py
str=c_char_p("AAA")
hensu.c
char *str="AAA"
Two programs like this are probably the same. I don't know the details, but maybe what I'm doing is the same. This is just one example, char, int, short, long, double, float, void * and many more.
By the way, if you want to pass by reference in C language, use a method called byref (). For example, if you want to pass a pointer to a function argument, you can use it like myfunc (byref (pointer)). In this case pointer is just a variable.
You can also use structures and unions as well as variables.
howToStruct.py
class Test(Structure): _fields_=[ ("testInt",c_int), ("testChar",c_char), ]
You can also make a structure like this. (I will omit the union because I haven't studied enough and I don't know how to use it yet.)
By the way, I bought a book called "Reverse Engineering-Binary Analysis Techniques with Python-" and started reading this story, so I wrote it. I've just started reading, so I'd like to upload it again if I read a little more! URL: Reverse Engineering-Binary Analysis Techniques with Python-
By the way, this is Qiita's first time, so I hope you can see it with warm eyes ... w I'm a complete beginner high school student, so it would be very helpful if you could point out any mistakes!
Recommended Posts | https://memotut.com/en/09e0bcb4803ea5f9b6c8/ | CC-MAIN-2021-49 | refinedweb | 434 | 74.08 |
John J. Lee wrote: > Jim Bublitz <jbublitzno at spamnwinternet.com> writes: >> John J. Lee wrote: >> >> > Have you seen GCC-XML and pyste (part of Boost Python)? >> I've looked at both just out of curiousity, but not in enough >> detail to say anything intelligent about either. I'm very >> comfortable with sip, and from that bias didn't see anything >> that would make me want to switch methods. > [...] > I was thinking of it as a way to generate sip files, not to > replace sip. Wouldn't work for me (directly). I need an intermediate format for both the h files AND the previous version's sip files to generate the new version's sip files. I need to read in PyQt's sip files too. That's both for versioning (change detection) and to transfer forward any handwritten code, doc markup, ignored methods (like the "virtualHook" stuff that's everywhere in KDE), auxiliary code like mapped types, etc. The same parser builds a symbol table for each set of files (the other two above wouldn't handle sip syntax) and then merges the two symbol tables and spits out the sip files. I also need to build some kind of hierarchy so I can scope names - sip needs fully-qualified names in a lot of places C++ will allow implicit scope (eg namespaces). It took me 8-10 hours to do just scoping manually last time I did it that way - the whole KDE generation run takes 2-3 minutes now (everything except new handwritten code that's needed, and those are flagged). Jim | https://mail.python.org/pipermail/python-list/2003-November/193461.html | CC-MAIN-2017-17 | refinedweb | 264 | 69.01 |
…)
OK, I get:
Traceback (most recent call last):
File “/Users/ajcann/Desktop/Python/googPlusFrFo-preliminarySketch.py”, line 1, in
import networkx as nx
ImportError: No module named networkx
How do I get networkx in Python (OS X)?
Thanks,
@alan If you have easy_install on your machine, just type: easy_install networkx
Otherwise, follow this: (Download and unzip, cd to the directory, type: python setup.py install )
Thanks, easy_install networkx worked.
Do I have to do that each time or is the installation persistent?
@alan the library should be available ever more without the need to reinstall..
Nice graph. What program do you use to render graphml?
Graphs are rendered using Gephi – gephi.org | https://blog.ouseful.info/2011/10/16/so-where-am-i-socially-situated-on-google/ | CC-MAIN-2017-17 | refinedweb | 112 | 66.74 |
Internet Relay Chat (IRC) is a network chat system used by millions of people all
over the world. It has been around for several years and is used by groups of friends,
programmers, universities, and even banks to facilitate discussions, the exchanging of
ideas, and collaborative research.
Because IRC is very much a real-time chat system, you will rarely benefit from using
it unless you are able to pay close attention to the sequence of dialog as it transpires.
Unfortunately, this can lead to a lack of productivity in the workplace, which is why
many employers naively frown upon the use of IRC. However, when used properly,
IRC can let employees work effectively with remote colleagues, regardless of whether
they are on the other side of the planet or just in the next building. Real-time group
chat systems like IRC make it easier to organize meetings (and possibly even carry
out virtual meetings), ask questions, and to negotiate the less-important things such as
where to go for lunch.
Many bosses would argue that the most obvious way to boost productivity in the
workplace is to avoid using IRC altogether. While this may be true to some extent,
there really are cases where IRC can be useful. When you carry out a conversation on
IRC--even if it's with someone in the same office--your colleagues elsewhere will
be able to see what you are both saying. You will also be able to see what was
discussed while you were away from your desk. These are both important aspects that
cannot be achieved easily using a telephone or conventional peer-to-peer chat system.
Related Reading
IRC Hacks
100 Industrial-Strength Tips & Tools
By Paul Mutton
The ideal solution is to engineer a way to keep track of IRC dialog without having to
constantly check to see if there are any new messages to read. As long as your IRC
channel is not too busy, a text-to-speech system provides an excellent solution. By
reading out messages as they arrive, you will be able to continue working and only
divert your attention to IRC when absolutely necessary.
This article will show you how to create a multi-platform IRC bot (an automated
client) that uses the FreeTTS Java speech synthesizer library to convert IRC messages
into audible speech.
The FreeTTS library can be downloaded from freetts.sourceforge.net. To
connect to an IRC server, you will need to download the PircBot Java IRC API from.
Once you have downloaded both of the required libraries, create a lib directory and
copy the following .jar files into it:
Writing the IRC bot is now a simple task, as these libraries will do most of the hard
work for you. Create a file called SpeechBot.java:
import org.jibble.pircbot.*;
import com.sun.speech.freetts.*;
import com.sun.speech.freetts.audio.*;
import javax.sound.sampled.*;
import java.io.File;
public class SpeechBot extends PircBot {
private Voice voice;
public SpeechBot(String name) {
setName(name);
// Choose the voice for the speech synthesizer.
String voiceName = "kevin16";
VoiceManager voiceManager =
VoiceManager.getInstance();
voice = voiceManager.getVoice(voiceName);
if (voice == null) {
System.out.println("Voice not found.");
System.exit(1);
}
voice.allocate();
// Set up the output format.
AudioPlayer voicePlayer = new JavaClipAudioPlayer();
voicePlayer.setAudioFormat(new AudioFormat(8000,
16, 1, false, true));
voice.setAudioPlayer(voicePlayer);
}
public void onMessage(String channel, String sender,
String login, String hostname, String message) {
// Send all IRC messages to the voice
synthesizer.
message = message.trim();
String input = sender + " on " + channel + "
says: " + message;
voice.speak(input);
}
public static void main(String[] args) throws
Exception {
if (args.length < 2) {
System.out.println("Usage: java SpeechBot
<server> <channel>");
System.exit(1);
}
SpeechBot bot = new SpeechBot("SpeechBot");
bot.connect(args[0]);
bot.joinChannel(args[1]);
}
}
You can now compile the IRC bot. Make sure to include the necessary .jar files in
the classpath:
javac -classpath .;./lib/pircbot.jar;./lib/freetts.jar
SpeechBot.java
Note that this way of specifying the classpath will only work on Windows systems.
On Unix/Linux systems, you will need to use a colon (:) instead of a semicolon (;) to separate the entries.
You will also need to specify the classpath when running the IRC bot.
:
;
When running the bot, you will need to provide a couple of command-line parameters
to tell it which IRC server to connect to and which IRC channel to join:
java -classpath .;./lib/pircbot.jar;./lib/freetts.jar
SpeechBot irc.freenode.net #irchacks
Note: Make sure your directory names do not contain any spaces, as the version of
FreeTTS used here seems to have trouble reading itself when there is a space in the
path.
After you have launched the bot, it will shortly join the specified IRC channel (in this
case, #irchacks on the freenode IRC network). You can now test the bot by sending a
message to the channel. If everything is set up properly, you will now hear the bot
speak to you:
"Jibbler on #irchacks says: Hello, world!"
Now you can carry on working hard while you listen to IRC!
Paul Mutton
is the author of the PircBot IRC framework
and several other Java programs that can be found on
his web site.
In July 2004, O'Reilly Media released IRC Hacks.
Sample Hacks are available. | http://archive.oreilly.com/pub/a/onjava/2004/09/08/IRCinJava.html?page=last&x-maxdepth=0 | CC-MAIN-2015-48 | refinedweb | 881 | 55.54 |
04 November 2010 12:49 [Source: ICIS news]
LONDON (ICIS)--The European Central Bank (ECB) held interest rates at 1.0% for the 16-nation eurozone on Thursday for the 18th consecutive month, despite fears over debt problems facing some of its members and a move by the US Federal Reserve to inject more money into the economy.
The US Federal Reserve said on Wednesday that it would purchase $600bn (€426m) worth of Treasury Department securities in a bid to lower long-term interest rates, noting that the ?xml:namespace>
However, the Frankfurt-based central bank has said it intends to continue withdrawing its emergency measures.
Also, disagreement has been prevalent within the eurozone about the way the economy is run as
The bloc has seen a rise in manufacturing output, albeit at a slower pace during the second half of the year. Economic sentiment has exceeded expectations and inflation in the eurozone rose to 1.9% last month, just below the ECB's target of 2.0%.
But ECB policy makers from
The bank cut its key rate several times from the October 2008 level of 4.25% as it tried to take
Earlier, the Bank of England announced it would hold interest rates at 0.5% for the 20th consecutive month and leave its quantitative easing policy unchanged.
($1 = €0.71)
?xml:namespace>
To discuss issues facing the chemical industry go to ICIS connect | http://www.icis.com/Articles/2010/11/04/9407241/ecb-holds-eurozone-interest-rates-at-1.0.html | CC-MAIN-2014-35 | refinedweb | 236 | 50.97 |
Can someone please explain the following code to me...
Waria Ahmed
Ranch Hand
Joined: Jul 09, 2008
Posts: 56
posted
Aug 22, 2008 15:57:00
0
Hi guys,
I'm just going through the sun tutorials, learning as much as i can and i got stuck in the following piece of code:
for (i = 0; i < arrayOfInts.length; i++) { for (j = 0; j < arrayOfInts[i].length; j++) { if (arrayOfInts[i][j] == searchfor) { foundIt = true; break search; } } }
I understand what it does, but I dont know how... I would be glad if someone could kindly break it down for me to understand. The main lines im struggling with the first 2.
Thanks in advance for any help guys.
Steve Luke
Bartender
Joined: Jan 28, 2003
Posts: 4181
21
I like...
posted
Aug 22, 2008 16:43:00
0
The for loop has four parts:
1) Initializer to configure the counter for the loop
2) Comparison to determine when the loop should stop
3) Increment to count the loop's progress
4) Body to perform an action for each time through the loop
Your code is just one loop inside another. Try looking at this code (based on code I saw on the Sun Forums) and see if you understand how it will work. Then run it to see how it does work. Then apply it to your more complex loop.
public class ForRunner { public static void main(String[] args) { /* * doA() is initializer, and prints A to Console, * doB() is the comparison, and prints B to Console, * doC() is the incrementor, and prints C to Console, * doD() is the body and prints D to the Console. * * Before you run this, can you guess the order the * letters are printed in when the loop runs twice? */ for (doA(); doB(); doC()) { doD(); } } /* used for counting */ static int index = 0; /* loop 2 times */ static int end = 2; /* initialize loop and report that I was called */ static void doA() { System.out.print("A"); index = 0; } /* stop loop after 2 rounds and report that I was called */ static boolean doB() { System.out.print("B"); return index < end; } /* increment counter and report that I was called */ static void doC() { System.out.print("C"); index++; } /* the body of the loop = report that I was called */ static void doD() { System.out.print("D"); } }
Steve
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 45251
42
posted
Aug 22, 2008 16:49:00
0
Pretty dreadful bit of code there, both because of the awkward "if" and the labelled break.
What you are doing is iterating through an array of arrays; for all
i
in the range arrayOfInts[
i
] is in itself an array. It will have been declared as
arrayOfInts[][]
. The first member (No 0) of arrayOfInts is an array, so you can use a for loop with
j
to iterate through it.
If you find the value you are looking for, the labelled break moves control to outside the for loop; in fact I suspect the label "search:" is just before
for (int i = 0 etc
so the labelled break takes you outside both loops.
Break doesn't restart the loops, unlike continue.
I would suggest you can improve the code by changing the middle bit to
found = arrayOfInts[i][j] == searchfor;
You can dispense with the labelled break by putting a
test
for found in the continuation. You would end up with this code
boolean foundIt = false; for (i = 0; !foundIt && i < arrayOfInts.length; i++) { for (j = 0; !foundIt && j < arrayOfInts[i].length; j++) { foundIt = (arrayOfInts[i][j] == searchfor); } }
Now let's see how many people disagree with me! I'm sure they will
[ August 22, 2008: Message edited by: Campbell Ritchie ]
Waria Ahmed
Ranch Hand
Joined: Jul 09, 2008
Posts: 56
posted
Aug 23, 2008 04:45:00
0
Cheers guys,
The code is actually from the sun tutorials, I'm just learning about labeled break statement. But point taken
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 45251
42
posted
Aug 23, 2008 05:36:00
0
I ought to have explained more yesterday.
There is an older programming paradigm called structured programming going back to the classic paper by B�hm and Jacopini in 1966 which demonstrates that all programs can be written with a combination of sequence iteration and selection only (an older concept attributed to Alan Turing in the 1930s says the same with sequence recursion and selection). This was followed 2 years later by a paper by Edsger Dijkstra demonstrating that a "goto" statement is regarded as "harmful." Many people, myself included, regard "break" and "continue" as equivalent to "goto"s. And the labelled version is even worse.
As I implied in my earlier posting, there are many people who disagree.
Structured programming predated object-oriented programming which wasn't introduced until 1967.
It would have been better to call your thread "What does labelled break mean?"-please look at this
.
I agree. Here's the link:
subject: Can someone please explain the following code to me...
Similar Threads
The flow control: for
array read from left to right or right to left?
Explanation needed on Break and continue questions
Break with if {}
Flow Control -JQ+
All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter
JForum
|
Paul Wheaton | http://www.coderanch.com/t/411600/java/java/explain-code | CC-MAIN-2015-40 | refinedweb | 881 | 68.81 |
public void foo(List<?> list) { }
public void foo(List<Object> list) { }
If there IS a difference (and we're not yet saying there is), what is it?
There IS a huge difference. List<?>, which is the wildcard <?> without the keywords extends or super, simply means "any type." So that means any type of List can be assigned to the argument. That could be a List of <Dog>, <Integer>, <JButton>, <Socket>, whatever. And using the wildcard alone, without the keyword super (followed by a type), means that you cannot ADD anything to the list referred to as List<?>.
Mahesh Murugaiyan wrote:
Q1: If i cant add anything to List<?> what is the point of allowing this?
Consider this example:
class Animal {}
class Dog extends Animal {}
class Cat extends Animal {}
public class Zoo {
List<?> animals = new ArrayList<Animal>();
// rest deleted
}
Mahesh Murugaiyan wrote:
Q2: Why im not able to add a Animal object to List<? extends Animal> animals2? doesnt it mean "allow all object that are of type Animal or extends Animal"? it doesnt allow me to add both Animal and Dog. | http://www.coderanch.com/t/584641/java-programmer-SCJP/certification/Generic-typing-confusion-polymorphism | CC-MAIN-2014-52 | refinedweb | 180 | 68.06 |
Muses on Distributed Computing, SOA, and other tidbits
Well, Clemens threw the glove so here goes :-)
The first thing that we define is the contracts
using System.ServiceModel;
namespace DuplexSample.Interfaces
{
[ServiceContract]
interface IClientSide
{
[OperationContract(IsOneWay = true)]
void WriteString(string s);
}
[ServiceContract(CallbackContract = typeof(IClientSide))]
interface IServiceSide
void Rotate(string s);
}
The client side contract defines a single method that the client needs to implement on his side (WriteString). The service side defines a single method that the service must implement (Rotate). The ServiceContract attribute on the IServiceSide interface defines this to be a duplex contract, and requires that the caller would implement the IClientSide interface.
Both methods are “one-way” methods. None-one-way methods might throw, so even when you call a void method you need to wait for it to complete before you can say that the operation was successful. One-way methods are true “fire and forget”, and do not wait for the operation to complete.
Ok, now for the client implementation:
using System;
using DuplexSample.Interfaces;
namespace DuplexClient
class ClientImpl : IClientSide
public void WriteString(string s)
{
Console.WriteLine(s);
}
class Program
static void Main(string[] args)
IServiceSide service;
ServiceSite mySite = new ServiceSite(new ClientImpl());
service = ChannelFactory.CreateDuplexChannel<IServiceSide>(mySite, "Default Client Config");
Console.WriteLine("Enter strings to rotate, or hit [Enter] to end.");
string str = " ";
while (str.Length > 0)
{
str = Console.ReadLine();
if (str.Length!=0) service.Rotate(str);
}
We first define a class that implements the client contract (ClientImpl). When the service operation WriteString is called, the implementation writes the string to the screen.
The Main method defines a local variable that would be used to reference the service (service) as well as a service site for the incoming calls (mySite). The service site is the object that would dispatch the calls made by the server to the instance of the client-side-contract-implementation-object that was passed in (the ClientImpl object created there).
Next, we create a duplex channel to the service, passing in the service site we created. The samples that Clemens and Bruce created hard-coded the server address and binding information into the app. Guys, come on, you know better J. Where’s the address and binding in this sample? They’re in the application configuration file. We’ll look at the configuration file format a little later.
We then go into a loop where we call the service with the string entered by the user. For each time we call the service, it would call us back multiple times on the duplex interface, resulting in the following output:
Enter strings to rotate, or hit [Enter] to end.
Indigo Rocks!
!Indigo Rocks
s!Indigo Rock
ks!Indigo Roc
cks!Indigo Ro
ocks!Indigo R
Rocks!Indigo
Rocks!Indigo
o Rocks!Indig
go Rocks!Indi
igo Rocks!Ind
digo Rocks!In
ndigo Rocks!I
Now, let’s look at the service side.
using System.Text;
namespace DuplexService
class ServiceImpl : IServiceSide
public void Rotate(string s)
IClientSide client = OperationContext.Current.GetCallbackChannel<IClientSide>();
char[] chars = s.ToCharArray();
int len = chars.Length;
for (int i = 0; i < len; i++)
StringBuilder sb = new StringBuilder(len);
sb.Append(chars, len - i, i);
sb.Append(chars, 0, len - i);
client.WriteString(sb.ToString());
The service implementation class (ServiceImpl) implements the service-side contract (IServiceSide). This contract defines a single method (Rotate). The first thing we do here is to get the callback interface to the client. This interface is exposed through the GetCallbackChannel method on the static member GetCallbackChannel of the class OperationContext, and it is set for us by Indigo before the infrastructure code calls into our implementation. We then have a loop where we rotate the string and call the client interface for each variation.
The code that hosts this service is:
class Program
ServiceHost<ServiceImpl> host = new ServiceHost<ServiceImpl>(new ServiceImpl());
host.Open();
Console.WriteLine("Service is ready. Press [Enter] to exit.");
Console.ReadLine();
In this code, we first create the host (again, the endpoints are defined in the service’s configuration file) and then open it. We then wait for clients to connect and call the service method, or for the user to hit Enter.
That’s it for the code. Now, let’s look at the configuration files:
Let’s start with the service’s configuration:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.serviceModel>
<services>
<service serviceType="DuplexService.ServiceImpl, DuplexService">
<endpoint contractType="DuplexSample.Interfaces.IServiceSide, DuplexService, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"
address="net.tcp://localhost:50210/DuplexService"
bindingSectionName="customBinding"
bindingConfiguration="ServiceCustomBinding"
/>
</service>
</services>
<bindings>
<customBinding>
<binding configurationName="ServiceCustomBinding">
<tcpTransport />
</binding>
</customBinding>
</bindings>
</system.serviceModel>
</configuration>
A single application can host many services. Those services are defined inside the <services> element. In our case, we have a single service. Each service can have one or more endpoints, defined using the <endpoint .../> element. This element defines the 3 elements of the endpoint (Address, Binding, and Contract) as follows:
o The address we use is a TCP address. The URI consists of the schema (net.tcp), host + port, and the path for the service. A single application can listen on multiple paths on the same TCP port.
o The contract type is a strongly named CLR type, consisting of the fully qualified interface name, the assembly in which it is defines, and the assembly version, culture, and public key token.
o The binding, referred to by type (in our case, a custom binding) and the name of the specific configuration section for that type (ServiceCustomBinding). For each type we can have multiple named configurations, and the name here helps distinguish between them.
The next section is the binding section. Each binding type has a section; in our case there’s a single binding type (we’re using a custom binding that we define ourselves (customBinding) and therefore a there’s a single binding section inside the bindings element. This custom binding has a single named configuration section that says that we’re only going to use TCP. In future samples I’ll show how to create more interesting custom bindings.
Now to the client configuration file:
<?xml version="1.0" encoding="utf-8" ?>
<client>
<endpoint address="net.tcp://localhost:50210/DuplexService"
bindingSectionName="customBinding"
bindingConfiguration="ClientCustomBinding"
configurationName="Default Client Config"
contractType="DuplexSample.Interfaces.IServiceSide, DuplexClient, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null">
</endpoint>
</client>
<binding configurationName="ClientCustomBinding">
The client side defines one endpoint that allows it to connect to the service. It specifies the same address as the service, the same contract (this one is compiled into a different assembly since the client and service do not share implementation – see if you can spot the difference). The binding type and configuration are defined in the same way they are defined on the service, and the interesting thing remaining is the configuration name. This is the name that was passed in when we called the ChannelFactory.CreateDuplexChannel method on the client. The client configuration file can contain many endpoints, but the client only picks one (by name) and uses it.
That’s it! Clemens, bring on the next challenge J | http://blogs.msdn.com/shycohen/archive/2005/02/11/370946.aspx | crawl-002 | refinedweb | 1,182 | 50.94 |
Once we understand the common social norms of interacting with others, it is a matter of knowing how to express it in the particular language to the person we are interacting with. Similarly once we understand the fundamentals of computer programming, it is a matter of knowing the syntax of a particular language to express what needs to be accomplished. The following details the basic syntax of the Python language which will help get started with it and be able to build solutions for most of the programming tasks. The assumption is that the reader is familiar with fundamentals of programming and have been programming is another language.
Python programs are exectued through an interpreter called
python and falls under the category of interpreted languages i.e. small chunks of code gets executed by an intrepreter program. So it is a pre-req to install the python interpreter. Python programs can be stored in a file with the extension
.py normally referred as python script and passed as input to the python interpreter or python code can be executed through the python interpreter command prompt.
Or the python interpreter can be invoked by the
python command. Code can be developed and tested in the python interpreter command line.
Variables
Python is a dynamically typed language i.e. the type of the variables are determined during runtime based on what is stored and doesn’t have to be specified when variables are defined. Variable names can be of arbitrary length, can contain letter, numbers and underscore. But variable name need to start with a letter and avoid reserved words (no surprises!!). We can find the type of the variable using the
type() function.
Operators and Expressions
All the arithmetic operators
+ - * / % ** are supported by Python and follows PEMDAS (Parentheses, Exponentiation, Multiplication, Division, Addition, Subtraction) order of execution. Python 3 has a new operator
// which performs floor division i.e.
5/6 will produce a flot value of
0.8333333333333334 while it is zero in Python 2 and
5//6 will result in zero in Python 3. The
+ * operators can be used on String data as in the following examples
Also all the standard relational operators
== != < <= > >= and logical operators
and or not are supported. Basic Python expressions are same as in any other language.
Data Structures
Python has inbuilt
list, tuple, dictionary data structures.
Lists are similar to arrays where the indexes are integers and are auto assigned. Lists can store objects of mixed types and they are mutable. Some of the list functions are
append
extend
insert(idx,val)
pop
count
sort
reverse
Tuples are similar to lists but are not mutable and are created by using
( ) instead of
[] used for lists. All the functions which can be used to access elements in list can be used to access elements of tuples. Since tuples are not mutable functions which modifies list like
append pop del extend are not supported by tuples.
Dictionaries are unordered set of key value pairs and indexed by the keys.
{ } are used to create dictionaries and they are mutable. Elements in dictionaries are accessed using the key values. All datatypes including tuples which are not mutable can be used as key values for dictionaries.
len is a common function across all the three data structures which can be used to find the length i.e the number of elements stored in them.
All the three data structures have iterators which can be used to iterate through all the elements
If you have a list, a tuple can be created using the
tuple function
If you have a tuple, a list can be created using the
list function.
If you have two lists then a list of tuples can be created using the
zip function.
When you have a list of tuples as in the previous example, then a dictionary can be created using the
dict function.
Also when you have a dictionary a list of tuples can be created using the
items dictionary function.
Note that strings are nothing but list of characters.
Functions and Modules
Sequence of related statements can be grouped in to a function so that it can be reused. Group of related functions can be saved in a file and it is called a module. For e.g. Pythons inbuilt module math stores mathematical functions like
sqrt cos sin etc. To access a function in a module, the module need to be imported into the python script or in the interpreter command line. If you are someone who know C programing, this will be very familiar.
When the whole module is imported as above, then a specific function need to be called by qualifying it with the module name like in the code above
math.sqrt(). If you are interested only in a certain function is a module, that particular module can be imported as in the following example.
Note that when a specific function is imported as above, it doesn’t have to be qualified with the module name when the function is called.
Defining a function
Functions can be defined using a
def keyword
def function_name(optional parameters):. The statements which belong to the function is grouped by intendation using spaces. The end of the function is determined by a blank space after the function or begining of another function or end of the file storing the function.
All parameters and variables defined in a function are all local to the function. Any changes made to the parameters passed to the function will not be reflected in the parent code calling the function i.e. all the parameters are passed by value and not by reference.
When a group of related functions are stored in a file then it becomes a module and the file name is the module name. As with the inbuilt module like
math, functions from user defined modules can be made available for use in python scripts using the
import statement.
Documenting the code is key.
# can be used to add comments to Python code and anything added after
# until the end of line is considered comment. Also Python supports adding documentationusing
docstring to modules and functions so that they can read by users using the
__doc__ function.
docstring starts and ends with
""" triple quotes.
Execution Flow Control
Commonly found
if
for
while statements are supported in Python. As in function definition,
: is used to define the start of flow control and the list of statments to be executed is grouped using proper intendation.
Python for statement is different from other languages where users can define an initial value, end condition and an arithmetic expression which can be used to control the number of times the loop gets executed. In python
for statement iterates over the items of any sequence in the order they appear in the sequence. In the previous example the for statement iterates over the list “a”.
range function can create a number list which inturn can be used in
for loops.
if statement supports
elif which prevents deep code indendation and
else clauses.
while statement is similar to other languages.
break and
continue statements are available to control the
for and
while loops.
Console Input Output
raw_input() function can be used to receive input from users through console. The function takes an optional String, which will be output on console and waits for user to input value.
Output to console can be done using
% operator.
Note that the values passed should be elements if a tuple.
Files
open and
close functions can be used to (as you guessed) open and close files.
open function takes in the file name including the path to the file and a character to indicate whether the file need to be opened for read or write. The returned value of
open is a file handle which can be used for file processing and at the end of processing can be used to close the file.
readline function can be used to read a line from the file at a time and
read can be used to read the complete file.
write function can be used to write data into the file.
Exception Handling
Similar to “try” “catch” block in JAVA for exception handling, Python uses
try
except clauses to handle exceptions.
Executing Python Scripts
As you may have noticed all the code block shown so far is using the Python command line interpreter. If a Python script is created and stored in a file then the script can be executed using the
python filename command.
For e.g., if the following is the contend of the Python script file test.py
Then the script can be executed as below
If a file (module) is created with Python functions, the functions can be exected as in the following example. This will avoid the functions to be executed when the module is imported into another script.
What is covered so far could be used to accomplish most of the fundamantal tasks. This is intended to give a quick start on Python so that scripts can be created and used by the reader. | http://blog.asquareb.com/blog/2014/09/14/python-basics-for-programmers/ | CC-MAIN-2019-13 | refinedweb | 1,521 | 62.17 |
Preface
This is part departs from the very beginner nature of the previous three, so this may be of more interest to readers who already have some programming experience in another language. (Though also, see the section on using matching in Scala in Part 3.)
Iteration, the Scala way(s)
Up to now, we have (mostly) accessed individual items on a list by using their indices. But one of the most natural things to do with a list is to repeat some action for each item on the list, for example: “For each word in the given list of words: print it”. Here is how to say this in Scala.
scala> val animals = List("newt", "armadillo", "cat", "guppy") animals: List = List(newt, armadillo, cat, guppy) scala> animals.foreach(println) newt armadillo cat guppy
This says to take each element of the list (indicated by foreach) and apply a function (in this case, println) to it, in order. There is some underspecification going on in that we aren’t providing a variable to name elements. This works in some cases, such as above, but won’t always be possible. Here’s is how it looks in full, with a variable naming the element.
scala> animals.foreach(animal => println(animal)) newt armadillo cat guppy
This is useful when you need to do a bit more, such as concatenating a String element with another String.
scala> animals.foreach(animal => println("She turned me into a " + animal)) She turned me into a newt She turned me into a armadillo She turned me into a cat She turned me into a guppy
Or, if you are performing a computation with it, like outputing the length of each element in a list of strings.
scala> animals.foreach(animal => println(animal.length)) 4 9 3 5
We can obtain the same result as foreach using a for expression.
scala> for (animal <- animals) println(animal.length) 4 9 3 5
With what we have been doing so far, these two ways of expressing the pattern of iterating over the elements of a List are equivalent. However, they are different: a for expression returns a value, whereas foreach simply performs some function on every element of the list. This latter kind of use is termed a side-effect: by printing out each element, we are not creating new values, we are just performing an action on each element. With for expressions, we can yield values that create transformed Lists. For example, contrast using println with the following.
scala> val lengths = for (animal <- animals) yield animal.length lengths: List[Int] = List(4, 9, 3, 5)
The result is a new list that contains the lengths (number of characters) of each of the elements of the animals list. (You can of course print its contents now by doing lengths.foreach(println), but typically we want to do other, usually more interesting, things with such values.)
What we just did was map the values of animals into a new set of values in a one-to-one manner, using the function length. Lists have another function called map that does this directly.
scala> val lengthsMapped = animals.map(animal => animal.length) lengthsMapped: List[Int] = List(4, 9, 3, 5)
So, the for-yield expression and the map method achieve the same output, and in many cases they are pretty much equivalent. Using map, however, is often more convenient because you can easily chain a series of operations together. For example, let’s say you want to add 1 to a List of numbers and then get the square of that, so turning List(1,2,3) into List(2,3,4) into List(4,9,16). You can do that quite easily using map.
nums.map(x=>x+1).map(x=>x*x)
Some readers will be puzzled by what was just done. Here it is more explicitly, using an intermediate variable nums2 to store the add-one list.
scala> val nums2 = nums.map(x=>x+1) nums2: List[Int] = List(2, 3, 4) scala> nums2.map(x=>x*x) res9: List[Int] = List(4, 9, 16)
Since nums.map(x=>x+1) returns a List, we don’t have to name it to a variable to use it — we can just immediately use it, including doing another map function on it. (Of course, one could do this computation in a single go, e.g. map((x+1)*(x+1)), but often one is using a series of built-in functions, or functions one has predefined already).
You can keep on mapping to your heart’s content, including mapping from Ints to Strings.
scala> nums.map(x=>x+1).map(x=>x*x).map(x=>x-1).map(x=>x*(-1)).map(x=>"The answer is: " + x) res12: List = List(The answer is: -3, The answer is: -8, The answer is: -15)
Note: the use of x in all these cases is not important. They could have been named x, y, z and turlingdromes42 — any valid variable name.
Iterating through multiple lists
Sometimes you have two lists that are paired up and you need to do something to elements from each list simultaneously. For example, let’s say you have a list of word tokens and another list with their parts-of-speech. (See the previous tutorial for discussion of parts-of-speech.)
scala> val tokens = List("the", "program", "halted") tokens: List = List(the, program, halted) scala> val tags = List("DT","NN","VB") tags: List = List(DT, NN, VB)
Now, let’s say we want to output these as the following string:
the/DT program/NN halted/VB
Initially, we’ll do it a step at a time, and then show how it can be done all in one line.
First, we use the zip function to bring two lists together and get a new list of pairs of elements from each list.
scala> val tokenTagPairs = tokens.zip(tags) tokenTagPairs: List[(java.lang.String, java.lang.String)] = List((the,DT), (program,NN), (halted,VB)) Zipping two lists together in this way is a common pattern used for iterating over two lists. Now we have a list of token-tag pairs we can use a for expression to turn it into a List of strings. 1 scala> val tokenTagSlashStrings = for ((token, tag) <- tokenTagPairs) yield token + "/" + tag tokenTagSlashStrings: List = List(the/DT, program/NN, halted/VB)
Now we just need to turn that list of strings into a single string by concatenating all its elements with a space between each. The function mkString makes this easy.
scala> tokenTagSlashStrings.mkString(" ") res19: String = the/DT program/NN halted/VB
Finally, here it all is in one step.
scala> (for ((token, tag) <- tokens.zip(tags)) yield token + "/" + tag).mkString(" ") res23: String = the/DT program/NN halted/VB
Ripping a string into a useful data structure
It is common in computational linguistics to need convert string inputs into useful data structures. Consider the part-of-speech tagged sentence mentioned in the previous tutorial. Let’s begin by assigning it to the variable sentRaw.
val sentRaw = "The/DT index/NN of/IN the/DT 100/CD largest/JJS Nasdaq/NNP financial/JJ stocks/NNS rose/VBD modestly/RB as/IN well/RB ./."
Now, let’s turn it into a List of Tuples, where each Tuple has the word as its first element and the postag as its second. We begin with the single line that does this so that you can see what the desired result is, and then we’ll examine each step in detail.
scala> val tokenTagPairs = sentRaw.split(" ").toList.map(x => x.split("/"))), (.,.))
Let’s take each of these in turn. The first split cuts sentRaw at each space character, and returns an Array of Strings, where each element is the material between the spaces.
scala> sentRaw.split(" ") res0: Array = Array(The/DT, index/NN, of/IN, the/DT, 100/CD, largest/JJS, Nasdaq/NNP, financial/JJ, stocks/NNS, rose/VBD, modestly/RB, as/IN, well/RB, ./.)
What’s an Array? It’s a kind of sequence, like List, but it has some different properties that we’ll discuss later. For now, let’s stick with Lists, which we can do by using the toList method. Additionally, let’s assign it to a variable so that the remaining operations are easier to focus on.
scala> val tokenTagSlashStrings = sentRaw.split(" ").toList tokenTagSlashStrings: List = List(The/DT, index/NN, of/IN, the/DT, 100/CD, largest/JJS, Nasdaq/NNP, financial/JJ, stocks/NNS, rose/VBD, modestly/RB, as/IN, well/RB, ./.)
Now, we need to turn each of the elements in that list into pairs of token and tag. Let’s first consider a single element, turning something like “The/DT” into the pair (“The”,”DT”). The next lines show how to do this one step at a time, using intermediate variables.
scala> val first = "The/DT" first: java.lang.String = The/DT scala> val firstSplit = first.split("/") firstSplit: Array = Array(The, DT) scala> val firstPair = Tuple2(firstSplit(0), firstSplit(1)) firstPair: (java.lang.String, java.lang.String) = (The,DT)
So, firstPair is a tuple representing the information encoded in the string first. This involved two operations, splitting and then creating a tuple from the Array that resulted from the split. We can do this for all of the elements in tokenTagSlashStrings using map. Let’s first convert the Strings into Arrays.
scala> val tokenTagArrays = tokenTagSlashStrings.map(x => x.split("/")) res0: List[Array] = List(Array(The, DT), Array(index, NN), Array(of, IN), Array(the, DT), Array(100, CD), Array(largest, JJS), Array(Nasdaq, NNP), Array(financial, JJ), Array(stocks, NNS), Array(rose, VBD), Array(modestly, RB), Array(as, IN), Array(well, RB), Array(., .))
And finally, we turn the Arrays into Tuple2s and get the result we obtained with the one-liner earlier.
scala> val tokenTagPairs = tokenTagArrays), (.,.))
Note: if you are comfortable with using one-liners that chain a bunch of operations together, then by all means use them. However, there is no shame in using several lines involving a bunch of intermediate variables if that helps you break apart the task and get the result you need.
One of the very useful things of having a List of pairs (Tuple2s) is that the unzip function gives us back two Lists, one with all of the first elements and another with all of the second elements.
scala> val (tokens, tags) = tokenTagPairs.unzip tokens: List = List(The, index, of, the, 100, largest, Nasdaq, financial, stocks, rose, modestly, as, well, .) tags: List = List(DT, NN, IN, DT, CD, JJS, NNP, JJ, NNS, VBD, RB, IN, RB, .)
With this, we’ve come full circle. Having started with a raw string (such as we are likely to read in from a text file), we now have Lists that allow us to do useful computations, such as converting those tags into another form.
Providing a function you have defined to map
Let’s return to the postag simplification exercise we did in the previous tutorial. We’ll modify it a bit: rather than shortening the Penn Treebank parts-of-speech, let’s convert them to course parts-of-speech using the English words that most people are familiar with, like noun and verb. The following function turns Penn Treebank tags into these course tags, for more tags than we covered in the last tutorial (note: this is still incomplete, but serves to illustrate the point).
def coursePos (tag: String) = tag match { case "NN" | "NNS" | "NNP" | "NNPS" => "Noun" case "JJ" | "JJR" | "JJS" => "Adjective" case "VB" | "VBD" | "VBG" | "VBN" | "VBP" | "VBZ" | "MD" => "Verb" case "RB" | "RBR" | "RBS" | "WRB" | "EX" => "Adverb" case "PRP" | "PRP$" | "WP" | "WP$" => "Pronoun" case "DT" | "PDT" | "WDT" => "Article" case "CC" => "Conjunction" case "IN" | "TO" => "Preposition" case _ => "Other" }
We can now map this function over the parts of speech in the collection obtained previously.
scala> tags.map(coursePos) res1: List = List(Article, Noun, Preposition, Article, Other, Adjective, Noun, Adjective, Noun, Verb, Adverb, Preposition, Adverb, Other)
Voila! If we want to convert the tags in this manner and then output them as a string like what we started with, it’s just a few steps. We’ll start from the beginning and recap. Try running the following for yourself.
val sentRaw = "The/DT index/NN of/IN the/DT 100/CD largest/JJS Nasdaq/NNP financial/JJ stocks/NNS rose/VBD modestly/RB as/IN well/RB ./." val (tokens, tags) = sentRaw.split(" ").toList.map(x => x.split("/")).map(x => Tuple2(x(0), x(1))).unzip tokens.zip(tags.map(coursePos)).map(x => x._1+"/"+x._2).mkString(" ")
A further point is that when you provide expressions like (x => x+1) to map, you are actually defining an anonymous function! Here is the same map operation with different levels of specification
scala> val numbers = (1 to 5).toList numbers: List[Int] = List(1, 2, 3, 4, 5) scala> numbers.map(1+) res11: List[Int] = List(2, 3, 4, 5, 6) scala> numbers.map(_+1) res12: List[Int] = List(2, 3, 4, 5, 6) scala> numbers.map(x=>x+1) res13: List[Int] = List(2, 3, 4, 5, 6) scala> numbers.map((x: Int) => x+1) res14: List[Int] = List(2, 3, 4, 5, 6)
So, it’s all consistent: whether you pass in a named function or an anonymous function, map will apply it to each element in the list.
Finally, note that you can use that final form to define a function.
scala> def addOne = (x: Int) => x + 1 addOne: (Int) => Int scala> addOne(1) res15: Int = 2
This is similar to defining functions as we had previously (e.g. def addOne (x: Int) = x+1), but it is more convenient in certain contexts, which we’ll get to later. For now, the thing to realize is that whenever you map, you are either using a function that already existed or creating one on the fly.
Filtering and counting
The map method is a convenient way of performing computations on each element of a List, effectively transforming a List from one set of values to a new List with a set of values computed from each corresponding element. There are yet more methods that have other actions, such as removing elements from a List (filter), counting the number of elements satisfying a given predicate (count), and computing an aggregate single result from all elements in a List (reduce and fold). Let’s consider a simple task: count how many tokens are not a noun or adjective in a tagged sentence. As a starting point, let’s take the list of mapped postags from before.
scala> val courseTags = tags.map(coursePos) courseTags: List = List(Article, Noun, Preposition, Article, Other, Adjective, Noun, Adjective, Noun, Verb, Adverb, Preposition, Adverb, Other)
One way of doing this is to filter out all of the nouns and adjectives to obtain a list without them and then get its length.
scala> val noNouns = courseTags.filter(x => x != "Noun")noNouns: List = List(Article, Preposition, Article, Other, Adjective, Adjective, Verb, Adverb, Preposition, Adverb, Other) scala> val noNounsOrAdjectives = noNouns.filter(x => x != "Adjective") noNounsOrAdjectives: List = List(Article, Preposition, Article, Other, Verb, Adverb, Preposition, Adverb, Other) scala> noNounsOrAdjectives.length res8: Int = 9
However, because filter just takes a Boolean value, we can of course use Boolean conjunction and disjunction to simplify things. And, we don’t need to save intermediate variables. Here’s the one liner.
scala> courseTags.filter(x => x != "Noun" && x != "Adjective").length res9: Int = 9
If all we want is the number of elements, we can instead just use count with the same predicate.
scala> courseTags.count(x => x != "Noun" && x != "Adjective") res10: Int = 9
As an exercise, try doing a one-liner that starts with sentRaw and provides the value “resX: Int = 9” (where X is whatever you get in your Scala REPL).
In the next tutorial, we’ll see how to use reduce and fold to compute aggregate results from a List.
Reference: First steps in Scala for beginning programmers, Part | http://www.javacodegeeks.com/2011/10/scala-tutorial-iteration-for.html | CC-MAIN-2015-32 | refinedweb | 2,662 | 61.87 |
[UPDATE]:
This is not a working solution as pointed out by @andhddn below.
I have a greedy algorithm that is accepted. Can't prove the correctness though. Main idea is to use the shortest string first. We sort all the string based on the number of 1s it has once, and then based on the 0s second time. Each time we try to consume as much string as possible. Result is the bigger of the 2 iterations.
Any counter example/ proof of correctness is appreciated
public class Solution { public int findMaxForm(String[] strs, int m, int n) { int result = 0; if(strs.length == 0) return 0; PriorityQueue<Element> oneQueue = new PriorityQueue<Element>(new oneComparator()); PriorityQueue<Element> zeroQueue = new PriorityQueue<Element>(new zeroComparator()); for(String s : strs){ int ones = 0; int zeros = 0; for(char c : s.toCharArray()){ if(c == '0') { zeros++; }else{ ones++; } } Element e = new Element(ones, zeros); oneQueue.offer(e); zeroQueue.offer(e); } int numZero = m; int numOne = n; /*sort the string based on # of 0 each string has and try to consume as many string as possible*/ while(!zeroQueue.isEmpty()){ if(numZero >= zeroQueue.peek().zero && numOne >= zeroQueue.peek().one){ result++; numZero -= zeroQueue.peek().zero; numOne -= zeroQueue.peek().one; } zeroQueue.poll(); } int secondResult = 0; numZero = m; numOne = n; /*sort the string based on # of 1 each string has and try to consume as many string as possible*/ while(!oneQueue.isEmpty()){ if(numOne >= oneQueue.peek().one && numZero >= oneQueue.peek().zero){ secondResult++; numZero -= oneQueue.peek().zero; numOne -= oneQueue.peek().one; } oneQueue.poll(); } return Math.max(result, secondResult); } class oneComparator implements Comparator<Element>{ public int compare(Element e1, Element e2){ if(e1.one == e2.one) return e1.zero - e2.zero; return e1.one - e2.one; } } class zeroComparator implements Comparator<Element>{ public int compare(Element e1, Element e2){ if(e1.zero == e2.zero) return e1.one - e2.one; return e1.zero - e2.zero; } } class Element{ public int one; public int zero; public Element(int one, int zero){ this.one = one; this.zero = zero; } } }```
@DonaldTrump Does not work for this input:
{
"0000111",
"0000111111",
"01111111",
"0001",
"000111111",
"0000001111111",
"00011111",
"000011111",
"00000011",
"0111111",
"0000000001111111",
"0011",
"001111",
"00000001111",
"0011",
"0000111111111",
"0001111111",
"011111111"
};
M = 4
N = 6
It returns 1, while there are 2 "0011" strings which satisfy M and N {4, 6}
@andhddn Yes you are right. I will update this post. I wonder how did you come up with the test case?
@DonaldTrump I had similar thoughts at the beginning, but had significant doubts too. I.e. my brain was not strong enough to disprove it mathematically. So I took one of the correct versions and wrote a program which generates inputs, compares the two outputs and chooses the simplest repro case.
Oh Yeah, I came up with similar greedy approach and got accepted beating 100% :P
but it's wrong:
public int findMaxForm(String[] strs, int m, int n) { Arrays.sort(strs, new Comparator<String>(){ @Override public int compare(String s1, String s2){ int[] cnt1 = count(s1); int[] cnt2 = count(s2); if(cnt1[1] == cnt2[1]){ return cnt1[0] - cnt2[0]; } return cnt1[1] - cnt2[1]; } }); int i = 0; int count = 0; while((m > 0 || n > 0) && i < strs.length){ int[] cnt = count(strs[i]); if(cnt[0] > m && cnt[1] > n) break; if(cnt[0] <= m && cnt[1] <= n){ m -= cnt[0]; n -= cnt[1]; count++; } i++; } return count; } public int[] count(String s){ int[] cnt = new int[2]; for(int i = 0; i < s.length(); i++){ if(s.charAt(i) == '0') cnt[0]++; if(s.charAt(i) == '1') cnt[1]++; } return cnt; }
It fails this simple test case which is missing from test cases:
["000","0111","0111","0111"]
3
9
Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect. | https://discuss.leetcode.com/topic/72628/accepted-greedy-algorithm | CC-MAIN-2017-47 | refinedweb | 624 | 67.15 |
0
I know this is probably an unbelievably simple error somewhere, but I can't see it. I keep getting "undefined reference to Machine::Machine()" and all of Machine's other functions.
main.cpp
#include "machine.h" using namespace std; int main(int argc, char** argv) { Machine* m = new Machine(); m->reset(); m->run(); delete m; return 0; }
machine.h
#ifndef _MACHINE_H_ #define _MACHINE_H_ #include "user.h" class Machine { public: Machine(); ~Machine(); void run(); void reset(); private: User currentUser; }; #endif
machine.cpp
#include "machine.h" Machine::Machine() { } Machine::~Machine() { } void Machine::run() { } void Machine::reset() { }
I know I'm going to kick myself once someone answers this. Thanks in advance.
-andrax | https://www.daniweb.com/programming/software-development/threads/88756/dumb-class-scoping-error | CC-MAIN-2016-50 | refinedweb | 111 | 60.92 |
Blend 3 brings to the table really sophisticated support for sample data, enabiling better designability of your applications. In my previous post, I demonstrated how designers could leverage this feature to prototype data connected applications inside Blend . However, for really sophisticated applications, richer support might be desirable - for example, you might want to use your own custom types for sample data in the cases where you cannot re-create the schema from scratch using the primitives that we provide.
Here is a small example that will help you get started on a feature that we just introduced in recently available Blend 3 build – we call this feature “design data”. This feature allows developers to enable designers to be more productive inside Blend for practical LOB applications where there is a clear separation between model and view, and where you can’t use the Blend sample data feature as your UI might depend on your custom business objects (for example, think typed data templates in WPF).
Let us take a quick tour of this example, and see how things work behind the covers:
ShoppingCart.cs defines a data structure that we are trying to visualize in ShoppingCartView.xaml. The type ShoppingCart does not have a public constructor, neither does ShoppingCartItem. Similarly, ShoppingCart has a read-only property ItemsCount. These kinds of limitations are extremely common in real-world data structures (and is being demonstrated here to show how our system handles these limitations just fine, without requiring your to make changes to your run-time code)
The sample data for ShoppingCartView.xaml is defined in ShoppingCartSampleData.xaml, which is included with a special build item type in the project file: <DesignData Include="ShoppingCartSampleData.xaml" />. This ensures that you don't pay any run-time penalties for enabling this design-time only feature.
The contents of ShoppingCartSampleData.xaml look like following:
<local:ShoppingCart
xmlns:
<local:ShoppingCart.Items>
<local:ShoppingCartItem
</local:ShoppingCart.Items>
</local:ShoppingCart>
There are a few things to note about the contents of this file:
a) While the format is XAML, we have relaxed the specification quite a bit. You are allowed to specify a value for the read only property (ShoppingCart.ItemCount, ShoppingCartItem.ItemName), as well as initialize objects that don’t have public constructors (ShoppingCart, ShoppingCartItem). Blend creates on the fly types which look like user types. You could choose to prevent reflection (in which case, what you can specify in XAML is severely restricted) by specifying <IsDesignTimeCreatable>true</IsDesignTimeCreatable> in the project file for the sample data XAML item.
b) You can specify any platform type like Brushes, ImageSource, Uri, etc.
c) You get full intellisense in Blend for typing this XAML.
In ShoppingCartView.xaml, we then hookup the sample data like so:
<Grid x:
For WPF projects, if your XAML was using typed data templates, you need to add the following attribute to those typed data templates to get picked up automatically, if you were using the reflection based sample data types and you wanted a good design experience.
<DataTemplate x:
This particular sample data feature will also be supported in VS 2010. As always, please don't hesitate to ask for further clarifications, and I really value your feedback on how we could make this feature more useful for you.
Could you release walkthroughs on how to convert the sample data bindings to use with production connections? Could you include a basic demo for items like LINQ to SQL Class? Another with new .NEW RIA Services? BTW, what kind of support will Blend 3 have with RIA Services? Thanks in advance.
Can you go into more detail about what the d:IsDesignTimeCreatable property does? Also you didn’t mention the d:DesignInstance property. Is there any connection between d:DesignInstance and DataTemplates? I’ve created some custom controls that have dependency properties that are custom types without a default constructor, and I’m having trouble getting this to work. I am suspecting that the dependency property isn’t getting set because the design time created type doesn’t match the type of the dependency property. Does this sound like what may be happening or am I missing something? And if so, then is there anything I can do about it?
Hi Joey,
Please feel free to get in touch with me at unnir at microsoft dot com with a sample sample that demonstrates your problem. I can investigate and help you out with a solution.
Thanks,
Unni
Two questions:
(1) When I open this project in VS, it tells me that "ShoppingCart" and "ShoppingCartItem" aren’t usable as object elements because they don’t define a public parameterless constructor. That makes sense — so why *are* they usable?
(2) How do you use this approach for complex object graphs, for instance, if you have a Customer with Orders with OrderItems with Products?
Never mind, figured it out for both of them:
(1) As you mention in your article above, Blend isn’t really creating the objects, it’s just creating objects that *look* like the objects you’re defining. Sorta like "duck typing".
(2) I was able to get XAML like this working:
<rs:Room d:IsDataSource="True"
xmlns=""
xmlns:rs="clr-namespace:SlideLinc.Client.Common.RoomService;assembly=SlideLinc.Client.Common"
xmlns:mc=""
xmlns:d=""
xmlns:x=""
mc:
<rs:Room.Owner>
<rs:RegisteredUser x:
</rs:Room.Owner>
<rs:Room.Sessions>
<rs:Session>
<rs:Session.User>
<rs:RegisteredUser
</rs:Session.User>
<rs:Session.Whiteboards >
<rs:Whiteboard />
</rs:Session.Whiteboards>
</rs:Session>
<rs:Session>
<rs:Session.User>
<rs:RegisteredUser
</rs:Session.User>
<rs:Session.Whiteboards >
<rs:Whiteboard />
</rs:Session.Whiteboards>
</rs:Session>
<rs:Session>
<rs:Session.User>
<rs:RegisteredUser
</rs:Session.User>
<rs:Session.Whiteboards >
<rs:Whiteboard />
</rs:Session.Whiteboards>
</rs:Session>
</rs:Room.Sessions>
<rs:Room.SharedFile>
<rs:SharedFile
<rs:SharedFile
<rs:SharedFile
</rs:Room.SharedFile>
</rs:Room>
I still haven’t figured out how to point later object references back to earlier objects, but I don’t think that’s critical for most things.
Hi Ken,
Yes, you are right – we use reflection to generate dummy types on the fly so we can instantiate them, and yet have the the same signatures for properties, etc.
The objects are really supposed to be only for visualization purposes, so things like pointing back to existing instances might not work – you might just need to duplicate them.
Thanks,
Unni
Hi Unni,
I have played with the DesignData build action and it’s absolutely gorgeous. I have noticed one somewhat strange behavior. If a class has a property of generic type, Blend fails to create a duplicate for this entire class. There are two minor variations of this:
1. If the “faked” class has no default constructor, Blend will say:” The type … does not include any accessible constructors”
2. If the “faked” class does provide a default constructor, Blend will accept it in the.xaml file but won’t display the actual data in design time.
3. If the generic property is commented out, everything is fine.
My question is: Can you please explain this behavior to us and what is more important, tell us if there is a work-around for that. If the generic-type property is declared with an interface instead, this will hide the generic type inside the “get” accessor of the property and this will obviously work, but there is no guarantee it will be applicable everywhere. If we don’t really need to provide data for those “problematic” properties it would be absolutely sufficient if we could exclude them from the generated “fake” type (maybe using an attribute like [Browsable(false)], etc. ). Probably you would come with a better idea?
Here’s a demonstration for this. The code file looks like this:
namespace WpfApplication1
{
public class Test
{
//Default constructor
//public Test(){} – commented out
//Constructor
public Test(object initializer){}
public int SimpleProperty { get; set; }
public ObservableCollection<Item> Items { get; set; }
//Property using a generic
public BusinessOperation<Delivery> Operation { get; set; }
}
public class Item
{
public string Name { get; set; }
}
public class BusinessOperation<T>
{
public T SomeData { get; set; }
}
public class Delivery
{
public string TrackingNumber { get; set; }
}
}
… And .xaml file with DesignData build action looks like this:
<local:Test xmlns:
<local:Test.Items>
<local:Item
</local:Test.Items>
</local:Test> | https://blogs.msdn.microsoft.com/unnir/2009/07/12/introducing-sample-data-for-developers/ | CC-MAIN-2018-51 | refinedweb | 1,373 | 55.54 |
Windows plugins are written in C# .NET. An example plugin can be found with the Windows agent source code.
C:\Users\Ryan\Documents\Plugins through Windows Explorer.
Tell the agent where the directory is
Open Server Density by locating it in your start menu. Click the
Enable plugins check box and then click the
Browse... button. Choose the folder that you created that contains your plugin DLLs. The agent will parse this directory for any new monitoring plugin DLLs each time the agent is started.
Step 2: Writing a plugin
Requirements
- Plugins must be written in C# (.NET Framework 3.5 and above).
- Plugins must be within their own self contained class file.
- Plugins must return a key value which is what will be displayed in the web UI
- Plugins must reference the
BoxedIce.ServerDensity.Agent.PluginSupport.dlllibrary, which can be found in the directory where Server Density was installed.
- Plugins must implement the
ICheckinterface.
Class file
Your plugin class's
Key property is what will show up in the web UI. For example, if you created a plugin called
New Users your plugin class would have a
Key whose return value must be
NewUsers.
Structure
The class must have a
DoCheck() method which returns a
Dictionary<string, object> and a
Key property that returns a string. The
Key property, as mentioned above, needs to return a string. The agent will import the library and then immediately call the
DoCheck() method, using the return value as part of the postback payload. You can, of course, create other classes and methods to do anything you like.
Configuration
You can access the configuration values from the agent's config file using
ConfigurationManager.AppSettings if your values are within the
AppSettings section in the config file. If you set up your own section then you can use
ConfigurationManager.GetSection..
For example, the following function for the plugin with the internal name
Plugin1 returns two fixed value key/pairs:
using System;
using System.Collections.Generic;
using BoxedIce.ServerDensity.Agent.PluginSupport;
namespace PluginExample
{
public class Hats : ICheck
{
public string Key
{
get { return "Plugin1"; }
}
public object DoCheck()
{
IDictionary<string, object> values = new Dictionary<string, object>();
values.Add("hats", 5);
values.Add("Dinosaur Rex", 25.4);
return values;
}
}
}
.net version
You will need to build your project for .net 3.5/4.0. If you get this error:
System.BadImageFormatException: This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded.
You can add the following to your
BoxedIce.ServerDensity.Agent.WindowsService.exe.config:
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" /> <supportedRuntime version="v4.0" />
Finally
Once you have written and compiled your plugin and it exists in the plugin directory, just restart the agent and it will immediately be picked up and executed. | https://support.serverdensity.com/hc/en-us/articles/360001066623-Writing-a-plugin-Windows | CC-MAIN-2021-43 | refinedweb | 465 | 51.14 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.