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
For a long time I was surprised why if I have a script testme.py: import subprocess subprocess.call("echo Something", shell=True) and I try to execute it like this: python testme.py >testme.txt I get the output: The handle is invalid. Strange failures randomly happened with different programs, so I thought maybe this was intended (mis)behavior, and I found that I can workaround this by explicitly specifying std* handles: subprocess.call(...., stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr) I lived with this until I understood that if something substitutes sys.std* with a proxy (examples: running under IDLE or wxPython, or when there is a custom logger on stdout/stderr, etc), this will no longer work: File "C:\Programs\Python25\Lib\subprocess.py", line 698, in _get_handles p2cread = msvcrt.get_osfhandle(stdin.fileno()) AttributeError: fileno Now I finally found that my problem are these two lines in subprocess.py: if stdin is None and stdout is None and stderr is None: return (None, None, None, None, None, None) These lines add an interesting quirk: if I explicitly specify any single channel (i.e. stdout=1) the problem suddenly disappears, and if I just comment these lines altogether my problem vanishes completely! (i.e. output redirection works absolutely well) Further investigations showed that it seems to be some strange OS quirk/bug, i.e. this behavior is caused when STARTF_USESTDHANDLES is not used, and crt's spawnl* behaves incorrectly too: os.spawnl(r"C:\WINDOWS\system32\cmd.exe", r"C:\WINDOWS\system32\cmd.exe /c echo Something") So the question is should these two lines be removed to workaround this OS bug? To my thinking, this will not change behavior when any std* arguments are passed to Popen, and the only case when it kicks in is when no std* arguments are specified and the resulting side effects are previously failing cases start working correctly. Or am I wrong here, are there any side effects of using STARTF_USESTDHANDLES that I'm missing here? Best regards, Alexey.
https://mail.python.org/pipermail/python-dev/2007-August/074265.html
CC-MAIN-2016-44
refinedweb
340
53.81
It's not the same without you Join the community to find out what other Atlassian users are discussing, debating and creating. In custom field, can we add below evalutaion condition ? if 55 < TotalCustomField1 < 80 = 1.5 If 30 < TotalCustomField1 < 55 = 3.5 If TotalCustomField1 < 30 = 4 i went through below link, but i could not found as above how i want: Can we add as below in custom field ? if((issue.get("customfield_11246") != null ? Integer.parseInt(issue.get("customfield_11246")) : 0) >55 && (issue.get("customfield_11246") != null ? Integer.parseInt(issue.get("customfield_11246")) <80) { return 1.5 } or any alternative solution ? Yes, this would work, assuming the two customfields are text fields or equivalent. If the customfields are numeric fields, you don't need to parse them, and if they are select fields, you'll need to add a getValue() on the result of the get(). when i paste above stuff then unable to see the field in screen.. yes, value is from calculation textbox field only (used in 'if' condition). You can also use the free Script Runner plugin and create a scripted custom field with code like yours above. Henning can you please correct me if below stuff not work direclty .. then how to fetch custom field value in groovy script runner and based on it's value return the value as above comment example. if((issue.get("customfield_11246") != null ? Integer.parseInt(issue.get("customfield_11246")) : 0) >55 && (issue.get("customfield_11246") != null ? Integer.parseInt(issue.get("customfield_11246")) <80) { return 1.5 } If it's a text custom field, this should work. def user = componentManager.jiraAuthenticationContext.getLoggedInUser() Double ret = null if (componentManager.fieldManager.getAvailableCustomFields(user, issue).find{it.name == 'Custom Field Name'}) { try { int value = (getCustomFieldValue('Custom Field Name') as String)?.toInteger() } catch (NumberFormatException nfe) { value = 0 } switch (value){ case {it < 30}: ret = 4.0; break case {it < 55}: ret = 3.5; break case {it < 88}: ret = 1.5; break default: ret = 0.0 } } return ret Please be aware to choose the matching number templates. Henning Thanks @Henning. actually, this script field is not appearing in the screen where asscoiated. it shows in "where is my field" when i do it on edit screen but not appear in the screen. what can be the cause.. jira stand alone version - 5.2.11 my custom field type (whose value in evalutaion) is "calcualted custom field" Scripted fields will only be displayed on the view screen because they are not editable. I don't know which kind of object the customfield value of a "calculated custom field" is. If the script throws exceptions you may hav to look at the class of the return value from getCustomFieldValue(). log.error getCustomFieldValue('Custom Field Name')?.class?.name print the class name of the object to the log.
https://community.atlassian.com/t5/Questions/How-to-add-condition-in-custom-field/qaq-p/221366
CC-MAIN-2018-13
refinedweb
461
60.01
Feature #16425open Add Thread#dig Description Thread has #[] method like as Array, Hash, Struct and so on, but no #dig. For instance, PP::PPMethods#check_inspect_key in pp.rb can be simplified with the combination of this method and safe navigation operator. From def check_inspect_key(id) Thread.current[:__recursive_key__] && Thread.current[:__recursive_key__][:inspect] && Thread.current[:__recursive_key__][:inspect].include?(id) end To def check_inspect_key(id) Thread.current.dig(:__recursive_key__, :inspect)&.include?(id) end Patch: Updated by shevegen (Robert A. Heiler) almost 2 years ago I think the use case has been described and ruby users may agree that this could be an improvement (e. g. such as the example given by nobu for more succinct code). #dig on Array, Hash and Struct makes sense; for Thread perhaps the net benefit may be a bit more abstract (I guess the most common use case for .dig will be for Array and then possibly Hash ... or vice versa). The more relevant question may then be a language design question, e. g. whether matz thinks that ruby users should/could use dig for Threads too. From this point of view, nobu's comparison makes sense (to me), e. g. the general [] method compared to dig. I myself use [] a lot for custom classes since it is often nice to be able to use both Foobar.new and Foobar[] - the latter even allowing slightly fewer characters. :) IMO if matz is fine with Thread also being used/usable in that way through .dig then I think nobu's suggestion makes sense, so +1 about the idea. Also available in: Atom PDF
https://bugs.ruby-lang.org/issues/16425
CC-MAIN-2021-43
refinedweb
264
67.86
Results 1 to 1 of 1 - Join Date - Feb 2018 - 1 Does every call to write sends switches to kernel mode? because sys_call is a kernel function the CPU has to change the ring to zero store the processes registers and so on. But does it always switches to kernel mode? for example, if i do write(-1,buffer,LENGTH) does it still tries to find it in the file descriptors array? I see in the glibc source code that it does check for fd>0 but i don't see any jump to the sys_call there (it seems like the baracks for main() ends before any call to the alias_write. /*) #include <stub-tag.h> So the question is both: Where does the glibc actually calls the sys_write Is it true that glibc doesn't call the sys_write if fd<0?
http://www.linuxforums.org/forum/kernel/210937-does-every-call-write-sends-switches-kernel-mode-post994591.html?s=93782a998dfc977c998764385ed1de0e
CC-MAIN-2019-26
refinedweb
141
82.99
Welcome to your weekly update of JavaScript news and goodies. Features Tells you what percentage of users can use your page based on the features you employJavaScript Tools of the Trade: JSBinTo Hell with jQuery - get jQuery out of your frontend and replace it with simpler, more performant CSS equivalents (video)Creating and publishing a node.js moduleCreate an Analog Clock Using the Canvas - here's how About The JavaScript Alternatives - Three languages compete to make JavaScript easier to write and faster to execute. Which to choose?Why I don't suggest JavaScript as a first programming languageHow Node.js Got BigList of languages that compile to JS10 JavaScript editors and IDEs put to the test Coding Finding Array Elements with Array#indexOfJavaScript Array: slice vs spliceJavaScript String: substring, substr, sliceEvaluating JavaScript code via eval() and new Function()Truthy and Falsy Values in JavaScript - what do the terms actually mean? Testing Extending JavaScript with inline unit testsJavaScript unit tests with YUI TestGenerating JUnit test reports with Jasmine 2.0Headless Javascript testing with Jasmine 2.0Unit Testing JavaScript Bonus Disable the User’s JavaScript Console - because you can So what are your thoughts on the latest going-ons in the world of JavaScript? We're all testing our code, right? Is JavaScript a good first language to learn?Let us know and the debate can begin. Please PM us if you have anything of interest for the next issue, and happy reading! - [Paul & [URL=""]Pullo]() Whether JavaScript is or isn't a poor first language to learn depends on how it is taught. The way that JavaScript was written back in the Netscape days made it very different from all the other programming languages around. That made just about any other language a better choice for learning programming as very little of whay you could learn from JavaScript could be applied to make it easier to understand other languages. On the other hand properly written modrn JavaScript uses many of the same constructs as other languages. Nicholas Zakas's book "JavaScript for Web Developers" takes the same approach to teaching JavaScript as other books take to teaching other programming languages. This makes the book ideal for those who have already learnt one or more other languages to learn JavaScript properly as a serious programming language. I am not convinced that this type of programming book works as well for someone learning their first language and who is therefore unaware of many of the basic concepts of programming. The fact that such a book exists does show though that JavaScript can be treated as a serious programming language and so there is no reason why JavaScript could not be used as a first language provided that it is taught the right way so as to properly teach those programming concepts that make learning additional languages so much easier. As far as I am able to determine, the vast majority of courses teaching JavaScript do not teach it the right way (many are still teaching how to write JavaScript for Netscape). That you are more likely than not to be taking a history class rather than a programming class if you take a class that is teaching JavaScript as a first language is a good reason for NOT choosing to learn it as your first programming language. It will be much easier to determine if the JavaScript class is teaching programming or history if you already know another programming language and have a knowledge of programming concepts. That article about disabling the console was interesting, but it's fairly easy to get around. All you have to do is to use the location bar to delete the custom console, which then returns control back to the standard one. javascript:delete console I tried this, but it didn't work for me in Chrome.I opened the console, ascertained that it was disabled, then entered "javascript:delete console" into the address bar, pressing return.The console was still disabled.Am I missing anything? I checked FB using FireBug. That still works as expected I agree that how a language is taught makes a great difference. I think the author's point is that it's not very good for "software engineering" and/or "end-to-end systems programming", as its focus is too web-centric.For example, I recently wrote a small desktop GUI that should do some basic file manipulation, then upload the altered files to an FTP server.I ended up using Ruby, but briefly entertained having a go at writing it in JS. The file manipulation part and the FTP part put me off. I recently read some kid's page but can't find it anymore, listing a bunch of vulnerabilities in the Chrome dev toolbar, where manipulating the console allowed an attacker to take control of the browser... wish I could find it. All I remember is the kid was 17 and had this long list of vulns, showing Javascript code for each exploit. My search-fu is poor today. It was fairly recently tweeted. That's interesting - I tested using a local test page and things went well. I'll try again tonight and see if I can get my results to differ. Social engineering sucks, that's for sure, but disabling the JS console in this way is like disabling the terminal on a Linux machine in case you enter rm -rf / or :(){:|:&};: rm -rf / :(){:|:&};: Aha, someone else who saw the post vaguely remembered the logo looked like a fire hydrant. Adding "hydrant" to my search suddenly brings it up :/ The vulnerabilities outlined in the post allow the following:Detect the opening and executing of commands in the console. (Unpatched)Prevent the execution of commands in the console (Unpatched)Log the commands that are executed in the console (Unpatched)Censor variables from being accessed/read from the console (Unpatched)Other unexplored potential vulnerabilities that are children of these (Unpatched)Use these vulnerabilities to execute arbitrary scripts on webpages that can be framed (Patched) The exploits require little technical ability to exploit (many people can write some simple JavaScript), and the majority of them have remained unpatched for over a year. I hope that this post will help get those vulnerabilities fixed. I don't actually buy the "Facebook is doing it to protect you" line. That's interesting reading, poes.Thank you. Wouldn't it be easier to just create a userscript to attach to your browser that runs that command just on those sites that try to disable the console? That way it would be a set once and forget (until you find another site that you need to add to the list) rather than having to enter it every time. The following userscript will work in Google Chrome (tampermonkey) to reinstate the console. It should work in Firefox (GreaseMonkey) as well, may need slight alteration to work in Internet Explorer (depending on which userscript plugin you use). // ==UserScript== // @namespace // @author Stephen Chapman // @name Fix console // @description Reinstates the console when one of the following sites disables it // @include // ==/UserScript== delete console; This is set and forget - the only time you'd need to change it is if you need to add an include statement for another stupid site. It didn't work for me either in Chrome. Typing in the address bar in Chrome didn't work for me either but setting it up as a userscript did. This topic is now closed. New replies are no longer allowed.
http://community.sitepoint.com/t/this-week-in-javascript-10-march-2014/40081
CC-MAIN-2014-42
refinedweb
1,254
58.92
Seeking suggestions on a form that allow users to pass coding to the application Hi everyone, I am thinking of developing a form that allow users to define variables, set up conditions, design iterations, and output to predefined variables. This whole input is then passed to the coding and becomes part of the coding of the application. It is like a template that allow a user that is not familiar with c++ can write relatively complex functions. It is like a super calculator that allow the use to code within the given structure. It would be amazing if I could do this? Please help and thanks to everyone. :) - jsulm Moderators @pdsc_dy If it does not have to be C++ you can take a look at (JavaScript). @jsulm Thanks a lot. The program is in C++ but I can use it with Qt script. Thanks for the tips. Let me read the documentation and I hope you don't mind if I have some more questions. @jsulm, I went through the documentation. Are you referring to QML? Can you be more specific? Thanks. - mrjj Qt Champions 2016 @pdsc_dy Hi You got QScript with is an older scripting tech. Its very solid but no longer maintained. javascript. Then you got QML. Its the language of the Mobile generation and allows to build GUI too. It can also contain javascript and you can make it possible for user to define new functions etc and run it from c++. In c++ you can read values and such. Values can also be accessible to the QML part. You can even allow users to define new GUI for a function if you want so it can accept user input by itself. Its very dynamic. @mrjj, Thank you for your advice. Alternatively, is it possible for me to generate the functions using user's input and dump them in a library or resource file? In this case, I think I need to have two sub projects. The first one needs to be compiled and run to populate the libraries, and the second one use the libraries to finish up the run. By doing that would I avoid embedding the QML graphics in the widgets, which seems to be hard? Thanks! - mrjj Qt Champions 2016 Hi - dump them in a library or resource file Since you will be using javascript. Its just pure text files and need no compilation so it would be easy to save to file and use as lib. Note that QML is not compiled. it can run as it. So user can make a js function and the c++ app can run it. import QtQuick 2.0 Item { function someUserFunc(Obj) { var len = Obj.Variables.length; for (var i = 0;i < len; i++) { var c=Obj.Variables[i]; ... } } Thanks! I went through the QML / quick documentation and tried out some examples. There is quite a bit to learn but it seems very flexible. My main confusion is how to use QML/Quick from QWidget. I will need to include the merge the quick forms with widgets, and use the input from quick forms to populate a library. This may not be a fair question as it seems quite general. Can you point me to some documentation for this? Also do I have to use JS? Is it possible to use subproject and have the earlier sub project generate and compile the library first, and use it later for the main calculation, all using c++ and widgets, without using QML? Thanks again for taking the time to help me. - mrjj Qt Champions 2016 @pdsc_dy Hi If you dont use js/QML, then you would need to supply a compiler with your app to compile the user functions to a dll or something like that. Will get pretty complex fast.
https://forum.qt.io/topic/74490/seeking-suggestions-on-a-form-that-allow-users-to-pass-coding-to-the-application
CC-MAIN-2017-51
refinedweb
634
83.46
This site has been created By <?xml:namespace prefix = o Maya Vinod, 39, female, Indian, housewife living in Doha ¶ Qatar. [more] Topics frequently discussed: doha penpal, indian housewives, living in qatar, maya com, maya indians, mount carmel college, qatar living, qatar living, qatar living com, qatar living doha A group of Art of Living Followers in Doha Qatar. Discuss your experience of "Sudarshana Kriya" and share your ideas.[more] Topics frequently discussed: doha qatar, doha qatar, living in qatar, qatar doha, qatar living, qatar living, qatar living doha Welcome to Qatar!!! Welcome to Malaysians Qatar Yahoo Groups!!! This is a mailing list for all Malaysians residing in Qatar. The objective of this Yahoo group is to establish constant communications and strengthen relationships among Malaysians currently residing in Qatar. This is a place where Malaysians in Qatar are free to exchange and share information, get to know your other fellow count… [more] Topics frequently discussed: among other things that happened, bear in mind, become acquainted with, best country to live in, constantly updated with, constantly updated with, doha qatar, doha qatar, embassy in malaysia, gov malaysia, gov my, gov.my, http www gov my, in gov org, kln gov my, living in qatar, malaysia embassy, malaysia gov, malaysian embassy, more information please visit, most widely recognized, my gov, my gov, please improve this, qatar doha, qatar embassy, qatar living, qatar living, qatar living doha, send your suggestions, sos in gov, state of qatar, things to do doha qatar, what country would you like to visit, widely recognized that, www embassy, www gov it, www gov my, www gov qa, www kln gov my, www qatar, www qatar living, www sos gov, www sos in gov, www we the people org This is the website of Alumni of NSS College of Engineering Palakkad living in Qatar.Lets use this for effective communication among ourselves and keep it active by posting messages , uploading photos conducting polls etc.Your moderators are Mohammed Riyaz / Arun B.M. You can change your email ID by yourself if logged in through yahoo profile. Still you need any assistance please contact either R… [more] Topics frequently discussed: college assistance, living in qatar, log in yahoo, post university m b a, profile when logging, qatar leaving, qatar living, qatar living, qatar university, schools in qatar, universities in qatar, yahoo log in Dear fellow South Africans Due to complains from some Yahoo users this page will be closed with immediate effect. No more messages will be moderated and the groups will be closed. All enquiries or future adds should be reffered to the SA website. Thank you for all the support during the 8 years that we operated from the groups.[more] Topics frequently discussed: living in qatar, qatar living, qatar living Dohanaija is a gathering of Nigerians resident in Qatar who are willing to associate with each other socially and is a non-religious and non-political association with no intention to sway or influence anybody ²s political and religious views, or alter their religious, cultural or social values or ways of life. The aims and objectives of the community are as follows: 1. Promote unity, love and … [more] Topics frequently discussed: achieving their personal goals, associated with each, federal republic of nigeria, living in qatar, nigeria time, qatar government, qatar living, qatar living, qatar living com, qatar time, secretary general yahoo com, state of qatar, sway 1, time in qatar, ways religious life, who will be secretary of state Life is a blessing. Being single is a phase in our spiritual journey where we experience the freedom of living life and defining what life is worth living. This is found in having Jesus Christ as our pursuit in this spiritual walk and having similar individuals as our companions in this journey. God's Gift is everywhere and is ever present. Let us celebrate this blessing and gift. Qatar - in… [more] Topics frequently discussed: define christ, define freedom, living in qatar, qatar journey, qatar living, qatar living, singles for christ THIS GROUP IS FOR ALL LADIES LIVING IN THE QATAR/DXB AREA LOOKING FOR DISCREET 1-1 RELATIONSHIP WITH NO STRINGS ATTACHED AND NO HASSELS. NOTE: IT IS PREFERED THAT PEOPLE WITH HEART CONDITIONS DO NOT APPLY FOR MEMBERSHIP ;)[more] Topics frequently discussed: conditions that apply, discreet relationship, favour, heart strings, living in qatar, qatar living, qatar living, single ladies qatar This is a group for expats from anywhere in the world who are currently living in Qatar. This list will be conducted in English. This is the place to discuss any and all things relating to life in Doha (or Messaieed, or Ras Laffan - wherever you live, if you are in Qatar, you are welcome!). There are so many of us here; we need to talk! Because many of the folks who gather in Doha are famiil… [more] Topics frequently discussed: living in qatar, qatar living, qatar living, qatar living doha, ras laffan, smoothly, speaking in english tips, speaking in english tips An Indian Expatriate community board for sharing information, guidance, Fulltime/Part time Job search, Personal development, hobbies and assistance for better living in Qatar. So, go ahead be a part of this fine group.[more] Topics frequently discussed: expatriate jobs, expatriate jobs, job in qatar, jobs in qatar, jobs in qatar, live in assistance, living in qatar, qatar, qatar, qatar job, qatar jobs, qatar living, qatar living, qatar time, time in qatar ei...mga kasangga, brothers and sisters...this group is for CFC YFC Qatar chapter! spread Gods LOVE! yun lang....whahahahahahaha!!!. multiply site: http:… [more] Topics frequently discussed: brother yun, qatar living, qatar living, qatar living com DEAR SINDHI FRIEND THIS GROUPS IS FOR ALL SINDHI'S LIVING IN QATAR. YOU CAN SHARE AMONG MEMBERS ABOUT SINDHI CULTURE, JOKES, SHARE GOOD THINKINGS, PHOTOS OR ANYTHING YOU WANT TO SHARE AMONG ALL SINDHIS IN QATAR[more] Topics frequently discussed: living in qatar, qatar living, qatar living This group is for "westerners" ie. people from the USA, Australia, England, Ireland, etc. nationalities living in Doha, Qatar. I would like the group to be a place to meet other expats, find jobs, places to live, places to hang-out, organize outings, etc. Please keep the political and religious messages to yourself, unless it directly affects the members living in Doha. There are few ru… [more] Topics frequently discussed: doha, doha, doha qatar, doha qatar, find job in australia, find job in qatar, it jobs in qatar, job in qatar, jobs in doha qatar, jobs in qatar, jobs in qatar, living in qatar, qatar doha, qatar job, qatar jobs, qatar living, qatar living, qatar living doha Welcome to the Alpha Sigma Phi Alumni Association of Qatar! Here you will find the latest activities of the alumni association around Doha, Qatar, including members directory, uploaded files, photos, reports, other reference documents and links to Sig sites; and more! We're one of the most active and progressive Alumni Associations anywhere, with events for all interests, families, friends an… [more] Topics frequently discussed: alpha com, alpha sigma, alpha sigma phi, alpha sigma phi philippines, directory of family associations, directory of members philippines, doha qatar, doha qatar, living in qatar, official information directory, personal directory information, philippines school doha, qatar, qatar, qatar com, qatar doha, qatar living, qatar living, qatar living com, qatar living doha, schools directory with full school profiles, schools in qatar, sigma com, work in qatar Here,is a group,which could be a great success,It's for paki girls living in Qatar,or at least girls who have some pakistani connection to them,I have deep rooted respect for them,and want them to come together on a format.!! Would help you get new friends. Iam sorry,membership is open only to girls!! [more] Topics frequently discussed: living in qatar, paki girls, pakistani girl, pakistani girls, pakistani girls, qatar living, qatar living ************************** VERY IMPORTANT ************************** WE ARE MOVING THIS GROUP TO GOOGLE GROUPS. SHORTLY THIS GROUP WILL BE INACTIVE FOR ALL ACTIVITIES, THOUGH IT'S HIGHLY RECOMMENDED YOU JOIN OUR NEW GROUP AT BUT IF YOU DECIDE OTHERWISE, IT'S YOUR CHOICE REGARDS, MODERATOR ************************** Here you will find plent… [more] Topics frequently discussed: engineering jobs in qatar, field service engineer jobs, find date of birth, find job in qatar, find jobs from, find jobs in uae, gmail from google, google com religion, google job opportunities, google religion, google uae, gulf jobs, inshallah, it jobs in qatar, job in qatar, jobs in doha qatar, jobs in qatar, jobs in qatar, let me google that for you, living in qatar, more jobs in uae, nationality of names, qatar com, qatar job, qatar jobs, qatar living, qatar living, qatar living com, qatar living doha, that best fits, that fits best, what is a google number, what job is best for me Mahal is a group of Kerala Muslims living in Al Khor Housing Community in Qatar. Mahal is involved in various socio-religious activities. Currently, there are 51 families + 1 bachelor as members.[more] Topics frequently discussed: living in qatar, mahal, qatar living, qatar living For the love of being in this country, for the love of the living and eatting'n drinking in this country and for the love of loving in this country.just being all together..whenever'n wherever forever our memories'n secrets will be here in Qatar... [more] Topics frequently discussed: eatting, for love of country, just being together, living in qatar, qatar living, qatar living Hi, This is a forum of MITians living in Qatar, to share their views and touch base with old batch mates and fellow MITians. If you are a MITian living in Qatar, You are welcome to join the forum. Enjoy being in the family of mighty MITians. Best Regards, J.Balu [more] Topics frequently discussed: living in qatar, qatar living, qatar living, qatar university, schools in qatar, universities in qatar GOWDA SARASWATH BRAHMAN ( AMCHIGELE ) IN QATAR Priya samaja bandhavanka saprema namaskaru, This is an invitation to join the GSB Sabha Qatar yahoogroups. Please be informed that to have a common platform to exchange information, views and communication on the GSB Sabha Qatar activities I have created a "GSB SABHA QATAR" yahoogroups E-mail ID "gsbsabha_qatar@yahoogroups.com"… [more] Topics frequently discussed: living in qatar, qatar, qatar, qatar government, qatar living, qatar living, work in qatar this club is made mainly for Danish people living in Qatar or someone in Denmark that knows anyone that lives here in Qatar. The club is mainly made so you can chat to your friends, or just to waste your boring day-time.[more] Topics frequently discussed: living in qatar, qatar living, qatar living, qatar time, time in denmark, time in qatar This group is all about the lonely story and experiences of Filipino supervisors working in DOHA,QATAR. They are the most lucky guys that were chosen to work for DOHA, unfortunately with all the blessings and richness they had, they still live as virgins of DOHA. Inshala we will not lose our hope for the quests of the LAMAN LOOB.[more] Topics frequently discussed: doha qatar, doha qatar, filipino stories, qatar doha, qatar living, qatar living, qatar living doha, virgin stories, work in qatar The aim of this group is to deepen the relations between egyptian citizens live and worl in qatar, to transfer knowledge and break the feel of loneliness.[more] Topics frequently discussed: living in qatar, qatar, qatar, qatar living, qatar living We are members of Triskelion Grand Fraternity that are not SELFISH. We will always fight for what is right for the fraternity, family and most of all GOD! We will strive for the betterment of all TRISKELION worldwide and especially the TRISKELION in Qatar. We will not limit ourselves by helping only our fellow Triskelion but to be an integral part as well of the community where we live in. We … [more] Topics frequently discussed: living in qatar, qatar living, qatar living, triskelion grand fraternity Qatar is really beautiful and interesting country!! This is the right place to meet Malayali brothers and sisters who is living in Qatar. Let's share our feelings and hold our hands together to build up a "GOD'S OWN CULTURE" here in this Golden land..... Come & be a part. Our objectieves:- (1) Support each other. (2) Share thoughts & Experiences. (3) Discuss what we … [more] Topics frequently discussed: 2 for each and 1 in hand, living in qatar, malayali, qatar, qatar, qatar living, qatar living Qatar Pinoy Riders is a motorcycle club dedicated to all Filipino motorcycle enthusiasts living in Qatar.[more] Topics frequently discussed: living in qatar, motorcycle riders, qatar living, qatar living, riders club site. For other discussions related to AMU and global Alig community please subscribe to AMU Network (… [more] Topics frequently discussed: amu com, living in qatar, qatar com, qatar living, qatar living, qatar living com The group is the Forum for discussions among Pakistani expatriates working and living in Doha Qatar and have social relations with each other's family.[more] Topics frequently discussed: living in qatar, pakistani forum, qatar living, qatar living, qatar living doha, work in qatar this is for whom living in Qatar and need to set up a great friendship rather than sharing experience gained while living here. Hope everybody in this group be elegent and desent enough to be memorable by all along the time. the freindship here shall be made with all regardless of what nationallity, religion, etc.. one belong/ have. whish you all enjoy and have a good time. Best regards, [more] Topics frequently discussed: desent, living in qatar, qatar living, qatar living, qatar time, time in qatar Mitery Club of Nepal What is the Mitery Club of Nepal? Mitery Club of Nepal is non profit-making a social organization forming with an energetic member ²s executive team to work on Humanitarian voluntarily basis. Actually it has initiated in the beginning of 2000 and came into activate from last of year (2007) in the Kathmandu the capital State of Nepal. Why for the Mitery Club of Nepal … [more] Topics frequently discussed: autonomous organizations working with, basic human needs, born free foundation, capital of nepal, civil service club, club shelter, daily routines, different forms of stress, face cloth, gulf daily, gulf state security, healthcare it security, how to start a social club organization, human services food, living in kathmandu, make healthcare forms, make profit from crisis, officials have activated, profit humanitarian organization established, profit legal advocacy, qatar, qatar, qatar foundation, qatar living, qatar living, self regional healthcare, social security contributions, social services from crisis relief, social welfare services, state of qatar, subsistence, voluntarily, what is contributed capital, what is human capital, what is self advocacy, what is sustainability, with wide range i just wana meet some one in dubai i live in qatar.[more] Topics frequently discussed: living in qatar, qatar living, qatar living FON Qatar - FRIENDS OF NILA Qatar is group of like minded people from Ottappalam & Ponnani Taluks of Kerala working in Qatar. Nila - Bharatha Puzha is our life and we work for a live NILA. Nila is dying because of the continuous misuse of natural sand from it and we are afraid that it may become a story to the next generation. So WE HAVE TO WORK FOR NILA.[more] Topics frequently discussed: nila, qatar air, qatar air, qatar living, qatar living, work in qatar Assalam_Alaikum. Dear Brothers / Sisters, This is your brother Noor Ahmed, inviting you to this new forum, specially built for you. This forum aims to provide an interface for the Muslim expats hailing from North Karnataka (Belgaum, Dharwad, Hubli and surroundings), presently working in Qatar. Let us use this forum as a medium to interact, to share our viewpoints, to dicuss the current issues … [more] Topics frequently discussed: always more than, assalam alaikum, cheer invitations, how to make a forum, how to make invitations, karnataka, living in qatar, more than always, please bring the invitation, qatar living, qatar living, this initiative aims, work in qatar For all natives of kollam who live in qatar[more] Topics frequently discussed: living in qatar, qatar living, qatar living This is the place to unite Tanzanians who are living and working in Qatar. It is a place to meet new people and exchange ideas. We can conquer our problems through unity and support to each other. This is the best place to accomplish this task.[more] Topics frequently discussed: best places to live and work, living in qatar, qatar government, qatar living, qatar living, work in qatar "Keywords: AMU, Aligarh, Aligarh Muslim University, Alumni, AMU Alumni, Qatar, Sir Syed" s… [more] Topics frequently discussed: amu com, amu university, living in qatar, qatar living, qatar living, qatar living com, qatar university, schools in qatar, universities in qatar All you boners in Qatar - Doha who wanna have a bangin time here... come and join the fun... lets make Qatar a fun place to live in... only men / women willing to have meet and have fun should join... [more] Topics frequently discussed: all boner, boner, boner, boners, boners, living in qatar, qatar doha, qatar living, qatar living, qatar living doha, qatar time, time in qatar All expatriate men living in qatar who need to share their feelings/fantasies/love with other men ... meet your friends around you in qatar[more] Topics frequently discussed: living in qatar, qatar living, qatar living Hai Gurl I am looking gurl in qatar any in living qatar plz send phots and contact details. any one want to date with me and romance i am always for his. yours loves khan[more] Topics frequently discussed: living in qatar, qatar living, qatar living The group includes engineers having Pakistani origin and living in Qatar.[more] Topics frequently discussed: living in qatar, pef, qatar living, qatar living HEY! this group is dedicated to all those indians living in Qatar. Plz feel free to post or download anything. and also free to invite as many frends u want 2 add to this group.[more] Topics frequently discussed: east indian culture, east indian cultures, living in qatar, qatar living, qatar living This a social group serving all Kenyans Living in Qatar. [more] Topics frequently discussed: living in qatar, qatar living, qatar living A group of Art of Living followers in Qatar - Middle East.[more] Topics frequently discussed: living in qatar, qatar living, qatar living This is to unite the tamils living in Qatar with an objective to interact with one another share knowleged and to find out employment oppurtunities by helping one another.......and to maintain good relationship in the long run[more] Topics frequently discussed: living in qatar, qatar living, qatar living hi ia iqbal karim age 30 male single, home town bangladesh, living in qatar, i like this site, thanks iqbal karim, post box no 5615 doha qatar, cell 009746720162[more] Topics frequently discussed: iqbal, living in qatar, qatar living, qatar living, qatar living doha This Group is Initiated by Tarek Amer , an Egyptian Computer Systems Engineer working as an IT Manager in Doha - Qatar , this Group is intended to gather all Egyptians Working in Qatar together to form a strong community helping all egyptians to live better in Qatar , affording Information , Orientation , Help and Friendship Chances for all Egyptians , Families and Individuals, I hope we shall be … [more] Topics frequently discussed: doha qatar, doha qatar, living in qatar, qatar, qatar doha, qatar living, qatar living, qatar living doha, work in qatar This Forum is to share Sai related messages, Swami's discouses and photos, service activities, day to day spiritual and other useful informations with members living in Doha-Qatar. This group is to inform the Bhajan Timings and other events for the members who registered in this group. MEMBERSHIP IS FREE. Main objectives: **Spreading Sai life stories and Sai's universal messages for … [more] Topics frequently discussed: living in qatar, photo slide, qatar living, qatar living, qatar living doha, ramayana story, spiritual messages, story of ramayana, the ramayana, the ramayana story, the story of ramayana, universal event photo We are a group of expatriat ladies from many different countries living in Qatar. We meet every second week from Septemer through to June for morning tea, social time and a guest speaker, several times a year we have special events eg: Christmas Craft Fair and brunches for Christmas, Easter and Summer. The group aims to provide an oportunity for Ladies new to town or that have been here for some… [more] Topics frequently discussed: christmas brunch, christmas craft fair, christmas craft fairs, christmas fair, christmas in different country, christmas tea, country christmas crafts, country living christmas fair, crafts for christmas, current time in qatar, easter crafts, living in qatar, many different speakers, new year brunch, qatar living, qatar living, qatar living doha, qatar time, time in qatar A group for the alumni of T.K.M College of Engineering, living in Qatar.[more] Topics frequently discussed: living in qatar, qatar living, qatar living, qatar university, schools in qatar, universities in qatar Privacy Policy - Terms of Service - Copyright Policy - Guidelines - Help - Report Abuse
http://groups.yahoo.com/phrase/qatar-living
crawl-002
refinedweb
3,512
51.11
Dummy implementation of StelGuiBase to use when no GUI is used. More... #include <StelNoGui.hpp> Dummy implementation of StelGuiBase to use when no GUI is used. Add a new action managed by the GUI. This method should be used to add new shortcuts to the program Reimplemented from StelGuiBase. Add a new progress bar in the lower right corner of the screen. When the progress bar is deleted the layout is automatically rearranged. Implements StelGuiBase. Get a pointer on an action managed by the GUI. Reimplemented from StelGuiBase. Show wether the Gui is currently used. This can then be used to optimize the rendering to increase reactivity. Implements StelGuiBase. Show whether the GUI is visible. Implements StelGuiBase.
http://www.stellarium.org/doc/0.11.0/classStelNoGui.html
CC-MAIN-2015-27
refinedweb
117
69.28
Factory Design Pattern - An Effective Approach Factory Design Pattern - An Effective Approach As you might know, the Factory Method Pattern, popularly known as the Factory Design Pattern, is a design pattern categorized as a "Creational Design Pattern." Join the DZone community and get the full member experience.Join For Free Java-based (JDBC) data connectivity to SaaS, NoSQL, and Big Data. Download different methods. Some are better than others. In this article, I will show you what I think is the best way of designing a Factory Design Pattern. Technicalities As said before, we will get a similar type of object at run-time in case of factory design so that underlying implementation of object will be behind the screen, let us consider a simple approach. Let us consider a Person object. This object can be either Male or Female. At run-time we should only consider the behavior, not the gender. By rules of the traditional approach, we create a Person interface and then two implementation classes like MalePerson and FemalePerson. Given the run-time gender data, we pass to a Factory method of a Factory class and decide whether the gender type is Male or Female. We then create the instance of the particular class and return the reference type object accordingly. This approach sounds good and we adopt it in many developmental activities. Can we ensure that it is the effective approach in fine-grained, multi-threaded applications, though? What about the performance ? Is there any other approach? Fortunately, the answer is yes. Let us consider the real-time example of an organization where an employee can be a CEO, CTO, CFO, Developer, Test Engineer, HR, Personnel, Security, etc. If you want to know the role of an employee based on the organization, what will you do ? How will you create a better factory design so you can easily find the role without any performance penalty? Will you adopt the same traditional approach by providing multiple If clauses? You might argue that we should use the switch condition. Fine. Let's forge onward with the traditional approach and record the time it takes. Let us employ our factory design in a traditional manner. package com.ddlab.rnd.patterns; /** * @author Debadatta Mishra(PIKU) * */ public interface Roles { public String getRole(); } The above interface is used as a type. There can be various types of roles in the organization. One of its methods- "getRole()"- specifies the description of the role of the employee. With this we generate; } } Now let us write a simple harness class as a (and just so you know, my system has 4 GB of RAM and an I5 processor): Role ::: CEO is the supreme head of the companyTime difference ::: 3477574 nano seconds The above design seems to be correct, but what about performance? You may say it does not matter because it comes in terms of nano seconds. Sure, it doesn't matter, provided that your application is very small, but with large enterprise applications it's very important. If you are a good programmer or developer, you cannot ignore the performance issue, particularly in the case of product development where there may be similar products in the market. To address the above issue, let us try another approach of factory design where there may be changes in the factory class. Take a look at this next block harness class we've tested is shown below: package com.ddlab.rnd.patterns; import java.util.HashMap; import java.util.Map; /** * @author Debadatta Mishra(PIKU) * */ public class TestFactoryDesign { static Map typeMap = new HashMap();'s compare the time taken between the traditional approach and the modern approach. Can you think about the time difference? It's just about three times faster than the traditional approach. Which is better then? Of course the modern approach of using enum is. Apart from enum, I have used Map to maintain the list of employee type and its corresponding enum. In this case, the If clause isn't needed, which may impact our performance as far as cyclomatic complexity is concerned. It is always better to use the above approach of 1049108 nano seconds. You can use ConcurrentMap for your multi-threaded application. Conclusion So that's my article on factory design pattern. I hope you enjoyed it, and if you are confused at all, please contact me at debadatta.mishra@gmail.com. Connect any Java based application to your SaaS data. Over 100+ Java-based data source connectors. Opinions expressed by DZone contributors are their own. {{ parent.title || parent.header.title}} {{ parent.tldr }} {{ parent.linkDescription }}{{ parent.urlSource.name }}
https://dzone.com/articles/factory-design-pattern
CC-MAIN-2018-51
refinedweb
766
56.76
This post is intended to be a guide on the meaning of and distinction between several related concepts. What makes them related is that they're all pretty abstracted; they all feel sort of "up there". This also makes them unusually easy to confuse. These ideas are fairly important if you're going to try to understand similarly "up there" domains like mathematics, computer science, or AI. But they're also just really fun! Another thing that unites them is that uses of them feel somehow tricky or clever. Sometimes it's for play and puzzles, and sometimes it's the crux of an astounding theorem. I'm not a linguistic prescriptivist, so I'm not intending to declare that these words should mean exactly these things for the rest of time. But I am something of a conceptual prescriptivist, in the sense that I think reality has joints to be carved; I think all of the below words refer to concepts that are clearly distinct and useful, and deserve their own words. I hope this guide is helpful in clarifying any latent confusions that people may have had! Summary Meta The word "meta" has a somewhat strange and meandering history. It started out as a technical term, but has become somewhat common in everyday use.[1] It originally was (and still is) a greek prefix meaning something like "after", and there happened to be a chapter of a book of Aristotle named "Metaphysics". This initially meant "the book after the book about physics", but people apparently mistakenly inferred the meaning of meta from the contents of the book instead. The fact that it now has other meanings in narrow contexts, paired with the fact that its most common meaning is somewhat esoteric, means that it's often used incorrectly. In its modern usage, a meta-X is an X about X[2]. A meta-book is a book about books. If you take the conversation meta, then you start talking about conversations.[3] Metadata, like a timestamp or file size, is data about data. Metaprogramming is code that modifies other code (and is therefore programming about programming) and metamathematics proves theorems about whole axiomatic systems (and is thus math about math). Unknown unknowns are meta-epistemological. It is the trendiness of this word that gave me the idea for this post; I have heard people use "meta" to mean every other word listed here! I personally care a lot about sorting concepts correctly, so years ago I installed a TAP where the trigger is "I hear or use the word meta" and the action is "ask myself if this is an X about X". Self-reference This one is really easy to remember because it's just two separate words whose meanings are clearer. X is self-referential if X refers to itself. (An obligatory example is that this sentence references itself, and so does this post.) However that simplicity belies its usefulness. Applying the concept has led to the discovery of many paradoxes which themselves have led to whole branches of mathematics. Embedded agency is closely related to self-reference. AIXI has no concept of itself, and thus cannot entertain hypotheses or plans involving itself. Specifying intelligent systems which can conceptualize themselves is an active area of research. Recursive X is recursive if it somehow "uses" an instance of itself. The most frequent context in which I've heard this is recursive functions, which call [another instance of] themselves somewhere inside their function definition. For example, here's the classic recursive factorial function defined in python. Note the token factorial appearing twice. def factorial(n): if n <= 1: return 1 else: return n*factorial(n - 1) Math also has recursive functions, where the value of a function for some inputs is defined in terms of the same function at other inputs. It is structures like these that give rise to proof by induction, which shares the mind-bendy nature of the other concepts in this post. I think it would be fair to say that these functions are also self-referential, but they don't merely reference themselves, they in some sense actively use themselves, and they also rarely use the same instance of themselves; otherwise the recursion would not terminate, and there would be an infinite loop or cycle of some kind. A recursively self-improving AI is an AI that uses itself to make another, improved instance of itself. The word "self" is there to distinguish it from AIs that recursively improve something else. If an AI uses a factory to manufacture better parts for some machines in the factory, then it is a recursively factory-improving AI. Just about every modern machine learning system will use recursion heavily, such as Monte Carlo tree search and reinforcement learning. Generalization Concept X is a generalization of concept Y if X is just Y with some specific features removed. Often, as on wikipedia, definitions are given in so-called genus-species form. For example, "The horse is a domesticated, odd-toed, hoofed mammal". That is to say, a horse is a specific kind of mammal, namely a kind with hooves etc. If we remove those specifics, then we just end up with mammal. Thus, "mammal" is a generalization of "horse". You could also remove the "mammal" part and keep the "odd-toed" part; "odd-toed things" is another valid generalization of horses. The generalization "abstractions away" these specifics, and thus the word "abstraction" is often used synonamously. In math, numbers represent a generalization of things with that quantity; the number 4 is a generalization over 4 apples, 4 letters, 4 seconds, etc. Algebra uses variables to generalize over specific numbers, and abstract algebra, well, abstracts over sets of stuff that obey certain axioms. Fields of mathematics are virtually defined by their place on a big hierarchy of generalizations, because if you have proved something using only a certain collection of properties (the specifics), then you have proved it about everything that has those properties. In programming, the object-oriented concept of a class hierarchy most cleanly maps onto generalizations. For example, maybe one class Record defines an abstraction around database records in general, while a subclass User of it denotes a user record, which has the specific properties of an email and a password. A lot of the field of AI has been about figuring out exactly how we can get machines to represent these hierarchies of concepts. Deep neural networks seem to be doing a pretty good job. That said, I don't know if ML researchers ever actually work with the definition I gave above, or if they just look at classification performance and think to themselves, "it sure does seem to have captured the general concept of a cat". You could say that the difference between self-reference and meta is that meta references the genus of the self. A book about itself is a self-referencing book, but a book about books is a book about the genus of which itself is an instance. Repetition We're getting down to the crumbs now, but there are still simpler things that I've heard people use the word "meta" for. Repetition is basically what you're left with when a concept is used multiple times, but it's not any of the above concepts. "She sells sea shells by the sea shore" feels like it's doing something weird and clever, and that weird and clever thing is just repeating slightly shifted around phonemes. Other-than-X This is the most distant use of the word meta that I've noticed in the wild. People will sometimes be talking about a topic X, and then they'll start going on a tangent, and then they'll say something like, "okay this has gotten a little meta, let's get back to the main topic". Or maybe in a conversation they'll say "I have a meta question, where is the bathroom?" The question is not about questions, and it doesn't make the conversation be about conversations. It's just, a question that was not about what the conversation was about. Blurry boundaries The distinctions I've drawn between these concepts relies on english verbs like "uses", "references", and "is about"[4]. Thus, there is a noticeable grey area. Consider the look-and-say sequence. Start with 1. Then describe how many of each digit there are; one one. Then make that into digits; 11. Now there are two ones; 21. Now there is one two, one one; 1211. One one, one two, two ones; 111221. Et cetera. Does each term in this sequence "refer" to the previous term, or does it "use" the previous term, or is it merely "repeating" the previous term with a modification? I wouldn't fret about it. If you're in a context where the distinction matters, then that context will likely provide a more precise definition to check against. - ^ In this it reminds me of "random", which colloquially often just means "arbitrary" or "unwanted" or "not appropriate to the context". - ^ The popularization of this meaning is credited to Douglas Hofstadter's Pulitzer-winning Gödel, Escher, Bach. - ^ Often people will "go meta" by talking about the specific conversation they're already having. In this case, they're also going self-referential, but fortunately it's also going meta, so it's not a terribly inaccurate usage. - ^ Is this a verb? I'm not really a grammar person. I don't think it's syntactically a verb, but it seems to have the same semantic role as the other verbs. I'm also not deeply a grammar person, but in "is about", "is" is definitely a verb. That's the part that would conjugate (I am about, you are about, he/she/it is about). So I guess "about" is an adverb modifying the verb; or possibly "is about" in combination is a verb phrase. I find the word "meta" has been frequently used in a different connotation. Very often it does not mean "an X about X", but simply "look at X (itself) from a higher-level, outsider perspective". The first word that jumps into my mind is "Meta-ethics". It is less of "the ethics of ethics" but more of "what does ethics itself mean?", akin to the later use of the word "meta". Personally, I would love it if these meanings are expressed by different words. But language is a tricky thing that involves too many things besides strict definitions. Agree! That's part of what I meant by "The fact that it now has other meanings in narrow contexts...". I would guess that "meta-ethics" specifically is in analogy to metaphysics, though I couldn't verify that with a quick google. I'd be very happy about a similar explanation of the words converse/inverse/reverse/dual (I remember there being more I was confused about, but apparently didn't write them down). Mm, that does sound similar. Though my intuition says that those words are even more blurred. I think they often have precise meanings in technical contexts, but otherwise I'm actually not sure that I connotively distinguish most of them.
https://www.lesswrong.com/posts/gQ5eQjRTY87LpjhQv/when-to-use-meta-vs-self-reference-recursive-etc
CC-MAIN-2022-33
refinedweb
1,877
62.27
You can subscribe to this list here. Showing 3 results of 3 Hi, I'm sorry about my reply is late. I was busy current two weeks. On Tue, 18 Nov 2008 16:49:43 +0900, Bernd Holzmüller <bernd.holzmueller@...> wrote: >? Please show your important functions list. If we can add them easily, we'll add them before 0.11 release. But some functions are not easy to support. I think BeginSuppressUndo and EndSuppressUndo are wxRichTextBuffer class functions. wxHaskell doesn't support support wxRichTextCtrl and wxRichTextBuffer currently, so we can't support soonly. I planed to add some classes support after 0.11 release, so please wait next next version. > Or is there an easy way to make these functions available in my > application right now? If you're using unix platform, you can add these function easily. See this thead. But I think you're using Windows platform, so you can't add functions easily. If you want to make patches for soving your problem, please see my fixed version of above thead's functions. Best Regards, -- shelarcy <shelarcy hotmail.co.jp> Hi all,? Or is there an easy way to make these functions available in my application right now? Thanks, Bernd Hi Jules, I added your function with some changes (e.g. rename functions and use auto-generated haskell function instead of hardcode function) in the darcs repositoy. Please check these functions. If there is a bug in these functions, please send us tiny example. Because I want to fix that before wxhaskell 0.11 release when these functions have bug. Best regards, On Sat, 29 Mar 2008 20:04:55 +0900, Jules Bean <jules@...> wrote: > So, I have successfully added some of the missing bindings that I needed. > > The code is so short that I embed it in this email. I'd be interested > to hear any comments on the way I did this, and what you would want to > change before committing it to wxhaskell. > > 1) Loading images from in-memory blocks > > Stub C++ file to bind to the appropriate wxImage constructor: > > #include "wx/wx.h" > #include "wx/image.h" > #include "wx/mstream.h" > > extern "C" > { > void * wxImage_CreateFromFileInMemory(void* data,int length,int type) { > wxMemoryInputStream in(data,length); > return (void*) new wxImage(in,type); > } > } > > You can compile this with "g++ -c `wx-config --cppflags` cstub.cpp" > > Then a haskell stub file to wrap a Ptr version of this and two > bytestring versions: > > {-# OPTIONS -fglasgow-exts #-} > module ImageExtras where > > import qualified Data.ByteString.Lazy as LB > import qualified Data.ByteString as B > import Foreign > import Foreign.C > import Graphics.UI.WXCore.WxcTypes > import Graphics.UI.WXCore.WxcClassTypes > > imageCreateFromPtrFile :: Ptr b -> Int -> Int -> IO (Image ()) > imageCreateFromPtrFile ptr len typ > = withManagedObjectResult $ > wxImage_CreateFromFileInMemory ptr (fromIntegral len) (fromIntegral > typ) > foreign import ccall "wxImage_CreateFromFileInMemory" > wxImage_CreateFromFileInMemory :: Ptr b -> CInt -> CInt -> IO (Ptr > (TImage ())) > imageCreateFromLBytestringFile :: LB.ByteString -> Int -> IO (Image ()) > imageCreateFromLBytestringFile bs typ > = withArray (LB.unpack bs) $ \ptr -> > imageCreateFromPtrFile ptr (fromIntegral $ LB.length bs) typ > > imageCreateFromBytestringFile :: B.ByteString -> Int -> IO (Image ()) > imageCreateFromBytestringFile bs typ > = withArray (B.unpack bs) $ \ptr -> > imageCreateFromPtrFile ptr (B.length bs) typ > > I'm not sure if you can make these a bit more efficient by attacking > the underlying bytestring rep, but I didn't try. > > It works, anyhow. I am able to load images from bytestreams (as it > happens, the cover art from an M4A file). The magic invocation to get > ghc to link it correctly seems to be: > > ghc --make main.hs cstub.o -lstdc++ `wx-config --libs` -optl -fexceptions > > 2) GetOption / SetOption for Images > > Slightly more fiddly. The C++ stub looks like this: > > #include "wx/wx.h" > #include "wx/image.h" > > extern "C" > { > void wxImage_SetOption(void *_obj, void* key,void *value) { > ((wxImage*)_obj)->SetOption((wxChar*)key,(wxChar*)value); > } > wxString* wxImage_GetOption(void *_obj, void* key) { > return new wxString(((wxImage*)_obj)->GetOption((wxChar*)key)); > } > } > > (it took me quite a while to understand why casting to wxChar* works > when the underlying type is WxString&; there is an implicit conversion > because of a constructor) > > The haskell stub is this: > > {-# OPTIONS -fglasgow-exts #-} > module ImageOptions where > > import Graphics.UI.WXCore.WxcTypes > import Graphics.UI.WXCore.WxcClassTypes > > imageSetOption :: Image a -> String -> String -> IO () > imageSetOption _obj key value = > withObjectRef "imageSetOption" _obj $ \cobj -> > withCWString key $ \cstr_key -> > withCWString value $ \cstr_value -> > wxImage_SetOption cobj cstr_key cstr_value > foreign import ccall "wxImage_SetOption" wxImage_SetOption :: > Ptr (TImage a) -> CWString -> CWString -> IO () > > imageGetOption :: Image a -> String -> IO String > imageGetOption _obj key = > withManagedStringResult $ > withObjectRef "imageGetOption" _obj $ \cobj -> > withCWString key $ \cstr_key -> > wxImage_GetOption cobj cstr_key > foreign import ccall "wxImage_GetOption" wxImage_GetOption :: > Ptr (TImage a) -> CWString -> IO (Ptr (TWxString ())) > > > 3) Points of confusion: > > For return types of type String, looking at the examples in elj*.cpp, > why does it sometimes use copyStrToBuf to unpack the WxString on the > C++ side in combination with withWStringResult on the haskell side, > and other times just pass back the a freshly allocated WxString* from > C++ in combination with withManagedStringResult? > > For arguments of object types, why do some bindings use withObjectPtr > and some use withObjectRef? > > What's the EXWXEXPORT() macro for? It didn't seem very useful to me... -- shelarcy <shelarcy hotmail.co.jp>
http://sourceforge.net/p/wxhaskell/mailman/wxhaskell-users/?viewmonth=200811
CC-MAIN-2014-41
refinedweb
840
50.12
Agenda See also: IRC log <trackbot> Date: 02 September 2010 <DKA> Scribe: Dan <DKA> ScribeNick: DKA Resolved: minutes of 19th approved Noah: Call for next week is at risk depending on getting agenda / chairing set up... hrm Noah: on Webapps - I want to make some progress in September. Any thoughts? <noah> Let me state a bit more forcefully on WebApps: I don't think our level of investment and rate of progress has been consistent with our agreement that significant writing on WebApps would be one of our major goals for the year. <noah> I intend to work with TAG members in Sept to see whether serious writing can be done in time for discussion at the F2F. <Zakim> ht, you wanted to ask for a session on 3987 Henry: I support face-2-faces... Larry: In the last week, the IETF area directors have got together with the wg chairs to push the work forward. Henry: I feel we can't usefully respond to Roy without knowing if your idea for re-architecting the situation has support. Larry: The problem is: there's some work that needs to get done to resolve the differences between what the specs currently say and what really happens and what should happens... ... also there is a venue discussion (w3c-whatwg-ietf). ... or the unicode consortium... <ht> LM, last spring during an MIT TAG meeting we walked together to the pub, and you described your ideas for reworking the whole idea of URI grammar Larry: the only rational way of making progress is to start doing some of the work... <noah> ACTION-409? <trackbot> ACTION-409 -- Henry S. Thompson to run Larry's plan for closing IRIEverywhere by the XML Core WG -- due 2010-06-22 -- PENDINGREVIEW <trackbot> <noah> ACTION-410? <trackbot> ACTION-410 -- Larry Masinter to let the TAG know whether and when the IRIEverywhere plan in HTML WG went as planned -- due 2010-11-01 -- OPEN <trackbot> <noah> ACTION-448? <trackbot> ACTION-448 -- Noah Mendelsohn to schedule discussion of on 26 August (followup to 24 June and 12 August discussion) -- due 2010-09-28 -- OPEN <trackbot>. ... Roy's point was slightly different. <noah> is about URL processing in HTML Noah: Happy to see people pushing on substantive work leading up to the f2f. I have put action 409, 410 and 448 into the IRC - Henry can you comment? Henry: I think 409 is done. Noah: any objections? [none heard] <noah> close ACTION-409 <trackbot> ACTION-409 Run Larry's plan for closing IRIEverywhere by the XML Core WG closed <masinter> The IETF IRI working group chairs have indicated that they're going to start going through issues .... I hope that will result in making some progress <noah> HT: They have replied to us action-410? <trackbot> ACTION-410 -- Larry Masinter to let the TAG know whether and when the IRIEverywhere plan in HTML WG went as planned -- due 2010-11-01 -- OPEN <trackbot> Noah: Do we need any new actions? Henry: No. I want a session at the f2f to hear from Larry about this. ... [of IRI bis status and the status of larry's proposal] <noah> ACTION: Noah to schedule F2F discussion of IRIbis status and Larry's proposal due: 2010-10-05 [recorded in] <trackbot> Created ACTION-459 - Schedule F2F discussion of IRIbis status and Larry's proposal due: 2010-10-05 [on Noah Mendelsohn - due 2010-09-09]. Noah: anything else on oct f2f? Privacy workshop report: DKA: See workshop report link DKA: Workshop headlines: 1) very well attended, some reported it as most comprehensive in 5 years. DKA: Participation from academic groups, good representation from IETF DKA: We discussed need for better coordination between the IAB and the TAG...look for better progress now that summer is over DKA: There was lots of focus on device APIs. What's been learned from geolocation api deployment. Should privacy information be carried along with device data (e.g. location) in the context of an API call. Also a UI dimension. DKA: Privacy questions may have to be asked at time that user is asked for permission to collect data. DKA: We also discussed "privacy rulesets", presented by ????. Creative commons-like model that allows users to pick from standardized options for privacy settings. DKA: Can link a license for that piece of data, the link being carried along in user agent and onward into the network. Can indicate preference for allowing 3rd party access, etc. DKA: In summary, it was a very good opportunity for discussion. We probably achieved somewhat less consensus than I hoped, but the topics discussed were very pertinent for the DAP F2F that followed immediately after the workshop. Chairs reported it was valuable. DKA: Next steps are that we need to figure out coordination between TAG and Internet Architecture Board. I could take an action. <noah> ACTION: Appelquist to coordinate with IAB regarding next steps on privacy policy [recorded in] <trackbot> Created ACTION-460 - Coordinate with IAB regarding next steps on privacy policy [on Daniel Appelquist - due 2010-09-09]. <noah> ACTION-460 due 2010-09-14 <trackbot> ACTION-460 Coordinate with IAB regarding next steps on privacy policy due date now 2010-09-14 DKA_> <DKA_> ScribeNick: DKA_ Noah: Are you [dan] or is someone else willing to take on a writing assignment about "what the tag wants to tell the world about API design issues for webapps or something smaller like policy..." <noah> . ACTION: Appelquist to draft "finding" on Web Apps API design <noah> ACTION: Appelquist to draft "finding" on Web Apps API design [recorded in] <trackbot> Created ACTION-461 - Draft "finding" on Web Apps API design [on Daniel Appelquist - due 2010-09-09]. <noah> ACTION-461 due: 2010-10-11 Tim: [+1 to Noah's comments on producing substantive findings] Noah: Roy's finding on authoritative metadata is a good example of a good finding. Noah: I thought the idea was to have it at our f2f on the west coast... ... I've had some reservations... DKA: I took action to look into logistics. Raman seemed a bit negative, so I went looking for alternate hosts who migh contribute space. DKA: Goal is/was co-location with TAG meeting. Actually spoke with Carnegie Mellon West, but they couldn't manage it either. DKA: At this point, I'm not sure how much energy I have to push this forward. <noah> Chair is curious whether anyone else thinks this is high value? <noah> We need to settle soon so travel can be arranged. <noah> We also need to reach out to other attendees. <noah> I remain somewhat skeptical, but maybe I'm being too conservative. <johnk> I still think it's a good idea, but I don't have the time to do anything any more prior to October Tim: We could pick well-known established architects and/or people who have been making decisions that we care about... Noah: What kind of format and invite list would you have in mind? Tim: For format: maybe get people we don't know to present what the most important properties that we haven't mentioned in the architecture document? Noah: Invitation-only? Or open to anyone who signs up? ... Day-long thing? or Smaller meetings? ... what kind of discussion are we trying to foster with whom? DKA: Could do day long, or just invite experts. DKA: Logistics would be much easier.. ... option B (invited experts coming to talk to us) is less difficult. ... Anyone want to push for a full-day developer-camp style thing? If not, I propose we let it go... ... Anyone else interested in working with Dan on option (A) - a bigger developer camp on a different day? Tim: My concern about the "big" one is peoples' time may already be committed. Noah: What I'm hearing is it doesn't work... If you have ideas for other things that might fit in the 3 days - but inclined to let go. <noah> ACTION-454? <trackbot> ACTION-454 -- Daniel Appelquist to take lead in organizing possible Web apps architecture camp / workshop / openday -- due 2010-07-22 -- OPEN <trackbot> <noah> . ACTION: DanA to Take lead in organizing outside contacts for TAG F2f <noah> ACTION-455? <trackbot> ACTION-455 -- Noah Mendelsohn to schedule discussion on privacy workshop outcomes. -- due 2010-09-07 -- OPEN <trackbot> <noah> close ACTION-455 <trackbot> ACTION-455 Schedule discussion on privacy workshop outcomes. closed Noah: any objection to close 455? [none heard] Larry: I have no opinion on this. I see nothing that I object to. I'd be happy for it to go either way. <noah> Tim: I was very concerned about this. I've got code in tabulator that throws up an error message when it hits this. <noah> ACTION-456? <trackbot> ACTION-456 -- Yves Lafon to locate past HTTP WG discussion on Location: A#B change, and make the TAG aware of it -- due 2010-08-17 -- PENDINGREVIEW <trackbot> <noah> Tim: I was hoping TAG would promote best practices Tim: I'd been hoping that the TAG would say "there are best practices for redirecting from the object to the document about it" Tim: we see PERL site redirects with 302 from A#B to C#D, and then discover that there's no info in that result about C#D, only about A#B Tim: my code is unhappy with this <Yves> the redirection is from A to C#D <Yves> handling #B is done client-side Noah: Can the TAG write on this? <timbl> Ok, my current problem is with IIRC dcterms:title <noah> LM: I thought HTTP redirect is being addressed in http committee. Thus no need for TAG finding. Larry: I thought that the HTTP redirect was being addressed in http bis committee and that the TAG didn't need to write a finding. <noah> TBL: The httpbis committee? <noah> LM: Yves? <timbl> _________________________ Yves: My impression is that there are more people interested in solving that issue here than in http bis... <timbl> $ curl -I <timbl> HTTP/1.1 302 Moved Temporarily <timbl> Date: Thu, 02 Sep 2010 17:59:31 GMT <timbl> Server: 1060 NetKernel v3.3 - Powered by Jetty <timbl> Location: <timbl> Content-Type: text/html; charset=iso-8859-1 <timbl> X-Purl: 2.0; <noah> YL: I think there's more interest here on the TAG than there, because the focus is on the interpretation. <timbl> Expires: Thu, 01 Jan 1970 00:00:00 GMT <timbl> Content-Length: 283 Yves: if not enough people are interested in working on that here then we can say "allow http bis to do what they want." <timbl> __________________ <timbl> $ curl -I <timbl> HTTP/1.1 200 OK <timbl> Date: Thu, 02 Sep 2010 17:53:42 GMT <timbl> Server: Apache/2.0.59 (Unix) DAV/2 mod_ssl/2.0.59 OpenSSL/0.9.8g SVN/1.4.3 <timbl> Last-Modified: Mon, 30 Jun 2008 03:54:54 GMT <timbl> ETag: "8cd2f-133a9-38dddf80" <timbl> Accept-Ranges: bytes <timbl> Content-Length: 78761 <timbl> Content-Type: application/rdf+xml <timbl> ___________________________ <noah> TBL: I'm looking up to find dcterms:title, that's what I first typed in. Tim: The first thing - I'm looking up to see what /dc/terms/title <noah> Tim: It's telling me that I need to look at <noah> Tim: from that you get: Tim: And it's telling me that I need to go look at that local id (#title)... and then if you look at what you get back from <timbl> So then you look in what you get from that you find: <noah> HT: You get 80K of data, only a bit of which is of interest <timbl> <!ENTITY dctermsns ''> Tim: you get - it declares a namespace - <Yves> #title seems to be an absolute reference in the redirected content, even if that content got a # in it <timbl> ... xmlns:dcterms="" <timbl> <rdf:Description rdf: <noah> Tim: the key bit is <rdf:Description rdf: Tim: the information in that document says : <rdf:Description rdf: <timbl> RDF isn't about parts of documents, but things in this case the concept of title <timbl> so C has no infor about C#D <timbl> C#D basically does not exist Tim: RDF doesn't use anchors. ... If it was a hypertext document you'd be looking for an anchor... <timbl> Theer is information about A Tim: it didn't define a local name - it used the fully qualified URL which has purl.org in it - about "a" <timbl> Ther is no #B in this example Tim: [in the current state of affairs you would be forced to write code that ignores these fragment identifiers - which is not good] ... I've concluded from HTTP that I can use that URI to talk about this document... <Zakim> ht, you wanted to ask how the situation would change if the reply had been a 303 Henry: What you're saying is that there are two problems here - one is that there a 302 and the other is that there is a hash in the response. What if the first were fixed - a 303 response but still a hash. Tim: Then I would have required C#D to identify a document - again, I am expecting a document from the 303. <timbl> From the 302 and the 200 my code concludes that C is a document and A is a document Tim: Yes, they could have done a 303 but then give me a document about that other document - for example a document that provides me a SPARLQL query... Henry: But I though the point of the http range 14 finding was that you get a document that doesn't pretend to be what you requested... ... it is 303 that we recommend in http range 14 - yes? <Yves> I would note that one of the option was to delegate the "fragment combination" to the mime type definition. RDF can tell its story there, like ignoring the #D part (but you know that only when you dereference the URI) Tim: Yes where the original is a predicate. <timbl> for teh case where the original is a thing like dublin or the concpet of a title.. ... Next question - I'm not convinced that the range 14 finding envisaged RDF that was not ONLY about Dublin. Tim: No; there are lots of cases where people wrote an ontology in one file and they've used a slash in their URIs but all the URIs redirect to the same file... Henry: Someone might think - "actually this document contains info on every city in Ireland then I should put a hash on it to direct me to the part of that document about Dublin" Tim: But RDF documents don't have parts. Henry: But RDF tells me what the semantics of # are ? <Yves> semantic of # should be described in the application/rdf+xml type, no ? Tim: the RDF spec says: when you get one of these things you parse it - it tells you how to parse it when you get ... (?) ... the tutorials show you the fragment identifier is a local identifier in a local name space... ... there could be no other semantics to fragment IDs [than what the RDF spec states]. ... The C#D issue is up the stack a bit. Henry: I was trying to see if based on a reasonable reading, someone in the position of the Purl people might think that putting the # on was doing the right thing. I think they did. Tim: It may well be that if we got back to [Purl] then they could tweak their system accordingly. ... Anyone know the webmaster at dublin core? ... Anyone know anyone else who does this? Redirecting to a #? Henry: [points the finger at Yves] <noah> ACTION-456? <trackbot> ACTION-456 -- Yves Lafon to locate past HTTP WG discussion on Location: A#B change, and make the TAG aware of it -- due 2010-08-17 -- PENDINGREVIEW <trackbot> Yves: I want to continue working on this, with Tim, to understand if the issue is only with RDF documents or if it's a more general one. E.g. part of a video, part of a document, etc... <noah> . proposed ACTION: Yves to work with Tim to propose next steps regarding redirection for secondary resources <noah> Would close 456 Tim: We have to know what the semantics are and we have to specify it differently for hypertext and RDF. <noah> . proposed ACTION: Yves to write draft of best practices on redirection for secondary resources (with help from Tim) <noah> close ACTION-456 <trackbot> ACTION-456 Locate past HTTP WG discussion on Location: A#B change, and make the TAG aware of it closed <noah> ACTION: Yves to write draft of best practices on redirection for secondary resources (with help from Tim) [recorded in] <trackbot> Created ACTION-462 - Write draft of best practices on redirection for secondary resources (with help from Tim) [on Yves Lafon - due 2010-09-09]. <noah> ACTION-462 due: 2010-10-05 <ht> is the media type registration for rdf+xml <noah> ACTION-462: due 2010-10-05 <trackbot> ACTION-462 Write draft of best practices on redirection for secondary resources (with help from Tim) notes added <ht> And as TimBL said, it doesn't really answer the question, but points elsewhere: "More details on RDF's treatment of fragment identifiers can be found <ht> in the section "Fragment Identifiers" of the RDF Concepts document <ht> [ <ht> <ht> ] <timbl> tracker, help action <noah> ACTION-458? <trackbot> ACTION-458 -- Noah Mendelsohn to schedule discussion of followup actions for TAG to coordinate with IETF on MIME-type related activities -- due 2010-09-07 -- OPEN <trackbot> <noah> ACTION-447? <trackbot> ACTION-447 -- Yves Lafon to coordinate TAG positions on media type related work with IETF, and to represent TAG at IETF meetings in Mastricht Due: 2010-07-20 -- due 2010-07-20 -- CLOSED <trackbot> Noah: Yves said it didn't line up as well as we hoped - we said we would pick it up when Larry is back. Larry: I wrote this blog post on it - if you think it's good we could pick it up as a TAG note... Noah: if you did want to go forward with it - anything else need to be done? ... do you view this as "step on". ... I think October is a good target for this. ... Can we take a week or 2 to re-read it. Dan: should we bring it into W3C space? Larry: I can supply it. Noah: I can help to put it up. ... I think TAG members don't want to see this work lost or just left in Larry's blog. Larry: Anything that came up in the June meeting? Noah: I don't think we got to the point where we know what success is. In what further ways does the TAG want to engage? Larry: What I would like - some of this belongs in changing the ways in which MIME types are registered. So for this to have an effect on the Web it would need to be an IEFT document. Noah: Do you have time to help formulate [e.g.] a proposal to the IETF? Larry: [Yes I can do that.] +1 Noah: We will re-schedule in a week or 2. Larry: I'm willing to turn it into an Internet Draft - I can put it in that format. Tim: Regrets for next week. Noah: Adjourned. thanks! <noah> New note on ACTION-458: .
http://www.w3.org/2001/tag/2010/09/02-minutes.html
CC-MAIN-2014-10
refinedweb
3,251
69.21
Enrico, Am Mittwoch, 14. Februar 2018, 13:38:48 CET schrieb Enrico Weigelt: > On 14.02.2018 12:30, Richard Weinberger wrote: > > On Wed, Feb 14, 2018 at 12:27 PM, Enrico Weigelt <l... ? It does what you ask it for. Also see the --setgroups switch. AFAICT --setgroups=deny is the new default, then your command line should just work. Maybe your unshare tool is too old. > > private namespaces. This is exactly why we have the user namespace. In the user namespace you can create your own mount namespace and do (almost) whatever you want. Please note that you cannot mount any kind of filesystem. For FUSE, see Thanks, //richard -- sigma star gmbh - Eduard-Bodem-Gasse 6 - 6020 Innsbruck - Austria ATU66964118 - FN 374287y
https://www.mail-archive.com/linux-kernel@vger.kernel.org/msg1609762.html
CC-MAIN-2019-04
refinedweb
123
86.3
Hey quick question about something I’m a bit confused about. I’m writing some super simple code using examples of course and in the code the example has the word " data" as the character for received data from a bluetooth module, I thought it was similar to something like assigning a name to an LED so I could change it but when I did the compiler told me it wasn’t declared but the word data by itself was declared without error. I tried googling it but obviously things like " arduino data " don’t show me at all what I’m looking for. Side note, data shows up orange and not black if that means anything. If for some reason you need the code here ya go. Thanks to anyone who was willing to answer my silly question, have a nice day to you all! #include <Servo.h> Servo servoone; char data = 0; void setup() { servoone.attach(6); Serial.begin(9600); } void loop() { if(Serial.available() > 0); { doggo = Serial.read(); Serial.println(data); if(data == '1'); { Serial.print("WE RECIEVED A THING"); } } }
https://forum.arduino.cc/t/tiny-question-google-cant-really-answer/526493
CC-MAIN-2021-31
refinedweb
183
64.71
index Programming Tutorials : Many Free Programming tutorials Many links to the online programming tutorials. These programming tutorial links will help you in increasing your programming skills.  Programming Books Programming Books A Collection of Large number of Free books is presented here. You can browse these high quality programming...; Ada Books C# Programming Books C/C++ Programming Books | Many Programming Tutorials Links | Tutorials Books | VB Tutorial... largest collection of tutorials on various programming languages. These days... in many of the places, but other programming languages can also be used writing Free Java Books Free Java Books Sams Teach Yourself Java 2 in 24 Hours As the author of computer books, I spend a lot...; Noble and Borders, observing the behavior of shoppers browsing through the books Mysql Date Index Mysql Date Index Mysql Date Index is used to create a index on specified table. Indexes in database are similar to books in library. It is created on one or more Tomcat Books Tomcat Books  ... of your site. Tomcat Works This is one of the rare books...; Tomcat Books Tomcat is an application server built around Misc.Online Books takes a deeper look at object-oriented programming than previous Lisp books, showing... Misc.Online Books  ... and debug it. We do not assume knowledge of any particular programming PHP Basics Tutorial Index start learning the Basics of PHP quickly. Basics of PHP Programming Language JSP PDF books JSP PDF books Collection is jsp books in the pdf format. You can download these books and study it offline. The Servlets What is Index? What is Index? What is Index Ruby Books Ruby Books  ... of an alleged programming manual.) Then you ask yourself, ?Wait a minute. I thought this was a book on Ruby, the incredible new programming language from Linux Books Linux Books  .... Advanced Linux Programming Advanced Linux Programming is published under the Open Publication License index of javaprogram index of javaprogram what is the step of learning java. i am not asking syllabus am i am asking the step of program to teach a pesonal student. To learn java, please visit the following link: Java Tutorial Free PHP Books Free PHP Books PHP 5 Power Programming In this book, PHP 5's co-creator and two... it is at now, and the reasons for programming with it. Towards the end of the chapter   Search index Drop Index Drop Index Drop Index is used to remove one or more indexes from the current database. Understand with Example The Tutorial illustrate an example from Drop Index Java Certification Books Java Certification Books  ... programming skills and provides the IT industry wth a standard to use when... readers for the CJPE by teaching them sound Java programming skills and covering clustered and a non-clustered index? clustered and a non-clustered index? What is the difference between clustered and a non-clustered index Java server Faces Books Java server Faces Books  ...; Store-Java Buy two books direct from O'Reilly and get the third free by using code OPC10 in our shopping cart. This deal includes books Programming error - Java Beginners Programming error import javax.servlet.RequestDispatcher; import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class....") return false } //get the zero-based index of the "@" character checking index in prepared statement checking index in prepared statement If we write as follows: String query = "insert into st_details values(?,?,?)"; PreparedStatement ps = con.prepareStatement(query); then after query has been prepared, can we check the index Struts Book - Popular Struts Books Struts Book - Popular Struts Books Programming Jakarta... writing today's complex web applications. O'Reilly's Programming Jakarta Struts... potential. He calls the books, "the culmination of lessons learned (the hard way Java programming tutorial for very beginners Java programming tutorial for very beginners Hi, After completing my 12th Standard in India I would like to learn Java programming language. Is there any Java programming tutorial for very beginners? Thanks Hi Where to learn java programming language Where to learn java programming language I am beginner in Java and want to learn Java and become master of the Java programming language? Where to learn java programming language? Thanks Hi, Java is Object Java programming - Java Beginners ..............................abc This could be used as part of an index for a book Programming Programming Given a number n, write a programming to determine its square root if it is possible, in the contraly case print an appropriate massege on the screen Java programming using ArrayList Help? Java programming using ArrayList Help? Hi,can anybody help and guide me on doing this java program? (Largest rows and columns)Write a program... row index : 2 The largest column index : 2,3 Any help would be greatly Java programming using ArrayList Help? Java programming using ArrayList Help? Hi,can anybody help and guide me on doing this java program? (Largest rows and columns)Write a program... The largest row index : 2 The largest column index : 2,3 Any help would be greatly JavaScript array index of JavaScript array index of In this Tutorial we want to describe that makes you to easy to understand JavaScript array index of. We are using JavaScript... line. 1)index of( ) - This return the position of the value that is hold programming Java Constructor programming for single and double constructor write a program which have no argument constructor ,single parameter constructor constructor,double parameter constor,and the now when we create a object Java programming - Java Beginners Java programming write a method that computes the Body Mass Index (BMI) given the weight (kg) and height (metres) and displays a message as detailed below. In the main method you will need to use JOptionPane to get PHP OOP Concepts PHP OOP Concepts Object Oriented Programming is a paradigm which is nowadays the most popular way to develop any application and most of the modern day language is based on this paradigm. OOP or Object Oriented Programming PHP has Need E-Books - JSP-Servlet alter table create index mysql alter table create index mysql Hi, What is the query for altering table and adding index on a table field? Thanks Hi, Query is: ALTER TABLE account ADD INDEX (accounttype); Thanks index - Java Beginners programming PROGRAMMING Programming arraylist index() Function Java arrayList has index for each added element. This index starts from 0. arrayList values can be retrieved by the get(index) method. Example of Java Arraylist Index() Function import
http://roseindia.net/tutorialhelp/comment/82990
CC-MAIN-2014-42
refinedweb
1,070
55.34
I am very new to Python. I am trying to read a csv file and displaying the result to another CSV file. What I want to do is I want to write selective rows in the input csv file on to the output file. Below is the code I wrote so far. This code read every single row from the input file i.e. 1.csv and write it to an output file out.csv. How can I tweak this code say for example I want my output file to contain only those rows which starts with READ in column 8 and rows which are not equal to 0000 in column 10. Both of these conditions need to be met. Like start with READ and not equal to 0000. I want to write all these rows. Also this block of code is for a single csv file. Can anyone please tell me how I can do it for say 10000 csv files ? Also when I execute the code, I can see spaces between lines on my out csv. How can I remove those spaces ? import csv f1 = open("1.csv", "r") reader = csv.reader(f1) header = reader.next() f2 = open("out.csv", "w") writer = csv.writer(f2) writer.writerow(header) for row in reader: writer.writerow(row) f1.close() f2.close() Something like: import os import csv import glob class CSVReadWriter(object): def munge(self, filename, suffix): name,ext = os.path.split(filename) return '{0}{1}.{2}'.format(name, suffix, ext) def is_valid(self, row): return row[8] == 'READ' and row[10] == '0000' def filter_csv(fin, fout): reader = csv.reader(fin) writer = csv.writer(fout) writer.write(reader.next()) # header for row in reader: if self.is_valid(row): writer.writerow(row) def read_write(self, iname, suffix): with open(iname, 'rb') as fin: oname = self.munge(filename, suffix) with open(oname, 'wb') as fout: self.filter_csv(fin, fout) work_directory = r"C:\Temp\Data" for filename in glob.glob(work_directory): csvrw = CSVReadWriter() csvrw.read_write(filename, '_out') I've made it a class so that you can over ride the munge and is_valid methods to suit different cases. Being a class also means that you can store state better, for example if you wanted to output lines between certain criteria. The extra spaces between lines that you mention are to do with \r\n carriage return and line feed line endings. Using open with 'wb' might resolve it.
https://codedump.io/share/a8GtzdOWkESb/1/reading-data-from-one-csv-and-displaying-parsed-data-on-to-another-csv-file
CC-MAIN-2019-35
refinedweb
405
77.74
Often you need to have a custom context menu somewhere on your page. Chances are that you’re already using jQuery on your website since jQuery is used on half of all websites. This tutorial will show you how to implement your own jQuery plugin for creating cross-browser context menus. The final result will consist of one JavaScript file and one CSS file which can easily be included in your pages. In the interest of promoting good practices, the plugin will use the jQuery plugin suggested guidelines as a starting point. If you need some extra tips, you can also take a look at 10 Tips for Developing Better jQuery Plugins. The Basics Throughout this tutorial, the plugin will be referred to as the “Audero Context Menu.” This name is arbitrary, so feel free to call it whatever you want. The starting point of the JavaScript file is taken from the jQuery guidelines page. To summarize, we’ll use an IIFE to ensure that the plugin doesn’t collide with other libraries that use the dollar sign, such as Prototype. We’ll also use namespacing to ensure that the plugin will have a very low chance of being overwritten by other code living on the same page. The chosen namespace is auderoContextMenu. At line 2 of the snippet below, we add the namespace as a property of the $.fn object. Instead of adding every method to the $.fn object, we’ll put them in an object literal as suggested by the guidelines. The plugin’s methods can then be called by passing in the name of the method as a string. (function($) { $.fn.auderoContextMenu = function(method) { if (methods[method]) return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); else if (typeof method === 'object' || typeof method === 'string' || ! method) return methods.init.apply(this, arguments); else $.error('Method ' + method + ' does not exist on jQuery.auderoContextMenu'); }; })(jQuery); As you can see, the else if condition is slightly different from the guidelines. We have added a test to check if the method parameter is a string. This allows the user to use the plugin by simply passing a single parameter which should be the id of the custom context menu. This means that the context menu we’re building, which you’ll see is simply a list, will be a part of the DOM. The plugin works by replacing the default behavior of the right click event, but as you’ll see later, overriding the left click is also easy. Getting Started So far, we have code that accepts a method to invoke, along with some parameters. The next question is, what methods do we need? If you think of your browser’s context menu, it’s obvious that we need methods to show and hide the menu. We also need a method to initialize the context menu and some default settings. So, to reiterate, we need the following components. init()method show()method hide()method - default settings Since we’re so cool, the plugin we’re building will allow for several context menus on the same page. Every element will be completely independent from the others. Supporting multiple context menus requires changes to our code. So, let’s take a look at how the plugin changes. (function($) { // default values used for the menu var defaultValues = {'idMenu': null, 'posX': null, 'posY': null}; // settings for all the elements and menu specified by the user var elementsSettings = {}; var methods = { /* here we'll write the init, show and hide methods */ } $.fn.auderoContextMenu = function(method) { // Here is the code shown previously }; })(jQuery); Now it’s time to see the details of the init(), show(), and hide() methods mentioned above. The init() method This method, as you might expect, initializes the settings of the context menu and overrides the default behavior of the right click event. It also defines the clicked element, the chosen context menu, and its display position. The init() method takes one parameter, which can be an object or string. If an object is provided, it should contain the id of the menu and the coordinates to position it. If the user provides an object, it will be merged with the default settings using the jQuery extend() method. If a string is provided, it is used as the id of the menu to show. this.on('contextmenu auderoContextMenu', function(event) { event.preventDefault(); event.stopPropagation(); var params = $.extend({}, elementsSettings[id]); if (elementsSettings[id].posX == null || elementsSettings[id].posY == null) { params.posX = event.pageX; params.posY = event.pageY; } methods.show(params, event, id); }); Obviously, the most important part of this method is the replacement of the default context menu. To attach the custom menu, we need to listen to the contextmenu event using the jQuery on() method. on() takes a callback function as its second parameter. The callback function prevents the default behavior of displaying the browser’s native context menu. Next, we test if the menu has to be shown in a fixed position or at the click coordinates. The last part of the function calls our plugin’s show() method (not the jQuery method). The show() method The show() method displays the menu in the appropriate position. This method begins by hiding the menu that is going to be shown. This is done because it could already be visible due to a previous call to the method. The menu could be hidden using the jQuery hide() method, but since our plugin defines a hide() method, we’ll use our method as shown below. methods.hide(idMenu); The next step is to either use the coordinates provided by the user, or use the mouse coordinates at the time of the click event. The code to do this is shown below. if (typeof params !== 'object' || params.posX == undefined || params.posY == undefined) { if (event == undefined) { params = {'idMenu': params, 'posX': 0, 'posY': 0} } else { params = {'idMenu': params, 'posX': event.pageX, 'posY': event.pageY} } } The code that actually displays the menu is quite simple. We use jQuery to get the menu through its id, then set the position (in pixels) starting from the upper-left corner. Finally, the jQuery show() method is used to display the menu. Thanks to jQuery chaining, these steps are accomplished with just one statement, as shown below. Our amazing menu now magically appears. $('#' + idMenu) .css('top', params.posY + 'px') .css('left', params.posX + 'px') .show(); The hide() method The hide() method will be used to hide a menu. Since our plugin allows multiple context menus to be visible at the same time, it’ll be convenient to have the chance to hide all of the menus at once. Our hide() method takes a single optional parameter that represents the menu(s) to be hidden. If specified, the parameter can be a string or an array of strings. If the parameter is null or undefined, then all of the menus in elementsSettings will be recursively hidden. hide: function(id) { if (id === undefined || id === null) { for(var Key in elementsSettings) methods.hide(elementsSettings[Key].idMenu); } else if ($.isArray(id)) { for(i = 0; i < id.length; i++) methods.hide(id[i]); } else $('#' + id).hide(); } Adding Some Style! We would like our custom context menus to work like native context menus as much as possible. To do this, we’ll need some CSS. We’ll want to hide the list that contains the menu, and show it only when needed. Moreover, we need to use absolute positioning to move the element around the page. The last relevant choice is to use a border to separate the different entries of the menu. All these choices will result in the following CSS code. ul.audero-context-menu { position: absolute; display: none; background-color: menu; list-style-type: none !important; margin: 0px !important; padding: 0px !important; } ul.audero-context-menu * { color: menutext; } ul.audero-context-menu > li { border: 1px solid black; margin: 0px !important; padding: 2px 5px !important; } ul.audero-context-menu > li:hover { background-color: activecaption; } ul.audero-context-menu > li a { display: block; } Using the Plugin Our plugin is very easy to use. In fact, its basic usage consists of just one line of code. For example, let’s say we have the following piece of HTML. <ul id="context-menu" class="audero-context-menu"> <li><a href="">SitePoint</a></li> <li><a href="">Audero user group</a></li> </ul> <div id="area">Right click here to show the custom menu.</div> To allow the plugin to show the custom context menu, context-menu, when area is right clicked, you would write the following code. $(document).ready (function() { $('#area').auderoContextMenu('context-menu'); }); If you want to show the custom menu on the left click too, simply add the following code. $('#area').click (function(event) { $(this).auderoContextMenu('show', 'context-menu', event); }); Conclusions This tutorial has shown how to create a jQuery plugin that creates custom context menus. To see how it works, take a look at the online demo or download the source code. If you need more examples or a detailed explanation of the methods, please refer to the official documentation. The Audero Context Menu is completely free and is released under CC BY 3.0 license. - cir
http://www.sitepoint.com/implementing-a-cross-browser-context-menu-as-a-jquery-plugin/
CC-MAIN-2015-48
refinedweb
1,530
66.44
Re: YANQ (Yet another newbie Question) From: Sam Santiago (ssantiago_at_n0spam-SoftiTechture.com) Date: 10/14/04 - ] Date: Thu, 14 Oct 2004 08:15:44 -0700 Go to the QuickStart examples on GotDotNet: Scroll to the bottom of most examples and click on the C++ link in the Latebreaking Samples area. Also check out: HOW TO: Create client access to a remote server by using Visual C++ .NET;en-us;818781 and HOW TO: Create a remote server by using Visual C++ .NET and here's an example that uses events, though not in C++, but it might Remoting Chat Example;en-us;312114 Good luck. Thanks, Sam -- _______________________________ Sam Santiago ssantiago@n0spam-SoftiTechture.com _______________________________ "Fireangel" <Fireangel@discussions.microsoft.com> wrote in message news:FF0FAA90-F96B-4620-B118-A0D5DC9D7BA2@microsoft.com... > > > First off. Is there ANY C++.net examples out there?? In my google > experiance, I've hit alot of C# and some VB.net, but I'm doing C++.net. I've > tried to convert, but something always ends up broke and I don't know how to > fix it (Yet). > > This is from a conversion of a simple chat example from C#. I've got a DLL > project with just the chat base in it (Namespace ServerBase, __gc class > ChatBase : Public System::MarshalByRefObject). I've got a Client project > with just a form in it (Namespace RemoteClient, __gc class Form1). I've also > got a Server project with nothing but an int APIENTRY_tWinMain (ect). > > I can start up an object, and then connect to it remotely. But the problem > i'm having is that the client can't find assembly RemoteClient (Which is the > namespace and project name that its currently running inside). This occures > when the client tries add an event to a public delegate on the server. > I've look a few pages back in here, and somebody mentioned that the DLL > Project needs to have the Client class in it (An interface would work). Is > this the case?? I ask because even the C# example don't do this (atleast > none that I've found). If I take out the Delegate stuff, it works (but not > the way I want, hence the delegates). > > I'm not using config files for this (probably my first mistake, but I'd > rather do everything programatticaly). > > I've declare both sides to have a TypeFildterLevel::Full (Solved older bug). > > If you want some specific code, i'm sure I can put some up here. It may > help, it may not. > > Thanks you for any help > > GE - ]
http://www.tech-archive.net/Archive/DotNet/microsoft.public.dotnet.framework.remoting/2004-10/0166.html
crawl-002
refinedweb
427
75.1
Signal and signal handler in QtQuick Designer Hello forum, do we have to import any specific module to have the signal and signal handler into the qtquick designer interface ? I cannot have it with the following import: import QtQuick 2.5 I followed a youtube video QtQuick Designer where it demonstrates the use to signal and signal handler in the QtQuick Designer interface. I would like to have the same connections interface in QtQuick Designer, but it is not visible. Hope someone will show up with some tips! Thanks - p3c0 Moderators @sajis997 There must be a ComboBox on the top-right side. By default it will show Properties. Click on it and choose Connections. I tried as suggested , but the Connections is not in the combo-box - p3c0 Moderators - Thomas Hartmann Which version of Qt Creator are you using? The connection editor was added to the open source version of Qt Creator 3.6. I am using Qt Creator 3.5.1 - Thomas Hartmann Please update to Qt Creator 4.1. Qt Creator and the Qt Quick Designer improved a lot.
https://forum.qt.io/topic/71490/signal-and-signal-handler-in-qtquick-designer
CC-MAIN-2017-39
refinedweb
181
66.33
Previously, in Part II we discussed about running system commands and implementing our own built-in commands. In Part III, we explore signal handling. What are signals? When driving, one looks out for traffic signals, red or green and takes a decision based on it: to stop or to keep driving. But the traffic signals only come up after some intervals at crossroads and is not present continuously along the road. We can somewhat apply this analogy to signals in the context of computers as well. A signal is a software interrupt that is sent out from an external event to a process. It may be sent to the process by the kernel, by another process or by itself. A very common example is SIGINT, which is the signal that is sent out when you hit Ctrl-C to exit a program. Before going any further, let us take a look at the following diagram: The process executes three instructions and terminatess. However, after the second instruction, it receives a signal. At this point the regular execution of the program is interrupted and is passed on to the signal handler. The signal handler is a pre-defined function which is invoked when the signal is received. It returns the process to its normal execution flow, where it goes on to execute the third instruction and exits. However, depending on the code in the signal handler itself, instruction 3 might not be executed at all. For eg: If the signal being sent is SIGINT (Ctrl-C), the program exits. Also, it is not guaranteed that a signal interrupt will only occur when a program is between instructions. It may occur when an instruction is executing and in such a case the instruction will get interrupted. One important thing to note is that, while the main function runs in its own thread the signal handler also runs in its own thread. Both the threads belong to the same process though. Edit: I misunderstood this line from The Linux Programming Interface, section 21.1.2: Because a signal handler may asynchronously interrupt the execution of a program at any point in time, the main program and the signal handler in effect form two independent (althought not concurrent) threads of execution within the same process. I asked around on IRC[1]. Signal handling Now that we understand signals, let us run the code for the shell we had from Part II. If you run the executable and run the command sleep 10 in the shell and hit Ctrl-C before the command finishes, you will notice that along with the command, our shell has quit as well. $ gcc -lreadline shell_with_builtin.c && ./a.out unixsh> sleep 10 ^C $ You will notice the same behaviour if you hit Ctrl-Z as well, which generates the SIGTSTP signal. This stops the current running process. Currently, the shell is reacting to the default signal handlers set up by the operating system. The good news is that we can customize this behaviour. We can use the function signal() defined in signal.h: #include <signal.h> typedef void (*sighandler_t)(int); sighandler_t signal(int signum, sighandler_t handler); The first argument to the function is the signal number. Each signal has a predefined integer value assigned to it. This number is 2 for SIGINT and 20 for SIGTSTP. The second argument is a pointer to a signal handler. The signal handler is a function that must accept an int as the only parameter and return void as described by the typedef sighandler_t. Let us write a minimal program to handle SIGINT: #include <stdio.h> #include <signal.h> void sigint_handler(int signo) { printf("Caught SIGINT\n"); } int main() { signal(SIGINT, sigint_handler); while (1); /* Infinite loop */ } We run an infinite while loop here on typing Ctrl-C you will notice the text Caught SIGINT printed to the terminal, but the program will continue to run after that. You can stop it with Ctrl-Z. Here’s the output from a sample run: $ gcc sigint.c && ./a.out ^CCaught SIGINT ^CCaught SIGINT ^Z [2]+ Stopped ./a.out C provides two very useful macros that can be passed to the signal function: SIG_IGN: Ignores the signal. Usage: signal(SIGINT, SIG_IGN). SIG_DFL: Sets the default behaviour for the signal. This is useful when you want to reset the behaviour for a signal after having made some modifications. Usage: signal(SIGINT, SIG_DFL). However, it is not possible to ignore, block or setup a custom handler for SIGKILL and SIGSTOP. Blocking a signal means that the signal will not be delivered to the process at all. We will now use signal handling in our shell and modify our code by adding a call to signal() just before the while loop: ... int main() { ... signal(SIGINT, SIG_IGN); while (1) { ... The modified file is available here. If you compile and execute the binary and hit Ctrl-C, the shell does not quit anymore. But if you run sleep 10 in the shell and hit Ctrl-C, the command does not quit as well. The reason behind this is that when a fork is called, apart from duplicating the parent process, it copies the current signal configurations (also known as the signal dispositions) as well. Since we are ignoring SIGINT in the parent, the child also inherits the same property for SIGINT from its parent and conveninently ignores the keyboard interrupt ( Ctrl-C). To prevent this, we will restore the default behaviour of SIGINT in the child process after fork. Note that this must be done before the call to execvp since it will replace the current program with the program passed in the command. ... child_pid = fork(); ... if (child_pid == 0) { signal(SIGINT, SIG_DFL); /* Never returns if the call is successful */ if (execvp(command[0], command) < 0) { ... The modified file is available here. Signal masks Each process has an attribute called the process signal mask which is maintained by the kernel. Any signal that is added to the signal mask gets blocked from being delivered in the future, unless the signal is removed from it. This is useful when we want to block a signal based on the application logic. Now, let’s look at the following workflow for an example: - A signal is delivered. The signal handler gets invoked and is in the middle of executing some instructions. - The same signal is delivered again and the signal handler is invoked once again. The previous instance of the signal handler will get interrupted by a new instance of the signal handler.. Non local jumps Currently, the shell does not do anything when it encounters a Ctrl-C, while waiting for a command input. We would like to change this behaviour to restart the while loop from the top and print a newline. Effectively, Ctrl-C would mean a soft reset of the command line. This brings us to the functions setjmp and longjmp, which are used to perform a non local jump. This is equivalent of using a goto statement to jump across scopes, except that the scope of a goto is restricted to within a function. These functions are defined in setjmp.h and their signatures look like this: int setjmp(jmp_buf env); The setjmp() function sets a jump point and takes a buffer of type jmp_buf which is used to store details like the stack pointer and the instruction pointer. It returns 0 once the jump point has been set. void longjmp(jmp_buf env, int val); The longjmp() function uses the buffer which contains values saved by setjmp() to determine the jump point in the program. Additionally it takes an integer value, which is returned when the code returns to the jump point. Here’s an example: A few important things to note about the code above: - The call to signal()takes a pointer to the sigint_handler()function instead of SIG_IGN (line 13). - When the code reaches line 15for the first time, setjmp()is invoked and returns 0. - After the signal handler has been registered, if we type Ctrl-C, the longjmp()function call is invoked where we pass 42to it. The code jumps to line 15and this time setjmp()returns the value that was passed in longjmp()on line 9, i.e. 42. Thus the check evaluates to true, which signifies that we reached this code from a non local jump. This is also referred to as a fake returnby setjmp(). If you compile and execute the binary, the output would be similar to: $ gcc -lreadline -g setjmp_longjmp.c && ./a.out next iteration... ^CRestart. next iteration... ^Cnext iteration... next iteration... ^Z [6]+ Stopped ./a.out But, Restart will be printed to the screen only the first time you hit Ctrl-C. The reason behind this is that the first time the signal handler is invoked for SIGINT, it blocks the signal and the call to longjmp() does not unblock the signal since the signal handler never really returns. As a result, SIGINT does not get delivered after the first time. To fix this problem, we have sigsetjmp() and siglongjmp(). The function signatures are: int sigsetjmp(sigjmp_buf env, int savesigs); void siglongjmp(sigjmp_buf env, int val); They are similar to setjmp() and longjmp(), but they accept a buffer of type sigjmp_buf instead of jmp_buf. Also, the sigsetjmp() function accepts a flag savesigs. If value of this flag is non zero, then sigsetjmp() saves the current process signal mask and restores it when siglongjmp() is invoked. This means, that the signal which initially gets blocked on invoking the signal handler, gets unblocked as soon as siglongjmp() is invoked. And here’s an example using these functions: Note that the function call to sigsetjmp() on line 15 accepts an extra parameter for the savesigs flag. Also, env is of type sigjmp_buf. And if you compile and execute it you will notice that Ctrl-C is accepted more than once, until you stop the program: $ gcc -lreadline -g sigsetjmp_siglongjmp.c && ./a.out next iteration... ^CRestart. next iteration... ^CRestart. next iteration... ^Z [7]+ Stopped ./a false by default. Once the jump point has been set, we set the flag to true and add a check on this flag in our signal handler. If the flag is false, we skip the call to longjmp() and return from the handler instead. Here’s our updated signal handler and main function: sigsetjmp_siglongjmp_with_check.c ... static volatile sig_atomic_t jump_active = 0; void sigint_handler(int signo) { if (!jump_active) { return; } siglongjmp(env, 42); } int main() { signal(SIGINT, sigint_handler); while (1){ /* Infinite loop */ if (sigsetjmp(env, 1) == 42) { printf("Restart.\n"); } jump_active = 1; /* Set the flag */ printf("next iteration...\n"); sleep(2); } } The flag jump_active is of type volatile sig_atomic_t. This is essential, since this flag will be accessed asynchronously by multiple threads of the process, i.e. the main thread and the signal handler thread. The type guarantees atomic access to the variable across multiple threads. This brings us back to the first example, sigint.c where we used printf in the signal handler. printf is an async unsafe function. Which means, that if the signal handler is invoked while another printf is executing in a different part of the program, the output may be erratic. We use printf only to explain the concept here, and it should not be used in real life applications. A better way for signal handling: sigaction So far we have used the signal() function for setting signal handlers. However, its implementation differs from system to system and is generally not recommended to be used directly in application code since its usage makes portability hard. The alternative is to use the sigaction() function call. This is also defined in signal.h, but before we look at its signature, lets look at the definition of the struct sigaction (yes, sadly they are both named the same): struct sigaction { void (*sa_handler)(int); void (*sa_sigaction)(int, siginfo_t *, void *); sigset_t sa_mask; int sa_flags; void (*sa_restorer)(void); }; The struct requires: sa_handler: A pointer to the signal handler. sa_sigaction: A pointer to a signal handler that can access more information regarding the signal. Either one of sa_handleror sa_sigactionshould be used. sa_mask: An optional set of signals which are blocked while the signal handler is executing. sa_flags: A bitwise ORof config flags. sa_restorer: This is for internal use and should not be set. Now let us look at the signature of the sigaction() function: int sigaction(int signum, const struct sigaction *act, struct sigaction *oldact); It accepts the signal number and two sigaction struct objects. The first contains new configuration to be set, while the second is used to save the current configuration before overwriting it with the new one. In our previous code, we replace signal(SIGINT, signal_handler by: struct sigaction s; s.sa_handler = sigint_handler; sigemptyset(&s.sa_mask); s.sa_flags = SA_RESTART; sigaction(SIGINT, &s, NULL); The sigemptyset() function initializes the sa_mask attribute of the struct with an empty set. We set the SA_RESTART flag on the struct, which implies that if the signal handler is invoked while the program is in the middle of a system call, the system call will be restarted after the signal handler has finished its execution. And finally, we call the sigaction() function with the signal and the sigaction struct. We do not care about the previous configuration for the signal and pass NULL instead of another sigaction struct object. The example is available here. One last trivia During this exercise contrary to my belief I realized that on typing Ctrl-D no signal is generated like it does when we type Ctrl-C. Rather it sends the EOF character. Since we’ve changed Ctrl-C to not quit the shell, we implement Ctrl-D to do that instead for us, which is similar to the behaviour of bash. The following snippet helps us do this: ... input = readline("rcsh> "); if (input == NULL) { /* Exit on Ctrl-D */ printf("\n"); exit(0); } ... The code for the shell with the concepts explained above is available here, but it is recommended that readers try to implement it themselves. That brings us to the end of part III. All the code examples shown in this blog post are available here. In the next blog post we will see how to run background commands and perform job control. Stay tuned. Acknowledgements Once again thanks to Dominic Spadacene for pairing with me on this and to Saul Pwanson for being patient with my endless questions. [1] - Also, thanks to valdis and derRichard on #kernelnewbies (irc.oftc.net) for helping me understand the asynchronous nature of a signal handler. Resources - The Linux Programming Interface - Micahel Kerrisk - Advanced Programming in the UNIX Environment - Stephens & Rago - Linux man pages
https://indradhanush.github.io/blog/writing-a-unix-shell-part-3/
CC-MAIN-2018-30
refinedweb
2,439
63.9
vertex color. In OpenGL this matches glColor4f(c.r,c.g,c.b,c.a); on other graphics APIs the same functionality is emulated. In order for per-vertex colors to work reliably across different hardware, you have to use a shader that binds in the color channel. See BindChannels documentation. This function can only be called between GL.Begin and GL.End functions. using UnityEngine; public class Example : MonoBehaviour { // Draws a red line from the bottom right // to the top left of the Screen // And a yellow line from the bottom left // to the top right of the Screen Material mat; void OnPostRender() { if (!mat) { Debug.LogError("Please Assign a material on the inspector"); return; } GL.PushMatrix(); mat.SetPass(0); GL.LoadOrtho(); GL.Begin(GL.LINES); GL.Color(Color.red); GL.Vertex3(1, 0, 0); GL.Vertex3(0, 1, 0); GL.Color(Color.yellow); GL.Vertex3(0, 0, 0); GL.Vertex3(1, 1, 0); GL.End(); GL.PopMatrix(); } } Did you find this page useful? Please give it a rating:
https://docs.unity3d.com/2018.3/Documentation/ScriptReference/GL.Color.html
CC-MAIN-2022-40
refinedweb
170
53.27
Will Java security stop you from reading and writing to a file? Only if you can't hack it.... Java security: without it, Java would never even be looked at seriously as a viable programming option. But security is also the reason that file system access is so limited when you're using a Web browser as a Java interpreter. And with good reason--we wouldn't want anybody to be able to read and write to files on our system, let alone our Web server. Unfortunately, this is why it is so hard to write an applet that is able to read from and write to a fileƒeven a file on the same server that originally served the applet. Yet there seems to be an endless amount of reasons for wanting to do so. So how can we accomplish that task? By using what we have available: CGI and Java. With the security systems of today's Web browsers, if you want your applet to be able to write to a file you have two choices (not that these are the only methods for accomplishing the taskƒthere are always myriad ways of accomplishing a task). The first choice is obvious--use a combination of Java and CGI. The second is almost as obvious--write a server application in Java and let your applet communicate with that. That way the Java server actually writes to the file in question. We can also use a combination of the two; a Java applet that communicates with a CGI program or shell script (the wrapper) that starts the Java server application that writes to the server. We'll cover each of the three methods in this column. We hope to hear some more methods from you, the real Java experts out there. String myurl = getParameter("URL"); String url = myurl; try { this.theURL = new URL(url); } catch ( MalformedURLException e) { System.out.println("Bad URL: " + theURL); } public void run() { URLConnection conn = null; DataInputStream data = null; String line; StringBuffer buf = new StringBuffer(); try { conn = this.theURL.openConnection(); conn.connect(); ta.setText("Connection opened..."); data = new DataInputStream(new BufferedInputStream( conn.getInputStream())); ta.setText("Reading data..."); while ((line = data.readLine()) != null) { buf.append(line + "\n"); } ta.setText(buf.toString()); data.close(); } catch (IOException e) { System.out.println("IO Error:" + e.getMessage()); } } #!/usr/bin/perl # wdwrite # this is the CGI that will take the # applet info and write it to a file open(OUT, "> /public_html/opinion.txt"); print "content-type: text/plain\n\n"; while (<>) { print OUT $_; print $_; } close (OUT); exit 0; // Writeit.class import java.applet.Applet; import java.net.*; import java.io.*; import java.awt.*; public class Writeit extends Applet { Panel center; GridBagLayout gbl; GridBagConstraints gbs; TextArea info; Button send; public void init() { setLayout(new BorderLayout()); setBackground(Color.white); gbl = new GridBagLayout(); center = new Panel(); center.setLayout(gbl); gbs = new GridBagConstraints(); gbs.fill = GridBagConstraints.NONE; gbs.gridwidth = GridBagConstraints.REMAINDER; gbs.weightx = 1.0; showApp(); validate(); } public boolean action(Event e, Object o) { if (e.target.equals(send)) { try { writeMessage(); } catch (Exception e1) { } } return true; } public void writeMessage() throws Exception { String data; data = info.getText(); SendData(data); } public void showApp() { gbs.anchor = GridBagConstraints.WEST; center.add(info = addTextArea(3,50)); gbs.anchor = GridBagConstraints.CENTER; center.add(send = new Button("Write it!")); add("Center", center); } public TextArea addTextArea(int rows, int cols) { TextArea ta = new TextArea(rows, cols); gbl.setConstraints(ta, gbs); ta.setBackground(Color.white); return ta; } public void SendData(String data) throws Exception { URL url = new URL("http","", "/cgi-bin/wdwrite"); URLConnection con = url.openConnection(); con.setDoOutput(true); con.setDoInput(true); con.setUseCaches(false); con.setRequestProperty("Content-type", "text/plain"); con.setRequestProperty("Content-length", data.length()+""); PrintStream out = new PrintStream(con.getOutputStream()); out.print(data); out.flush(); out.close(); DataInputStream in = new DataInputStream(con.getInputStream()); String s; while ((s = in.readLine()) != null) { } in.close(); } } In these examples (see figure), we have shown how it is possible to use Java to both read the data from a file on the server and send the edited data to a CGI program that writes the data to a file on the server. These applets could be the basis for a Web message board (it is very fast!), a "real-time" online HTML editor, a "leave-a-quote" applet, a "real-time" chat system, or a type of INI file that would allow for the personalization of Web sites or Java applets. The possibilities are endless! As we previously stated, it is also possible to have the applet communicate with a server written in Java that resides on the same machine as the Web server, and have it do all the dirty work of reading, writingƒeven deleting files. Personally, I'm not going to take on the task of writing a Java server, since that enormous task has already been done, and quite well at that, by a generous Netizen (Jamie Cameron) that has freely given the server and source to the Web public. Jamie Cameron's JFS (Java File Server;) allows developers to provide NFS-like file and print services for Java applets. The JFS allows applets to read and write files, create and delete directories (and files), print files, send email and even open connections to servers other than the one the applet came from! The JFS uses a fairly simple name and password scheme, and the developer makes a connection to the server after passing the name of the JFS server to the applet's constructor. This is done using the JFSclient class. The only "catch" to using the JFS filesystem is that is a Java application, and as such, has to be executed and ran on the same machine as the Web server, specifically on a Unix operating system (although Java is multi-platform, Jamie designed this filesystem to be run on Unix). This brings up another question--how could you start the JFS server (or any other Java application) using CGI? If you can do this, your applet can simply call the CGI program and the CGI program will start the Java application. Basically, a CGI wrapper or shell script needs to call the Java interpreter like this: java -jit javaapplication java -jit -DREMOTE_HOST=yourdomain.com javaapplet CLASSPATH=/usr/local/java/lib/classes.zip:/usr/me/projects:. For future reference, you can view and try out the Readit/Writeit applets () along with their full source code. I couldn't have written this column without you, the readers of Web Developer® magazine. My thanks go out to Blair Hamilton for his gracious help with the Readit.class applet. Keep sending your comments, thoughts, source code, suggestions, and of course your best Java tips and tricks to me at sclark@jupitermedia.com. Till next time.
http://www.webdeveloper.com/java/java_jj_read_write.html
CC-MAIN-2016-50
refinedweb
1,119
55.74
PyX — Example: drawing2/clipping.py Clipping a canvas from pyx import * clippath = path.circle(0, 0, 1) drawpath = path.line(-2, -2, 1.2, 2) cl = canvas.canvas([canvas.clip(clippath)]) cl.stroke(drawpath, [color.rgb.red, style.linewidth(1.0)]) c = canvas.canvas() c.stroke(drawpath, [style.linewidth(1.0)]) c.insert(cl) c.stroke(clippath) c.writeEPSfile("clipping") c.writePDFfile("clipping") Description This example shows how drawing on a canvas can be clipped to a predefined region. The thick line is drawn two times, first in black onto an ordinary canvas, the second time in red onto a canvas which is clipped to the indicated circle. The clipping property of a canvas must be specified on creation with an instance of canvas.clip, which takes a path as an argument. Note that this way of clipping will probably be removed in future releases of PyX. Instead, it will become part of the box concept.
http://pyx.sourceforge.net/examples/drawing2/clipping.html
CC-MAIN-2014-10
refinedweb
156
52.56
In my last post, I showed you how to create a spreadsheet based on data from a database using the Open XML SDK. Today I am going to show you how to do the reverse, specifically, how to read data from a spreadsheet and insert it into some data source, like a database. Again, if you have any specific scenarios or solutions you would like me to address in future posts please let me know. Scenario Today’s scenario theme is document interrogation, which is all about reading data from a file. Imagine a scenario where I’m a developer working for a fictional company called Contoso. At my company, the sales team uses Excel to create sales orders for customers. These sales orders are all based on an Excel template that has designated regions that keep track of data such as customer id, invoice number, items being purchased, total dues, etc. The sales team typically creates hundreds of sales orders a day. My company has asked me to create a solution that is able to bulk export data from these sales orders into a database. The company wants this solution to be run every night on the server, so automating Excel is not an option. Solution If you want to skip ahead and just download the code + Excel template just click here. Step 1 – Create a Template File The scenario I listed above talks about reading sales orders that are based off of a workbook template. In this sales order template I will have designated regions where I expect people to fill in information. To simplify my coding and to ensure that my code is more robust, I am going to take advantage of defined name regions as specified in SpreadsheetML. Defined name regions allow me to “tag” one or more cells within my spreadsheet as having semantic meaning. For example, I can specify a defined name region for a cell that will have a value for customer id. The advantage of using defined names is that I won’t have to rely on looking up hardcoded columns and rows. For example, if a cell that contains my customer id changes from being B10 to B11 because a user added a row to the spreadsheet, I am still able to find that specific cell due to the defined name tag. In any case, I have created a simple template that looks like the following: Step 2 – Building a Defined Names Table Before I can use the SDK, I need to add the appropriate namespaces to our C# file. In this case, I need to add my Packaging and Spreadsheet API components as follows: Since my sales order file contains defined name regions, the first thing I will need to do is find all the defined names specified in my file. In SpreadsheetML, workbook-level defined names are stored in the main workbook part as follows: The defined name is stored as a string that I will need to parse. What I am going to do in my solution is read each of these defined names and then parse it out into the following components: - Defined name string (I will use this string as a reference to my data) - Sheet name - Start column - Start row - End column (only present if defined name is a range) - End row (only present if defined name is a range) I am going to then use this information to then find the value or sets of values that make up the defined name region. Note that my code assumes that no one changes the defined names or adds more defined names with the string “ItemsRange”. I can accomplish this task with the following code: Where I define the BuildDefineNamesTable method as follows (note that I created a class to store all my information called DefineNamesVal): Note that my code above assumes that none of my defined names are relative defined names. In other words, my defined name ranges contain “$” between the column and row. Okay, at this point I have all the necessary information for me to look up the values for my defined name regions. Step 3 – Access Worksheet Part Specified by Defined Name Regions Based on my Excel template, I have two types of data: - Defined names that specify values contained within one cell, for example, customer id - Defined names that specify a region of values, which in this case has the inventory information for the sales order. For example, what is being ordered, how many, how much, etc. In either case, the value for my defined name is contained in the worksheet specified by the defined name, which I already found. Here is a little method I wrote that returns back the worksheet part based on the defined name data: Step 4 – Get Cell Values Specified by Defined Name Regions Once I have the worksheet part and the cell reference (or region of cells) as specified in the defined name region I can get the cell values. I have two types of values stored in this sales order: numbers and strings. In SpreadsheetML, cell values that are strings can be represented as inline strings within the cell or stored within the shared string table that can be found in the sharedstrings part. The first step in retrieving a specific cell value based on column and row index is to first find that cell. The second step is then to look up the value for that cell. The following methods will retrieve the cell value based on the cell reference: If the cell is based on a shared string then you need to look up the appropriate value from the shared string table, otherwise you only have to look at the cell value. The following code accomplishes this task: Step 5 – Putting it All Together Now that I have all the basics in place I can put everything together. I need to go through all the defined names and find the appropriate values from the spreadsheet. For the sake of simplicity, instead of writing all found values into a database I am going to instead print out the data to my console. Yes, I got a bit lazy for creating a database to store this data. As mentioned before, I have two types of data based on my defined names: single cell values and range values based on the sales order. I am going to handle my first type of data, the single cell values, with the following code: Notice in the code above that I am converting a SpreadsheetML stored date as a human readable date. Since I am just going to print out my found values I am going to keep track of my inventory values as a separate list. I will retrieve my inventory values with the following code: In the code above, I am reading my entire inventory sales order until I reach an empty row, which means the list is complete. End Result Imagine I take a sales order with the following information: Running my code I will end up with the following output (remember I decided to print my information out rather than store the values in a database: Next Time In my next few posts I am going to walk through other solutions to some key scenarios. Suggestions are always welcome. Zeyad Rajabi I’d like to get in touch with Zeyad and run some scenarios by him for future 2.0 examples. What is the best method of contacting him? His PDC presentation was excellent and we’re really looking forward to using 2.0. Thanks. don.capuano@thomsonreuters.com In my last two posts, I showed you how to create a spreadsheet based on data and how to read data from Hi Don, Thanks for the feedback. I will contact you by email. Zeyad Rajabi Dernier post de cette série sur la suppresion des commentaires dans les documents PowerPoint 2007 (PresentationML). Comme à l’accoutumé, voici une brochettes de liens de la semaine sur Open XML. Posts techniques en vrac Over on Brian Jones’ blog there are two recent articles that may be of interest to our readers here.
https://blogs.msdn.microsoft.com/brian_jones/2008/11/10/reading-data-from-spreadsheetml/
CC-MAIN-2017-13
refinedweb
1,365
62.51
1. Overview of Oracle GlassFish Server Troubleshooting Verify System Requirements and Configuration Search the Product Documentation Search the GlassFish Mailing Lists and Forums When Does the Problem Occur? What Is Your Environment? What Is Your System Configuration? Operating System Utilities Stack Traces and Thread Dumps To Obtain a Server Thread Dump Where to Go for More Information Oracle GlassFish Server Support 3. Frequently Asked Questions.1-3.1.1 Release Notes. Problems are likely to arise if you attempt to install on a platform that is not supported or on a system that in some other way does not meet release requirements. Also see Known Issues in Oracle GlassFish Server 3.1-3.1.1 Release Notes for known issues related to installation. Oracle GlassFish Server requires JDK release 6. The minimum (and certified) version of the JDK that is required for Oracle, Oracle.1-3.1.1 Release Notes for the latest information regarding known issues and possible workarounds. Also search the GlassFish Issue Tracker at. Oracle GlassFish Server includes complete product documentation. Search the documentation to see if your problem is addressed..1-3.1.1 Release Notes, which provides the latest information regarding known issues and possible workarounds. Oracle GlassFish Server 3.1 Error Message Reference, which lists error messages you might encounter when using GlassFish Server. Use the product documentation to learn more about Oracle GlassFish Server. The more you know about the product the easier it might be to figure out why something isn't working. Lists and forums are extremely helpful resources, and are accessed as follows: GlassFish mailing lists (start with users@glassfish.java.net and search the archives): GlassFish user forum: Other GlassFish forums: Troubles Oracle GlassFish Server are you using? What operating system and version? What JDK version? Many problems are caused simply because system requirements for the release are not met. Refer to the Oracle GlassFish Server 3.1-3.1 Oracle GlassFish Server? On the same system? How is Oracle GlassFish Server connected to the directory server? What JDBC driver is being used to access the database? What are your settings? On which port is Oracle GlassFish Server? Logging is one of your most important troubleshooting tools. It is the process by which Oracle GlassFish Server captures data about events that occur during server operation, such as configuration errors, security failures, or server malfunction. This data is recorded in log files, and is usually your first source of information when Enterprise Server problems occur. The primary purpose of log files is to provide troubleshooting information. Analyzing the log files can help determine the health of the server and identify problem areas. By default, log information for each Oracle GlassFish Server server instance is captured in a server.log file. That is, each instance, including the domain administration server (DAS), has an individual log file. By default, the log file for the DAS is located in domain-dir/logs, and the log file for each instance is located in instance-dir/logs. In addition, for domains that use clustering, Oracle GlassFish Server captures log information for each cluster instance in a cluster.log file. By default, the cluster.log file is also located in instance-dir/logs. Oracle recommends using the Administration Console to view logging information. However, you can open a log file in a text editor and search for the module or message in which you are interested. Oracle GlassFish Server also lets you collect log files into a ZIP file, which provides a convenient means to collect and view the log files for an instance or a domain even when it is not running. You configure the Logging Service by setting attributes in the logging.properties file. Each server, configuration, instance, and cluster in the Oracle GlassFish Server domain has an individual logging.properties file. The root directory in which these logging.properties files are located is the same directory as for the domain.xml file, typically domain-dir/config. The default target when configuring logging attributes is the DAS. However, you can optionally target a specific server, instance, or cluster. You can also target a configuration that is shared by one or more instances or clusters. The Logging Service can also be configured using the Administration Console. Log levels such as SEVERE, WARNING, INFO, CONFIG, and others can be set to provide different types and amounts of information. The default setting is INFO. Each Oracle GlassFish Server module has its own logger, and each logger has its own namespace. Log levels can be set globally for all loggers, or individually for module-specific loggers. For information about using the Administration Console log viewer and logging functions, see the Administration Console online help. For information about using the command line for logging functions, see Chapter 7, Administering the Logging Service, in Oracle GlassFish Server 3.1 Administration Guide. Monitoring is another helpful tool. It is the process of reviewing the statistics of a system to improve performance or solve problems. By monitoring the state of various components and services deployed in Oracle GlassFish Server you can identify performance bottlenecks, predict failures, perform root cause analysis, and ensure that everything is functioning as expected. For more information about monitoring, including JConsole information, see Chapter 8, Administering the Monitoring Service, in Oracle GlassFish Server 3.1 Administration Guide.
http://docs.oracle.com/cd/E18930_01/html/821-2436/abgar.html
CC-MAIN-2015-48
refinedweb
889
50.23
Perhaps you already learn what Pure Component stands for. Here is link to the post. A pure component only render when the content changes even if the parent re-render all its components. In big data application this type of component produce performance boost. This is a class component only feature. So what we do when some functional component need to be render with change? This what a Memo stands for. Memo is functional component feature which can be added to a component as follows import React from 'react' function MemoComp({name}) { console.log('Rendering Memo Comp'); return ( <div> {name} </div> ) } export default React.memo( MemoComp) Using the memo keyword in export statement , we can specify the component as memo. The above component only render for the first time when the component mounted and then it render when the name changes only.
https://developerm.dev/2020/12/05/how-to-add-performance-boost-to-functional-component/
CC-MAIN-2021-17
refinedweb
142
67.25
I have read a couple of the same topics on the forums and it boils down to relative path. I’m deploying my app on streamlit cloud from my GitHub repository (). The error occurs when I’m trying to open all the .csv files in a folder (which is in the same directory as my app.py that runs!). The error: FileNotFoundError: [Errno 2] No such file or directory: 'Data\\Payment' So a selection of payment is being made which sets the path to the payment folder and calls for a function to open the files and create a dataframe: if selection == 'Payment': path = r'Data\Payment' df = open_df(path) def open_df(path): files = [f for f in listdir(path) if isfile(join(path, f)) and f.endswith('.csv')] dataframes = list() for file in files: df = pd.read_csv(join(path, file)) Everything works smoothly if I run the app localy (i.e. streamlit run app.py)
https://discuss.streamlit.io/t/filenotfounderror-errno-2-no-such-file-or-directory-yes-im-using-relative-path/28249
CC-MAIN-2022-33
refinedweb
156
72.87
Python bindings for Selenium Project description Introduction Python language bindings for Selenium WebDriver. The selenium package is used to automate web browser interaction from Python. Several browsers/drivers are supported (Firefox, Chrome, Internet Explorer, PhantomJS), as well as the Remote protocol. Supported Python Versions - Python 2.6, 2.7 - Python 3.3+ Installing If you have pip on your system, you can simply install or upgrade the Python bindings: pip install -U selenium Alternately, you can download the source distribution from PyPI (e.g. selenium-3.0.2.tar.gz), unarchive it, and run: python setup.py install Note: both of the methods described above install selenium as a system-wide package That will require administrative/root access to their machine. You may consider using a virtualenv to create isolated Python environments instead. Drivers Selenium requires a driver to interface with the chosen browser. Firefox, for example, requires geckodriver, which needs to be installed before the below examples can be run. Make sure it’s in your PATH, e. g., place it in /usr/bin or /usr/local/bin. Failure to observe this step will give you an error selenium.common.exceptions.WebDriverException: Message: ‘geckodriver’ executable needs to be in PATH. Other supported browsers will have their own drivers available. Links to some of the more popular browser drivers follow. uisng Python’s standard unittest library: import unittest.0.0.jar Then run your Python client scripts. Use The Source Luke! View source code online: Project details Release history Release notifications | RSS feed Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/selenium/3.0.2/
CC-MAIN-2021-25
refinedweb
274
51.55
IMPORTANT: these bookmarklets are outdated. Please visit the latest version. This is a collection of RDFa-based bookmarklets. To use them: These have been tested on Safari, Mozilla, and Firefox. IE6 should work for most of these, too. Opera should work for most, too. This new version of the bookmarklet uses the current base URI as the default namespace for CURIEs. It then special-cases REL=next,home,prev in an HGRDDL transform. You can look at the hGRDDL transform. This version also includes a hard-wired handling of the hcard microformat profile, loads up the hGRDDL transform hcard-rdfa.js, and then does the RDFa parsing. The CC License Boomarklet can be tested on: The RDFa Highlighter can be tested on: The GetCal can be tested on: Read the HOWTO.
http://www.w3.org/2001/sw/BestPractices/HTML/rdfa-bookmarklet/
CC-MAIN-2015-18
refinedweb
131
77.94
Namespaces in Visual Basic Namespaces organize the objects defined in an assembly. Assemblies can contain multiple namespaces, which can in turn contain other namespaces. Namespaces prevent ambiguity and simplify references when using large groups of objects such as class libraries. For example, the .NET Framework defines the ListBox class in the System.Windows.Forms namespace. The following code fragment shows how to declare a variable using the fully qualified name for this class: Avoiding Name Collisions .NET Framework namespaces address a problem sometimes called namespace pollution, in which the developer of a class library is hampered by the use of similar names in another library. These conflicts with existing components are sometimes called name collisions. For example, if you create a new class named ListBox, you can use it inside your project without qualification. However, if you want to use the .NET Framework ListBox class in the same project, you must use a fully qualified reference to make the reference unique. If the reference is not unique, Visual Basic produces an error stating that the name is ambiguous. The following code example demonstrates how to declare these objects: The following illustration shows two namespace hierarchies, both containing an object named ListBox. By default, every executable file you create with Visual Basic contains a namespace with the same name as your project. For example, if you define an object within a project named ListBoxProject, the executable file ListBoxProject.exe contains a namespace called ListBoxProject. Multiple assemblies can use the same namespace. Visual Basic treats them as a single set of names. For example, you can define classes for a namespace called SomeNameSpace in an assembly named Assemb1, and define additional classes for the same namespace from an assembly named Assemb2. Fully Qualified Names Fully qualified names are object references that are prefixed with the name of the namespace in which the object is defined. You can use objects defined in other projects if you create a reference to the class (by choosing Add Reference from the Project menu) and then use the fully qualified name for the object in your code. The following code fragment shows how to use the fully qualified name for an object from another project's namespace: Fully qualified names prevent naming conflicts because they make it possible for the compiler to determine which object is being used. However, the names themselves can get long and cumbersome. To get around this, you can use the Imports statement to define an alias—an abbreviated name you can use in place of a fully qualified name. For example, the following code example creates aliases for two fully qualified names, and uses these aliases to define two objects. If you use the Imports statement without an alias, you can use all the names in that namespace without qualification, provided they are unique to the project. If your project contains Imports statements for namespaces that contain items with the same name, you must fully qualify that name when you use it. Suppose, for example, your project contained the following two Imports statements: If you attempt to use Class1 without fully qualifying it, Visual Basic produces an error stating that the name Class1 is ambiguous. Namespace Level Statements Within a namespace, you can define items such as modules, interfaces, classes, delegates, enumerations, structures, and other namespaces. You cannot define items such as properties, procedures, variables and events at the namespace level. These items must be declared within containers such as modules, structures, or classes.
http://msdn.microsoft.com/en-us/library/zt9tafza(v=vs.80).aspx
CC-MAIN-2013-20
refinedweb
582
52.6
Hello, I've always been a backend (pure java) programmer, but now I find myself working in the HTML, JSP and JavaScript more. I am becoming frustrated by the fact that Intellij's Find Usages functionality can't help me when a String literal that infact represents a java constant is used in a xyz.js file. I'm wondering if anyone has any good techniques to help "link" the usage to the constant. For example I have a Java file named ComponentType.java. It has a constant as defined below: public class ComponentType { public static final String FOO = "FOO"; Then I have a javascript file named bangMyHead.js which constains the following: isFoo: function() { return this._componentType === "FOO"; } I am willing to adopt some type of inconvenient convention to help structure the code in a way that will help Intellij. For example, the following will not work but if it did I would happily start doing it. If I could resturcture bangMyHead.js as: /** * @see com.acme.ComponentType#FOO */ var COMPONENT_TYPE_FOO = "FOO"; isFoo: function() { return this._componentType === "FOO"; } I'm tempted to make the files JSPs, but I'm told that will have a negative impact on performance by preventing caching.
https://intellij-support.jetbrains.com/hc/en-us/community/posts/206180809-Techniques-to-associate-Java-constants-to-Javascript-files
CC-MAIN-2020-24
refinedweb
202
55.64
I was impressed, and thankful for the time and attention that resulted from the serendipitous intersection of my venting frustration, and his proactive preparation for advocating Python at work. I was impressed by the community that suddenly showed up at my first public sign of angst. Now that I've had time to calm down, and consider the advice given... I'm still disappointed in Python... but it doesn't suck anymore. Al is right when he says Your Ignorance Does Not Make a Programming Language Suck I'm surprised by immutable strings in Python. It was frustrating hitting an unexpected roadblock in what otherwise seems to be a cool programming language that I'm just getting into. I can do what I want, but not in the way I had intended. I have to use a kludge to work around the immutable strings in Python, or just give up and find another way. Needless to say, it's frustrating when a language just doesn't match your expectations... it's an impedance mismatch. I've read PEP 3137 - Immutable Bytes and Mutable Buffer, and at first I was hopeful that change was in the air, and I could really LIKE python again... but alas... the immutable string is here to stay. Python has so many cool features, it's really strange that they can't handle the idea of strings that are variables, or variable parameters, like Pascal. Even a namespace hack to allow access one level up would be better than nothing. I'm finding it really hard to let go of string variables, and I guess that's just a mismatch for me to be aware of in the future. Perhaps I'll have to implement a sourcebuffer class, with functions like expect, getchar, getstring, getnumber, getfloat, etc. I've managed to sidestep the issue for now by using split and some other tricks. I do like the trick given in the comments: a,c = s[:1], s[1:]Of course, it would be nice not to have to keep putting the string back into itself... which I think is really my main objection to immutable strings. Why should I have to keep manually putting data back into the place it just came from? Doesn't that increase the risk of putting back into the wrong place? Oh well... it's interesting having my 15 minutes of fame over a programming issue. Thanks to everyone for your time and attention. --Mike--
http://mikewarot.blogspot.com/2008_03_01_archive.html
CC-MAIN-2013-20
refinedweb
414
71.75
The QR Code libraries allows your program to create (encode) QR Code image or, read (decode) an image containing one or more QR Codes. The attached source code is made of two solutions, a QR Code Encoder solution and a QR Code decoder solution. The encoder solution targets .NET framework (net462) and .NET standard (netstandard2.0). The decoder solution targets .NET framework (net462). The source code is written in C#. It is an open source code. The source downloads attached to this article include two libraries and four demo/test applications. Version 2.1.0 Support was added for ECI Assignment Number. The assignment number range is zero to 999999. The number is not part of the QR Code data. It is used for encoding data subject to alternative interpretations of byte values (e.g. alternative character sets). QRCodeEncoderLibrary QRCodeEncoderDemo string QRCodeConsoleDemo QRCodeDecoderLibrary QRCodeDecoderDemo QRCodeVideoDecoder The QR Code encoder part of this library is includer in the PDF File Writer C# Class Library article. The open source code attached is made of two Visual Studio solutions. Each solution is made of one library project and two demo/test projects. As described above. Integrating the code to your application requires the following steps. Install either the QRCodeEncoderLibrary.dll or the QRCodeDecoderLibrary.dll in your development area. Start the Visual Studio C# program and open your application. Go to the Solution Explorer, right click on References and select Add Reference. Select the Browse tab and navigate your file system to the location of the required library. When your application is published, the relevant library file must be included and installed in the same folder as your executable (.exe) file. The relevant "using" statement must be added to all your source files: using using QRCodeEncoderLibrary; // or Using QRCodeDecoderLibrary; QR Code stands for Quick Response Code. It is a two-dimensional barcode. Visually, it is a square made of small black and white square modules. The square is surrounded by a white quite zone. The QR Code is defined by the international standard ISO/IEC 18004. A free copy of this standard is available here. The ISO standard document defines the QR Code as “QR Code is a matrix consisting of an array of nominally square modules arranged in an overall square pattern, including a unique finder pattern located at three corners of the symbol and intended to assist in easy location of its position, size and inclination. A wide range of sizes of symbol is provided for together with four levels of error correction. Module dimensions are user-specified to enable symbol production by a wide variety of techniques.” The ISO standard 18004 is the best source of information for understanding the details of the QR Code. Searching the internet yields many more articles on this subject. Wikipedia article about QR Code can be viewed here. The QR Code standard is a collection of 40 different squares varying in size. Each square has a version number from 1 to 40. The size of each square varies from 21 by 21 modules (version 1) to 177 by 177 modules (version 40). Each version has 4 more modules per side than the previous version. Square-Dimension = 21 + 4 * (Version - 1) Some of the modules are fixed. The most obvious ones are the three-square finders. The remaining modules are divided between data and error correction. There are 4 levels of error correction: Each module in the data area represent one bit. Black module is 1 and white module is 0. The data area can be divided into segments. Each input segment byte array is encoded to data bits in one of three ways as described below. Note: The QR Code standard has one more encoding method for Kanji characters. It is not supported by this project. To encode a QR Code, you supply the data to be encoded and one of the four error correction codes. The system will calculate the smallest version number required to represent the data. The program analyzes each segment to find the "best" encoding. If you want to reduce the size of the QR Code and you have long strings of digits or alphanumeric data as defined above, then break your input into several strings or byte arrays. Some of these strings must be numeric only or Alphanumeric as defined above. During the decoding process, all resulted string segments will be concatenated together. When the library decodes an image containing one or more QR Codes, the result will be an array of strings or array of byte arrays. Each array item is one QR Code. The main class for encoding is QREncoder. It will convert a byte array or a text string into a QR Code image. To create a QR Code image, follow the steps below: QREncoder Create QREncoder object. Set the four optional parameters. This object is reusable. If you want to create many QR Codes, just reuse this object. There is no initialization or dispose requirement. The four optional parameters will keep their value from the last run. // create QR Code encoder object QRCodeEncoder Encoder = new QREncoder(); Set the four optional parameters if required // Error correction // error correction low (7%) Encoder.ErrorCorrection = ErrorCorrection.L; // or // error correction medium (15%) The Default Encoder.ErrorCorrection = ErrorCorrection.M; // or // error correction quarter (25%) Encoder.ErrorCorrection = ErrorCorrection.Q; // or // error correction high (30%) Encoder.ErrorCorrection = ErrorCorrection.H; // module size in pixels (default is 2) Encoder.ModuleSize = 2; // Quiet zone around the symbol (default is 8) // Quiet zone must be at least 4 times the module size Encoder.QuietZone = 8; // ECI Assignment Value (default is -1 not used) // The ECI value is a number in the range of 0 to 999999. // or -1 if it is not used Encoder.ECIAssignValue = -1; Higher error correction percentage gives you better protection against damaged QR Code images. The cost is the size of the QR symbol. Call one of the four Encode methods: Encode // single text string input public void Encode(string StringDataSegment); // multiple text strings input public void Encode(string[] StringDataSegments); // single byte array input public void Encode(byte[] ByteDataSegment); // multiple byte arrays input public void Encode(byte[][] ByteDataSegments); If input data is text string, or array of text strings. The text will be converted to byte array using the following method. // the encoder converts text string to byte array using the conversion below byte[] ByteArray = Encoding.UTF8.GetBytes(Text); Effectively, the library software will convert the first and second Encode methods to the third and fourth methods respectively. The QRCodeEncoderLibrary will scan each incoming data byte array segment to determine the best encoding method. The program will not attempt to break a single segment to minimize the size of the QR Code matrix. You can submit array of segments in such a way as to take advantage of long strings of numeric or alphanumeric data. The Encode method has no return value. If encoding is successful, a two-dimensional bool array (QRCodeMatrix) representing a QR Code image is saved within the Encode class. If encoding fails, an exception will be thrown. The QRCodeMatrix is a square array. Black modules are true and white modules are false. The matrix dimension is given in QRCodeEncoder.QRCodeDimension. QRCodeMatrix true false QRCodeEncoder.QRCodeDimension The next step is to save the QR Code symbol to a file or, to create a Bitmap. The example below shows how to create QR Code image file with the content "QR Code Library Project". // create QREncoder object QREncoder Encoder = new QREncoder() // set optional parameters Encoder.ErrorCorrection = ErrorCorrection.Q; Encoder.ModuleSize = 4; Encoder.QuietZone = 16; // encode input text string // Note: there are 4 Encode methods in total Encode("QR Code barcode example text string"); // save the barcode to PNG file // This method DOES NOT use Bitmap class and is suitable for net-core and net-standard // It produces files significantly smaller than SaveQRCodeToFile. Encoder.SaveQRCodeToPngFile("File-Name"); // or // save barcode image to an open stream Encoder.SaveQRCodeToPngFile(OutputStream); // or // save barcode image to file using Bitmap class // this is for net-framework and not for net-code or net-standard // you can produce PNG file but consider the QRCOdeToPngFile method above. Encoder.SaveQRCodeToFile("File-Name", ImageFormat); // or // save barcode image to an open stream Encoder.SaveQRCodeToFile(OutputStream, ImageFormat); // or // create Bitmap class (net-framework only) Bitmap bitmap = CreateQRCodeBitmap(); // or // create Bitmap class with different colors (net-framework only) Bitmap bitmap = CreateQRCodeBitmap(WhiteBrush, BlackBrush); // or // create bool array of image pixels Bool[,] ImagePixels = ConvertQRCodeMatrixToPixels(); The command line arguments are described below. A more detail description of each option is given above. Command line arguments format [optional arguments] input-file output-file Output file must have .png extension Options format /code:value or -code:value (the : can be =) Error correction level. code=[error|e], value=low|l|medium|m|quarter|q|high|h], default=m Module size. code=[module|m], value=[1-100], default=2 Quiet zone. code=[quiet|q], value=[4-400], default=8, min=4*width Text file format. code=[text|t] see notes below Input file is binary unless text file option is specified If input file format is text or t, the string will be encoded to byte array The QRDecoder converts QR Code Bitmap images into an array of byte arrays. If the QR Code image contains optional ECI Assignment Value it can be retrived as noted below. To decode a Bitmap containing one or more QR Code images, follow the steps below. QRDecoder Bitmap Create QRDecoder object. This object is reusable. If you want to create many QR Codes, just reuse this object. There is no initialization or dispose requirement. And call the ImageDecoder method. ImageDecoder // create QR Code decoder object QRDecoder Decoder = new QRDecoder(); // call image decoder methos with <code>Bitmap</code> image of QRCode barcode byte[][] DataByteArray = Decoder.ImageDecoder(InputImage) // get the ECI Assignment value ECIValue = Decoder.ECIAssignValue; if(ECIValue == -1) { // Assignment value not defined } else { // Assignment value between 0 to 999999 } If DataByteArray is null, no QR Code was detected within the Bitmap. If DataByteArray length is one, one QR Code was found. If DataByteArray length is more than one, there were more than one QR Code images within the Bitmap. Each QR Code image is represented by a byte array. To convert a byte array to string use: DataByteArray null // convert binary result to text string string Result = QRCode.ByteArrayToStr(DataByteArray[Index]); The ByteArrayToStr method converts byte array into string in the following way: ByteArrayToStr // The QRDecoder converts byte array to text string the class using this conversion public static string ByteArrayToStr(byte[] DataArray) { Decoder = Encoding.UTF8.GetDecoder(); int CharCount = Decoder.GetCharCount(DataArray, 0, DataArray.Length); char[] CharArray = new char[CharCount]; Decoder.GetChars(DataArray, 0, DataArray.Length, CharArray, 0); return new string(CharArray); } For example, the image below is of two QR Codes one within the other. The big one data is: Big QR Code, the small one data is: Small QR Code. The big one has error correction set to High. The program will find both QR Codes and recover the missing area of the big one using error correction to get the correct content. style="width: 432px; height: 432px" data-src="/KB/library/1250071/DoubleQRCode.png" class="lazyload" data-sizes="auto" data-> QR Code 1 Big QR Code QR Code 2 Small QR Code Another example of three QR Codes. The decoder finds 9 finders in the picture. All possible 3 out of 9 finders are tested. The result is three groups of three finders test for valid QR Code structure. The result is given below in the picture. QR Code 1 Top left corner QR Code 2 Top right corner QR Code 3 Bottom left corner QR Code Encoder Demo is a test program showing how to encode a QR Code and save it as an image file. style="width: 596px; height: 543px" data-src="/KB/library/1250071/QRCodeEncoderDemo.png" class="lazyload" data-sizes="auto" data-> style="width: 570px; height: 600px" data-src="/KB/library/1250071/QRCodeEncoderSave.png" class="lazyload" data-sizes="auto" data-> QR Code Decoder Demo is a test program showing how to scan an image file for QR Codes and convert the decoded data into an array of byte arrays or strings. width="626" data-src="/KB/library/1250071/QRCodeDecoderDemo.png" class="lazyload" data-sizes="auto" data-> QR Code Video Decoder QRCodeVideoDecoder is a test/demo application that will use the first found web camera in your system. A demo program combining QR Code decoder and video camera image capture. The video camera software is based on the Direct Show Library. This demo program is using some of the source modules of Camera_Net project published at CodeProject.com and at Github This project is based on DirectShowLib.. Please note the DirectShowLib in this project is a modified subset of the original source modules. DirectShowLib Please note, I have only tested this application on my own video camera. My camera is Logitech HD Webcam C615. I am using frame size of 640 by 480 pixels. The program sets the camera software to display the video stream in a preview area on the screen. The scanning is 5 frames per seconds. Each frame is captured and tested for a QR Code. Once a QR Code is found, the result is displayed at the Decoded data text box. Decoding stops until the reset button is pressed. If the decoded data is a URI, the Go To URI button is enabled, and you can display this URI on your default web browser. For video decoding to be successful, each QR Code module must be represented by a few camera pixels. For example, 4 by 4 or more pixels. The QR Code must be reasonably sharp, flat and parallel to the camera. The picture below illustrates the power of the software to transform the image to a square with the finder symbols at their correct positions. style="width: 617px; height: 629px" data-src="/KB/library/1250071/QRCodeVideoDecoder.png" class="lazyload" data-sizes="auto" data-> This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL) // convert results to text DataTextBox.Text = QRCodeResult(DataByteArray); #if DEBUG if(DataByteArray != null && DataByteArray.Length > 0) { byte[] Data = DataByteArray[0]; for(int Index = 0; Index < Data.Length; Index++) { QRCodeTrace.Format("{0}: Dec {1}, Hex {1:x2}", Index, Data[Index]); } } #endif 2021/03/04 11:24:46 Decode image: D:\CSharp2017\QRCode\QRCodeDecoder\QRCodeDecoderDemo\Work\qr-test2.jpg 2021/03/04 11:24:46 Image width: 70, Height: 70 2021/03/04 11:24:46 Convert image to black and white 2021/03/04 11:24:46 Time: 16 2021/03/04 11:24:46 Finders search 2021/03/04 11:24:46 Horizontal Finders count: 21 2021/03/04 11:24:46 Matched Finders count: 15 2021/03/04 11:24:46 Remove all unused finders 2021/03/04 11:24:46 Time: 47 2021/03/04 11:24:46 Finder: Row: 20, Col: 20, Module: 2.00, Distance: 0.00 2021/03/04 11:24:46 Finder: Row: 56, Col: 20, Module: 2.00, Distance: 0.00 2021/03/04 11:24:46 Finder: Row: 56, Col: 56, Module: 2.00, Distance: 0.00 2021/03/04 11:24:46 Search for QR corners 2021/03/04 11:24:46 Decode Corner: Top Left: Finder: Row: 56, Col: 20, Module: 2.00, Distance: 0.00 2021/03/04 11:24:46 Decode Corner: Top Right: Finder: Row: 20, Col: 20, Module: 2.00, Distance: 0.00 2021/03/04 11:24:46 Decode Corner: Bottom Left: Finder: Row: 56, Col: 56, Module: 2.00, Distance: 0.00 2021/03/04 11:24:46 Initial version number: 2, dimension: 25 2021/03/04 11:24:46 Format info match with errors: 7D56, EC: L, mask: 2, errors: 3 2021/03/04 11:24:46 Decode QR code using three finders 2021/03/04 11:24:46 Fixed modules some errors: 1 / 236 2021/03/04 11:24:47 Decode QR code exception. Data is damaged. Error correction failed 2021/03/04 11:24:47 Estimated alignment mark: Row 26, Col 50 2021/03/04 11:24:47 Calculated alignment mark: Row 26, Col 50 2021/03/04 11:24:47 Fixed modules some errors: 1 / 236 2021/03/04 11:24:47 Decode QR code exception. Data is damaged. Error correction failed 2021/03/04 11:24:47 Time: 250 2021/03/04 11:24:47 No QR Code found QRDecoder Decoder = new QRDecoder(); byte[][] byteArrayQR = Decoder.ImageDecoder(picBitmap); return QRDecoder.ByteArrayToStr(byteArrayQR[0]); FileInfo TraceFileInfo = new FileInfo(TraceFileName); System.ArgumentNullException 'Value cannot be null. Parameter name: fileName' QRCodeDecoderLibrary.QRCodeTrace.TestSize() in QRCodeTrace.cs QRCodeDecoderLibrary.QRCodeTrace.Write(string) in QRCodeTrace.cs QRCodeDecoderLibrary.QRDecoder.ImageDecoder(System.Drawing.Bitmap) in QRDecoder.cs QRCodeDecoderDemo.cs #if DEBUG // current directory string CurDir = Environment.CurrentDirectory; string WorkDir = CurDir.Replace("bin\\Debug", "Work"); if(WorkDir != CurDir && Directory.Exists(WorkDir)) Environment.CurrentDirectory = WorkDir; // open trace file QRCodeTrace.Open("QRCodeDecoderTrace.txt"); QRCodeTrace.Write("QRCodeDecoderDemo"); #endif QRDecoder.cs internal const double SIGNATURE_MAX_DEVIATION = 0.25; internal const double SIGNATURE_MAX_DEVIATION = 0.35; 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.
https://codeproject.freetls.fastly.net/Articles/1250071/QR-Code-Encoder-and-Decoder-NET-Framework-Standard
CC-MAIN-2021-43
refinedweb
2,880
58.48
#include <Thread.h> class Thread{ Thread()(); Thread(std::string name); virtual ~Thread(); int detach(); unsigned long getId(); void start(); void setName(std::string name); void join(); const std::string getName(); virtual void run();} Thread is an abstract base class that can be used to create threads. To make a thread you will normally derive a class from Thread and write the run method to implement the thread's code. A thread can then be created like any other object. The start method schedules the thread's run member for execution Threads can block on the completion of a thread via the join method. Constructors. Constructors create a thread. The thread is not scheduled for execution until the start method is called. Threads can have an optional thread name. Thread()(); Constructs an anonymous thread. Thread(std::string name); Constructs a named thread. Thread identification. Threads are identified by an optional name, which need not be unique, and a unique identifier (thread id), that is assigned by the underlying operating systemn. unsigned long getId(); Returns the thread id. If the thread has not yet been started, -1 is returned regardless of the thread. A thread only gets an id when it has been started. void start(); Starts a thread. A thread id is allocated and the run method is scheduled for execution. void setName(std::string name); Modifies the name of the thread. int detach(); Detaches an executing thread. If the thread has not started, this returns -1. Detaching a thread indicates that any operating system storage (not object storage) associated with a thread can be released when the thread exits. If the thread does not detach, it is necessary to join the thread to fully release its storage. On success, 0 should be returned, otherwise a value that is one of the values in errno.h is returned to describe why the call failed. void join(); join blocks until the thread exits. When the thread does exit, thread specific storage is reclaimed. Note that if a thread has calledis detach it is not clear clear wht clear what this member will do. const std::string getName(); Returns the name of the thread. virtual void run(); You must implement this pure virtual function to provide a concrete Thread run-time behavior.
http://docs.nscl.msu.edu/daq/newsite/nscldaq-11.2/r36196.html
CC-MAIN-2017-39
refinedweb
379
74.69
The fields from the browser to the specified Command object. Input fields are passed as Strings, even if it is an Integer or a Date. In Spring there is a class called ServletRequestDataBinder which does the mapping from input fields to a Command class. This is all hidden for the developer and I also didn’t know it before yesterday. I’m currently reading “Expert Spring MVC and Web Flow†and came across a nice subsection. In chapter 6 is explained how the SimpleFormController maps the request parameters to an object and since we’re talking about Spring there is a super class with which you can do a lot of nice things. The super super class of ServletRequestDataBinder is DataBinder. The DataBinder class binds a list of values to an object. So let’s say we have a list of values we want to map to an Employee object. First create an Employee class with getters and setters for id (Long), name (String) and department (Integer). Then override the toString method so we can see what happens in the following steps. public String toString() { return "[" + id + ", " + name + ", " + department + "]"; } Now create a simple testcase with a testBind method. public void testBind() { MutablePropertyValues values = new MutablePropertyValues(); values.addPropertyValue("id", "7839"); values.addPropertyValue("name", "KING"); values.addPropertyValue("department", "20"); Employee employee = new Employee(); DataBinder binder = new DataBinder(employee); binder.bind(values); log.debug(employee); } First we put all the values on a MutablePropertyValues object. Then we create a new Employee object on which we want the values set. The last steps are creating a DataBinder object and binding the values to that object. When we run the testcase the following line will be printed: DEBUG nl.amis.BinderTest - [7839, KING, 20] That was quite easy, no fuzz with Long.valueOf and NumberFormatExceptions. But you’re probably wondering what happens when we provide invalid parameters. Let’s change the department to X20 and run the test again. DEBUG nl.amis.BinderTest - [7839, KING, null] The test runs successfully and you won’t get any errors. This is not what you want. Add the lines try { binder.close(); } catch (BindException bindException) { List<FieldError> errors = bindException.getAllErrors(); for (FieldError error : errors) { log.error(error); log.error("cannot bind " + error.getRejectedValue() + " to the field " + error.getField()); } } Now an error is printed on the console. The FieldError object is quite useful to print out nice error messages to end users.You can invoke the getBindingResult right after invoking the bind method, but I think it’s better to close the binder and catch the BindException, but you’re free to do what you prefer. With web applications you want to have some kind of protection. Let’s say we use our own DataBinder to save an Employee object to a database. We have a web page with an Employee form and we have an input field for name and department. Now some kind of evil person can add an Id field and save that field to the database. Luckily the guys from Spring thought about this. On the DataBinder you can invoke the setAllowedFields method (or the setDisallowedFields the other way around). So add the following line to the test just before invoking bind. binder.setAllowedFields(new String[]{"name", "department"}); Now the id parameter is not set. No error is added to the list of errors by the way. With the Spring PropertyEditor system you can add your own data type and bind any String to any object. Using the DataBinder with a RowMapper The following example wasn’t what I hoped for, but I think it can be useful for some people. I wanted to make an automatic RowMapper for the Spring JdbcTemplate. When you do a query you can include a RowMapper. That RowMapper looks like this: public class EmployeeRowMapper implements RowMapper { public Employee mapRow(ResultSet rs, int row) throws SQLException { MutablePropertyValues values = new MutablePropertyValues(); ResultSetMetaData setMetaData = rs.getMetaData(); int count = setMetaData.getColumnCount(); for (int i = 1; i <= count; i++) { values.addPropertyValue( setMetaData.getColumnName(i).toLowerCase(), rs.getObject(i)); } Employee employee = new Employee(); DataBinder binder = new DataBinder(employee); binder.bind(values); try { binder.close(); } catch (BindException e) { throw new SQLException(e.getMessage()); } return employee; } } With the getMetaData you can get all the column names and with the DataBinder you can bind those values to the object automatically. You have to do the naming of your parameters in sql. The query for all employees: select empno id, deptno department, ename name from emp But the big problem is that getColumnName returns uppercase characters and usually you want to have mixed case with java field names (departmentName, orderStatus etc.). When your field names have the same case it’s no problem, but you can’t rely on this. There will be a programmer in your project who forgets about is and then everything is messed up and you end up with two different methods. It’s probably better to use iBatis or Hibernate when you want ‘automatic’ binding. Nested Properties Let’s take it one step further (thanks for the tip qinxian). It is possible to have nested properties. Let’s say our Employee object has a Department object. This Department object has an id, name and location. When we want to set the location of the department of a certain employee we just use the d ot-notation: values.addPropertyValue(“department.location”, “NEW YORK”); Create a Department class with getters and setters for id, name and location. Change the department field of Employee fromk Integer to Department (and don’t forget to update the get and set method). Then change the code in your unit test: MutablePropertyValues values = new MutablePropertyValues(); values.addPropertyValue("id", "7839"); values.addPropertyValue("name", "KING"); values.addPropertyValue("department.id", "10"); values.addPropertyValue("department.name", "ACCOUNTING"); values.addPropertyValue("department.location", "NEW YORK"); Employee employee = new Employee(); employee.setDepartment(new Department()); DataBinder binder = new DataBinder(employee); binder.bind(values); Don’t forget to create a Department object, this isn’t done for you. It’s also possible to use indexed properties, key/value properties and array properties. I’ll explain binding to a List, the key/value and array properties are done in almost exactly the same way. Our employee now can work in multiple departments. So change the department field on Employee to private List<Department> departments (and update the get and set). Now replace the lines in your test: MutablePropertyValues values = new MutablePropertyValues(); values.addPropertyValue("id", "7839"); values.addPropertyValue("name", "KING"); values.addPropertyValue("departments[0].id", "10"); values.addPropertyValue("departments[0].name", "ACCOUNTING"); values.addPropertyValue("departments[0].location", "NEW YORK"); values.addPropertyValue("departments[1].id", "20"); values.addPropertyValue("departments[1].name", "RESEARCH"); values.addPropertyValue("departments[1].location", "DALLAS"); Employee employee = new Employee(); employee.setDepartments(new ArrayList<Department>()); employee.getDepartments().add(new Department()); employee.getDepartments().add(new Department()); DataBinder binder = new DataBinder(employee); binder.bind(values); Note that we have to create the List and add two departments to it. When we run the test this is the result in the debugger: Conclusion Digging in the Spring code base can be very useful and can save you a lot of work. I always did my own binding and now I can do it the Spring-way. In our current project I do some binding to objects. We have some MultiActionControllers with different input objects. When we use the DataBinder we can clean up a lot of checks for NumberFormatExceptions and null values. And you don’t have to write documentation for the binder, because the Spring guys already did this for you Thanks for the nice example! What about if I need to do a “departments['Accounting'].id” — is that possible? Geeta, The data binding process works the same with a collection as it does with one. You need to extended the SimpleFormController, with an implementation that retrieves the List of Milestones from the data layer in its formBackingObject() method. Just remember that Spring’s data binding assumes that the command object is a simple object (not a List, Map or other Collection), otherwise you will get an error saying the object command[0] does not exist as an attribute. Also the special List and Map syntax doesnt apply the command object itself. Your formBackingObject() method needs to return a command object that wraps a List of Milestones objects. Also see: Hi, I am facing problem in binding collection. I have a command class MonthlyMilestone which contains Collection of Milestones. User can dynamically add or delete the milestones. I am using DHTML to add milestone. Could you please guide me how to go about? How do I bind the dynamically created collection to my command object. Thanks, Geeta You may also like to look at ResultSetMapper. It relies on Java 5/1.5, and can plug into Apache DBUtils or Spring (and probably others). It works with inheritance and aggregate objects. A simple Spring example would be: //——————————————————— // By default the MapToData annotations are required // but they can be turned off if the property name // maps to the database column (given your name // mapping strategy). By default the name mapping strategy // is camelCase = camel_case / under_score = underScore. //——————————————————— public class JellyCompany { @MapToData String companyName; @MapToData ( columnAliases= { “company_address” } ) String address; } … CallbackResultSetMapper mapper = new CallbackResultSetMapper(JellyCompany.class); JdbcTemplate template = new JdbcTemplate(dataSource); template.query(“SELECT * FROM jelly_companies”, mapper); List jellyCompanies = mapper.getObjects(); … Sounds good Thomas! When I need it anytime soon I’ll just include that file. Great idea qinxian, I added nested properties and nested properties with a List. Hi, maybe it would be more ? if you add a short sample code for nested structure. Very clear introduction Jeroen. What a enormous collection of often useful utilities is Spring! There is a class that has been in the sandbox for a while that maps a result set to bean properties. I just committed an improved version and renamed it from ActiveRowMapper to BeanPropertyRowMapper. I’m hoping to finish this up and add it to the core distribution soon. See
http://technology.amis.nl/2007/02/04/using-the-spring-databinder-to-map-strings-to-objects/
CC-MAIN-2014-35
refinedweb
1,662
51.14
11 May 2007 17:01 [Source: ICIS news] LONDON (ICIS news)--The International Energy Agency (IEA) has renewed its call on OPEC to increase oil output before the summer to avoid a sharp decline in global oil stocks. ?xml:namespace> In its monthly oil market report, the Paris-based IEA estimated total OPEC production for April at 30.35m bbl/day, including ?xml:namespace> Nigerian crude capacity shut-ins rose to 815,000 bbl/day in early May, adding to pressures caused by a gasoline market already tightened by an unusually high level of unplanned refinery outages, IEA said. Unsurprisingly, gasoline remained the primary driver behind oil prices, with US retail prices reaching levels not seen since the post-Hurricane Katrina spike in September 2005. Seasonal refinery maintenance and a spate of unplanned outages were expected to depress global throughput, IEA said. With demand increasing in June, this implies that there will be a further tightening of product stocks. Refinery runs, and therefore crude demand, should rise sharply in July (2.5m bbl/day over March) as refiners seek to meet peak summer demand. Preliminary OECD stock data continued to point to a 930,000 bbl/day draw in first-quarter total oil stocks, following on from a similar draw in the previous quarter. Forward demand cover provided by total oil inventories remained around the five-year average, but gasoline stocks are low in all regions. World oil output in April rose by 55,000 bbl/day to 85.5m bbl/day, with OPEC supply levelling off near 30.3m bbl/day. Non-OPEC growth in 2007 trimmed to 1.0m bbl/day, plus 0.2m bbl/day of OPEC NGLs. This leaves the 2.3m bbl/day rise in the ‘call on OPEC’ by the fourth quarter running well ahead of expected OPEC capacity additions, implying lower spare capacity later in the year. Global oil product demand was revised down marginally to 84.2m bbl/day in 2006 and 85.7m bbl/day in 2007 following adjustments to baseline historical data. The changes were centred
http://www.icis.com/Articles/2007/05/11/9028233/iea-calls-on-opec-to-help-build-up-stocks.html
CC-MAIN-2014-52
refinedweb
346
57.06
29 September 2009 19:38 [Source: ICIS news] By George Martin HOUSTON (ICIS news)--The prospects for packaging in the US expandable polystyrene (EPS) industry remained grim with the economy still in the doldrums, high unemployment, consumer fears and low demand, a plastics transformer said on Tuesday. Talk of another "black Christmas" at the retail level has begun, and the usual inventory build at this time for packaged goods was weak, the transformer added. Construction demand in some parts of the country appeared to be stronger, but new business was still being stymied by banks still not lending as before, the source said. Government stimulus spending was underway, but the bulk of those projects will hit in 2010, according to news reports. In the meantime, the prospects for the fourth quarter of 2009 were dim, the source said. Transformer companies reported that business ranged from flat to off by 40% relative to the low levels seen last year. Some estimated that business was down to about one half of last year. A large transformer in ?xml:namespace> The problem for all resin suppliers was a lack of forward demand by the transformers. Until demand picks up, attempts to raise prices would be met with resistance or ignored by the transformers, another transformer said. With benzene and styrene monomer prices heading back down, the likelihood of EPS price reductions in October was increasing. Another possibility is that October prices would be flat because the increases announced for September did not take hold with many buyers. The initial announcement called for a 5 cent/lb ($110/tonne, €75/tonne) increase in September that was later reduced to 3 cents/lb by all producers. However, many transformers had yet to see any increase. Many decided early on not to buy during September. The weak demand has allowed them to stretch their resin stocks while waiting for lower prices ahead. US producers acknowledged that volumes had suffered in September and they were preparing for a tough fourth quarter. “If all we lose in October is the September gains, that will be a blessing,” a producer said. EPS prices in the North American producers include NOVA Chemicals, Flint-Hill Resources, StyroChem, Nexkemia, BASF, Polioles and Polidesa, with the last three based in $1 = €0.68
http://www.icis.com/Articles/2009/09/29/9251301/us-expandable-polystyrene-demand-may-worsen-in-q4.html
CC-MAIN-2013-48
refinedweb
380
60.14
For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See: ATR problem Can someone put ATR into my code? I get that you can either build one yourself , utilize a built-in indicator, or use a third-party's but I am not sure how to use the make one myself or even use the built-in. I am trying to use the ATR as stop loss(Exiting a long position). import datetime import backtrader as bt # Create a subclass of Strategy to define the indicators and logic class SmaCross(bt.Strategy): # list of parameters which are configurable for the strategy params = dict( pfast=10, # period for the fast moving average pslow=30 # period for the slow moving average ) def __init__(self): sma1 = bt.ind.SMA(period=self.p.pfast) # fast moving average sma2 = bt.ind.SMA() # create a "Cerebro" engine instance data = bt.feeds.YahooFinanceCSVData( dataname="oracle.csv", fromdate=datetime.datetime(2000, 3, 1), todate=datetime.datetime(2000, 8, 29), reverse=False) cerebro.adddata(data) cerebro.addstrategy(SmaCross) # Add the trading strategy cerebro.run() # run it all cerebro.plot(style="candlestick",barup='green', bardown='red') I found a blog on how to build your own indicator, and the example is an ATR indicator. I tried running this but somethings not right class ATR (bt.indicator): range_total = 0 for i in range(-13, 1): true_range = self.datahigh[i] - self.datalow[i] range_total += true_range ATR = range_total / 14 def next(self): # CLOSING LOGS self.log('Close, %.2f, ATR: %.4f' % (self.dataclose[0], AtrStop)) Average True Range is a built in indicator found here. Build in indicators are mostly added during the init() of the strategy class. So for example, in your code: def __init__(self): sma1 = bt.ind.SMA(period=self.p.pfast) # fast moving average sma2 = bt.ind.SMA(period=self.p.pslow) # slow moving average self.crossover = bt.ind.CrossOver(sma1, sma2) # crossover signal self.my_atr = bt.ind.ATR(period=14) You can now access the value of your ATR at each bar in next: def next(self): if self.my_atr[0] > 'whatever': 'do something' Spend some time on the basic concepts and quickstart in the documentation. This will help you a lot.
https://community.backtrader.com/topic/2850/atr-problem/1
CC-MAIN-2021-31
refinedweb
373
51.04
Strings Skill Area 313 Part C Materials Prepared by DhimasRuswanto, BMm Lecture Overview • Char • Strings Char • A sequence of characters is often referred to as a character “string”. • A string is stored in an array of type charending with the null character “\0”. Char • A string containing a single character takes up 2 bytes of storage. Char • A string constant is a sequence of characters enclosed in double quotes. • E.g. char s1[2]=“a”; //takes 2 bytes of storage • On the other hand, the character, in single quotes: • E.g. char s2=‘a’; //takes only a byte of storage Char char message1[12] = “Hello world”; cout << message1 << endl; char message2[12]; cin >> message2; //type “Hello” as input getline • The function getline can be used to read an entire line of input into a string variable. • The getline function has three parameters: • The first specifies the area into which the string is to be read. • The second specifies the maximum number of characters, including the string delimiter. • The third specifies an optional terminating character. If not included, getline stops at “\n”. getline charA_string[80]; //80 is the size of A_string cout << “Enter some words in a string: \n”; cin.getline (A_string, 80); cout << A_string << “\nEnd of Output\n”; Output: Enter some words in a string: This is a test. This is a test. End of Output getline charlastName[30], firstName[30]; cout << “Enter a name <last,first>: \n”; cin.getline (lastName, sizeof(lastName)); cin.getline (firstName, sizeof(firstName)); cout << “Here is the name you typed: \n\t|” << firstName << “ ” <<lastName << “|\n”; Output: Enter a name <last, first>: Chan Anson Here is the name you typed: |Anson Chan| Strings #include <string> //string header file stringmystr; //declare string getline (cin, mystr); //getline for string Example (Strings) #include <iostream> #include <string> usingnamespacestd; intmain () { stringmystr; cout << "What's your name? "; getline (cin, mystr); cout << "Hello " << mystr << ".\n"; cout << "What is your favorite team? "; getline (cin, mystr); cout << "I like " << mystr << " too!\n"; return 0; } stringstream • The standard header file <sstream> defines a class called stringstream that allows a string-based object to be treated as a stream. This way we can perform extraction or insertion operations from/to strings, which is especially useful to convert strings to numerical values and vice versa. • For example, if we want to extract an integer from a string we can write: string mystr ("1204"); intmyint; stringstream(mystr) >> myint; Example (stringstream) #include <iostream> #include <string> #include <sstream> usingnamespacestd; intmain () { stringmystr; float price=0; intquantity=0; cout << "Enter price: "; getline (cin,mystr); stringstream(mystr) >> price; cout << "Enter quantity: "; getline (cin,mystr); stringstream(mystr) >> quantity; cout << "Total price: " << price*quantity <<endl; return 0; } strcpy char name1[16], name2 [16]; strcpy(name2, name1) //copies string name2 into string name1 Name1[16]=“Chan Tai Man” Name2[16]=“9999999999999999” strcpy(name2, name1); Examples Exchange the value of 2 numbers; inta,b,temp; cout<< “Enter a: ”; cin >> a; cout << “Enter b: “; cin >> b; temp=a; a=b; b=temp; cout << a <<endl; cout << b << endl; --- continue to next slide ---
https://www.slideserve.com/toki/strings
CC-MAIN-2021-39
refinedweb
503
58.62
Introducing Advanced Deep Learning with Keras In this first chapter, we will introduce three deep learning artificial neural networks that we will be using throughout the book. detection and segmentation, and unsupervised learning using mutual information. Together, we'll discuss how to implement MLP, CNN, and RNN based models using the Keras library in this chapter. More specifically, we will use the TensorFlow Keras library called tf.keras. We'll start by looking at why tf.keras is an excellent choice as a tool for us. Next, we'll dig into the implementation details within the three deep learning networks. This chapter will: - Establish why the tf.keraslibrary is a great choice to use for advanced deep learning - Introduce MLP, CNN, and RNN – the core building blocks of advanced deep learning models, which we'll be using throughout this book - Provide examples of how to implement MLP, CNN, and RNN based models using tf.keras - Along the way, start to introduce important deep learning concepts, including optimization, regularization, and loss function By the end of this chapter, we'll have the fundamental deep learning networks implemented using tf.keras. In the next chapter, we'll get into the advanced deep learning topics that build on these foundations. Let's begin this chapter by discussing Keras and its capabilities as a deep learning library. 1. Why is Keras the perfect deep learning library? Keras [1] is a popular deep learning library with over 370,000 developers using it at the time of writing – a number that is increasing by about 35% every year. Over 800 contributors actively maintain it. Some of the examples we'll use in this book have been contributed to the official Keras GitHub repository. Google's TensorFlow, a popular open source deep learning library, uses Keras as a high-level API for its library. It is commonly called tf.keras. In this book, we will use the word Keras and tf.keras interchangeably. tf.keras is a popular choice as a deep learning library since it is highly integrated into TensorFlow, which is known in production deployments for its reliability. TensorFlow also offers various tools for production deployment and maintenance, debugging and visualization, and running models on embedded devices and browsers. In the technology industry, Keras is used by Google, Netflix, Uber, and NVIDIA. We have chosen tf.keras as our tool of choice to work with in this book because it is a library dedicated to accelerating the implementation of deep learning models. This makes Keras ideal for when we want to be practical and hands-on, such as when we're exploring the advanced deep learning concepts in this book. Because Keras is designed to accelerate the development, training, and validation of deep learning models, it is essential to learn the key concepts in this field before someone can maximize the use of the library. All of the examples in this book can be found on GitHub at the following link:. In the tf.ker significantly fewer lines of code compared to other deep learning libraries such as PyTorch. By using Keras, we'll boost productivity by saving time in code implementation, which can instead be spent on more critical tasks such as formulating better deep learning algorithms. Likewise, Keras is ideal for the rapid implementation of deep learning models, like the ones that we will be using in this book. Typical models can be built in just a few lines of code using the Sequential model API. However, do not be misled by its simplicity. Keras can also build more advanced and complex models using its functional API and Model and Layer classes for dynamic graphs, which can be customized to satisfy unique requirements. The functional API supports building graph-like models, layer reuse, and creating models that behave like Python functions. Meanwhile, the Model and Layer classes provide a framework for implementing uncommon or experimental deep learning models and layers. Installing Keras and TensorFlow Keras is not an independent deep learning library. As you can see in Figure 1.1.1, it is built on top of another deep learning library or backend. This could be Google's TensorFlow, MILA's Theano, Microsoft's CNTK, or Apache MXNet. However, unlike the previous edition of this book, we will use Keras as provided by TensorFlow 2.0 ( tf2 or simply tf), which is better known as tf.keras, to take advantage of the useful tools offered by tf2. tf.keras is also considered the de facto frontend of TensorFlow, which has exhibited its proven reliability in the production environment. Furthermore, Keras' support for backends other than TensorFlow will no longer be available in the near future. Migration from Keras to tf.keras is generally as straightforward as changing: from keras... import ... to from tensorflow.keras... import ... In this book, the code examples are all written in Python 3 as support for Python 2 ends in the year 2020. On hardware, Keras runs on a CPU, GPU, and Google's TPU. In this book, we'll test on a CPU and NVIDIA GPUs (specifically, the GTX 1060, GTX 1080Ti, RTX 2080Ti, V100, and Quadro RTX 8000 models): Figure 1.1.1: Keras is a high-level library that sits on top of other deep learning frameworks. Keras is supported on CPU, GPU, and TPU. Before proceeding with the rest of the book, we need to ensure that tf2 is correctly installed. There are multiple ways to perform the installation; one example is by installing tf2 using pip3: $ sudo pip3 install tensorflow If we have a supported NVIDIA GPU, with properly installed drivers, and both NVIDIA CUDA toolkit and the cuDNN Deep Neural Network library, it is highly recommended that you install the GPU-enabled version since it can accelerate both training and predictions: $ sudo pip3 install tensorflow-gpu There is no need to install Keras as it is already a package in tf2. If you are uncomfortable installing libraries system-wide, it is highly recommended to use an environment such as Anaconda (). Other than having an isolated environment, the Anaconda distribution installs commonly used third-party packages for data sciences that are indispensable for deep learning. The examples presented in this book will require additional packages, such as pydot, pydot_ng, vizgraph, python3-tk, and matplotlib. We'll need to install these packages before proceeding beyond this chapter. The following should not generate any errors if tf2 is installed along with its dependencies: $ python3 import tensorflow as tf print(tf.__version__) 2.0.0 from tensorflow.keras import backend as K print(K.epsilon()) 1e-07 This book does not cover the complete Keras API. We'll only be covering the materials needed to explain selected advanced deep learning topics in this book. For further information, we can consult the official Keras documentation, which can be found at or. In the succeeding sections, the details of MLP, CNN, and RNN will be discussed. These networks will be used to build a simple classifier using tf.keras. 2. MLP, CNN, and RNN We've already mentioned that we'll be using three deep learning networks, they are: - MLP: Multilayer Perceptron - CNN: Convolutional Neural Network - RNN: Recurrent Neural Network These are the three networks that we will be using throughout this book. Later on, you'll find that they are often combined together in order to take advantage of the strength of each network. In this chapter, we'll discuss these building blocks one by one in more detail. In the following sections, MLP is covered alongside other important topics such as loss functions, optimizers, and regularizers. Following this, we'll cover both CNNs and RNNs. The differences between MLP, CNN, and RNN An MLP is a fully connected (FC) network. You'll often find it referred to as either deep feed-forward network or feed-forward neural network in some literature. In this book, we will use the term MLP. Understanding this network in terms of known target applications will help us to get insights about the underlying reasons for the design of the advanced deep learning models. MLPs are common in simple logistic and linear regression problems. However, MLPs are not optimal for processing sequential and multi-dimensional data patterns. By design, an MLP struggles to remember patterns in sequential data and requires a substantial number of parameters to process multi-dimensional data. For sequential data input, RNNs are popular because the internal design allows the network to discover dependency in the history of the data, which is useful for prediction. For multi-dimensional data like images and videos, CNNs excel in extracting feature maps for classification, segmentation, generation, and other downstream tasks. In some cases, a CNN in the form of a 1D convolution is also used for networks with sequential input data. However, in most deep learning models, MLP and CNN or RNN are combined to make the most out of each network. MLP, CNN, and RNN do not complete the whole picture of deep networks. There is a need to identify an objective or loss function, an optimizer, and a regularizer. The goal is to reduce the loss function value during training, since such a reduction is a good indicator that a model is learning. To minimize this value, the model employs an optimizer. This is an algorithm that determines how weights and biases should be adjusted at each training step. A trained model must work not only on the training data but also on data outside of the training environment. The role of the regularizer is to ensure that the trained model generalizes to new data. Now, let's get into the three networks – we'll begin by talking about the MLP network. 3. Multilayer Perceptron (MLP) The first of the three networks we will be looking at is the MLP network. [2] for short, is often considered as the Hello World! of deep learning datasets. It is a suitable dataset for handwritten digit classification. Before we discuss the MLP classifier model, it's essential that we understand the MNIST dataset. A large number of examples in this book use the MNIST dataset. MNIST is used to explain and validate many deep learning theories because the 70,000 samples it contains are small, yet sufficiently rich in information: Figure 1.3.1: Example images from the MNIST dataset. Each grayscale image is 28 × 28-pixels. In the following section, we'll briefly introduce MNIST. The MNIST dataset MNIST is a collection of handwritten digits ranging from, in 25 random digit images. Listing 1.3.1: mnist-sampler-1.3.1.py import numpy as np from tensorflow.keras.datasets import mnist import matplotlib.pyplot as plt (x_train, y_train), (x_test, y_test) = mnist.load_data().savefig("mnist-samples.png") plt.show() plt.close('all') The mnist.load_data() method is convenient since there is no need to load all 70,000 images and labels individually and store them in arrays. Execute the following: python3 mnist-sampler-1.3.1.py On the command line, the code previously in Figure 1.3.1. Before discussing the MLP classifier model, it is essential to keep in mind that while the MNIST data consists of two dimensional tensors, it should be reshaped depending on the type of input layer. The following Figure 1.3.2 shows how a 3 × 3 grayscale image is reshaped for MLP, CNN, and RNN input layers: Figure 1.3.2: An input image similar to the MNIST data is reshaped depending on the type of input layer. For simplicity, the reshaping of a 3 × 3 grayscale image is shown. In the following sections, an MLP classifier model for MNIST will be introduced. We will demonstrate how to efficiently build, train, and validate the model using tf.keras. The MNIST digit classifier model The proposed MLP model shown in Figure 1.3.3 can be used for MNIST digit classification. When the units or perceptrons are exposed, the MLP model is a fully connected network, as shown in Figure 1.3.4. We will also show how the output of the perceptron is computed from inputs as a function of weights, wi, and bias, bn, for the n-th unit. The corresponding tf.keras implementation is illustrated in Listing 1.3.2: Figure 1.3.3: The MLP MNIST digit classifier model Figure 1.3.4: The MLP MNIST digit classifier in Figure 1.3.3 is made of fully connected layers. For simplicity, the activation and dropout layers are not shown. One unit or perceptron is also shown in detail. Listing 1.3.2: mlp-mnist-1.3.2.py import numpy as np from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Activation, Drop) # image dimensions (assumed square) # network parameters batch_size = 128 hidden_units = 256 dropout = 0.45 #')) model.summary() plot_model(model, to_file='mlp=20, batch_size=batch_size) # validate the model on test dataset to determine generalization _, acc = model.evaluate(x_test, y_test, batch_size=batch_size, verbose=0)coding num_labels = 10 is also an option. But, it's always a good practice to let the computer do its job. The code assumes that y_train has labels 0 to 9. At this point, the labels are in digit format, that is, from 0 to 9. This sparse scalar representation of labels is not suitable for the neural network prediction layer that outputs probabilities per class. A more suitable format is called a one-hot vector, a 10-dimensional are stored in tensors. The term tensor applies to a scalar (0D tensor), vector (1D tensor), matrix (two dimensional tensor), and multi-dimensional tensor. From this point, the term tensor is used unless scalar, vector, or matrix makes the explanation clearer. The rest of the code as shown below computes the image dimensions, the input_size value of the first dense layer, and scales each pixel value from 0 to 255 to range from 0.0 to 1.0. Although raw pixel values can be used directly, it is better to normalize the input data so [60,000, 28 * 28] and [10,000, 28 * 28], respectively. In NumPy, a size of -1 means to let the library compute the correct dimension. In the case of x_train, this is 60,000. # image dimensions (assumed square) 400 After preparing the dataset, the following focuses on building the MLP classifier model using the Sequential API of Keras. Building a model using MLP and Keras After the the Rectified Linear Unit (ReLU) activation and dropout. 256 units are chosen since 128, 512, and 1,024 units have lower performance metrics. At 128 units, the network converges quickly but has a lower test accuracy. The additional number of units for 512 or 1,024 does not significantly increase the test accuracy. lines of code, the classifier model is implemented using the Sequential API of Keras. This is sufficient if the model requires one input and one output as processed by a sequence of layers. For simplicity, we'll use this for now; however, in Chapter 2, Deep Neural Networks, the Functional API of Keras will be introduced to implement advanced deep learning models that require more complex structures such as multiple inputs and outputs. #')) Since a Dense layer is a linear operation, a sequence of Dense layers can only approximate a linear function. The problem is that the MNIST digit classification is inherently a non-linear process. Inserting a relu activation between the Dense layers will enable an MLP network to model non-linear mappings. relu or ReLU is a simple non-linear function. It's very much like a filter that allows positive inputs to pass through unchanged while clamping everything else to zero. Mathematically, relu is expressed in the following equation and is plotted in Figure 1.3.5: Figure 1.3.5: Plot of the ReLU function. The ReLU function introduces non-linearity in neural networks. There are other non-linear functions that can be used, such as elu, selu, softplus, sigmoid, and tanh. However, relu is the most commonly used function and is computationally efficient due to its simplicity. The sigmoid and tanh functions are used as activation functions in the output layer and will be described later. Table 1.3.1 shows the equation for each of these activation functions: Table 1.3.1: Definition of common non-linear activation functions Although we have completed the key layers of the MLP classifier model, we have not addressed the issue of generalization or the ability of the model to perform beyond the train dataset. To address this issue, we will introduce regularization in the next section. Regularization A neural network has the tendency to memorize its training data, especially if it contains more than enough capacity. In such cases, the network fails catastrophically when subjected to the test data. This is the classic case of the network failing to generalize. To avoid this tendency, the model uses a regularizing layer or function. A common regularizing layer predictions. There are regularizers that can be used other than dropouts such as l1 or l2. In Keras, the bias, weight, and activation outputs can be regularized per layer. l1 and l2 favor smaller parameter values by adding a penalty function. Both l1 and l2 enforce the penalty using a fraction of the sum of the absolute ( l1) or square ( l2) of parameter values. In other words, the penalty function forces the optimizer to find parameter values that are small. Neural networks with small parameter values are more insensitive to the presence of noise from within the input data. As an example, an l2-weight regularizer with fraction=0.001 can be implemented as: from tensorflow.keras.regularizers import l2 model.add(Dense(hidden_units, kernel_regularizer=l2(0.001), input_dim=input_size)) No additional layer is added if an l1 or l2 regularization is used. The regularization is imposed in the Dense layer internally. For the proposed model, dropout still has a better performance than l2. We are almost complete with our model. The next section focuses on the output layer and loss function. Output activation and loss function The output layer has 10 units followed by a softmax activation layer. The 10 units correspond to the 10 possible labels, classes, or categories. The softmax activation can be expressed mathematically, as shown in the following equation: The equation is applied on all N = 10 outputs, xi, such as linear, sigmoid, or tanh. The linear activation is an identity function. It copies its input to its output. The sigmoid function is more specifically known as a logistic sigmoid. This will be used if the elements of the prediction tensor will be independently mapped between 0.0 and 1.0. The summation of all the elements of the predicted tensor is not constrained to 1.0 unlike in softmax. For example, sigmoid is used as the last layer in sentiment prediction (from 0.0 to 1.0, 0.0 being bad, and 1.0 being good) or in image generation (0.0 is mapped to pixel level 0 and 1.0 is mapped to pixel 255). to 1.0] using . The following graph in Figure 1.3.6 shows the sigmoid and tanh functions. Mathematically, sigmoid can be expressed in the following equation: the target or label and the prediction. In the current example, we are using categorical_crossentropy. It's the negative of the sum of the product of the target or label and the logarithm of the prediction per category. There are other loss functions that are available in Keras, such as mean_absolute_error and binary_crossentropy. Table 1.3.2 summarizes the common loss functions. Table 1.3.2: Summary of common loss functions. Categories refers to the number of classes (for example: 10 for MNIST) in both the label and the prediction. Loss equations shown are for one output only. The mean loss value is the average for the entire batch. The choice of the loss function is not arbitrary but should be a criterion that the model is learning. For classification by category, either categorical_crossentropy or mean_squared_error is a good choice after the softmax activation layer. The binary_crossentropy loss function is normally used after the sigmoid activation layer, while mean_squared_error is an option for the tanh output. In the next section, we will discuss optimization algorithms to minimize the loss functions that we discussed here. Optimization With optimization, the objective is to minimize the loss function. The idea is that if the loss is reduced to an acceptable level, the model has indirectly learned the function that maps inputs to outputs. Performance metrics are used to determine if a model has learned the underlying data distribution. The default metric in Keras is loss. During training, validation, and testing, other metrics such as accuracy can also be included. Accuracy is the percentage, or fraction, of correct predictions based on ground truth. In deep learning, there are many other performance metrics. However, it depends on the target application of the model. In literature, the performance metrics of the trained model on the test dataset is reported for comparison until the bottom is reached. The GD algorithm is illustrated in Figure 1.3.7. Let's suppose x is the parameter (for example, weight) being tuned to find the minimum value of y (for example, the loss function). Starting at an arbitrary point of x= -0.5. the gradient . The GD algorithm imposes that x is then updated to . The new value of x is equal to the old value, plus the opposite of the gradient scaled by . The small number refers to the learning rate. If = 0.01 then the new value of x = -0.48. GD is performed iteratively. At each step, y will get closer to its minimum value. At x = 0.5, . one hand, a large value of may take a significant number of iterations before the minimum is found. In the case of multiple minima, the search might get stuck in a local minimum. Figure 1.3.7: GD GD to overcome the hill at x = 0.0. In deep learning practices, it is normally recommended to start with a bigger learning rate (for example, 0.1 to 0.001) and gradually decrease this as the loss gets closer to the minimum. Figure 1.3.8: Plot of a function with 2 minima, x = -1.51 and x = 1.66. Also shown is the derivative of the function. GD is not typically used in deep neural networks since it is common to encounter millions of parameters to train. It is computationally inefficient to perform a full GD. Instead, SGD is used. In SGD, a mini batch of samples is chosen to compute an approximate value of the descent. The parameters (for example, weights and biases) are adjusted by the following equation: In this equation, and are the parameters and gradient tensor of the loss function, respectively. The g is computed from partial derivatives of the loss function. The mini-batch size is recommended to be a power of 2 for GPU optimization purposes. In the proposed network, batch_size = 128. Equation 1.3.8 computes the last layer parameter updates. So, how do we adjust the parameters of the preceding layers?() will process the number of steps equal to the size of the train dataset divided by the batch size plus 1 to compensate for any fractional part. After training the model, we can now evaluate its performance. Performance evaluation At this point, the model for the MNIST digit classifier is now complete. Performance evaluation will be the next crucial step to determine if the proposed trained model has come up with a satisfactory solution. Training the model for 20 epochs will be sufficient to obtain comparable performance metrics. The following table, Table 1.3.3, shows the different network configurations and corresponding performance measures. Under Layers, the number of units is shown for layers 1 to 3. For each optimizer, the default parameters in tf.keras are used. The effects of varying the regularizer, optimizer, and the number of units per layer can be observed. Another important observation in Table 1.3.3 is that bigger networks do not necessarily translate to better performance. Increasing the depth of this network shows no added benefits in terms of accuracy for both the a better performance than l2. The following table demonstrates a typical deep neural network performance during tuning: Table 1.3.3 Different MLP network configurations and performance measures The example indicates that there is a need to improve the network architecture. After discussing the MLP classifier model summary in the next section, we will present another MNIST classifier. The next model is based on CNN and demonstrates a significant improvement in test accuracy. Model summary Using the Keras library provides us with a quick mechanism to double-check the model description by calling: model.summary() Listing 1.3.3 below the input to the Dense layer: 784 × 256 + 256 = 200,960. From the first Dense layer to the second Dense layer: 256 × 256 + 256 = 65,792. From the second Dense layer to the output layer: 10 × 256 + 10 = 2,570. The total is 269,322. Listing 1.3.3:) 2750 Having summarized our model, this concludes our discussion of MLPs. In the next section, we will build a MNIST digit classifier model based on CNN. 4. Convolutional Neural Network (CNN) We are now going to move onto the second artificial neural network, CNN. In this section, we're going to solve the same MNIST digit classification problem, but this time using a CNN. Figure 1.4.1 shows the CNN model that we'll use for the MNIST digit classification, while its implementation is illustrated in Listing 1.4.1. Some changes in the previous model will be needed to implement the CNN model. Instead of having an: The CNN model for MNIST digit classification Implement the preceding figure: Listing 1.4.1: cnn-mnist-1.4.1.py import numpy as np from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Activation, Dense, Dropout from tensorflow=10, batch_size=batch_size) _, acc = model.evaluate(x_test, y_test, batch_size=batch_size, verbose=0) print("\nTest accuracy: %.1f%%" % (100.0 * acc)) The major change here is the use of utilized without causing instability during training. Convolution from top to bottom. This operation is called convolution. It transforms the input image into a feature map, which is a representation of what the kernel has learned from the input image. The feature map is then transformed into another feature map: Figure 1.4.3: The convolution operation shows how one element of the feature map is computed accepts the option padding='same'. The input is padded with zeros around its borders to keep the dimensions unchanged after the convolution. Pooling operations The last change is the addition of a MaxPooling2D layer with the argument pool_size=2. MaxPooling2D compresses each feature map. Every patch of size pool_size × pool_size is reduced to 1 feature map point. The value is equal to the maximum feature point map size, which translates to an increase in receptive field size. For example, after MaxPooling2D(2), the 2 × 2 kernel is now approximately convolving with a 4 × 4 patch. The CNN has learned a new set of feature maps for a different receptive field size. operation is a stack of feature maps. The role of Flatten is to convert the stack of feature maps into a vector format that is suitable for either Dropout or Dense layers, similar to the MLP model output layer. In the next section, we will evaluate the performance of the trained MNIST CNN classifier model. Performance evaluation and model summary. Listing 1.4.2: Summary of a CNN MNIST digit classifier Layer (type) Output Shape Param # ================================================================= conv2d_1 (Conv2D) (None, 26, 26, 64) 640 max_pooling2d_1 (MaxPooiling2) (None, 13, 13, 64) 0 conv2d_2 (Conv2D) (None, 11, 11, 64) 36928 max_pooling2d_2 (MaxPooiling2) (None, 5.5, 5, 64) 0 conv2d_3 (Conv2D) (None, 3.3, 3,: shows a graphical representation of the CNN MNIST digit classifier. Figure 1.4.5: Graphical description of the CNN MNIST digit classifier Table 1.4.1 shows. Table 1.4.1: Different CNN network configurations and performance measures for the CNN MNIST digit classifier. Having looked at CNNs and evaluated the trained model, let's look at the final core network that we will discuss in this chapter: RNN. 5. Recurrent Neural Network (RNN) We're now going to look at the last of our three artificial neural networks, RNN. RNNs are a family of networks that are suitable for learning representations of sequential data like text in natural language processing (NLP) or Listing 1.5.1: rnn-mnist-1.5.1.py import numpy as np from tensorflow.keras.models import Sequential from tensorflow) _, acc = model.evaluate(x_test, y_test, batch_size=batch_size, verbose=0) print("\nTest accuracy: %.1f%%" % (100.0 * acc)) There are two main differences between the RNN classifier kernels: In this equation, b is the bias, while W and U are called recurrent kernel (weights for the previous output) and kernel (weights for the current input), respectively. Subscript t is used to indicate the position in the sequence. For a SimpleRNN layer with units=256, the total number of parameters is 256 + 256 × 256 + 256 × 28 = 72,960, corresponding to b, W, and U contributions. The following figure shows the diagrams of both SimpleRNN and RNN when used for classification tasks. What makes SimpleRNN simpler than an RNN is the absence of the output values ot = Vht + c before the softmax function is computed: Figure 1.5.2: Diagram of SimpleRNN and RNN RNNs might be initially harder to understand when compared to MLPs or CNNs. In an MLP, the perceptron is the fundamental unit. Once the concept of the perceptron is understood, an MLP is just a network of perceptrons. In a CNN, the kernel is a patch or window that slides through the feature map to generate another feature map. In an RNN,. Listing 1.5.2: Summary of an RNN MNIST digit classifier Layer (type) Output Shape Param # ================================================================= simple_rnn_1 (SimpleRNN) (None, 256) 72960 dense_1 (Dense) (None, 10) 2570 activation_1 (Activation) (None, 10) 36928 ================================================================= Total params: 75,530 Trainable params: 75,530 Non-trainable params: 0 Figure 1.5.3 shows the graphical description of the RNN MNIST digit classifier. The model is very concise: Figure 1.5.3: The RNN MNIST digit classifier graphical description Table 1.5.1 shows that the SimpleRNN has the lowest accuracy among the networks presented: Table 1.5.1: The different SimpleRNN network configurations and performance measures In many deep neural networks, other members of the RNN family are more commonly used. For example, Long Short-Term Memory (LSTM) has been used in both machine translation and question answering problems. LSTM addresses the problem of long-term dependency or remembering relevant past information to the present output. Unlike an RNN or a SimpleRNN, the internal structure of the LSTM cell is more complex. Figure 1.5.4 shows a diagram of LSTM. LSTM uses not only the present input and past outputs or hidden states, but it introduces a cell state, st, that carries information from one cell to the other. TheMs can be found at. The LSTM() layer can be used as a drop-in replacement for SimpleRNN(). If LSTM is overkill for the task at hand, a simpler version called a Gated Recurrent Unit (GRU) can be used. A GRU simplifies LSTM by combining the cell state and hidden state together. A number of units will also increase the capacity. However, another way of increasing the capacity is by stacking the RNN layers. It should be noted though that as a general rule of thumb, the capacity of the model should only be increased if needed. Excess capacity may contribute to overfitting, and, as a result, may lead to both a longer training time and a slower performance during prediction. 6. Conclusion This chapter provided an overview of the three deep learning models – MLP, RNN, CNN – and also introduced TensorFlow 2 tf.keras, a library for rapid development, training, and testing deep learning models that is suitable for a production environment. functions. For ease of understanding, these concepts were presented in the context of MNIST digit classification. Different solutions to MNIST digit classification using artificial neural networks, specifically MLP, CNN, and RNN, which are important building blocks of deep neural networks, were also discussed together with their performance measures. With an understanding of deep learning concepts and how Keras can be used as a tool with them, we are now equipped to analyze advanced deep learning models. After discussing the Functional API in the next chapter, we'll move on to the implementation of popular deep learning models. Subsequent chapters will discuss selected advanced topics such as autoregressive models (autoencoder, GAN, VAE), deep reinforcement learning, object detection and segmentation, and unsupervised learning using mutual information. The accompanying Keras code implementations will play an important role in understanding these topics. 7. References - Chollet, François. Keras (2015).. - LeCun, Yann, Corinna Cortes, and C. J. Burges. MNIST handwritten digit database. AT&T Labs [Online]. Available: (2010).
https://www.packtpub.com/product/advanced-deep-learning-with-tensorflow-2-and-keras-second-edition/9781838821654
CC-MAIN-2020-40
refinedweb
5,531
56.76
05 November 2013 11:09 [Source: ICIS news] LONDON (ICIS)--Polish fertilizer producer Pulawy shut one line of its melamine production over the weekend because of technical problems, a company source said on Tuesday. Pulawy plans to restart the unit at the end of this week.?xml:namespace> The company has three melamine production lines, with a total nameplate capacity of 96,000 tonnes a year, the source said. The other two lines are running normally, the source added. The melamine facility is located in Pulawy, eastern Poland. “We are running our production to meet our contract requirements but we have no extra
http://www.icis.com/Articles/2013/11/05/9722227/technical-issues-force-polands-pulawy-to-shut-melamine-prod.html
CC-MAIN-2015-11
refinedweb
103
63.39
Since the release of Next.js, we’ve worked to introduce new features and tools that drastically improve application performance, as well as overall developer experience. Let’s take a look at what a difference upgrading to the latest version of Next.js can make. In 2019, our team at Vercel created a serverless demo app called VRS (Virtual Reality Store) using Next.js 8, Three.js, Express, MongoDB, Mongoose, Passport.js, and Stripe Elements. Users could sign up, browse multiple 3D models, and purchase them. Although this demo is still fully functional three years later, it lacked some of the performance improvements that were added over the years. Let's explore the changes we made to improve performance and streamline the developer experience using new Next.js features. Using getStaticProps and getStaticPaths The old implementation relied on a separate backend folder that contained a custom Express server, which exposed an /api/checkout endpoint to handle payments, /api/get-products to fetch data used to render all models, and the /api/get-product/:id endpoint to fetch the data for a specific model. When a user navigated from the landing page to the /store page, getInitialProps would make a request to the /api/get-products endpoint to retrieve data for the shown models. The store page was only visible to the user once the request had been resolved. This could take a while, depending on the quality of their internet connection. Although the user hadn’t clicked the "Store" link yet, the store.js and store.json files that are necessary to render the store page had already been prefetched. Using getStaticProps with the <Link /> component drastically improves the responsiveness of the application. You might notice that the time it takes to fetch the thumbnails has also been reduced tremendously. We were able to do this by replacing the native <img /> tag in favor of the <Image /> component. Using next/image The <Image /> component was introduced in Next.js 10 and further improved in later versions, allowing developers to efficiently serve images using modern image formats without layout shift. The performance improvement is instantly noticeable when we compare the loading time of the /store page, which renders an image for each model thumbnail. Let’s look at the differences between using the native <img /> tag, and using the <Image /> component. Next-gen image format The <Image /> component serves the next-gen image format webp format. Images using this format are 25-35% smaller than JPEG files with the exact same quality index. This difference is clearly visible when comparing the sizes of the fetched images: whereas the red car model’s image used to be 1.3MB in the old implementation, we were able to reduce the size by -98.75% to only 16.6kB by using the <Image /> component. Lazy Loading The old implementation requested the images for all models, resulting in 12 fetch requests. The <Image /> component only fetches the image once it detects the intersection of the viewport with the image’s bounding box. Although no changes had to be made to the images themselves, we were able to decrease the image loading time from an average of ~3000ms down to ~270ms. Dynamic Routes When browsing through the store, users can click on each item to better view the model. The old implementation used a combination of query parameters and getInitialProps to render the page and fetch the needed data to render each model. Similar to what we saw on the /store page, the user can only see the model once the API request initiated within the getInitialProps function has resolved. Next.js 9 introduced file-system-based dynamic routes. In combination with the new getStaticPaths function used together with getStaticProps, this feature makes it possible to dynamically pre-render the model pages based on their id. Instead of having one model page and using getInitialProps and query parameters to determine which data to fetch and what model to render, we can directly use a path parameter to generate pages for each model statically. By wrapping each model card in the grid in a <Link /> component, we can prefetch each /model/[id] page once the card appears in the viewport, allowing instant navigation when a user clicks on the card. API Routes Next.js 9 introduced API Routes, making it easy to create API endpoints from within the /pages folder. Although we could replace the /api/get-products and /api/get-product/:id endpoints by using getStaticProps, we still need the /api/checkout endpoint to handle payments on the server-side. This endpoint cannot be replaced with the getStaticProps method, since it needs to be available to the client during runtime with values that are unknown during build time. When a user purchases an item, the client makes a call to this endpoint using the unique token that was generated for their card. Instead of hosting our own server to provide this endpoint, we can recreate this endpoint as an API Route instead! NextAuth.js The old implementation also had user authentication using Passport.js. To more easily add authentication to our application, we can take advantage of NextAuth.js, which simplifies this process to a few lines of code with support for 50+ providers. // pages/api/[...nextauth].ts import NextAuth from "next-auth"; import GithubProvider from "next-auth/providers/github"; export default NextAuth({ providers: [ GithubProvider({ clientId: process.env.GITHUB_CLIENT_ID, clientSecret: process.env.GITHUB_CLIENT_SECRET }) ] }) Since all endpoints have been replaced, we no longer need a separate backend folder! We can use the frontend folder as the project's root folder, simplifying the project architecture significantly. Import on Interaction Some components aren’t instantly visible to the user. Instead of including them in the main JavaScript bundle, we can dynamically import these components using next/dynamic. One of these components is the CartSidebar. This component is imported in the Nav component and is only visible to the user when they click on the cart icon or add an item to the cart. import CartSidebar from "../components/CartSidebar" export default function Nav() { ... return ( <div> ... <CartSidebar /> </div> ) } Instead of statically importing this component, we can tell Next.js to create a separate JavaScript chunk for this component through code-splitting. That way, we can delay the import of this non-critical component, and only fetch it on-demand once the user actually requires it. import dynamic from "next/dynamic" const CartSidebar = dynamic(() => import("../components/CartSidebar")); export default function Nav() { ... return ( <div> ... {open && <CartSidebar />} </div> ) } Since the CartSidebar component is the only component in the application that imported and used third-party libraries for payments (Stripe), we were also able to defer the imports of these libraries until the moment the user actually needed them (instead of unnecessarily fetching unused code). This resulted in sending less initial JavaScript to the user and improving page loading performance. Automatic Font Optimization Automatic Font Optimization is available since Next.js 10 and automatically inlines font CSS at build time, eliminating an extra round trip to fetch font declarations. <link href="" rel="stylesheet"> <style data- @font-face{font-family:'Space Mono';font-style:normal;... </style> This means that font declarations no longer have to be fetched, improving initial page load performance. We were able to reduce the number of requests needed to load the font from 4 to 2 just by upgrading to the latest version. Developer experience Besides performance optimizations, the developer experience has also massively improved over the years. Built-in TypeScript support Whereas adding TypeScript support required quite a bit of custom configuration, Next.js 9 added support for TypeScript out of the box! We no longer have to deal with our own config, but instead can start using TypeScript by adding a tsconfig.json file to the root of existing projects, or by running npx create-next-app --ts for newly created projects. Faster builds through SWC Next.js 12 includes a new Rust-based compiler built on SWC that takes advantage of native compilation. We reduced our build time from ~90s down to ~30s just by upgrading the Next.js version. React Fast Refresh Fast Refresh is a Next.js feature enabled in all Next.js apps on version 9.4 or newer. It provides instantaneous feedback on edits made to your React components within a second without losing component state. The introduction of SWC in Next.js 12 improved the refresh rate significantly, resulting in 3x faster refreshes compared to prior versions. Conclusion The improvements and new features Next.js has introduced over the past couple of years have made it easy to create fast fullstack applications, all while ensuring backward compatibility and making incremental adoption to new versions possible. By upgrading to the latest version, we were able to vastly optimize our application and developer experience with minimal effort on our end. Try out the upgraded demo or view the full PR for the upgrade. If you'd like to upgrade your Next.js app, check out our upgrade guide.
https://vercel.com/blog/upgrading-nextjs-for-instant-performance-improvements
CC-MAIN-2022-27
refinedweb
1,502
56.15
Crash caused when node-editing empty path Bug Description While chasing a crash in the previous version 0.48, we stumbled upon a crash in the current build:_ > 0x005f57df in Inkscape: > 82 x->updateState(); > (gdb) bt > #0 0x005f57df in Inkscape: > #1 0x005f57df in Inkscape: > #2 0x005f57df in Inkscape: > #3 0x005fc7d8 in Inkscape: > #4 0x000fed2c in Inkscape: > #5 0x00333040 in sp_action_perform (action=0x4787700, data=0x0) at ui/tool/ > #6 0x00111a53 in sp_shortcut_invoke (shortcut=65289, view=0x476bd20) at ui/tool/ > #7 0x00071b11 in sp_event_ > #8 0x0060ca11 in (anonymous namespace) > #9 0x0006d77c in sp_event_ > #10 0x000396f7 in sp_desktop_ > #11 0x0033ed55 in sp_marshal_ > #12 0x032ec0a9 in g_closure_invoke () > #13 0x032fe163 in signal_ > #14 0x032ff537 in g_signal_ > #15 0x01918741 in gtk_signal_emit () > #16 0x00263f03 in emit_event (canvas=<value temporarily unavailable, due to optimizations>, event=0x6d9ba20) at ui/tool/ > #17 0x0026a427 in sp_canvas_key (widget=0x41ff380, event=0x6d9ba20) at ui/tool/ > #18 0x0178052b in _gtk_marshal_ > #19 0x032ec0a9 in g_closure_invoke () > #20 0x032fe2e8 in signal_ > #21 0x032ff537 in g_signal_ > #22 0x032ffaf9 in g_signal_emit () > #23 0x018af8a6 in gtk_widget_ > #24 0x018c5c99 in gtk_window_ > #25 0x018caefc in gtk_window_ > #26 0x0178052b in _gtk_marshal_ > #27 0x032ec0a9 in g_closure_invoke () > #28 0x032fe2e8 in signal_ > #29 0x032ff537 in g_signal_ > #30 0x032ffaf9 in g_signal_emit () > #31 0x018af8a6 in gtk_widget_ > _ > #36 0x033aa59b in g_main_ > #37 0x033aa877 in g_main_loop_run () > #38 0x0177dc71 in gtk_main () > #39 0x01192d4b in Gtk::Main::run () > #40 0x0000555c in Inkscape: > #41 sp_main_gui (argc=1, argv=0xbffff394) at ui/tool/ > #42 0x00004156 in start () > (gdb) Backtrace done with Inkscape 0.48+devel r10019 on OS X 10.5.8 See also: <http:// Retesting this bug shows it's gone. It must have been fixed in the new release. > Retesting this bug shows it's gone. It must have been fixed in the new release. Cannot confirm this being fixed - reported crash (see bug description and backtrace) still reproduced with latest stable release (0.48.4) and current trunk (r12395) on OS X 10.7.5 (GTK+/X11 2.24.13, GTK+/Quartz 2.24.19), as well as on Ubuntu 12.04 (0.48+devel r12388 (PPA)), Ubuntu 12.10 (0.48.3.1, 0.48+devel r12383 (local build)), Ubuntu 13.04 (0.48.4): Steps to reproduce: 1) launch Inkscape 2) open sample SVG file 3) use 'Shift+<TAB>' to select the path which triggers the crash 4) switch to the node tool, and use <TAB> to cycle through all nodes --> crash Proposing to reopen. Thanks for retesting suv, I clonked the error on the head with this commit: r12396 thanks to your STR The changes from r12396 merge cleanly into <lp:inkscape/0.48.x>, and fix the crash otherwise easily reproducible with current stable 0.48.4 (tested with 0.48.x r9961 on OS X 10.7.5). @Martin - can you think of any special reason not to backport your fix to the stable branch? Reproduced on Ubuntu 10.10, Inkscape trunk revision 10037.
https://bugs.launchpad.net/inkscape/+bug/710637
CC-MAIN-2019-13
refinedweb
480
69.11
Mystified by JSF 2 composition components Tom Fulton Ranch Hand Joined: Mar 30, 2006 Posts: 95 posted Mar 15, 2011 15:30:30 1 In Facelets prior to JSF 2, composition components were fairly easy to use and understand. I must say, such is not the case any longer with the same feature in JSF 2. Here is my problem: One use I made of composition components in Facelets (JSF 1.2) was to encapsulate the repetitive coding needed for columns in a dataTable. I cannot seem to get this to work at all in JSF 2. I understand that there is a <composition:facet> tag, a <composition:insertFacet> tag and a <composition:renderFacet> tag. I cannot find a single example anywhere as to how these tags would be used. I'd like to do something like this: <cc:interface> <cc:facet </cc:interface> <cc:implementation> <cc:renderFacet <h:outputText </cc:renderFacet> <cc:insertChildren/> </cc:implementation> And have the client page use it this way: <h:dataTable value=""{customerBean.list} > <comp:datatableColumn ...> <comp:datatableColumn ...> </h:dataTable> Obviously with values passed in to represent the beans properties to be displayed. I have had no luck doing this, and was wondering if anyone on this forum has enough experience to tell me (a) how this might be done, and (b) what the general use of the facet tags is. Thanks for any help in advance Tim Holloway Saloon Keeper Joined: Jun 25, 2001 Posts: 16718 25 I like... posted Mar 16, 2011 06:31:15 0 I'm confused here. I thought that the difference between JSF 1.x and JSF2 was that Facelets is integrated into JSF2 but had to be added manually to JSF1 apps. In any event, I'm doing Facelets tags using ui:include in JSF2 just fine myself. I couldn't find a whole lot out about any "cc" namespage tags, except for one blog entry. Which made me wonder if the author hadn't simply defined "cc" as a custom tagset himself. Customer surveys are for companies who didn't pay proper attention to begin with. Tom Fulton Ranch Hand Joined: Mar 30, 2006 Posts: 95 posted Mar 16, 2011 12:19:06 0 OK, maybe I'm the one confused, yet again! JSF 2 does, indeed, include Facelets...and it no longer needs to be configured in faces-config.xml as it did in JSF 1.2. However, a few things have been added to Facelets in JSF 2. Composition components (as opposed to templating) have undergone a change, but it's possible that the previous strategy is still supported...I never thought to check that. A composition component is defined as an XHTML file in a specific location in the web project, and accessed via a tag (the tag being the name of the file itself). As a namespace, the prefix is arbitrary...I have seen it both as cc: as well as composition:. This new approach recommends that two distinct areas within the file be specified...one that represents the interface (<composition: interface>), and the other representing the implementation (<composition: implementation>). The difference is that the interface defines the way in which the client page would use the tag, typically identifying attributes that are then used within the implementation. The implementation is the code that replaces the tag when compiled. I will have to check to see whether my old code still works. If it does, sweet! I'm still interested in finding out how to use the various facet tags, but that can wait for another day. A better day. Perhaps a day when I have a functioning brain. Tim Holloway Saloon Keeper Joined: Jun 25, 2001 Posts: 16718 25 I like... posted Mar 16, 2011 12:25:24 0 It looks like you've been referring to what I know of as "custom tags via facelets". And, unless I'm mistaken the two element types are like the way we did C/C++, with external definitions separated from the implementation. I've used this feature, but it was several months back. It's not that hard, actually. But the old include technique still works as well. I've been using it this very morning. Brendan Healey Ranch Hand Joined: May 12, 2009 Posts: 218 posted Mar 18, 2011 12:54:13 0 This is an interesting point. Firstly the use of "cc" or "composite" is purely dependent on the prefix you use in your namespace declaration and "cc" is widely used. Just remember that all the docs will refer to composite:. xmlns:cc="" The insertFacet and renderFacet tags are intended to allow the composite component itself to have (or not have) facets (i.e. on the calling page): <cclib:mycc <h:outputText </f:facet> </cclib:mycc> Then there are two scenarios within the composite component worth considering regarding the use of renderFacet and insertFacet: cclib/mycc.xhtml <cc:implementation> <cc:renderFacet <h:dataTable ...> <cc:insertFacet </h:dataTable> </cc:implementation> cc:renderFacet is rendering the facet as a child component of the composite component, which is fine, in this context it's "standalone", there's no parent component that can take facets. cc:insertFacet is adding the facet to the h:dataTable's facet map, which is what it's supposed to be doing in this context. The big point is that in the code above if you use cc:renderFacet within the dataTable there is no output, if you use insertFacet it works as expected. Equally if you use insertFacet in place of renderFacet above, there is no output. I thought you might be able to achieve simple code replacement doing something like this: cclib/mycc.xhtml <cc:implementation> <f:facet ... </f:facet> </cc:implementation> and then: <h:dataTable ...> <cclib:mycc/> </h:dataTable> But this doesn't work. I think that the problem is that we're trying to add the header facet to the facet map of h:dataTable, but it's being added to the facet map of the composite component and stays there. What you can do is have a file containing content within <ui:composition> tags that you ui:include into the main file. I tested this as follows and it works: main.xhtml <h:dataTable> <ui:include </h:dataTable> myfacet_1.xhtml <?xml version='1.0' encoding='UTF-8' ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ""> <ui:composition <f:facet <h:outputText </f:facet> </ui:composition> You can add a ui:param child tag to ui:include which makes it fairly useful: main.xhtml <ui:include <ui:param <ui:param </ui:include> pageFragment.xhtml ... <h:outputText <h:outputText I don't know if this would help with what you want to do but it's got to be worth looking into. The facelets templating mechanism in general can do a lot for you but is far from intuitive, but in the long run it'll save you a lot of time. Regards, Brendan. Tom Fulton Ranch Hand Joined: Mar 30, 2006 Posts: 95 posted Mar 23, 2011 06:37:40 0 Brenden, I have to thank you immensely for the help. This is exactly what I needed, and I appreciate the guidance. This leads to another observation...composition components are obaque enough that a really, really good article or book is badly needed. Badly. And again (although I understand it might be more powerful) the original way in which composition components worked was pretty darn easy. This is not. I can't help but wonder what the JSF 2 committe was thinking in designing an approach that is far, far less intutive. Thanks again. Brendan Healey Ranch Hand Joined: May 12, 2009 Posts: 218 posted Mar 23, 2011 06:58:06 0 Glad it was of help, writing it down helped me understand it myself. It hit a problem yesterday where I was getting an IndexOutOfBoundsException in a composite component and this turns out to be due to a bug when using h utputStylesheet and cc:insertChildren in the same cc. I was able to work around this by replacing h utputStylesheet with link type="text/css" rel="stylesheet" ... Just so you know... Brendan. I agree. Here's the link: subject: Mystified by JSF 2 composition components Similar Threads set value in a composite component JSF and Facelets question ajax within a composite component composite component not working cc:insertChildren only works once All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter JForum | Paul Wheaton
http://www.coderanch.com/t/530821/JSF/java/Mystified-JSF-composition-components
CC-MAIN-2015-22
refinedweb
1,416
63.49
Catching Cheats With the Perl Compiler The Perl Journal March, 2004 By Deborah Pickett Debbie teaches Perl and assembly at Monash University in Australia. She can be reached at debbiep@csse.monash.edu.au. Laziness, impatience, hubris. Perl users have been raised to believe that these are the virtues of a good programmer, but they have a dark side. They are also the character flaws of the cheat and plagiarist: Laziness: I can't be bothered learning how to program in this language. Impatience: If I copy off my friend, then I'll be able to do stuff I actually enjoy doing sooner. Hubris: I won't get caught. The issue of plagiarism doesn't often come up in the world of Perl, perhaps because of the Perl community's commitment to open source and giving credit where it's due. But it's a different story in the introductory Perl programming course that I teach at Monash University. Here, the assignments I set for my students must be the students' own work, and students who copy others' work without giving credit are considered to be cheating the system. Transgressors are punished, swiftly and mercilessly. At least they would be if a tool existed for comparing Perl programs with each other. There are plenty of tools for comparing C and Java and other languages, but I couldn't locate any for Perl. Ironically, a package my university uses to compare C code, called "Moss," uses Perl, but doesn't compare Perl source code itself. Perhaps this absence of a comparison tool is partly due to the aforementioned lack of need, but it surely must also be because Perl is a notoriously difficult language to parse. Simple substring comparison isn't good for detecting similarities in code because people change indentation, comments and variable names. To properly get a picture of what the program is doing, it's necessary to parse the source. Only perl can Parse Perl There are two choices when it comes to parsing Perl. The first option is to write a Perl grammar in whatever yacc-like notation you prefer, and generate a parser that accepts that grammar. While this is easy in C, it's close to impossible in Perl because of the language's syntactic idiosyncrasies. However, this may not be too great a handicap since typical Perl programs, as written by neophytes, don't use such features; it may be possible to parse a decent subset of Perl using off-the-shelf tools such as Parse::RecDescent. A big advantage of this approach is that whitespace, comments, and other nontokens that the Perl parser ignores could be examined, too, for hints of common source-code ancestry. The second solution is to make perl (the executable) parse Perl (the language), something that, by definition, it will always get right. There are two ways: The first is to use Perl's -Dx command-line option, which spits out an ugly syntax dump of a program, and parses the output into some other form. A few years ago, this would have been the only option. But with the introduction of the B::* suite of compiler back ends, there is a better choice: Create a new subclass of B that picks salient features in the source code's parse tree, and pipe the program through it. Unfortunately, some features of the source, such as whitespace, will be lost because the Perl tokenizer strips these before the parse tree is built. I think that a robust solution to the code-similarity problem needs to use some of each of the aforementioned two approaches. For a quick-and-dirty solution, however, I opted to make use of the Perl compiler and wrote a module called B::Fingerprint, which turns a program into a reasonably short and descriptive string, which, in turn, can be analyzed using more traditional string-comparison tools. The M.O. of a Plagiarist Plagiarists typically start with a working, completed piece of code written by someone else, and either try to work it into their own broken code or scrap their own code and spend the rest of their time trying to make the original code look different. Because they don't have a great deal of confidence in the language, they tend to make small, incremental changes to the code and hope the program still works (as a rule, plagiarists aren't terribly good at testing code). The most common transformations are: - Rewriting the comments; - Indenting the code differently; - Changing variable names, and - Reordering subroutines in the program. Somewhat rarer changes include changing if to unless and reordering a bunch of independent initialization statements. Any technique that compares programs for evidence of copying should try to downplay the effects of these transformations and look at the program's deeper structure, which will probably be left untouched. B::Fingerprint As its prefix suggests, B::Fingerprint is a compiler back end. Back ends are modules that can examine or manipulate the opcode tree of a Perl program, and usually finish up printing something interesting about the program. Perhaps the most well known is B::Deparse, which emits a human- (and perl-) readable rendition of Perl code. That something like B::Deparse can even exist means that there is a great deal of information available in the opcode tree for B::Fingerprint to examine. Some back ends (such as B::Deparse) are interested in the tiny details that make up a piece of code. Others, like B::Showlex (which identifies the lexical variables that a subroutine uses), are interested in only one part of the code. B::Fingerprint, on the other hand, needs to give a broad overview of all of the code, so that similarities between two programs will engender similar fingerprints. In this case, a fingerprint is a long string that characterizes the program. To understand how to detect when programs come from the same source, you have to use an almost forensic technique. You have the scene of the crime (the programs) but nothing else. The rest you have to assemble yourself from the evidence. So it helps to understand what usually happens to a piece of code when someone tries to cover their tracks. B::Fingerprint manages to work because it completely ignores the things that a plagiarist usually changes. For instance, B::Fingerprint doesn't care about variable names at all; all it knows is that a scalar was used here in the code. Even if you change all the scalar variable names in a program to $fish, the fingerprint will be unchanged. From a technical viewpoint, B::Fingerprint walks the opcode tree of the program, printing a symbol for each tree node it sees. Perl opcodes come in about a dozen different kinds; for instance, there are binary operators that correspond to two-argument Perl operations like addition, and list operators that appear anywhere a sequence of operators needs to be evaluated in some order, such as in a Perl list or a sequence of Perl statements. Each opcode type that B::Fingerprint sees produces a different character of output in the fingerprint. Some operator types have child nodes; these are always printed as suffixes, between braces. Here's the fingerprint for B::Fingerprint itself: perl -MO=Fingerprint B/Fingerprint.pm 1{@{;@{01{1{0$}}}}}1{@{;2{1{1{#}}0};@{02{1{#}1{1{001{#}}}}}; 1{|{2{1{00$}$}@{0;@{0$};2{1{00$}0}@{;2{L1{|{1{0}@{@{01{1{001 {#}}}}2{1{00$}0}0}}}}};@{0$}}}};1{|{2{1{1{001{#}}}$}@{0;1{|{ 1{|{1{1{00$}}1{01{00$}$$}}}@{0;@{0$};1{1{01{00$}1{#}}};@{0$} }}}}}}}}1{@{;2{1{1{#}}0};0;1{|{2{0$}@{02{1{1{01{#}}}0}}@{0;2 {1{1{01{0}}}0}}}};2{1{01{01{1{001{#}}}$}}1{00}};2{L1{|{2{1{0 1{0}}1{000}}@{;1{|{2{0$}0}};1{|{2{1{1{001{#}}}$}@{0;1{|{2{1{ 1{02{1{00$}0}1{#}}}$}@{0;1{|{1{2{1{#}1{0}}}0}};1{|{2{1{0}1{@ {01{00$}}}}0}};1{|{2{1{00$}1{#}}0}};1{1{01{00$}1{#}}}}}};1{| {1{|{2{1{1{01{00$}1{#}}}$}/{0}}}@{01{1{02{00}1{#}}}}}}}}}0}} }}}}@{0;2{$1{#}};2{1{0$$$$$$$$$$$$$$$$$$$$$$$$}1{01{#}}};2{1 {00}1{01{#}}};0} Probably the only salient feature you could pick out easily is the string of 24 "$" characters, corresponding to the list of initializers for the %opclass variable. Comparing Fingerprints Creating the fingerprints of programs is only half of the problem. It's still necessary to compare two fingerprints to see how similar they are (hence, how similar the original programs are). Doing this well turns out to be surprisingly difficult. One metric that can be used to establish how similar programs are is to take one fingerprint, and find out how many changes need to be made to it to arrive at the other program's fingerprint. This isn't always symmetrical (so, for instance, program A can be 80 percent the same as program B, but B may be only 65 percent the same as A), but it's capable of ranking similar pairs of fingerprints above dissimilar ones. Ideally, the comparison algorithm should be able to distinguish small changes from large changes. However, "small" and "large" don't necessarily relate to lines of code affected. For instance, changing the order of subroutines in a file is a trivial modification, even though several hundred lines may have been relocated. Wrapping an if condition around a block is a more significant change to a program, though it may result in only a small change to its fingerprint. The algorithm I settled on is Walter Tichy's string-to-string block-move algorithm, used in his RCS source-code revision control package. The challenges faced in keeping track of a program's revisions are similar to those involved in detecting plagiarism: You want to keep the deltas between revisions as short as possible, so it is a good idea to try to eliminate the parts of each revision that are the same. So, it turns out that the block-move algorithm is also good at detecting the less innocuous kinds of "revision" that happen in a case of plagiarism. The Block-Move Algorithm The block-move algorithm acts rather like a repeated cut-and-paste operation. Given two strings, A and B, it tries to reconstruct string B using only substrings from A. For example, if string A contained "full hands" and string B contained "handfuls," then B could be built with three block moves: 0 1 2 3 4 5 6 7 8 9 f u l l h a n d s <ol> <li>From position 5, for 4 characters (<i>hand</i>)</li> <li>From position 0, for 3 characters (<i>ful</i>)</li> <li>From position 9, for 1 character (<i>s</i>)</li> </ol> In RCS, these numbers constitute the delta from A to B, and are all that is actually stored in the revision control directory. For my purposes, all I care about is that it took three block moves to create a string of length 8. This ratio is a good indicator of how much of B came from A: the lower the ratio, the more similar the code is. (In rare cases, there might be a character in B that doesn't appear in A at all. In RCS, such characters have to be encoded directly into the delta; in my application, they will simply count as an additional block move.) Suffix Trees In the aforementioned example, three block moves are necessary to create B from A. It's important to get the best figure here because it's possible to get a higher number by choosing blocks badly. Thus, the block-move algorithm needs to be greedy, always choosing the longest possible block to copy at each point. Greediness guarantees an optimum result and, in terms of the block-move algorithm, means that it must scan one string (A) for the longest prefix from another string (B). A naive implementation of the longest-prefix problem is likely to run very slowly, as there are many choices to make at each characterso it makes sense to transform the search string (A) into some appropriate data structure to accelerate the process. The appropriate data structure turns out, in this case, to be a suffix tree. A suffix tree is a form of trie, which is an n-ary tree optimized for fast lookup. To give you an idea, a trie containing the strings camel, cat, catfish, dog, dromedary, and fish is shown in Figure 1. A suffix tree for a string A is simply a trie of all substrings in A from each character to the end of the string (i.e., substr($A, $i) foreach $i 0..length $A). A suffix tree for "abracadabra" is given in Figure 2. Armed with a suffix tree of A, it is now possible to determine the longest substring of A that matches the beginning of B: Simply walk down the tree, matching characters, turning at each node according to the next character in B. When the next character in B isn't available at the current node in the tree, the substring is complete and guaranteed to be the longest. To count the number of block moves, simply repeat the procedure from the tree root on the remainder of B until there is nothing left. The number of block moves is equal to the number of times you visited the root node. Because each character is examined only once, this takes time proportional to the length of B. The program compare (See Listing 1) accepts a number of file names as arguments and constructs fingerprints for each of them with B::Fingerprint. For each fingerprint, it then constructs a suffix tree, storing it in a hash. (I took the code for creating the suffix trees from the Allison web page listed in References.) With this "forest" of suffix trees, the program calculates the number of block moves required to convert every fingerprint into every other fingerprint. It then prints out the most similar cases. Results To test the program, I ran it on a selection of assignment submissions from my 190 Perl course students. I already knew of one case of plagiarism in these assignments, so I hoped to find that one near the top of the resulting list. The assignment source code was, on average, 300 lines long, resulting in fingerprints of about 2000 characters. It took my three-year-old laptop about 400 MB and half an hour to finish processing every pair of fingerprints. Sure enough, back came the plagiarism case I already knew, along with at least 10 other cases involving more than 20 students. There was a lot more laziness, impatience, and hubris in my course than I'd expected. Interviews with the flagged students revealed that compare had been spot on. Explanations I received from the students ranged from outright copying to working together on the program structure before going off and coding separately. There was only one obvious false positive, and that I classified as such by looking at the source code and deciding that, though there was probably a shared heritage, I didn't have enough evidence to convict. Discussion I should reiterate that compare isn't completely automatic; I did need to examine the source code of the programs that compare flagged, and look for other signs of commonality between the programs. In this respect, compare is nothing more than a quick way of weeding out all the negatives in the n2 pairs in any set. But the fact that I originally detected only 10 percent of the plagiarism cases on a visual inspection suggests that this is still a useful tool. A couple of years ago, students at Monash University did a similar kind of project comparing C files. It sort of worked, but not nearly as well. So why does it work so well with Perl? I think there are two reasons. First, there's more than one way to do it. Perl has such a rich syntax and such a wide variety of approaches to solving a problem that the likelihood of any two given programs using the same algorithm is smaller with Perl than C. Second, compare doesn't compare Perl source code, but compiled Perl syntax trees. The transformation that Perl's compiler makes to a program's source code makes the resulting fingerprint a truer representation of the program's execution order, reducing the impact of the source's sometimes nonlinear execution (compare if (condition) {code} to code if condition). Further Work Now that I've released B::Fingerprint and compare, it's only a matter of time before students learn to pipe their future assignments through it before submission, just to see if I'm going to catch them. This doesn't worry me greatly; the amount of effort needed to change a program so that it no longer resembles the original is large enough that the programmer will learn something about Perl through pure osmosis. Nonetheless, I have some backup plans in case compare's success rate falls. For instance, the block-move algorithm is only able to perform exact matches. If two strings are identical except for one character in the middle, then the block count increases. A better solution would be to allow approximate matches. This turns out to be a significantly harder problem, however, as some classes are in the computational too-hard basket called "NP-complete" (see the Lopresti and Tomkins paper in References). Approximate matching would likely increase the quantity of false positives, too. Related to this is the fact that the block-move algorithm can't accurately tell me how much, as a percentage, of one program can be found in another, which is perhaps a more useful metric than the one compare reports. This isn't because the information is lost in the creation of the suffix tree, but rather because the block move algorithm is greedy and always picks the longest substrings. This means that blocks can and often do overlap, and while this results in the optimal number of block moves, those blocks don't necessarily produce the best coverage of the fingerprint. I briefly experimented with the aspect of coverage but it turned out to be an unreliable measurement under the greedy block-move model. compare reports back on pairs of similar programs, but often there are cliques of students who all work together on a piece of code. It'd be nice if some clustering analysis could be performed on the results, so that I don't have to figure out the "study groups" manually. On another front, it's worth noting that B::Fingerprint cannot detect whitespace and commenting. Indentation style and other cues (some of which I classify as trade secrets) are often big giveaways that code has changed hands and simply undergone a search-and-replace regime. Comparing whitespace and commenting will greatly reduce the false positives to the point where it may even be possible to trust double-checking cases to a program. Finally, there's a lot more information available in a syntax tree than B::Fingerprint extracts. For instance, scalar literals have a value that is often an important part of the algorithm, and variable names, while they can be changed, are usually modified globally over a function. Comparing these aspects of the syntax tree will probably require an overhaul of the comparison algorithm and might even necessitate switching to a hierarchical tree-comparison algorithm rather than the flat block move that I am presently using. Each of these enhancements will probably highlight slightly different pairs of similar programs, so a robust plagiarism detector will likely contain a combination of them. Conclusion compare is capable of comparing a fairly large number of Perl programs to each other. It reports back on pairs that are likely to be related, with human inspection required. On real-world sample data, it correctly identified 10 percent of the population as not being original work. B::Fingerprint and compare are available for download at. References L. Allison, "Suffix Trees," ~lloyd/tildeAlgDS/Tree/Suffix/ (contains an explanation of Ukkonen's algorithm and pseudocode, which I copied with permission). D. Lopresti and A. Tomkins. "Block Edit Models for Approximate String Matching," Theoretical Computer Science (1997), vol. 181, no. 1, pages 159-179. Moss (Measure of Software Similarity): .edu/~aiken/moss.html W.F. Tichy, "The String-to-String Correction Problem with Block Moves," ACM Transactions on Computer Systems (1984), vol. 2, no. 4, pages 309-321. W.F. Tichy, "RCS: A System for Version Control," SoftwarePractice and Experience (1991), vol. 15, no. 7, pages 637-654. E. Ukkonen, "On-line Construction of Suffix Trees," Algorithmica (1995), vol. 14, no. 3, pages 249-260. TPJ #!/usr/bin/perl -w # # compare: compare N Perl programs with each other. # # usage: # compare [-n max] file ... # where # max is the maximum number of pairs of similar programs to report. # use strict; use Getopt::Std; our %opts; getopts("n:", \%opts); # How many cases to report? our $topcases = $opts{"n"}; # Suffix-tree-building code, adapted from # based on # E. Ukkonen's linear-time suffix tree creation algorithm. Used with # permission. { my $infinity = 999999; # Just has to be longer than any string passed in. sub buildTree { my $fp = shift; # Build root state node. my $rootState = { }; my $bottomState = { }; my ($sState, $k, $i); for ($i = 0; $i < length $fp; $i++) { addTransition($fp, $bottomState, $i, $i, $rootState); } $rootState->{sLink} = $bottomState; $sState = $rootState; $k = 0; # Add each character to the suffix tree. for ($i = 0; $i < length $fp; $i++) { ($sState, $k) = update($rootState, $fp, $sState, $k, $i); ($sState, $k) = canonicalize($fp, $sState, $k, $i); } return $rootState; } sub update { my ($rootState, $fp, $sState, $k, $i) = @_; my ($oldRootState) = $rootState; my ($endPoint, $rState) = testAndSplit($fp, $sState, $k, $i-1, substr($fp, $i, 1)); while (!$endPoint) { addTransition($fp, $rState, $i, $infinity, { }); if ($oldRootState != $rootState) { $oldRootState->{sLink} = $rState; } $oldRootState = $rState; ($sState, $k) = canonicalize($fp, $sState->{sLink}, $k, $i-1); ($endPoint, $rState) = testAndSplit($fp, $sState, $k, $i-1, substr($fp, $i, 1)); } if ($oldRootState != $rootState) { $oldRootState->{sLink} = $sState; } return ($sState, $k); } sub canonicalize { my ($fp, $sState, $k, $p) = @_; if ($p < $k) { return ($sState, $k); } my ($k1, $p1, $sState1) = @{$sState->{substr($fp, $k, 1)}}; while ($p1 - $k1 <= $p - $k) { $k += $p1 - $k1 + 1; $sState = $sState1; if ($k <= $p) { ($k1, $p1, $sState1) = @{$sState->{substr($fp, $k, 1)}}; } } return ($sState, $k); } sub testAndSplit { my ($fp, $sState, $k, $p, $t) = @_; if ($k <= $p) { my ($k1, $p1, $sState1) = @{$sState->{substr($fp, $k, 1)}}; if ($t eq substr($fp, $k1 + $p - $k + 1, 1)) { return (1, $sState); } else { my $rState = { }; addTransition($fp, $sState, $k1, $k1 + $p - $k, $rState); addTransition($fp, $rState, $k1 + $p - $k + 1, $p1, $sState1); return (0, $rState); } } else { return (exists $sState->{$t}, $sState); } } sub addTransition { my ($fp, $thisState, $left, $right, $thatState) = @_; $thisState->{substr($fp, $left, 1)} = [$left, $right, $thatState]; } } $| = 1; # Perl executable. our $perl = $^X; # All fingerprints, keyed by filename. our %fp; # Suffix trees of all fingerprints, keyed by filename. our %tree; # Stop comparing fingerprints after this many blocks. our $ceiling; # Get all fingerprints. foreach my $filename (@ARGV) { # This is OK as long as characters in name of $file are safe. my $fingerprint = `$perl -MO=Fingerprint $filename`; if (! $?) { # Remember this file's fingerprint. $fp{$filename} = $fingerprint; # Insert the fingerprint into the suffix tree forest. $tree{$filename} = buildTree($fingerprint); } } # Now compare each pair of fingerprints. my @result; my $count = 0; foreach my $file1 (keys %fp) { foreach my $file2 (keys %fp) { next if $file1 eq $file2; my $length1 = length $fp{$file1}; my $length2 = length $fp{$file2}; # Progress meter. print int ($count++ / ((keys %fp) * (keys %fp)) * 100), "% complete\r" if -t STDOUT; # Do we have a maximum number of cases to report? if (defined $topcases && @result >= $topcases) { $ceiling = $result[-1]{ratio} * $length2; } else { undef $ceiling; } # Compare the files. my $blocks = compare($file1, $file2); push @result, { file1 => $file1, length1 => $length1, file2 => $file2, length2 => $length2, blocks => $blocks, ratio => $blocks / $length2, }; # Ripple down new element in @result to keep it sorted. # If keeping only the top N cases, this is quicker than # sorting afterwards. if (defined $topcases) { my $pos; my $new = $result[-1]; # Insertion sort algorithm. for ($pos = @result - 2; $pos >= 0; $pos--) { if ($new->{ratio} < $result[$pos]->{ratio}) { # Ripple up an element. $result[$pos+1] = $result[$pos]; } else { # Found the right place. last; } } # Insert the new item at its place. $result[$pos+1] = $new; # Lose the (now) last element? if (@result > $topcases) { pop @result; } } } } # If collecting all cases, sort so that more similar code is near start # of list. if (!defined $topcases) { @result = sort {$a->{ratio} <=> $b->{ratio}} @result; } # Present results. foreach my $result (@result) { print $result->{ratio}, " ", $result->{blocks}, "/", $result->{length2}, ": ", $result->{file1}, " => ", $result->{file2}, "\n"; } sub compare { my ($file1, $file2) = @_; # We're trying to reconstruct fingerprint $fp2 from $fp1, so need # suffix tree from $fp1. my $tree1 = $tree{$file1}; my $fp1 = $fp{$file1}; my $fp2 = $fp{$file2}; # Number of blocks counted so far. my $blocks = 0; my $pos2 = 0; # Keep going while there's any of fingerprint 2 to do. BLOCK: while ($pos2 < length $fp2) { # Find a path through $tree1 that matches the part of $fp2 # we're up to. if (!exists $tree1->{substr($fp2, $pos2, 1)}) { # This character doesn't exist at all in $tree1. Next block. $pos2++; next BLOCK; } # There's an entry in the suffix tree. for (my $state = $tree1->{substr($fp2, $pos2, 1)}; # Start at root. defined $state; # Stop if finished a leaf node. $state = $state->[2]{substr($fp2, $pos2, 1)}) # Next node. { # Walk through characters in this state, comparing with $fp2. for (my $count = 0; $count <= $state->[1] - $state->[0]; $count++) { # Are there any more characters, and if so, do they match? if ($state->[0] + $count < length $fp1 && $pos2 < length $fp2 && substr($fp1, $state->[0] + $count, 1) eq substr($fp2, $pos2, 1)) { # Got a match, move on to the next character. $pos2++; } else { # Characters don't match; this is the end of a block. next BLOCK; } } # Finished this state, and it all matched. Go do the next one. } } continue { # Count the blocks as we go. $blocks++; if (defined $ceiling && $blocks > $ceiling) { # Exceeded the ceiling, return. last; } } return $blocks; }Back to article
http://www.drdobbs.com/web-development/catching-cheats-with-the-perl-compiler/184416093?pgno=1
CC-MAIN-2014-52
refinedweb
4,397
60.04
The .NET platform does not provide intrinsic classes to play sounds- these are handled natively in the Windows APIs resident in the Winmm.dll library. However, once you've isolated the API calls, it's no more difficult to play WAV files, and even WAV files stored in your assembly as embedded resources - than in any other language. I wanted to embed a couple of handy WAV files in an assembly to be able to play them on demand for various events raised in one of my creations, and so I put together this handy class, which can simply be added to any project, to provide static access to the PlaySound export for embedded resources. There are several overloads, the one we want accepts a byte array containing the resource, an IntPtr and UInt32 flags parameter which as with many API calls is the result of performing an OR method against defined constants. The beauty of my little creation is that it can normally be added to any project as is, and uses Reflection to get the namespace of the assembly dynamically. To add WAV files as embedded resources, simply ADD them to your project and set the property attribute of each to "Embedded Resource", and .NET takes care of the rest. First, here's the class - you can see I've given it a namespace and class name that reflect where the call is being made to: // [DllImport("Winmm.dll")] // public static extern bool PlaySound(string Sound, IntPtr hMod, UInt32 dwFlags); // this is the overload we want to play embedded resource... [DllImport("Winmm.dll")] public static extern bool PlaySound(byte[] data, IntPtr hMod, UInt32 dwFlags); public Winmm() { } public static void PlayWavResource(string wav) { // get the namespace string strNameSpace= System.Reflection.Assembly.GetExecutingAssembly().GetName().Name.ToString(); // get the resource into a stream Stream str = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream( strNameSpace +"."+ wav ); if ( str == null ) return; // bring stream into a byte array byte[] bStr = new Byte[str.Length]; str.Read(bStr, 0, (int)str.Length); // play the resource PlaySound(bStr, IntPtr.Zero, SND_ASYNC | SND_MEMORY); } } } To use the class, we would make the call as follows: private void button2_Click(object sender, System.EventArgs e) { Win32.Winmm.PlayWavResource("chimes.wav"); } N.B. Reader Jim McLendon converted the class to VB.NET for those who are interested, and has posted his code on our forums. You can view it here. That's all there is to it! The download has a complete solution, including the famous "chimes.wav" and "chord.wav" that everyone has, I am sure, heard many times.
http://www.eggheadcafe.com/articles/20030302.asp
crawl-002
refinedweb
426
62.98
Datagrid checkbox headerrenderer check off problemsubhajitnag1982 Jun 30, 2010 1:11 AM I have a datagrid where one column has select option like what we have in mail inboxes. User can select one or many row items to perform any actions by selecting the checkbox. It has also one select all option which is shown in the header renderer of that particular column. If user clicks on that all checkboxes gets selected. I have done that but the problem is that whenever i am performing any action by selecting all(header checkbox) and as a result the datagrid sometimes sets visible off or switches to some other mxml component from the component which is holding the datagrid and after coming back from that scenario again to the datagrid, its seen that the checkbox is still checked ... i want that checkbox to set to non-checked. help me. 1. Re: Datagrid checkbox headerrenderer check off problemBhaskerChari Jun 30, 2010 3:06 AM (in response to subhajitnag1982) Hi subhajit nag, I think you can make use of the show event for your mxml component in which you have the Datagrid checkbox headerrenderer....Once this event is fired try to deselect the check box... You can also do this by using a boolean bindable variable which is binded to the selected property of your checkbox headerrenderer....Change the value of the bindable property to false then it will automaticallt deselect/uncheck the check box when you move to other components... Thanks, Bhasker Chari.S 2. Re: Datagrid checkbox headerrenderer check off problemsubhajitnag1982 Jun 30, 2010 5:01 AM (in response to BhaskerChari) Let me explain u more the scenario. I have one mxml component which is within a viewstack. say this mxml is the 2 child of the viewstack. Now my 1st query is : If according to u i call a method whch deselects the checkbox header renderer on the mxml's show event then how will i point the inline checkbox headerrender ? i can use outerDocument within the renderer in order to access methods of parent document. But how to access methods of renderer from parent document ? 2nd query is : in this mxml component file i have another datagrid which has been set as visible in the initial. Clicking on a button sets that datagrid to visible and the datagrid havin checkbox headerrenderer sets to invisible. So if i click on the header checkbox and after that i click on the button toggles the visibility and when i am again returnin back to the actual scenario where the checkbox datagrid is visible. there i can see still the checkbox checked whch i dont want. hw to achieve that ? 3. Re: Datagrid checkbox headerrenderer check off problemBhaskerChari Jun 30, 2010 5:28 AM (in response to subhajitnag1982) Hi subhajit nag, Say the below is your mxml component in viewStack... <your component> <mx:Script> <![CDATA[ [Bindable]private var headerChecked:Boolean = false; private function onShow():void { headerChecked = false; } ]]> </mx:Script> </your component> <mx:DataGrid <mx:columns> <mx:DataGridColumn <mx:headerRenderer> <mx:Component> <mx:CheckBox <mx:Script> <![CDATA[ import mx.collections.ArrayCollection; private function checkUnCheckCheckBoxes():void { // You can handle your logic what you want to do when header check box is clicked.... } ]]> </mx:Script> </mx:CheckBox> </mx:Component> </mx:headerRenderer> <mx:itemRenderer> <mx:Component> <mx:CheckBox </mx:Component> </mx:itemRenderer> </mx:DataGridColumn> <mx:DataGridColumn <mx:DataGridColumn </mx:columns> </mx:DataGrid> So you just need to change the value of the headerChecked bindable variable to false..in show event for your first scenario...and your header check box is automatically unselected because this check box is binded to a bindable variable to which you are setting to false... For your second scenario....you can use the same changing the headerChecked value to false... You need to set this varibale to false in your second scenario where you know that your Header Render datagrid is making it visible after you made it unvisible... say you have clicked header check box and you made this datagrid invisible and this header checkbox datagrid will be visible once again when you click toggle button so set the value to false in the toggle button click function.... private function toggleButtonClickHandler():void { headerChecked = false; yourHeaderChkDataGrid.visible = true; yourAnotherDG.visible = false; } Hope this is clear for you now...Try this and let me know... Thanks, Bhasker Chari
https://forums.adobe.com/thread/670638
CC-MAIN-2017-30
refinedweb
723
53.92
__popcnt16, __popcnt, __popcnt64 Microsoft Specific Counts the number of one bits (population count) in a 16-, 32-, or 64-byte unsigned integer. - [in] value The 16-, 32-, or 64-bit unsigned integer for which we want the population count. The number of one bits in the value parameter. Requirements Header file <intrin.h> Each of these intrinsics generates the popcnt instruction. The size of the value that the popcnt instruction returns is the same as the size of its argument. In 32-bit mode there are no 64-bit general-purpose registers, hence no 64-bit popcnt. To determine hardware support for the popcnt instruction, call the __cpuid intrinsic with InfoType=0x00000001 and check bit 23 of CPUInfo[2] (ECX). This bit is 1 if the instruction is supported, and 0 otherwise. If you run code that uses this intrinsic on hardware that does not support the popcnt instruction, the results are unpredictable. Example #include <iostream> #include <intrin.h> using namespace std; int main() { unsigned short us[3] = {0, 0xFF, 0xFFFF}; unsigned short usr; unsigned int ui[4] = {0, 0xFF, 0xFFFF, 0xFFFFFFFF}; unsigned int uir; for (int i=0; i<3; i++) { usr = __popcnt16(us[i]); cout << "__popcnt16(0x" << hex << us[i] << ") = " << dec << usr << endl; } for (int i=0; i<4; i++) { uir = __popcnt(ui[i]); cout << "__popcnt(0x" << hex << ui[i] << ") = " << dec << uir << endl; } } Copyright 2007 by Advanced Micro Devices, Inc. All rights reserved. Reproduced with permission from Advanced Micro Devices, Inc.
https://msdn.microsoft.com/en-us/library/bb385231.aspx
CC-MAIN-2016-40
refinedweb
243
64.1
collective.syndication 1.0b3 Improved syndication for Plone sites providing Atom, iTunes, NewsML 1, RSS 1.0 and RSS 2.0 feeds. Table of Contents - Life, the Universe, and Everything - Mostly Harmless - Don’t Panic - Share and Enjoy - There’s a frood who really knows where his towel is Life, the Universe, and Everything collective.syndication improves standard syndication on Plone sites by providing 5 feed types: Atom, iTunes, NewsML 1, RSS 1.0 and RSS 2.0. This package is a backport for Plone 4.1 and 4.2 of Nathan Van Gheem’s Improved Syndication PLIP implementation made for Plone 4.3. Mostly Harmless Got an idea? Found a bug? Let us know by opening a support ticket. Don’t Panic Installation To enable this product in a buildout-based installation: Edit your buildout.cfg and add collective.syndication to the list of eggs to install: [buildout] ... eggs = collective.syndication After updating the configuration you need to run ”bin/buildout”, which will take care of updating your system. Go to the ‘Site Setup’ page in a Plone site and click on the ‘Add-ons’ link. Check the box next to collective.syndication and click the ‘Activate’ button. Note You may have to empty your browser cache and save your resource registries in order to see the effects of the product installation. Feeds Atom feeds have multiple advantages over RSS feeds. NewsML 1 NewsML 1 is an XML standard designed to provide a media-independent, structural framework for multi-media news. In this package, we implement part of the standard, to be usable by MSN. There’s no online reference on how MSN expects data, just a PDF included in the docs folder of this package. RSS 1.0 (RDF Site Summary) RDF Site Summary is a lightweight multipurpose extensible metadata description and syndication format. RSS is an XML application, conforms to the W3C’s RDF Specification and is extensible via XML-namespace and/or RDF based modularization. There’s a frood who really knows where his towel is 1.0b3 (2014-02-04) - Fix a problem with ViewPageTemplateFile overriding the Content-Type header, now we set the header after rendering the body, this way third party products can’t break the feeds Content-Type. [jpgimenez] 1.0b2 (2014-01-23) 1.0b1 (2013-09-03) - Replace beautifulsoup4 with lxml. [jpgimenez] - Fix a bug with body text coming from dexterity content. [jpgimenez] 1.0a4 (2013-03-27) - (Bugfix) Return proper headers with the feeds. [frapell] 1.0a3 (2013-03-21) - Don’t use an interface as filtering mechanism to get NewsML items. [frapell] 1.0a2 (2013-01-15) - Implement NewsML 1 syndication. [frapell] 1.0a1 (2013-01-10) - Initial release. - Downloads (All Versions): - 24 downloads in the last day - 136 downloads in the last week - 511 downloads in the last month - Author: Nathan Van Gheem - Keywords: plone atom itunes rss syndication newsml rdf - Categories - Development Status :: 4 - Beta - Environment :: Web Environment - Framework :: Plone - Framework :: Plone :: 4.1 - Framework :: Plone :: 4.2 - Intended Audience :: End Users/Desktop - Intended Audience :: System Administrators - License :: OSI Approved :: GNU General Public License v2 (GPLv2) - Operating System :: OS Independent - Programming Language :: Python - Programming Language :: Python :: 2.6 - Programming Language :: Python :: 2.7 - Topic :: Office/Business :: News/Diary - Topic :: Software Development :: Libraries :: Python Modules - Package Index Owner: hvelarde - Package Index Maintainer: collective - DOAP record: collective.syndication-1.0b3.xml
https://pypi.python.org/pypi/collective.syndication/1.0b3
CC-MAIN-2015-22
refinedweb
563
58.48
Key Takeaways - Auth0 is a secure authentication platform that's easy to set up and provides features like SSO integration, cloud functions, and user management. - Hasura is a GraphQL engine for PostgreSQL that provides tools for rapid development. Hasura has both on-premise and cloud solutions. - Using Hasura and Auth0, you can bootstrap your authentication layer and save yourself days, if not weeks, of development time. - You can use the Auth0 auth pipeline rules to automatically create JWT tokens with a custom payload to power Hasura's access control rules. - Hasura provides tools for setting up complex access control rules such as table relationships, session variables, and operators such as `_and`, `_or`, and `_not`. When you're trying to prototype an MVP for your app and want to start iterating quickly, the upfront cost of setting up authentication can be a massive roadblock. The authentication layer requires significant work, and you must always be on the lookout for security vulnerabilities. So it is logical to use third-party solutions to help yourself as much as possible.Today there's an abundance of cloud and on-premise services to help you reduce your development time. Additionally, you can save effort by setting up a GraphQL server. For any application, one of the main reasons for a server, at least in the beginning, is to provide secure communication between your database and client. With GraphQL, you no longer need to construct custom API endpoints to fetch data. Your client gets the flexibility to write GraphQL queries to fetch and format data however you wish, without any changes on the server. More direct access to data does not mean less security. With GraphQL you still can and should implement a robust and modular security layer. Let's cover bootstrapping an authentication system and server using Auth0.js and Hasura. Using these tools, you can save yourself days, if not weeks, of development time and offload most of the complexity around setting up a secure and granular data access system. We will set up a simple application with authentication powered by Auth0 and Hasura GraphQL as a server. Our front-end framework of choice is React, but the lessons of this tutorial equally apply Angular, Vue, or any other modern framework. What is Auth0? Auth0 is an authorization and authentication platform as a service. Auth0 helps you maintain and track user sessions, set up secure communication between your client and a server, and securely store sensitive user information on their platform. Auth0 solves some of the main pain points of dealing with authentication. Other notable features of Auth0 include SSO integrations, automated authentication pipelines, and a customizable authentication interface. Reasons to use Auth0 Auth0 is not the only authentication service on the market. Another well-known one is Okta. Both Okta and Auth0 are great options but have slightly different target audiences and use cases. Okta is focused more on the enterprise. One of its main features is allowing users in your company to sign into all their other company apps with ease. Auth0, on the other hand, focuses more on supporting various SSO providers and serverless automation. As a side note, Okta recently acquired Auth0, so it will be interesting to see how that will affect the features of these two products. A third solid option for an authentication provider is AWS Cognito. At the time of writing, Cognito provides a generous 50,000 monthly active users with their free tier. Like the other providers, Cognito allows bootstrapping authentication interface, setting up SSO providers, and running automated functions using AWS Lambda. The main benefit of Cognito is that you can set it up as an access control system for other AWS resources that your app consumes. The biggest drawback of Cognito is the lack of support when it comes to customizing authentication flows and poor documentation. Both Okta and Auth0 have much more mature and user-friendly documentation. For our tutorial, we will use Auth0 as it has a free plan for up to 7,000 users that requires no credit card, but Okta and Cognito might be other viable options for you. What is Hasura? Hasura is a GraphQL engine for PostgreSQL databases. Hasura is also not the only available GraphQL engine. There are other solutions like Postgraphile and Prisma. However, after trying a few of them, I've come to appreciate Hasura for several reasons: - Hasura is designed for client-facing applications and is one of the simplest solutions to set up. With Hasura, you get a production-level GraphQL server out-of-the-box that’s performant and has a built-in caching system. - Powerful authentication engine that’s based on the RLS (Row Level Security) that allows building granular and complex permission systems. - You can host Hasura on-premise using their Docker image, but you can also set up a working GraphQL server in a matter of minutes using Hasura cloud. This option is perfect for scaffolding your app and is the one we will use today. - Hasura's dashboard is powerful and user-friendly. You can write and test your GraphQL queries, manage your database schema, add custom resolvers and create subscriptions, all from one place. There are, however, a few drawbacks to take into account when working with Hasura: - Not all databases are supported. Currently, Hasura works with PostgreSQL, Microsoft SQL Server, AWS Aurora, and Google's BigQUery. The team is also working on supporting other database engines such as Oracle, MongoDB, MySQL, and Elastic. - Hasura doesn't support aggregating data from multiple GraphQL nodes. It is something that their team is actively working on, but for right now, you can only run queries on a single GraphQL server instance. All in all, Hasura is one of the best solutions for quickly setting up a GraphQL engine for your client-facing application. Tutorial Now that we have introduced both Auth0 and Hasura, let's get started with our tutorial! We will build a simple React application that uses Auth0's React SDK to communicate securely with our Hasura GraphQL server. React application Let's start by setting up our React app. Here's the repo of the project. To follow along, you will need to install create-react-app. First, we initialize the project using the `npx create-react-app my-app` command. If you don’t have npx, you can easily install it globally by running the `npm install -g npx` command. Next, we will need to install `react-router-dom` and Auth0 React SDK for setting up routes within a React web app and adding authentication code: `yarn add react-router-dom @auth0/auth0-react` Before moving further, we should set up our Auth0 and Hasura projects. Let's start with Auth0. Auth0 project Navigate to `manage.auth0.com` and log in to their dashboard. From there, create a new application: Once you create the application, take a note of the following information: - Domain - Client id Auth0 also provides you with a client secret. The client secret is a private key that you can use on your server to make requests to Auth0 API, but we won't be needing it for this tutorial. Next, we need to set up application URLs for Auth0. We need to set up three URLs: - Allowed Callback URLs. The list of URLs to redirect the user back from the authentication process. In our case, it'll be the root URL of our server. - Allowed Logout URLs. URLs to return to after logging out the user. This will also be the root URL. - Allowed Web origins. List of URLs that can use your Auth0 project. You need to add your app's URL to this list. Make sure to click the "Save" button for the changes to propagate. Now let's hop back to our React app and finish setting up Auth0 SDK. To do that, we need to add Auth0Provider at the root of your application which will allow us to use the SDK throughout the app: import './App.css'; import Routes from './routes'; import { Auth0Provider } from '@auth0/auth0-react' import ApolloGraphqlProvider from './ApolloProvider'; const redirectURL = window.location.origin; function App() { return ( <div className="App"> <Auth0Provider domain="YOUR_DOMAIN" clientId="YOUR_CLIENT_ID" redirectUri={redirectURL}> <ApolloGraphqlProvider> <Routes /> </ApolloGraphqlProvider> </Auth0Provider> </div> ); } export default App; Now we can use Auth0’s functionality using the `useAuth0` hook. There are many things we can do with it. For example, we can access user information stored in Auth0 from any component: import { useAuth0 } from '@auth0/auth0-react' import React from 'react' export default function Private() { const { user } = useAuth0() return ( <div> <h1>Private</h1> <p>{user.email}</p> <p>{user.name}</p> </div> ) Some of the other features you’re most likely to use are: - `getAccessTokenSilently` - allows generating access tokens that you can use to communicate safely with your server. As a side note: Auth0 also has SDKs for server-side applications that help with verifying generated access tokens. - `logout` - `logout` logs the user out of the application by clearing the current session and redirecting to the URI you specified when setting up the `Auth0Provider`. - `isAuthenticated` - a boolean that indicates whether the user is currently logged in. Using `isAuthenticated`, you can decide whether to allow the user to see certain routes or components. Hasura project Next, let's move on to setting up our Hasura project. To follow along with this tutorial, you will need a running PostgreSQL database instance. As I mentioned, to keep things simple, we will use Hasura cloud. Navigate to Hasura and click on the `Get Started` button: Once you log in, click on `Create a project`, pick a free tier and provide a name for your project. Finally, click `Launch Console` to get redirected to your project's console. Hasura’s dashboard is pretty powerful, you can manage your database and access-control system from it, among many other things. Let's connect our database. Click on the `Data` tab, and you will see a connection form. You can choose to provide a PostgreSQL connection string or input each database parameter separately. Once you have connected your database, you can start adding schemas and tables as well as writing GraphQL queries. Hasura provides a graphiql IDE interface that will be familiar if you've worked with GraphQL before. We will circle back to setting up table permissions, but first, we need to set up secure JWT token generation. JWT with Auth0 cloud functions The next step is setting up the JWT token system for sending secure queries to Hasura. We will need to provide Hasura with a payload it understands and uses to enforce table security rules. Auth0 generate JTW tokens for us, but they don't have the payload Hasura needs. To solve that, we can use Auth0's pipeline rules. We will create a custom rule that will add the necessary payload data when JWT token is generated. Navigate to the rules console from Auth0's dashboard under the `Pipeline` menu. From there, create a new rule, you can call it whatever you want. Input the following code: function (user, context, callback) { const namespace = " context.accessToken[namespace] = { 'x-hasura-default-role': 'user', // do some custom logic to decide allowed roles 'x-hasura-allowed-roles': ['user'], 'x-hasura-user-id': user.email }; callback(null, user, context); } Here we're simply adding `x-hasura-user-id`, `x-hasura-default-role` and `x-hasura-allowed-roles` fields that Hasura understands and which we will use later when setting up our database access control system. Configuring Hasura to use JWT token The next thing we need to do is configure Hasura to verify our JWT tokens. Each Auth0 application has a domain and we will need it to set up our configuration. Navigate to the settings page of your Auth0 application and copy your domain. Next, visit and use the form Hasura provides for generating the JWT config objects. The config object will contain a certificate string that Hasura will use on its back-end to verify the token’s signature. All you need to do is specify your Auth0 domain, and the tool will create the config object for you. Now you need to set the config object you created as an environment variable for your Hasura instance. Navigate to your Hasura project's settings page and click on `New env var` from the `Env vars` tab. Use `HASURA_GRAPHQL_JWT_SECRET` and save your JSON config as a variable. At this point, your Hasura engine should be fully configured to work with JWT tokens generated by Auth0. Using JWT tokens in React You’re free to use any GraphQL client you prefer, just be aware of how Auth0 creates JWT tokens. The `getAccessTokenSilently` method Auth0 provides for generating tokens is asynchronous. This might be a problem for GraphQL clients that typically instantiate synchronously on the page load, for example, the Apollo client. There is, however, a workaround you can implement with Apollo client using setContext: import { ApolloClient, InMemoryCache, createHttpLink, ApolloProvider, } from "@apollo/client"; import { setContext } from "@apollo/client/link/context"; import { useAuth0 } from "@auth0/auth0-react"; import fetch from "isomorphic-fetch"; const API_URL = " export default function ApolloGraphqlProvider({ children, }) { const { getAccessTokenSilently } = useAuth0(); const authLink = setContext(async (_, { headers }) => { let accessToken = null; try { accessToken = await getAccessTokenSilently(); } catch (e) { console.log({ e }); } headers = { ...headers }; if (accessToken) { headers.authorization = `Bearer ${accessToken}`; } return { headers }; }); const = createHttpLink({ fetch, uri: API_URL, }); const client = new ApolloClient({ link: authLink.concat( cache: new InMemoryCache(), }); return <ApolloProvider client={client}>{children}</ApolloProvider>; } `setContext` is made specifically for situations where you need to asynchronously generate or lookup authentication data, such as tokens. It accepts a function that can either return an object or a promise returning an object. The object returned is used as a context for your GraphQL queries. Another thing to note in the code above is our use of isomorphic-fetch. isomorphic-fetch is a library that ensures consistent implementation of the fetch API across all the browsers (and within Node.js) and guarantees the same behavior for our GraphQL client. Now we’re ready to start sending queries with our GraphQL client. Hasura Access control rules Now that we have our JWT token communicating safely with Hasura, it's time to set up the access control system for our database. Under the hood, access control rules are enforced using PostgreSQL row-level security. When you send GraphQL queries, Hasura transforms them into SQL statements and applies the access control rules you specified. Granularity With Hasura, there are three levels of granularity you can control: - Role - Table - Action You can configure role permissions for each table. Click on any table and select the Permissions tab: The role of the current user is derived from the `x-hasura-default-role` payload field we set up earlier. By default, your GraphQL engine generates the admin role, but you can always add more custom roles. On top of that, you can specify which actions the role can perform on a given table. Notice how we have four distinct columns for each role: insert, update, read and delete. Controlling permissions for each action type allows you to get as granular with your role permissions as you want. Row & Column permissions For each of the four actions, you can specify additional permissions on row and column levels. Again, Hasura will use the token payload to enforce this kind of access. Row-level permissions are boolean expressions that run each time the table is accessed to determine which rows are allowed. In the screenshot above, the boolean expression states that we can only insert rows with `user_id` equal to the value of `X-Hasura-User-Id` JWT payload field. Under the hood, Hasura translates the payload fields into session variables. We will cover using session variables in more detail shortly. We can also specify which columns the given role can access by toggling checkboxes in the `Column Insert Permissions` section. I hope this shows you how powerful Hasura's access control dashboard is. If you've ever set up granular database permissions manually or using command-line tools, you know how tedious this process can get. Guide to setting up access control rules Now let's cover in more detail the different scenarios you might run into when trying to set up access control rules for your application. Using session variables If you recall, payload fields from our JWT token get translated into session variables that you can use to build dynamic access rules. Let's revisit our earlier example: In this case, we're using the JWT payload field `X-Hasura-User-Id`. Hasura translates that field into a session variable with the same name. We use the variable to make sure each user can only see the rows they created. Using table relationships and nested objects We can also build access rules using table relationships that are based on foreign keys. Let’s look at the example. Say we have `message` and ` user` tables, and they have a table relationship through their foreign keys. We also have a `Team-Id` payload field that we want to use to get all the messages that belong to your teammates. We can create an access rule on the `message` table that uses the `team_id` column of the related `user` table. Here's what it would look like: Using this access rule, you can read the messages of all of the users whose `team_id` column matches the `Team-Id` field of your payload. In other words, all of the messages that belong to your teammates. Setting up more complex permissions with _and, _or and _not You can build even more complex rules using `_and`, `_or` and `_not` operators. Using these operators you can combine multiple boolean expressions to create a unique permission logic to meet the needs of any application. Let's say you want to let the users read only the messages they create that also have a type of "free". We can use the `_and` operator to combine these two boolean expressions like so: Operators for combining multiple boolean expressions make it possible to support the logic of the highest complexity. Conclusion To summarize, we talked about bootstrapping authentication systems in your application using the Hasura GraphQL engine and Auth0.js. We covered the pros and cons of each tool and how to set them up in your project. We also covered how to use Hasura's access control rules to build a granular, role-based access system. We explored advanced use cases that involve session variables, table relations, and combining multiple boolean expressions using operators. Hasura's GraphQL engine is an open-source project available under the "Apache 2" license. To learn more about contributing, read their contribution guidelines. About the Author Iskander Samatov is currently a senior software engineer at HubSpot. He was previously involved with several startups in legal tech such as Joinder, building communication platforms and streamlining processes for professionals in the legal industry. Iskander has developed a number of mobile and web apps, used by thousands of people, like Planly. Iskander frequently blogs at Inspired by this content? Write for InfoQ. Becoming an editor for InfoQ was one of the best decisions of my career. It has challenged me and helped me grow in so many ways. We'd love to have more people join our team. Community comments
https://www.infoq.com/articles/auth-layer-auth0-hasura/?itm_source=articles_about_javascript&itm_medium=link&itm_campaign=javascript
CC-MAIN-2022-21
refinedweb
3,222
54.93
As part of some of my adventures with F#, I've seen a lot of interesting things coming from others with regards to SharePoint, ASP.NET and other technologies. This had me thinking of any possibilities and ramifications of using F# with ASP.NET MVC. Was it possible, and better question, what might make someone use this over their existing toolsets. Those are some of the questions to explore. But, in the mean time, let's take the journey of F# and ASP.NET MVC. First, let's cover what it takes to get F# to work with ASP.NET MVC. The required downloads are: Side by side, I think it's easier to first create a sample C# ASP.NET MVC project, so it's easy to cut and paste the configuration file information. What works better is to open the NHamlViewEngine sample from MVCContrib. Also, create a standard F# library, and in my case, I called it MvcFSharp. I then add references to the following assemblies: Since the F# projects do not support creating folders, this next step requires some Visual Notepad support. First, create the Models, Controllers, Content and Views directories through Windows Explorer. Create dummy files in each folder is probably the easiest thing to do. When you are done, your project file contain this: <ItemGroup> <Compile Include="Models\ListViewData.fs" /> <Compile Include="Controllers\HomeController.fs" /> <Compile Include="Default.aspx.fs"> <DependentUpon>Default.aspx</DependentUpon> <SubType>ASPXCodeBehind</SubType> </Compile> <Compile Include="Global.asax.fs"> <DependentUpon>Global.asax</DependentUpon> </Compile> <Content Include="Default.aspx" /> <Content Include="Global.asax" /> <Content Include="Content\Site.css" /> <Content Include="Content\MicrosoftAjax.js" /> <Content Include="Content\MicrosoftAjax.debug.js" /> <Content Include="Content\MicrosoftMvcAjax.js" /> <Content Include="Content\MicrosoftMvcAjax.debug.js" /> <Content Include="Views\Home\About.haml" /> <Content Include="Views\Home\Index.haml" /> <Content Include="Views\Home\Numbers.haml" /> <Content Include="Views\Masters\Application.haml" /> <Content Include="Web.config" /> </ItemGroup> In this actual case, these are the real files listed for our first F# ASP.NET MVC application. Once you reload the project file from Visual Studio, you should be ready to go. One thing to keep in mind with your project compilation is that in F#, order of files does matter. Any further work where order may matter could force you to change the project file configuration with notepad once again. Once the project file has been modified, let's move onto modifying the web.config to reflect using F# as a compiler. There are several items we need to add in order to get both NHaml and F# to work as one inside our web.config. As I said earlier, it's probably easiest to copy/paste some basic information from the NHamlViewEngine sample from MVCContrib to save yourself from having to reference additional things. First, let's add NHaml support to our project file. We need to modify the configSections area to add nhamlViewEngine support. Add the following text to your configSections: <configSections> <section name="nhamlViewEngine" type="MvcContrib.NHamlViewEngine.Configuration.NHamlViewEngineSection, MvcContrib.NHamlViewEngine, Version=0.0.1.159, Culture=neutral, PublicKeyToken=null" /> Now, add the nhamlViewEngine information in as follows. Note that I'm adding some references to F#. The reason being is that should I return a type that is F# specific such as a list, seq or otherwise, NHaml will not be able to reference properly without access to the FSharp.Core.dll. <nhamlViewEngine production="false"> <views> <assemblies> <add assembly="FSharp.Core, Version=1.9.6.2, Culture=neutral, PublicKeyToken=a19089b1c74d0809"/> </assemblies> <namespaces> <add namespace="Microsoft.FSharp.Core" /> </namespaces> </views> </nhamlViewEngine> In order for us to compile our default.aspx.fs and global.asax.fs file, we need to add support for the F# compiler in our web.config. Add the following section of XML to your compilers section, right next to your C# compiler registration. <compiler language="F#;f#;fs;fsharp" extension=".fs" warningLevel="4" type="Microsoft.FSharp.Compiler.CodeDom.FSharpAspNetCodeProvider, FSharp.Compiler.CodeDom, Version=1.9.6.2, Culture=neutral, PublicKeyToken=a19089b1c74d0809"> <providerOption name="CompilerVersion" value="v3.5" /> <providerOption name="WarnAsError" value="false" /></compiler> We now have the F# ASP.NET Code Provider installed in our web.config, so our focus now shifts to proper registration in our global.asax.fs and default.aspx.fs. Now we turn our attention to the two defaults for our application, the global.asax and the default.aspx. First, modify the global.asax to indicate the following: <%@ Application CodeBehind="Global.asax.fs" Inherits="MvcFSharp.MvcApplication" Language="F#" %> If you followed the project structure from above, open the global.asax.fs file and modify it to look like this. As you can see from above, I had to add two record types, called MvcConstraint2 and MvcConstraint3. The reason being is that F# does not do anonymous types as C# does. Instead, you define a simple record type to hold the data as needed. Since there are two different needs, one with two fields and one with three, there is a need to define two separate instances. Much as you would in the C# code, the registration should not look all that different. But, I kept the RegisterRoutes function so that I can test my routes in a nice TDD fashion. Moving onto the default.aspx file, modify the default.aspx to look like the following: <%@ Page Language="F#" AutoEventWireup="true" CodeBehind="Default.aspx.fs" Inherits="MvcFSharp._Default" %> Once that is complete, move onto the default.aspx.fs file. It should look like the following: We now have a basic setup in which to build upon for our application. Now we can concentrate on the models, controllers and views. I want just a basic model to show that creating concise and compact models is relatively simple using F#. As I did for the MvcConstraint record types above, I can easily apply to my model. Sometimes, our models may be nothing more than just a write once operation, so simple immutable record types suffice. Other times, we may need to make some of the fields mutable. But, that's the beauty of F#, is that it allows us to do both. Let's create one to hold just some numbers to display on the screen. If following the above project structure, your ListViewData.fs should look like the following: Done! Now that was easy! Moving onto the controller... We have the models now defined, so let's move onto the controllers. I only want one controller during this example, in this case the HomeController.fs. Let's say I have three views I want to work with, the Index, About and Data. Defining such a controller is quite simple. It should look something like this: In this example, I did nothing more than just tell the system to render the view. Each time, it's best that you cast it to the appropriate return type much as I did above. In the case of the Numbers function, I wanted to create a set of numbers to render to the screen, so I create my new ListViewData with my numbers set. Then, I pass that to the view to render. As I've stated before, I'm interested in following the example from MVCContrib for the NHamlViewEngine as much as possible. So, the views look 100% like they do from the project, except for my numbers.haml file. Let's look at the views that matter. First, the index.haml file.. Once the application is built, we can then create the virtual directory in IIS to host our application. Once that is complete, launching the browser will give us this for our Index view. Our about page will look like the following: And lastly, our numbers page will display the numbers from 1-10 in an unordered list: So, as you can see, we now display our data from our F# controller and F# models. But, is that all of our story to tell? Of course not? I think it's important to emphasize TDD with this approach. This works no different than it would in C#, quite frankly. Much like when you create a new ASP.NET MVC project, it will by default help you create a set of unit tests using the xUnit framework of your hoice. In this case, my default is xUnit.net. Let's talk about testing here once again. As I've stated before, I created an overall project called FsTest which creates a DSL over the assertion syntax. This allows me to more naturally test using functional programming strengths. Using this, I'm able to test all of my code much as you would in your C# solution. Let's first start with our MvcApplication tests. Let's go through one of the tests that I did earlier in regards to my Numbers function. This is just one in the number of unit tests that I defined for this application. As you can see, it's quite easy to use FsxUnit in using the AAA syntax. As you can see, getting F# to work with ASP.NET MVC wasn't absolutely trivial. But once the overall project skeleton is defined, modifying it to fit your application is easier. But, the question comes up, why bother doing this? I know I'm going to get that question a lot. Well, first off, it was a challenge to myself. But, secondly, I'm able to use the concise F# syntax to express controllers and models quite easily without much pomp and circumstance. Maybe a hybrid approach may work better? Maybe F# as a view engine may yield better results? Anyhow, feel free to pick through this sample and let me know your thoughts. I've made the project available here. Pingback from Dew Drop - October 7, 2008 | Alvin Ashcraft's Morning Dew .NET Richmond Code Camp 2008.2 - Functional C# Recap ASP.NET MVC with NHaml - F# Edition Formatting strings Tried to get this going but keep getting the following error: Method 'FindPartialView' in type 'MvcContrib.NHamlViewEngine.NHamlViewFactory' from assembly 'MvcContrib.NHamlViewEngine, Version=0.0.1.159, Culture=neutral, PublicKeyToken=null' does not have an implementation. MVC works fine using c# on my machine but would really like to get the f# build going @Graham This was a while ago and since then the assemblies have changed. I haven't looked at it lately, so I'm not sure what has changed and what hasn't. Sorry about that. Matt Looks like the zip file for the project is gone? Anyway I could get a copy? Thanks! I've recently been smitten by F#, and always wanted to see a good MVC web framework for .NET. Wow, I can have my cake and eat it too! Thanks for saving me some time as I was considering embarking on this very path myself. I even bought a book on ASP.NET MVC with the express idea of figuring out how to configure the framework for F# development. @Bob, You might also want to look at the Bistro project which is an MVC implementation in F#:
http://weblogs.asp.net/podwysocki/archive/2008/10/06/asp-net-mvc-with-nhaml-f-edition.aspx
crawl-002
refinedweb
1,845
59.9
I have frequently run into this (or similar) error message: File "/home/django/domains/substanceis.com/substanceis.com/lib/python2.5/site-packages/django/db/__init__.py", line 16, in <module> backend = __import__('%s%s.base' % (_import_path, settings.DATABASE_ENGINE), {}, {}, ['']) File "/home/django/domains/substanceis.com/substanceis.com/lib/python2.5/site-packages/django/db/backends/postgresql_psycopg2/base.py", line 20, in <module> raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e) ImproperlyConfigured: Error loading psycopg2 module: cannot import name tz And each time I am very confused by it. Then I realize the problem. Then I solve it. Then I forget about it. Until the next time. Your server cannot write to the PYTHON_EGG_CACHE path, and thus cannot use eggs. That's the entire problem right there. Although you might need to install egenix-mx-base. I'm not even sure if it's relevant or just something I want to be relevant as I tirelessly struggle against this error. sudo easy_install egenix-mx-base The real fix to this problem is in either your mod_python or mod_wsgi configuration files. For mod_wsgi a line like this should be added to your site's .wsgi file. os.environ['PYTHON_EGG_CACHE'] = '/home/django/.python-eggs' It doesn't need to be home/django/.python-eggs specifically, just somewhere that www-data can write to (for Ubuntu). To check just su to www-data and give it a wack. sudo su www-data cd /home/django/.python-eggs mkdir test rm -rf test If that worked, then you're golden. Restart your server and get outa here. If you're using mod_python, then you'll need to make this change in a different location. It's explained more fully here, but basically you need to make a eggs.py file somewhere that contains these lines import os os.environ['PYTHON_EGG_CACHE'] = '/home/django/.python-eggs' And then add these directives to your domain's VirtualHost. PythonInterpreter my_django PythonImport /path/to/my/profile/eggs.py my_django Then you're done. Phew. I hope I never get thrown for a loop by this silly error again.
http://lethain.com/when-psycopg2-can-t-import-tz/
CC-MAIN-2015-18
refinedweb
348
53.17
Before we learn what you need to support TypeScript and Flow, let's think about why people use them in the first place. The main problem is that JavaScript is a dynamically, weakly typed language, but many programmers want static (and sometimes strong) typing. Dynamic typing means that there are no types at compile-time. This means that you could accidentally add a function and a number, but you wouldn't know until runtime. Very few interpreted and JIT-compiled languages support static typing. // There is no way to declare a type for a and b, even // though a clearly needs to be a function const myFunction = (a, b) => { return a(b); } // This function call does not throw a type error // until it is executed, but a statically typed // language would not compile. // Think of a compile-time type error like a syntax // error. Your code doesn't need to run for a type // error to occur in statically typed languages. const myResult = myFunction( { you: 'should not' }, 'be able to do this' ); In contrast, a language like C will never allow something like this: #include <stdio.h> // This throws a compile time warning (or error, // depending on your configuration) const char* example() { // Not a string literal, so the program does // not compile and you cannot run it return 20; } int main() { printf("%s", example()); return 0; } Weak typing means that JavaScript will not crash/throw an error when performing an illegal operation and will instead try to make that operation work. This kind of behavior is the origin of many WTFs by JS developers. // This is perfectly valid JavaScript const weirdAddition = [] + []; console.log(weirdAddition); // "" // That worked because the engine implicitly called // [].toString() when it saw the addition operator. // An empty array gives an empty string, hence the // result is "" + "" = "". This behavior is the polar opposite of Python: any invalid operation will immediately cause an exception. Even adding a string and a number will fail and ask you to convert the number to a string first. a = '9 + 10 = ' b = 9 + 10 # This fails: you must explicitly cast b to string print(a + b) # Only this works print(a + str(b)) Although JavaScript's virtually non-existent type system give programmers more flexibility, it's also the source of many bugs. Being both dynamically and weakly typed, at no point will you get an error if you make a mistake with types. Therefore, programmers wanted a solution to add types to JavaScript. Enter TypeScript: an extension to JavaScript that adds syntax support for typings, a compiler, and incredible autocomplete support that was never previously possible in JavaScript. // TypeScript accepts reasonable implicit conversions const myFunction = (x: number) => 'hello ' + x; // This will not compile, even with an explicit return type // Adding arrays is not a reasonable use of dynamic typing const myOtherFunction = ( x: string[], y: string[] ): string => x + y; // This will fail at compile time as well, since the first // parameter of myFunction must be a number myFunction('hello'); I highly recommend using TypeScript in your library because it compiles to any version of JavaScript, even as early as ES3. You can support legacy and modern JS environments, support both JavaScript and TypeScript users, and prevent bugs within your code by using TypeScript. Whether or not you decide to use TS, supporting TS users can be confusing, so read on. Supporting TypeScript from a TypeScript project If your library is written in TypeScript, you can automatically generate both JavaScript code (to support all users) and TypeScript declaration files (which add TypeScript types to JavaScript code). You will almost never need to export TypeScript files in your package, unless all of your users will use TypeScript (i.e. for something like typegoose). The main think you need to do is enable the declaration compiler option in tsconfig.json. { "compilerOptions": { "outDir": "lib/", // This is the relevant option // The types you need will be exported to lib/ "declaration": true } } If you're not using the TypeScript compiler to build your code (using the noEmit option), you'll want to use emitDeclarationOnly as well. { "compilerOptions": { "outDir": "lib/", "declaration": true, // Remove noEmit and replace it with this "emitDeclarationOnly": true } } Then, in package.json, use the "types" field to include your types. { "main": "lib/index.js", "types": "lib/index.d.ts" } Supporting TypeScript from a JavaScript project Just as with a TypeScript project, you need to export both JavaScript files and TypeScript declaration files to make your code usable for both TypeScript and JavaScript users. Creating and maintaining a declaration file by hand can be difficult, so you'll want to make sure to read the docs on declaration files. If you have trouble with the syntax, try looking at the typings for popular packages such as Express. First, you'll need to figure out whether the files you export from your package use CommonJS or ES Modules. CommonJS looks like this: // module.exports or exports indicate CommonJS module.exports = { a: 1, b(c, op) { if (op == 'sq') return c ** 2; if (op == 'sqrt') return Math.sqrt(c); throw new TypeError('invalid operation') } } // For exporting one thing: module.exports = 'hello'; In contrast, ES Modules look like this: // The export keyword indicates ESM export const a = 1; export function b(c, op) { if (op == 'sq') return c ** 2; if (op == 'sqrt') return Math.sqrt(c); throw new TypeError('invalid operation') } // export default for one thing export default 'hello'; If you export both (we'll get into how to do this in a future article), only make a declaration file using ESM because the CommonJS declarations can almost always be inferred by the TypeScript compiler from the ESM version. If you're using CommonJS, use namespaces to encapsulate your package. Optimally, you'll also export types and interfaces that make TypeScript use more convenient. // index.d.ts // Everything in the namespace is exported // If you want to use a type within the declaration // file but not export it, declare it outside declare namespace MyPackage { const a: number; // This type prevents TypeScript users from // using an invalid operation type MyOp = 'sq' | 'sqrt'; function b(c: number, op: MyOp): number; } export = MyPackageName; // For a single export: declare const myPackage: string; export = myPackage; Alternatively, if you're using ESM, you don't need (and shouldn't use) a namespace; export as you would in JavaScript. export const a: number; export type MyOp = 'sq' | 'sqrt'; export function b(c: number, op: MyOp): number; // For a single export: declare const myPackage: string; export default myPackage; Now that you have a complete index.d.ts, you can do one of two things. You can either: - Add it to your own NPM package, as with the TypeScript version - Add it to the DefinitelyTyped repository to get an @types/your-package-namepackage automatically I recommend adding the declaration to the NPM package because that reduces the amount of time and effort it takes to update your package, as well as giving you more flexibility with regards to the TypeScript features you can use and removing the need to add tests. However, if you have many dependencies whose types you need to include (e.g. if you export a React component, you depend on the React typings), you need to add @types/dependency-name to your dependencies, not devDependencies, and that adds bloat for your end users that don't use TypeScript. In those cases, it's often better to publish to DefinitelyTyped. What about Flow? The process of supporting Flow users is extremely similar to that of TypeScript. Instead of adding the definition file to "types" in package.json, make a .js.flow file alongside every .js file that is being exported (for example, if you export lib/index.js, make sure to create lib/index.js.flow with the definitions). See the docs on how to create such a definition. If you want to support Flow yourself, don't publish to flow-typed; it's mainly meant for community members to create their own types for third-party packages and publish them there. // @flow // If this is an ES Module: declare export function sayHello(to: string): void; // Alternatively, if this is CommonJS: declare module.exports: { sayHello(to: string): void; } If you are writing your library with Flow, you can use build tooling to automate the process. Alternatively, use flowgen to only need to maintain a TypeScript definition file and automate the process of Flow support. In any case, Flow is pretty rare today; supporting just TypeScript will probably never be a problem. Discussion (0)
https://practicaldev-herokuapp-com.global.ssl.fastly.net/101arrowz/creating-a-modern-js-library-typescript-and-flow-3ge
CC-MAIN-2021-31
refinedweb
1,416
50.57
import AutoCAD plan to landscaping architects hi dears! is my first topic , and i am sure you can find a lot of grammar problem and bad english first sorry for my poor language --------------------------------- i am using from " landscaping architects " software version-2009. but i have a big problem with it. I will now know how i can import a plan from AutoCAD to it, because landscaping can not drawing plan like CAD ! do there is a way for do ? probably i not know it or landscaping can not support it. with a lot of thanks. import AutoCAD plan to landscaping architects You can post your problem related to Civil Projects here. We will try our best to help you out. Post Reply 1 post • Page 1 of 1 Post Reply 1 post • Page 1 of 1
https://www.theengineeringprojects.com/forum/viewtopic.php?p=664
CC-MAIN-2020-10
refinedweb
136
83.15
From: Michel André (michel.andre_at_[hidden]) Date: 2003-02-21 15:48:37 Is shared_count scheduled to come out from the detail namespace and be publically available and maybe a bit documented? I don't think we should encourage users to use things from detail namespace? /Michel Phil Nash wrote: > Peter suggested I use shared_count when I first started talking about > smart_resource (or shared_resource as I was then calling it) over a > year > ago - so it's not a new thing :-) > > [)o > IhIL.. Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk
https://lists.boost.org/Archives/boost/2003/02/44809.php
CC-MAIN-2020-50
refinedweb
105
76.82
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.17) Gecko/20110420 Firefox/3.6.17 Build Identifier: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.17) Gecko/20110414 Lightning/1.0b2 Thunderbird/3.1.10 sometimes when checking for new messages, an error is logged: "The current operation on 'Inbox' did not succeed. The mail server for account: <account> responded: [SERVERBUG] UID FETCH Server error - Please try again later." all inbox messaged are deleted: "Deleted <all> messages from Inbox" and subsequently refetched Reproducible: Sometimes Why should a server error cause data loss on the client? The only time messages should be deleted is if the server reports without any error that they are gone, and even then there should be safeguards/confirmations for bulk deletes. But if there is an error, definitely nothing should be deleted. In general, I've noticed that Thunderbird is way too eager to blow away local messages/folders on the slightest server hiccup. I seem to remember situations when an IMAP server would somehow misconfigure the "IMAP server directory" or some namespace, which would cause a problem with folder enum, and Thunderbird just deleted entire folders (from disk). Just noticed it again, about two hours after the last one. An imap protocol log of a session where this happens would be helpful. It's possible that the IMAP server is changing UID validity when it has the server error as well, which requires the IMAP client to blow away cached data. Calling this data loss cheapens the term, imo - the data is still there on your server, if I'm understanding you correctly. (In reply to comment #4) > Calling this data loss cheapens the term, imo - the data is still > there on your server The client message store is a backup of the server, not just a perf cache, so "blowing away cached data" is a euphemism for "deleting my backup" That you view this merely as "cached data" of course explains why TB is frequently so careless with it. As I mentioned, over the years of using TB, I've encountered many scenarios where the all messages and/or entire folders were blown away, due to temporary server glitches. TB should treat the message store as valuable data and go to some lengths to protect it. For example, even when a server wants to perform a legitimate bulk delete or drop folders, the user should be warned and have an opportunity to cancel and create a more permanent backup of the current message store. Please see as to why Thunderbird is REQUIRED to delete cached data when UID VALIDITY changes. Not doing that would lead directly to data loss on the server. If UID VALIDITY is not changing, then I agree Thunderbird should not delete the cached data. That's why I asked for an IMAP Protocol log, so I can see what's going on. It doesn't look like uid validity is changing _______________________________________________________________________________ 2764[5c66dc0]: ImapThreadMainLoop entering [this=2f5f000] 0[1931140]: 2f5f000:yahoo.com:NA:SetupWithUrl: clearing IMAP_CONNECTION_IS_OPEN 2764[5c66dc0]: 2f5f000:yahoo.com:NA:ProcessCurrentURL: entering 2764[5c66dc0]: 2f5f000:yahoo.com:NA:ProcessCurrentURL:imap://<account>/select%3E/INBOX: = currentUrl 2764[5c66dc0]: 2f5f000:yahoo.com:NA:CreateNewLineFromSocket: * OK [CAPABILITY IMAP4rev1 ID NAMESPACE X-ID-ACLID UIDPLUS LITERAL+ CHILDREN XAPPLEPUSHSERVICE XYMHIGHESTMODSEQ AUTH=PLAIN AUTH=LOGIN AUTH=XYMCOOKIE AUTH=XYMECOOKIE AUTH=XYMCOOKIEB64 AUTH=XYMPKI] IMAP4rev1 imapgate-0.7.68_5.309535 imap424.mail.ne1.yahoo.com 2764[5c66dc0]: 2f5f000:yahoo.com:NA:SendData: 1 authenticate plain 2764[5c66dc0]: 2f5f000:yahoo.com:NA:CreateNewLineFromSocket: + 2764[5c66dc0]: 2f5f000:yahoo.com:NA:SendData: Logging suppressed for this command (it probably contained authentication information) 2764[5c66dc0]: 2f5f000:yahoo.com:NA:CreateNewLineFromSocket: 1 OK AUTHENTICATE completed - Mailbox size in bytes is 16641614 2764[5c66dc0]: 2f5f000:yahoo.com:A:SendData: 2 select "INBOX" 2764[5c66dc0]: 2f5f000:yahoo.com:A:CreateNewLineFromSocket: * 80 EXISTS 2764[5c66dc0]: 2f5f000:yahoo.com:A:CreateNewLineFromSocket: * 0 RECENT 2764[5c66dc0]: 2f5f000:yahoo.com:A:CreateNewLineFromSocket: * OK [UIDVALIDITY 1] UIDs valid 2764[5c66dc0]: 2f5f000:yahoo.com:A:CreateNewLineFromSocket: * OK [UIDNEXT 11501] Predicted next UID 2764[5c66dc0]: 2f5f000:yahoo.com:A:CreateNewLineFromSocket: * FLAGS (\Answered \Flagged \Deleted \Seen \Draft) 2764[5c66dc0]: 2f5f000:yahoo.com:A:CreateNewLineFromSocket: * OK [PERMANENTFLAGS (\Answered \Flagged \Deleted \Seen \Draft)] Permanent flags 2764[5c66dc0]: 2f5f000:yahoo.com:A:CreateNewLineFromSocket: * OK [HIGHESTMODSEQ 5614042411583794968] 2764[5c66dc0]: 2f5f000:yahoo.com:A:CreateNewLineFromSocket: 2 OK [READ-WRITE] SELECT completed; now in selected state 2764[5c66dc0]: 2f5f000:yahoo.com:S-INBOX:SendData: 3 UID fetch 1:* (FLAGS) 2764[5c66dc0]: 2f5f000:yahoo.com:S-INBOX:CreateNewLineFromSocket: 3 BAD [SERVERBUG] UID FETCH Server error - Please try again later 2764[5c66dc0]: 2f5f000:yahoo.com:S-INBOX:ProcessCurrentURL: entering 2764[5c66dc0]: 2f5f000:yahoo.com:S-INBOX:ProcessCurrentURL:imap://<accout>/folderstatus%3E/INBOX: = currentUrl 2764[5c66dc0]: 2f5f000:yahoo.com:S-INBOX:SendData: 4 noop 2764[5c66dc0]: 2f5f000:yahoo.com:S-INBOX:CreateNewLineFromSocket: 4 OK NOOP completed _______________________________________________________________________________ OK, thx, the server is giving us an error when we're trying to determine which messages exist on the server and we're treating that as having no messages in the folder. This will prevent us from getting new headers, etc. We may have to log out of the connection since it's not useful to us, and our state is stale (e.g., we won't know about messages deleted from a different machine/client). But we definitely don't have to delete our cached data, and I'll try to come up with a patch. > The client message store is a backup of the server, not just a perf cache FYI, no, that's not true. The client-side store of IMAP messages is really just a cache, and *not* a backup. It is not complete, and when messages at the server are gone (e.g. due to all sorts of server errors), they are automatically deleted locally, too. This is as designed. So, if you need a backup, please make a dedicated and separate backup. (In reply to comment #9) > > The client message store is a backup of the server, not just a perf cache > > FYI, no, that's not true. We are not dealing with natural laws here, it's not true because it hasn't been a priority, there is no reason TB couldn't be far more careful about deleting messages and folders. This bug is an example of a unnecessary bulk delete, but even valid, non error related auto deletes, could be done more safely: warning the user, allowing the user to cancel the operation and go offline, using some sort of recycle bin for auto deleted folders and messages. (In reply to comment #8) > and I'll try to come up with a patch. Please backport it into the release, the problem has remained fairly consistent, and the constant redownloading of messages can only exacerbate whatever issues the server has. This bug is fairly serious as it creates a positive feedback loop: the more errors a server has, the more load TB subjects it to, which is likely to further increase the errors ... Noticed another type of server error with the same effect (total deletion): [INUSE] UID FETCH Mailbox in use. Please try again later. Created attachment 541859 [details] [diff] [review] proposed fix GetServerStateParser().LastCommandSuccessful() checks DeathSignalReceived() already so this change essentially is adding a check that !CommandFailed() && fParserState == stateOK (i.e., no syntax error). We could probably do some earlier returns out of this method, but I'd rather just fix the issue in this bug and deal with more potential cleanup of this function elsewhere. Can you backport it? This problem is still fairly regular with yahoo, would be nice to have a 3.1 release that takes care of it. How general is the solution, are there still situations where some error would cause a needless folder reset? If it's backported to anything, it would be 5.0, which comes out next week. More likely, it will just be in 6.0, which comes out roughly 6 weeks after 5.0. The fix handles errors fetching the flags causing us to think there are no messages in the folder, which is this bug. (In reply to comment #15) > If it's backported to anything, it would be 5.0, which comes out next week. > More likely, it will just be in 6.0, which comes out roughly 6 weeks after > 5.0. Will you try to get it into 5.0? 5.0 is coming out Tuesday, and this hasn't even been reviewed or landed on the trunk yet, so, no. Comment on attachment 541859 [details] [diff] [review] proposed fix > if (!DeathSignalReceived() && GetServerStateParser().NumberOfMessages()) Was it intentional to leave some calls to DeathSignalReceived? (In reply to comment #18) > Comment on attachment 541859 [details] [diff] [review] [review] > proposed fix > > > if (!DeathSignalReceived() && GetServerStateParser().NumberOfMessages()) > Was it intentional to leave some calls to DeathSignalReceived? Yes, I didn't want failures getting the quota info to prevent you from using an imap folder. (In reply to comment #17) > 5.0 is coming out Tuesday, and this hasn't even been reviewed or landed on > the trunk yet, so, no. Are there going to be interim releases you can get this it into? If one's inbox is sufficiently large it could result in nearly continuous syncing. By the time one lengthy sync completes another UID FETCH error resets the inbox and starts another one. With enough users, this becomes an inadvertent DOS. Is it any wonder that yahoo has occasional difficulties fetching 17 messages (Bug 668143)? You should release this fix as soon as possible. we're releasing every 6 weeks. We're not doing interim releases between those releases because we have very limited resources. And again, this patch hasn't even been reviewed. pinging for review. fixed on trunk - Checked into aurora:
https://bugzilla.mozilla.org/show_bug.cgi?id=661774
CC-MAIN-2017-43
refinedweb
1,649
57.98
Objective In this article, I am going to show how programmatically Content type could be fetched. How we could manage parent child relationship of the Content types. Explanation Step 1 I have created two Site Content types. Note: To see how to create Content type sees my other articles on this site. TestParent is parent content type and TestChild is chid content type. TestParent content type - Parent of this content type is Folder - I added one column called OrderNumber as Number TestChild Content Type - Parent of this Content Type is Item - I added two columns OrderItem and SKU Step 2 I associated these two content types to a SharePoint List called Test. Note: To see how to attach Site Content type to SharePoint List see my other articles on this site. Step 3 I am putting some data in the list. The way to put data in list is as follows - First take Test Parent. Then fill all the column values for this. - Inside Test Parent create a Test Child and fill the column values. - Create more than one Test Child inside one Test Parent. List is as below Inside First Order Inside Second Order Code to Fetch Content Type I have created a console application and inside that I am going to display all the list items. using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.SharePoint; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { SPSite spsite = new SPSite(); SPWeb mysite = spsite.OpenWeb(); SPList parentList = mysite.Lists[“Test”]; foreach (SPListItem i in parentList.Folders) { Console.WriteLine(“Order : {0}”, i[“Name”]); Console.WriteLine(“Order Number : {0}”, i[“OrderNumber”]); SPQuery orderitemsquery = new SPQuery(); orderitemsquery.Folder = i.Folder; SPListItemCollection orderItems = parentList.GetItems(orderitemsquery); foreach (SPListItem p in orderItems) { Console.WriteLine(“\t Line Item from Child {0} : {1} {2}”, p[“OrderItem”], p[“SKU”], p[“Title”]); } } Console.Read(); } } } Explanation of code - SPSite is returning the site collection. - SPWeb is returning top level site. - SPList is returning the particular list. Test is name of the list here. - I am fetching all the folders in the list using Foreach statement. - I am retrieving the entire list inside a folder and printing that. Output Conclusion In this article, I have shown how to retrieve parent child related content types using SharePoint object model. Thanks for reading. Happy Coding
https://debugmode.net/2009/12/07/parent-child-content-type-using-sharepoint-object-model/
CC-MAIN-2022-05
refinedweb
387
60.41
Yes, there are numerous good articles on the subject, but still every time I am stumbled upon infamous UnicodeEncodeError: 'charmap' codec can't encode character u'\u0306' in position 50: character maps to <undefined> and I have to research it again. Somehow it does not stick. Perhaps because it just should have worked “out of box”. Anyway. Hereby a small recipe that “shuts the unicode nagging” in Python 2 when enumerating all the files: import sys import codecs sys.stdout = codecs.getwriter('utf-8')(sys.stdout, 'strict') for root, folders, files in os.walk(unicode(path), 'utf-8'): print u'%s\r' % root, <do whatever you want with the files></div>
https://blog.bidiuk.com/category/uncategorized/
CC-MAIN-2021-31
refinedweb
111
63.7
id summary reporter owner description type status priority component version resolution keywords cc 656 Missing DLL when importing Fiona, Geopandas or rasterio within QGIS cratcliff osgeo4w-dev@… "Hi, Since the release of **QGIS 3.16.2-Hannover** or **3.10.13-A Coruña** on Windows 10 I have been getting errors (see below) when trying to import fiona, geopandas and rasterio. I have installed fiona, geopandas and rasterio using the OSGeo4w. How do I go about fixing this issue for this release while not breaking older releases? Is there a way to configure these packages to work with QGIS without having to request a rebuild/fix every time a new version of QGIS is released? Thanks in Advance. Christina {{{ import geopandas Traceback (most recent call last): File ""C:\PROGRA~1\QGIS3~1.16\apps\Python37\lib\code.py"", line 90, in runcode exec(code, self.locals) File """", line 1, in
https://trac.osgeo.org/osgeo4w/ticket/656?format=tab
CC-MAIN-2022-40
refinedweb
150
58.28
Omen From Wikipedia, the free encyclopedia An omen (also called portent or presage) is a phenomenon that is believed to foretell the future[citation needed], often signifying the advent of change. Omens may be considered "good" or "bad", but the term is more often used in a foreboding sense, as with the word "ominous". [edit] In ancient Rome Ancient Roman religion employed two distinct types of professional omen readers. Augurs interpreted the flights of birds, while haruspices employed animal sacrifice to obtain the entrails necessary for divination. [edit] Astrology - See also: Eclipse cycle, Metonic cycle, Saros cycle, Comets In the field of astrology, solar and lunar eclipses (along with the appearance of comets and to some extent the full moon) have often been considered omens of notable births, deaths, or other significant events throughout history in many societies. For example the Magi in the Gospel of Matthew predict the birth of Jesus after seeing the Star of Bethlehem. [edit] Good or bad . Comets also have been considered to be both good and bad omens. The best-known example is probably Halley's Comet, which was a "bad omen" for King Harold II of England but a "good omen" for William the Conqueror. [edit] Omens in Indian Astrology Omenology is called Nimmita or shukuna shastra in Vedic Astrology Omen seen or heard or even visualized at the initiation of an activity, are said to foretell the outcome of the activity. Omens & portents (Shakun & Utpaats) is a useful branch of India astrology, which includes interpretation of dreams, status of living & non-living items in the environment, sounds produced by human & animals, portents, mode of pacification of adverse omens & portents. It acts as a guide in horary astrology, to clinch the issue when there is a stalemate. Coming events cast their shadows before & it is the ingenuity & skill of the interpreters to decode omens correctly for their profitable usage in their daily life. Treatises on omen (Shakun) have commended that omen has the final say in Election. Omens seen at the start of an action does foretell its success. In case adverse omen is seen or heard or even visualized; the activity should not be initiated. Omen is a wonderful knowledge which acts like a medicine. Vasant Raj in his treatise titled ‘Vasantraj Shakunan’ - an authoritative book on the subject - has opined that when ephemeral elements (Tithi, Nakshatra, election ascendant etc.) are fully auspicious & efficacious (Uttam & Gunyukta), fortified ascendant & strong Moon is present, but there prevails an inauspicious omen (Shakun) then, nothing materializes regarding election. Some opine that an election clinched only on the basis of an omen, does not have lasting effects. Some has opined that in the matter like making a theft or the like activities, omen is to considered. The treatises on Hindu /Vedic electional astrology have dilated omens in details in travel elections. On seeing an inauspicious omen, the person should return (not undertake journey), & recite Pranayam (a specific Mantra’s recitation) eleven times & then start the journey. If inauspicious omen is again is seen, then he should return & recite Pranayam 16 times & start the journey. And if inauspicious omen is again observed at the third start of the journey, the journey should be abandoned. Best of the sages agree with this, & from this one may infer the importance given to omens in elections. One must develop faculty of interpretation of omen seen or heard or even visualized at the initiation of an activity, & use it profitably. In case of adverse omen of high potency, execution of an election should be withheld / postponed. Exponents have laid down rules to interpret omens, examine potency of an omen & timing of event based on omens. Potency of an omen is examined based on its position with respect from the observer (front / back / left / right / higher & lower level), position of omen in geographical direction (East-South-West-North), time of its observation, motion / speed of the omen, sound produced / heard, expression, place where it is observed. Here are some items & persons signifying auspicious / favourable & inauspicious / unfavourable omens. The list in no means is exhaustive, but provides adequate information. Omens differ from place to place, country to country & religion to religion..
http://ornacle.com/wiki/Omen
crawl-002
refinedweb
697
50.26
Forum Index Summary: gdb can not show code Product: D Version: 2.022 Platform: PC URL: OS/Version: Linux Status: NEW Severity: normal Priority: P2 Component: DMD AssignedTo: bugzilla@digitalmars.com ReportedBy: jason.james.house@gmail.com The URL shows how this bug typically manifests itself. GDB seems to look for .s files for assembly code and can't seem to find them. This behavior exhibits itself with all D2 programs I've tried, including void main(){} -- ------- Comment #1 from jason.james.house@gmail.com 2009-01-24 11:16 ------- After a lot of help from volodya on irc #gdb, it looks like the issue is that the low_pc and high_pc attributes are missing. GDB can try to compensate for this (as if it was some legacy producer of debug info) by walking the children, but it only looks at "namespace" and "subprogram". D has "module" which stops it. -- ------- Comment #2 from mihail.zenkov@gmail.com 2009-01-24 16:09 ------- Break points don't work with demangled name. Not sure but imho problem in incorrect DW_AT_name and/or not provided DW_AT_MIPS_linkage by DMD. DMD put mangled name to DW_AT_name: <2><91>: Abbrev Number: 6 (DW_TAG_subprogram) DW_AT_sibling : <c8> DW_AT_name : _D5crash3fooFZv DW_AT_decl_file : 1 DW_AT_decl_line : 12 DW_AT_low_pc : 0 DW_AT_high_pc : 0x16 DW_AT_frame_base : 1 byte block: 55 (DW_OP_reg5) GDC/GCC put mangled name to DW_AT_MIPS_linkage_name and demandled to DW_AT_name: <1><bd>: Abbrev Number: 6 (DW_TAG_subprogram) DW_AT_external : 1 DW_AT_name : foo DW_AT_decl_file : 1 DW_AT_decl_line : 12 DW_AT_MIPS_linkage_name: _D5crash3fooFZv DW_AT_low_pc : 0x3b DW_AT_high_pc : 0x51 DW_AT_frame_base : 0x43 (location list) After fix DW_TAG_module you can try use mangled name, for example main - _Dmain -- ------- Comment #3 from mihail.zenkov@gmail.com 2009-02-07 20:56 ------- GDB also work fine with LDC debug info. <1><a7>: Abbrev Number: 3 (DW_TAG_subprogram) DW_AT_name : crash.foo DW_AT_MIPS_linkage_name: _D5crash3fooFZv DW_AT_external : 1 DW_AT_prototyped : 1 DW_AT_decl_file : 1 DW_AT_decl_line : 11 DW_AT_low_pc : 0x20 DW_AT_high_pc : 0x21 DW_AT_frame_base : 1 byte block: 54 (DW_OP_reg4) -- jason.james.house@gmail.com changed: What |Removed |Added ---------------------------------------------------------------------------- URL| |f | Severity|normal |major Version|2.022 |2.025 ------- Comment #4 from jason.james.house@gmail.com 2009-02-15 10:00 ------- It looks like the URL showing the problem has expired. Here's a sample session. I upped the severity because this is a really painful bug in dmd for me. I'm forced to place tons of writefln statements into the code instead of being able to step through it in the debugger jhouse@jhouse-laptop:~/housebot/0.8$ gdb ./housebot-0.8) break main Breakpoint 1 at 0x8059e87 (gdb) run Starting program: /home/jhouse/housebot/0.8/housebot-0.8 [Thread debugging using libthread_db enabled] [New Thread 0xb7c3eb00 (LWP 23503)] [Switching to Thread 0xb7c3eb00 (LWP 23503)] Breakpoint 1, 0x08059e87 in main () Current language: auto; currently asm (gdb) list 1 /tmp/ccPssJzP.s: No such file or directory. in /tmp/ccPssJzP.s (gdb) quit The program is running. Exit anyway? (y or n) y jhouse@jhouse-laptop:~/housebot/0.8$ -- ------- Comment #5 from bugzilla@digitalmars.com 2009-02-20 04:42 ------- But dmd does emit the low_pc and high_pc data. Compile: int foo(int i) { return i * i; } with: dmd -c -g foo.d Then run dumpobj on it: dumpobj -p foo.o which will pretty-print the dwarf debug into. The attributes are there. -- ------- Comment #6 from jason.james.house@gmail.com 2009-02-20 07:54 ------- D'oh, if only I reported more information when I remembered it. Trying now, I'm doing "objdump -Wgs <executable>" and then searching for module. What I see right before it is DW_TAG_compile_unit. I don't see DW_AT_high_pc and DW_AT_low_pc in that section, but I don't know if it's supposed to be there. The impression I got from my chats on #gdb was that the debug data was stored in somewhat of a hierarchical structure. In order to figure out the offsets for the source file, it wanted to find the high and low attributes but did not. There's a workaround inside gdb that will walk the children in order to get around the behavior of old compilers, but it's fragile. Having modern stuff such as DW_TAG_module stops it from operating (since it doesn't match what old compilers did). That's all I can remember/reproduce with some experimentation with objdump. Can you reproduce the problem? Maybe chat with someone on #gdb? I had to wait ~12 hours to get a response. Once I did, they were very helpful. I'll guess the compile_unit should have high_pc and low_pc, but I'm only guessing. If you can reproduce the issue, then it should be easy to see if what you did works or not. Sorry for the lack of detail :( -- ------- Comment #7 from bugzilla@digitalmars.com 2009-02-25 00:30 ------- Looks like DW_AT_MIPS_linkage_name is an undocumented vendor extension to Dwarf. -- ------- Comment #8 from mihail.zenkov@gmail.com 2009-02-25 20:46 ------- It undocumented but widely used. IMHO better use them for mangled name than DW_AT_name. Current way violates DWARF: "Because the names of program objects described by DWARF are the names as they appear in the source program, implementations of language translators that use some form of mangled name (as do many implementations of C++) should use the unmangled form of the name in the DWARF DW_AT_name attribute, including the keyword operator (in names such as “operator +â€), if present. Sequences of multiple whitespace characters may be compressed." -- --- Comment #9 from Walter Bright <bugzilla@digitalmars.com> 2009-08-05 01:21:42 PDT --- I'll add the MIPS_linkage tag and change the name tag. We'll see how far that gets us. -- Configure issuemail: ------- You are receiving this mail because: -------
http://forum.dlang.org/thread/bug-2575-3@http.d.puremagic.com%2Fissues%2F
CC-MAIN-2016-44
refinedweb
939
66.33
import "nsIEditor.idl"; Add a DocumentStateListener to the editors list of doc state listeners. add an EditActionListener to the editors list of listeners. add an EditorObserver to the editors list of observers. sets the document selection to the beginning of the document beginTransaction is a signal from the caller to the editor that the caller will execute multiple updates to the content tree that should be treated as a single logical operation, in the most efficient way possible. All transactions executed between a call to beginTransaction and endTransaction will be undoable as an atomic action. endTransaction must be called after beginTransaction. Calls to beginTransaction can be nested, as long as endTransaction is called once per beginUpdate. Can we copy? True if we have a non-collapsed selection. Can we cut? True if the doc is modifiable, and we have a non- collapsed selection. canDrag decides if a drag should be started (for example, based on the current selection and mousepoint). Can we paste? True if the doc is modifiable, and we have pasteable data in the clipboard.|. returns state information about the redo system. returns state information about the undo system. cloneAttribute() copies the attribute from the source node to the destination node and delete those not in the source. The supplied nodes MUST BE ELEMENTS (most callers are working with nodes)) copy the currently selected text, putting it into the OS clipboard What if no text is selected? What about mixed selections? What are the clipboard formats? createNode instantiates a new element of type aTag and inserts it into aParent at aPosition. cut the currently selected text, putting it into the OS clipboard What if no text is selected? What about mixed selections? What are the clipboard formats? Dumps a text representation of the content tree to standard out. deleteNode removes aChild from aParent. DeleteSelection removes all nodes in the current selection. doDrag transfers the relevant data (as appropriate) to a transferable so it can later be dropped. doTransaction() fires a transaction. It is provided here so clients can create their own transactions. If a transaction manager is present, it is used. Otherwise, the transaction is just executed directly. And a debug method -- show us what the tree looks like right now. turn the undo system on or off sets the document selection to the end of the document endTransaction is a signal to the editor that the caller is finished updating the content model. beginUpdate must be called before endTransaction is called. Calls to beginTransaction can be nested, as long as endTransaction is called once per beginTransaction. getAttributeValue() retrieves the attribute's value for aElement. Returns the inline spell checker associated with this object. The spell checker is lazily created, so this function may create the object for you during this call. Gets the modification count of the document we are editing. called each time we modify the document. Increments the modification count of the document. insertFromDrop looks for a dragsession and inserts the relevant data in response to a drop. insertNode inserts aNode into aParent at aPosition. No checking is done to verify the legality of the insertion. That is the responsibility of the caller. joinNodes() takes 2 nodes and merge their content|children. There is no requirement that the two nodes be of the same type. However, a text node can be merged only with another text node. markNodeDirty() sets a special dirty attribute on the node. Usually this will be called immediately after creating a new node. Output methods: aFormatType is a mime type, like text/plain. paste the text in the OS clipboard at the cursor position, replacing the selected text (if any) Paste the text in |aTransferable| at the cursor position, replacing the selected text (if any). postCreate should be called after Init, and is the time that the editor tells its documentStateObservers that the document has been created. preDestroy is called before the editor goes away, and gives the editor a chance to tell its documentStateObservers that the document is going away.. removeAttribute() deletes aAttribute from the attribute list of aElement. If aAttribute is not an attribute of aElement, nothing is done. Remove a DocumentStateListener to the editors list of doc state listeners. Remove an EditActionListener from the editor's list of listeners. Remove an EditorObserver from the editor's list of observers. to be used ONLY when we need to override the doc's modification state (such as when it's saved). sets the document selection to the entire contents of the document setAttribute() sets the attribute of aElement. No checking is done to see if aAttribute is a legal attribute of the node, or if aValue is a legal value of aAttribute. Set the flag that prevents insertElementTxn from changing the selection. Called when the user manually overrides the spellchecking state for this editor. splitNode() creates a new node identical to an existing node, and split the contents between the two nodes Switches the editor element direction; from "Left-to-Right" to "Right-to-Left", and vice versa. Resyncs spellchecking state (enabled/disabled). This should be called when anything that affects spellchecking state changes, such as the spellcheck attribute value.. the MimeType of the document the DOM Document this editor is associated with, refcounted. Sets the current 'Save' document character set. Returns true if the document has no *meaningful* content. Returns true if the document is modifed and needs saving. edit flags for this editor. May be set at any time. Returns true if we have a document that is not marked read-only. the body element, i.e. the root of the editable document. the selection controller for the current presentation, refcounted. transactionManager Get the transaction manager the editor is using.
http://doxygen.db48x.net/comm-central/html/interfacensIEditor.html
CC-MAIN-2019-09
refinedweb
952
59.5
Next: Computed Includes, Previous: Search Path, Up: Header Files: /* File foo. */ #ifndef FILE_FOO_SEEN #define FILE_FOO_SEEN the entire file #endif /* !FILE_FOO_SEEN */ This construct is commonly known as a wrapper #ifndef. When the header is included again, the conditional will be false, because FILE_FOO_SEEN is defined. The preprocessor will skip over the entire contents of the file, and the compiler will not see it twice. CPP optimizes even further. It remembers when a header file has a wrapper `#ifndef'. If a subsequent `#include' specifies that header, and the macro in the `#ifndef' is still defined, it does not bother to rescan the file at all. You can put comments outside the wrapper. They will not interfere with this optimization. The macro FILE_FOO_SEEN is called the controlling macro or guard macro. In a user header file, the macro name should not begin with `_'. In a system header file, it should begin with `__' to avoid conflicts with user programs. In any kind of header file, the macro name should contain the name of the file and some additional text, to avoid conflicts with other header files.
http://gcc.gnu.org/onlinedocs/gcc-3.4.6/cpp/Once_002dOnly-Headers.html
CC-MAIN-2014-10
refinedweb
184
75.1
Hello. I am trying to integrate Optix into the Ogre3D rendering API. Context creation, loading PTX files, creating render buffer using GLBO, validate & compile etc all works, but I get a video driver crash during launch. But that is a topic for another thread on the Ogre3D forums. My problem is during shutdown. During Optix init, the application performs a test render, catches the exception and starts to shutdown. Of course that includes destroying the Optix context that was created. However, destroying the context causes an access violation. I am guessing the driver crash is invalidating the Optix context. Before calling destroy() on the Context, I am calling validate() which does not throw any errors. Yet destroy() causes access violation in optixpp_namespace.h on line 1593. Is there a way to check that the context is actually still valid? If possible I’d rather not have to use some ugly hack where a render fail skips destroying the Optix context during shutdown.
https://forums.developer.nvidia.com/t/checking-for-invalidated-optix-context-after-driver-crash/27976/3
CC-MAIN-2020-34
refinedweb
162
58.99
- NAME - SYNOPSIS - ABSTRACT - DESCRIPTION - INSTALLATION - CAVEATS - CHANGES - TODO - BUGS - VERSION - AUTHOR - SEE ALSO NAME Crypt::CBCeasy - Easy things make really easy with Crypt::CBC SYNOPSIS use Crypt::CBCeasy; # !!! YOU can not 'require' this module !!! IDEA::encipher($my_key, "plain-file", "crypted-file"); $plain_text = DES::decipher($my_key, \*CRYPTO_FILE); $crypted = Blowfish::encipher($my_key, \*PLAIN_SOCKET); ABSTRACT This module is just a helper for Crypt::CBC to make simple and usual jobs just one-liners. The current version of the module is available at CPAN. DESCRIPTION After you call this module as use Crypt::CBCeasy IMPORT-LIST; it creates the encipher() and decipher() functions in all namespaces (packages) listed in the IMPORT-LIST. Without the IMPORT-LIST it creates these 2 functions in the DES::, IDEA:: and Blowfish:: namespaces by default to stay compatible with the previous versions that were capable to handle only these 3 ciphers. You have to install Crypt::CBC v. 1.22 or later to work with Blowfish. Sure IDEA:: functions will work only if you have Crypt::IDEA installed, DES:: - if you have Crypt::DES, Blowfish:: - if you have Crypt::Blowfish and Crypt::CBC is version 1.22 or above etc. Here's the list of the ciphers that could be called via the Crypt::CBCeasy interface today (in fact the same modules that are Crypt::CBC compatible): Cipher CPAN module DES Crypt::DES IDEA Crypt::IDEA Blowfish Crypt::Blowfish Twofish2 Crypt::Twofish2 DES_PP Crypt::DES_PP Blowfish_PP Crypt::Blowfish_PP Rijndael Crypt::Rijndael TEA Crypt::TEA Note that cipher names are case sensitive in the IMPORT-LIST, so "blowfish" will give an error. Type them exactly as they are written in the correspondent underlying modules. Both encipher() and decipher() functions take 3 parameters: 1 - en/decryption key 2 - source 3 - destination The sources could be: an existing file, a scalar (just a string that would be encrypted), an opened filehandle, any other object that inherits from the filehandle, for example IO::File or FileHandle object, and socket. Destinations could be any of the above except scalar, because we can not distinguish between scalar and output file name here. Well, it's easier to look at the examples: ( $fh vars here are IO::Handle, IO::File or FileHandle objects, variables of type "GLOB", "GLOB" refs or sockets) IDEA::encipher( $my_key, "in-file", "out-file" ); IDEA::encipher( $my_key, *IN, "out-file" ); IDEA::encipher( $my_key, \*IN, "out-file" ); IDEA::encipher( $my_key, $fh_in, "out-file" ); IDEA::encipher( $my_key, "in-file", *OUT ); IDEA::encipher( $my_key, "in-file", \*OUT ); IDEA::encipher( $my_key, "in-file", $fh_out ); IDEA::encipher( $my_key, *IN, *OUT ); IDEA::encipher( $my_key, \*IN, \*OUT ); IDEA::encipher( $my_key, $fh_in, $fh_out ); IDEA::encipher( $my_key, $plain_text, "out-file" ); IDEA::encipher( $my_key, $plain_text, *OUT ); IDEA::encipher( $my_key, $plain_text, \*OUT ); IDEA::encipher( $my_key, $plain_text, $fh_out ); any of the above will work and do what was expected. In addition there is a 2-argument version that returns it's result as scalar: $crypted_text = IDEA::encipher( $my_key, $plain_text ); $crypted_text = IDEA::encipher( $my_key, "in-file" ); $crypted_text = IDEA::encipher( $my_key, *IN ); $crypted_text = IDEA::encipher( $my_key, \*IN ); $crypted_text = IDEA::encipher( $my_key, $fh ); All the same is possible for any of the ciphers in the IMPORT-LIST. All functions croak on errors (such as "input file not found"), so if you want to trap errors use them inside the eval{} block and check the $@. Note that all filehandles are used in binmode whether you claimed them binmode or not. On Win32 for example this will result in CRLF's in $plain_text after $plain_text = DES::decipher($my_key, "crypted_file"); if "crypted_file" was created by DES::encipher($my_key, "text_file", "crypted_file"); If the filehandle was used before - it's your job to rewind it to the beginning and/or close. INSTALLATION As this is just a plain module no special installation is needed. Put it into the /Crypt subdirectory somewhere in your @INC. The standard Makefile.PL make make test make install procedure is provided. In addition make html will produce the HTML-docs. This module requires Crypt::CBC by Lincoln Stein, lstein@cshl.org v.1.20 or later. one or more of Crypt::IDEA, Crypt::DES, Crypt::Blowfish, Crypt::Blowfish_PP, Crypt::Twofish2, Crypt::DES_PP or other Crypt::CBC compatible modules. CAVEATS This module has been created and tested in a Win95/98/2000Pro environment with Perl 5.004_02 and ActiveState ActivePerl build 618. I expect it to function correctly on other systems too. CHANGES 0.21 Mon Mar 6 07:28:41 2000 - first public release 0.22 Sun Feb 18 13:11:59 2001 A horrible BUG was found by Michael Drumheller <drumheller@alum.mit.edu> In fact 0.21 was ALWAYS using DES despite of the desired cipher. DAMN! Fixed. And the test is modified so that this will never happen again. Now you can define the list of ciphers that are compatible with Crypt::CBC in the import list. You can not call this module with the "require" statement. This is incompatible with the older versions. 0.23 Crypt::Rijndael 0.02 compatibility was approved. Tests are some more complex now. 0.24 Crypt::TEA 1.01 by Abhijit Menon-Sen <ams@wiw.org> is checked and approved. TODO Any suggestions are much appreciated. BUGS Please report. VERSION This man page documents "Crypt::CBCeasy" version 0.24 February 18, 2001 AUTHOR Mike Blazer, blazer@mail.nevalink.ru SEE ALSO Crypt::CBC This package is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
https://metacpan.org/pod/Crypt::CBCeasy
CC-MAIN-2016-18
refinedweb
905
55.34
Le Café Central de Deva ... Deva blogs!! I changed the way of blogging. Re-designed the site & started using the latest Windows Live Writer 2011!! Additionally added Microsoft Translator gadget available @ top of page, so that you can change the page in your preferred language!! Hi there, You can join this Jump Start session provided by Microsoft Virtual Academy – it’s tailored for experienced application developers interested in leveraging ASP.NET and Visual Studio 2012 to offer modern apps that target modern browsers. Two of Microsoft’s most seasoned ASP.NET speakers, Scott Hanselman and Jon Galloway, will provide an accelerated introduction to building modern web applications with ASP.NET 4.5 and ASP.NET MVC 4. In this course, they will target key scenarios like building mobile ready websites, social web applications as well as modern HTML5 browser features. Technologies Covered • New and advanced features in ASP.NET Web Forms • ASP.NET MVC 4 and ASP.NET Web API • jQuery • SignalR • Entity Framework • Visual Studio 2012 • Internet Explorer 10 and HTML5 • Building apps for Office with HTML5 • Windows Azure Web Sites for ASP.NET developers Details February 19, 2013 8:00am-5:00pm PST Register: In order to participate you need to register first. Where : Live online What : Engaging, demo virtual class Cost : Free Target Audience: Intended for developers who have at least six months of professional experience. Hope this helps. One of my customer reported that they created a ATL Project/MFC CDHtmlDialog based C++ application and they notice the following errors in afxdhtml.h (they created it using VS 2003). afxdhtml.h(272) : error C2238: unexpected token(s) preceding ';' afxdhtml.h(289) : error C2061: syntax error : identifier '_ATL_FUNC_INFO' afxdhtml.h(290) : error C2061: syntax error : identifier '_ATL_FUNC_INFO' I tried the code piece at my end locally and tested with latest visual studio – I failed to see the issue and it just works for me. Later I done further research on this and found the following: The #include <afxdhtml.h> directive is placed in the stdafx.h pre-compiled header file before the "using namespace ATL;" directive, and the #define _ATL_NO_AUTOMATIC_NAMESPACE was given previously. Thus, the symbols in the header file which belong to the ATL namespace are not properly resolved. When adding a class from the MFC dialog class wizard, you are given the choice of several dialog base classes, most of which do not require the ATL namespace "using" directive. Thus, the wizard script in default.htm doesn’t make any attempt to ensure that the header file corresponding to the class name come after a using directive. In Visual Studio 2005 and later versions, the problem doesn’t occur because all references to CComPtr are now prefixed with ::ATL::, alleviating the need to either direct “using namespace ATL;” or to define the macro to eliminate the automatic use of the ATL namespace. So I recommended them to try one of the following to move ahead: • Remove the #define _ATL_NO_AUTOMATIC_NAMESPACE directive from the stdafx.h header, or • Move the using namespace ATL; directive before the #include <afxdhtml.h> • Upgrade to Visual Studio 2005 and above. Also make sure they're fully patched with latest service pack/fixes.!!
http://blogs.msdn.com/b/deva/archive/2013/02.aspx?PostSortBy=MostViewed&PageIndex=1
CC-MAIN-2015-11
refinedweb
531
57.06
Radix Sort – Explanation, Pseudocode and Implementation Radix Sort is a non-comparative sorting algorithm with asymptotic complexity O(nd). It is one of the most efficient and fastest linear sorting algorithms. Radix sort was developed to sort large integers. As integer is treated as a string of digits so we can also call it as string sorting algorithm. The lower bound for comparison based sorting algorithm is O(n*log n) like merge sort, quick sort, heap sort. So radix sort is efficient than comparison sorting algorithm until the number of digits (key) is less than log n. Counting sort can’t be used if a range of key value is large (suppose range is 1 to n2) so radix sort is the best choice to sort in linear time. In radix sort, we first sort the elements based on last digit (least significant digit). Then the result is again sorted by second digit, continue this process for all digits until we reach most significant digit. We use counting sort to sort elements of every digit, so time complexity is O(nd). Here are some key points of radix sort algorithm – - Radix Sort is a linear sorting algorithm. - Time complexity of Radix Sort is O(nd), where n is the size of array and d is the number of digits in the largest number. - It is not an in-place sorting algorithm as it requires extra additional space. - Radix Sort is stable sort as relative order of elements with equal values is maintained. -. Let’s understand it with an example – Observe the image given below carefully and try to visualize the concept of this algorithm. In the above example: For 1st pass: we sort the array on basis of least significant digit (1s place) using counting sort. Notice that 435 is below 835, because 435 occurred below 835 in the original list. For 2nd pass: we sort the array on basis of next digit (10s place) using counting sort. Notice that here 608 is below 704, because 608 occurred below 704 in the previous list, and similarly for (835, 435) and (751, 453). For 3rd pass: we sort the array on basis of most significant digit (100s place) using counting sort. Notice that here 435 is below 453, because 435 occurred below 453 in the previous list, and similarly for (608, 690) and (704, 751). Pseudocode of Radix Sort Radix-Sort(A, d) //It works same as counting sort for d number of passes. //Each key in A[1..n] is a d-digit integer. //(Digits are numbered 1 to d from right to left.) for j = 1 to d do //A[]-- Initial Array to Sort int count[10] = {0}; //Store the count of "keys" in count[] //key- it is number at digit place j for i = 0 to n do count[key of(A[i]) in pass j]++ for k = 1 to 10 do count[k] = count[k] + count[k-1] //Build the resulting array by checking //new position of A[i] from count[k] for i = n-1 downto 0 do result[ count[key of(A[i])] ] = A[j] count[key of(A[i])]-- //Now main array A[] contains sorted numbers //according to current digit place for i=0 to n do A[i] = result[i] end for(j) end func Asymptotic Analysis of Radix Sort In this algorithm running time depends on intermediate sorting algorithm which is counting sort. If the range of digits is from 1 to k, then counting sort time complexity is O(n+k). There are d passes i.e counting sort is called d time, so total time complexity is O(nd+nk) =O(nd). As k=O(n) and d is constant, so radix sort runs in linear time. Worst Case Time complexity: O (nd) Average Case Time complexity: O(nd) Best Case Time complexity: O(nd) Space Complexity: O(n+k) Data Structure: Array Sorting In Place: No Stable: Yes Implementation of Radix Sort in C and Java programming language C // C implementation of Radix Sort #include<stdio.h> #include<stdlib.h> // This function gives maximum value in array[] int getMax(int A[], int n) { int i; int max = A[0]; for (i = 1; i < n; i++){ if (A[i] > max) max = A[i]; } return max; } // Main Radix Sort sort function void radixSort(int A[], int n) { int i,digitPlace = 1; int result[n]; // resulting array // Find the largest number to know number of digits int largestNum = getMax(A, n); //we run loop until we reach the largest digit place while(largestNum/digitPlace >0){ int count[10] = {0}; //Store the count of "keys" or digits in count[] for (i = 0; i < n; i++) count[ (A[i]/digitPlace)%10 ]++; // Change count[i] so that count[i] now contains actual // position of this digit in result[] // Working similar to the counting sort algorithm for (i = 1; i < 10; i++) count[i] += count[i - 1]; // Build the resulting array for (i = n - 1; i >= 0; i--) { result[count[ (A[i]/digitPlace)%10 ] - 1] = A[i]; count[ (A[i]/digitPlace)%10 ]--; } // Now main array A[] contains sorted // numbers according to current digit place for (i = 0; i < n; i++) A[i] = result[i]; // Move to next digit place digitPlace *= 10; } } // Function to print an array void printArray(int A[], int n) { int i; for (i = 0; i < n; i++) printf("%d ", A[i]); printf("\n"); } // Driver program to test above functions int main() { int a[] = {209,3,48,91,66,101,30,795}; int n = sizeof(a)/sizeof(a[0]); printf("Unsorted Array: "); printArray(a, n); radixSort(a, n); printf("Sorted Array: "); printArray(a, n); return 0; } JAVA /* Java implementation Radix Sort */ package codingeek; import java.util.Arrays; import java.util.Scanner; public class RadixSort { public static void main(String arg[]){ int a[] = {209,3,48,91,66,101,30,795}; //print unsorted array using Arrays.toString() System.out.print("Unsorted array: "); System.out.println(Arrays.toString(a)); RadixSort rs= new RadixSort(); rs.radixSort(a); System.out.print("Sorted array: "); //print sorted array System.out.println(Arrays.toString(a)); } // This function gives maximum value in array[] public int getMax(int A[]) { int max = A[0]; for (int i = 1; i < A.length; i++){ if (A[i] > max) max = A[i]; } return max; } // Main Radix Sort sort function public void radixSort(int A[]) { int digitPlace = 1; int n=A.length; int result[]=new int[n]; // resulting array // Find the largest number to know number of digits int largestNum = getMax(A); //we run loop until we reach the largest digit place while(largestNum/digitPlace >0){ int count[]=new int[10]; //Initializing counting array C[] to 0 for (int i=0; i <10; i++) count[i] = 0; //Store the count of "keys" or digits in count[] for (int i = 0; i < n; i++) count[ (A[i]/digitPlace)%10 ]++; // Change count[i] so that count[i] now contains actual // position of this digit in result[] // Working similar to the counting sort algorithm for (int i = 1; i < 10; i++) count[i] += count[i - 1]; // Build the resulting array for (int i = n - 1; i >= 0; i--) { result[count[ (A[i]/digitPlace)%10 ] - 1] = A[i]; count[ (A[i]/digitPlace)%10 ]--; } // Now main array A[] contains sorted // numbers according to current digit place for (int i = 0; i < n; i++) A[i] = result[i]; // Move to next digit place digitPlace *= 10; } } } Output:- Unsorted array: 209,3,48,91,66,101,30,795 Sorted array: 3,30,48,66,91,101,209,795 Radix Sort is one of the most efficient and fastest linear sorting algorithms. It is simple to understand and easy to implement. Radix Sort is a good choice for many programs which need a fast sort. Radix Sort can handle larger keys more efficiently as compare to Counting Sort. Radix sort is most equally efficient as the best comparison-based sorts (and worse if keys are much longer than log n). Another linear sorting algorithm is bucket sort which we will discuss in the future post. Knowledge is most useful when liberated and shared. Share this to motivate us to keep writing such online tutorials for free and do comment if anything is missing or wrong or you need any kind of help. Do not forget to SHARE and SUBSCRIBE. Keep Learning… Happy Learning.. 🙂 Recommended - - Rich Art - Priyansh Mangal
https://www.codingeek.com/algorithms/radix-sort-explanation-pseudocode-and-implementation/
CC-MAIN-2018-26
refinedweb
1,392
55.37
Design note: "Charlieplexing" LED matrices: Pin savings of Charlieplexing, easy assembly of multiplexed LED modules. ( dropbox mirror ) Charlieplexing ( named after Charlie Allen ) is a great way to save pins on a microcontroller. Since each pin can be either high, low, or off ( 'high impedence' ), and LEDs conduct in only one direction, one can place two LEDs for for each unique pair of microcontroller pins. This also works with other devices, like buttons, but you can only place one for each pair of pins since they conduct in both directions*. However, a recent foray into designing with Charlieplexing revealed its major drawback to me: soldering a zillion discrete LEDs is very time consuming and not for everyone. It is easier to use LED modules, which have LEDs already wired up, and are designed to be driven by multiplexing. For an N by M multiplexed grid you need N+M driving pins. However, for an N by M charlieplexed grid you need only K pins where K(K-1)=NM **. However, there is often a way to Charlieplex LED matrices to save pins without increasing assembly difficulty. Thinking about charlieplexed gridsOne might ask: how the hell am I supposed to keep track of all the possible combinations used in Charlieplexing? Since each pin can be either high (positive, or anode) or low (negative, or cathode), we can draw a K by K grid for K pins, where the cases where a pin acts as an anode are on one axis, and as a cathode, the other. Along the diagonal you have sites where a pin is supposed to act as both an anode and a cathode -- these are forbidden, and are blacked out. Here is an example grid for 16 pins: Placing modulesI can now place components on this grid to fill it up. Say I have an 8x8 LED matrix with 8 cathodes and 8 anodes. All I have to do is find an 8x8 space large enough to hold it somewhere on the grid. For example, two 8x8 LED matrices fit into this 16 grid: Another common size for LED matrices is 5x7. We can fit two of them on 12 pins like so: Now it gets fun. It's ok for components to wrap around the sides. We can fit four 5x7 ( for a 10x14 pixel game board perhaps? ) matrices on 16 pins like this: We can fit six 5x7 matrices on 18 pins ( for a 10x21 pixel game board perhaps? Large enough for original tetris! ). Eight 5x7 matrices fit on 20 pins. 8x8 matrices are a little more clunky, but you can still fit 3 of them onto 20 pins or 4 of them onto 22 pins ( 22 pins also fits 10 5x7 arrays ). We leave these last three as exercizes. ( solutions 1 2 3 4) To demonstrate that this approach does in fact work, I rigged up a little game of life on four 8x8 modules running on 22 pins on an AtMega328. After correcting for a problem with the brightness related to the PORTC pins sourcing less current, the display is quite functional -- the scanning is not visible and all lights are of equal brightness. I scan the lights one at a time, but only spend time on those that are on. (The variable frame rate is from the video processing -- the actual device is quite smooth) Other packaged LED modules can be laid out similarly. 7 segment displays ( 8 with decmal point ) come packaged in "common cathode" and "common anode" configurations, which would be represented as a column of 8 cells, or a row of 8 cells, respectively. Often, four 7-segment displays ( 8 with decimal ) are packaged at once in a multiplexed manner -- these would be represented as a 4x8 or 8x4 block on our grid, depending on whether they were common anode or cathode. RGB LEDs also come packaged in common cathode and anode configurations. For example, here is how one could charlieplex 14 common anode RGB LEDs on 7 pins: Hardware note: don't blow it upWhen driving LEDs with multiplexing or charlieplexing, it is not uncommon to omit current limiting resistors. Since the grid is scanned, only a few LEDs will be on at once, and all LEDs spend most of their time off. If the supply voltage lies between the typical forward voltage, and the peak instantaneous voltage, we can figure out the largest acceptable duty cycle and enforce this in software. However, now one must ensure that software glitches do not cause the array scanning to stall, or that LEDs can survive a period of elevated forward voltage. Microcontrollers will have a maximum safe current per IO pin. Sometimes, you can rely on the microcontroller to limit current to this level. Other times, attempting to force more than the maximum rating through a pin will damage the microcontroller. You can ensure that this never happens in software by never turning on more LEDs than a single IO pin can handle. Or, you can use tri-state drivers. If your microcontroller limits over-current, you can probably turn on as many LEDs as you want at once, but they will dim exponentionally with the reduction in current per LED. Combining devicesThere is nothing stopping us from combining different types of LED modules, or LEDs and buttons, in our grid. However, buttons conduct in both the forward and backward direction, so they occupy both the anode-cathode and cathode-anode positions for any pair of pins. I represent this as a black and white pair of buttons in the grid drawing. For example, one could get an acceptable calculator with 6 display digitis and 21 buttons onto 10 pins if you use a mix of common-cathode and common-anode 7-segment displays like so: You could probably get a pretty decent mini-game using the space left over from Charlie-muxing four 5x7 modules on 16 pins. There is enough room to fit 17 buttons and 6 7-segment displays (shown as earth-tone strips below): For the grand finali, we revisit the six 5x7 modules on 18 pins. Apart from giving us a grid large enough to hold classic Tetris, we also have room for 18 buttons, 6 7-segment displays (shown as earth-tone strips below), with 12 single-LED spots left over -- all on 18 pins. On an AtMega, this would leave 5 IO pins free -- enough room to fit a serial interface, piezo speaker, and crystal oscillator. Programming, however, would be a challenge.*** Hardware note: combining different LED colors in one gridThere are problems with combining different LEDs in one grid. If two LEDs with different forward voltages are placed on the same, say, cathode, then the one with the lower forward voltage can hog all the current, and the other LED won't light. I have found that ensuring in software that LEDs with mixed forward voltages are never illuminated simultaneously solves this problem. Also ensure that your largest forward voltage is smaller than twice the lowest forward voltage. For example, if you try to drive a 3.6V white LED in a matrix that contains 1.8V red LEDs, the current may decide take a shortcut through two red LEDs rather than the white LED. However, it may be possible to ensure that there are no such paths by design. You must ensure that for every 3.6V forward path from pin A to B, there are no two 1.8V forward paths AC and CB for any C. Driving softwareSaving microcontroller pins and soldering time in well and good, but programming for these grids can be a real challenge! Here are some practices ( for AVR ) that I have found useful. - Overclock the processor. Most AVRs are configured to 1MHz by default, but can run up to 8MHz even without an external crystal. The AVR fuse calculator is a godsend. Test the program first without overclocking, then raise the clock rate. Ensure that the power supply voltage is high enough for the selected clok rate. If things get dire and you need more speed, you can tweak the OSCCAL register as well. - Prototype driver code on a device that can be removed and replaced if necessary. Repeated *ucking with the fuses to tweak the clock risks bricking the AVR. It's a shame when you have bricked AVR soldered in a TQFP package. - Row-scan the grid. If this places too much current on the IO pins, break each row into smaller pieces that are safe. If too many LEDs are lit on a row and they appear dim, adjust the time the row is displayed to compensate. - Store the LED state vector in the format that you will use to scan. Write set() and get() methods to access and manipulate this state that maps the structure of the charlipelxing grid onto the logical structure of your displays. Scanning code is hard enough to get fast and correct without worrying about the abstract logical arrangement of the LED grid. - Use a single timer interrupt to do all of the scanning. Having multiple recurring timer interrupts along with a main loop can create interesting interference and beat effects in the LED matrix that are hard to debug. - If there are buttons and LEDs on the same grid, switch to polling the buttons every so often at a fixed interval, and write there state into volatile memory that other threads can query. - If your display is sparse ( e.g. a game of life ) you can skip sections that aren't illuminated to get a higher effective refresh rate. If your display is very sparse, and you have a lot of memory to spare, you can even scan LEDs one at a time. ConclusionThis document outlines how to drive many LED modules from a limited number of microcontroller pins. The savings in part cost and assembly time are offset by increased code complexity. These design practices would be useful for somone who enjoys coding puzzles, or gets a kick out of making microcontrollers do way more than they are supposed to. They could also be useful for reducing part costs and assembly time for mass produced devices, where the additional time in driver development is offset by the savings in production. I originally worked through these notes when considering how to bulid easy-to-assemble LED marquee kits, but as I have no means to produce such kits, nor easy mechanism for selling them, I am leaving the notes up here for general benefit. Also... Charrliee. *If you place a diode in series with a button you can place two buttons for each unique pair of pins. One can make this diode a LED to create a button-press indicator. **For those interested, K*(K-1)=N*M solves to K = ceil[ ( 1 + sqrt( 1+4NM ) ) / 2] ***I've tried this with an 8x16 grid using a maximally overclocked AtMega. It is tricky. To avoid beat effects, sound, display, and button polling are handeled with the same timer interrupt. The music is intentionally restricted to notes that can be rendered with low clock resolution. Some day i may even write this up. _______________________________________________ Driving software example: Game of Life on a 16x16 gridDue to popular demand I've gone through and commented the source code for the game of life demo. There are probably some things that I could have done better, but hopefully it will be a good place to start. /* Game of Life charliplexing 4 8x8 LED Matrix demo. Designed for AtMega _______________________________________________________________________________ # to compile and upload using avr-gcc and avrdude: # compile avr-gcc -Os -mmcu=atmega328p ./display.c -o a.o # grab the text and data sections and pack them into a binary avr-objcopy -j .text -j .data -O binary a.o a.bin # check that the binary is small enough to fit! du -b ./a.bin # upload using the avr ISP MKII. In this case, # it is located at /dev/ttyUSB1, but you would change that argument # to reflect whichever device your programmer has been mounted as avrdude -c avrispmkII -p m328p -B20 -P /dev/ttyUSB1 -U flash:w:a.bin Hardware notes =============================================================================== DDRx : 1 = output, 0 = input PORTx : output buffer PINx : digital input buffer ( writes set pullups ) ______ !RESET PC6 -| U |- PC5 PD0 -| |- PC4 PD1 -| |- PC3 PD2 -| |- PC2 PD3 -| m |- PC1 PD4 -| * |- PC0 VCC -| 8 |- GND GND -| |- AREF PB6 -| |- AVCC PB7 -| |- PB5 SCK ( yellow ) PD5 -| |- PB4 MISO ( green ) PD6 -| |- PB3 MOSI ( blue ) PD7 -| |- PB2 PB0 -|_____|- PB1 Programmer pinout, 6 pin: 6 MISO +-+ VCC 3 5 SCK + + MOSI 2 4 RST +-+ GND 1 Programmer pinout, 6 pin, linear: 6 MISO + 5 SCK + 4 RST + VCC 3 + MOSI 2 + GND 1 + Programmer pinout, 10 pin: 3 vcc +-+ MOSI 2 + + + +] RST 4 + + SCK 5 1 gnd +-+ MISO 6 PORT : write to here to set output DDR : write to here to set IO. 1 for output. PIN : digital input thanks to for explaining timer interrupts */ // avr io gives us common pin definitions, // and avr interrupt gives us definitions for setting interrupts. // ( we will use one timer interrupt to update the display ) #include <avr/io.h> #include <avr/interrupt.h> // Basic definitions. Our display is 16 pixels wide and 16 pixels high // This is set in N // There are 16*16=256 lights total, this is set in NN // We also use NOP to control timing sometimes, we use an assembly wrapper // reflected in the macro "NOP" #define N 16 #define NN ((N)*(N)) #define NOP __asm__("nop\n\t") // I use two different sets of buffers for display data. Part of this is // Laziness -- it does consume a lot of memory and wouldn't fly on say an // AtMega8. But it makes the code a little easier to understand. // First, I store the display pixels in a "raster-life" format. Here, // Each rown of the display is stored in a sequence of integers, and // If a pixel is on, then the bit corresponding to that pixel is set to 1, // Otherwise 0. // These displays are used to run the game of life logic because it is // straightforward to read and write pixel data. // We use 16 bit integers because this makes more sense for a 16x16 array // But this is an abstraction and 8 or 32 bit integers would work just as well. // We use a double buffering strategy. So, we declare two buffers, and then // also make two indirect pointers to these buffers. When we want to update // the display state, we write into the "buff" pointer, while reading the // previous game state from the "disp" pointer. Then, when we are ready to // show the next frame, these pointers will be flipped. #define BUFFLEN 16 uint16_t b0[BUFFLEN]; uint16_t b1[BUFFLEN]; uint16_t *buff=&b0[0]; uint16_t *disp=&b1[0]; // To actually scan the display, I use a sparse format. When we scan the lights // we turn them on one at a time. This can make the display very dim if we // have to turn on all of the lights. However, for something like the Game of // Life, only a few lights are ever on at the same time. If we only worry // about scanning the lights that are on, then our display is much brighter. // However, it is important that the code that scans the display is very // fast, so that we can run it thousands of times per second so that there is // no visible flicker to the human eye. So, we prepare a list of which lights // are on ahead of time. Then, the display scanning code only has to refer to // this list, which is rapid. // We use a double buffering strategy here. The active list of lights that // are on is stored in the "lightList" variable. This is the one that the // display scanning code acually uses. When we want to prepare a new list, // we write it into the lightBuff variable, then flip it once it is ready. // I am somewhat wasteful here and allocate enough space to store two lists // that might contain all 256 LEDs. I suspect there are ways to use less // space by being clever, but I can't think of anything at the moment. uint8_t ll0[NN],ll1[NN]; volatile uint8_t *lightList = &ll0[0]; volatile uint8_t *lightBuff = &ll1[0]; volatile uint16_t lighted = 0; // This is a simple random number generator. It is not very good, and will // produce the same sequence of numbers each time the AtMega is turned on, // but it will siffice for this demonstration. uint32_t rng = 6719; uint8_t rintn() { rng = ((uint64_t)rng * 279470273UL) % 4294967291UL; return rng&0xff; } // To simplify changing the pin states of the AtMega, I group the three ports // PORTB PORTC and PORTD into one logical port and then set all three with // one function call. void setDDR(uint32_t ddr) { DDRB = ddr & 0xff; ddr >>= 8; DDRD = ddr & 0xff; ddr >>= 8; DDRC = ddr & 0xff; } void setPort(uint32_t pins) { PORTB = pins & 0xff; pins >>= 8; PORTD = pins & 0xff; pins >>= 8; PORTC = pins & 0xff; } // Spin around NOP for a while -- a quick and lazy way to control timing void delay(uint32_t n) { while (n--) NOP;} // Read and write functions for the display data. // This abstracts away the bit packing and unpacking. // First argument: one of the display buffers ( either disp or buff ) // Second argument: the pixel index. We use row-major indexing, so // for example, the first row will count up indecies 0..15, then // the second row will start at index 16 .. 31 and so on and so forth. // For the set method, the third argument is 0 or 1 -- 1 for "on" and 0 for // "off" uint8_t get(uint16_t *b,uint16_t i) { return (b[i>>4]>>(i&15))&1;} uint8_t set(uint16_t *b,uint16_t i,uint8_t v) { if (get(b,i)!=v) b[i>>4]^=1<<(i&15);} // The game of life wraps around at the edges. To abstract away some of the // difficulty, these previous and next functions will return the previous // or next row or column, automatically handlign wrapping around the edges. // For example, the next column after column 15 is column 0. The previous // row to row 0 is row 15. uint8_t prev(uint8_t x) { return (x>0?x:N)-1; } uint8_t next(uint8_t x) { return x<N-1?x+1:0; } // These are parameters to configure the Game of Life. Sometimes the game // gets stuck. To poke it, I randomly drop in some primative shapes. // I have stored these shapes in a bit-packed representation here. // Also, the TIMEOUT variable tells us how long to let the game stay "stuck" // before we try to add a new life-form to it. The variable shownFor counts // how many frames the game has been stuck. #define glider 0xCE #define genesis 0x5E #define bomb 0x5D #define TIMEOUT 7 uint8_t shownFor; // These are some macros to make coding the Game of Life a little easier. // When we update the game, we are always reading from the current state, // which is stored in the "disp" display buffer, and we are always // writing the next state into the "buff" display buffer. So, we can // simplify the Get and Set functions for readability. #define getLifeRaster(i) get(disp,i) #define setLifeRaster(i,v) set(buff,i,(v)) // We store the display data in a bit-vector which is row-major ordered. // The bit vector is indexed by a single number from 0 to 255, but we want // to think about the Game of Life in terms of rows and columns. So, // this macro just wraps conversion of row and column numbers into an index // for readability #define rc2i(r,c) ((r)*N+(c)) // Finally, combine the index macro with the get and set macros to // create macros for reading and writing game state based on the row and // column numbers. #define getLife(r,c) getLifeRaster(rc2i(r,c)) #define setLife(r,c,v) setLifeRaster(rc2i(r,c),v) // One step in the Game of Life is to count the number of neighbors that // are "on". This function computes part of that: it counts the number of // neighbors that are "on" at the current position (r,c) and also the // row above and below. This is not a Macro because the Game of Life // implementation here was ported from an implementation with much less // flash memory. When you make a macro, that code is expanded with simple // text substitution before it even gets to the compiler. This means that // each time we "call" a macro a bunch of code gets included. Somtimes this // can be optimized out, but not always. By making this a function, we help // the compiler understand that each "call" can be computed using the same // code, and this resulted in a smaller binary. TLDR: esoteric design choice // for size optimization, IGNORE. uint8_t columnCount(r,c) { return getLife(prev(r),c) + getLife(r,c) + getLife(next(r),c); } // We store the game state in raster-like buffers of pixel data, but we // scan the display one light at a time based on a list of which lights are // on. This function converts from the raster-like representation to the // list reprentation. Once we have prepared a new frame of the game, we call // this function to create a new list of "on" lights for the display scanning // code. We also flip the pixel and light-list buffers here. void flipBuffers() { // flip the pixel buffers uint16_t *temp = buff; buff = disp; disp = temp; // scan the new pixel buffer for lit pixels and add them to the list // of lighted pixels for sparse scanning uint16_t r,c,i; uint16_t lightCount = 0; for (i=0;i<NN;i++) { if (get(disp,i)) { lightBuff[lightCount]=i; lightList[lightCount]=i; lightCount++; } } //swap the sparse scanning data buffers lighted = lighted<lightCount?lighted:lightCount; volatile uint8_t *ltemp = lightBuff; lightBuff = lightList; lightList = ltemp; lighted = lightCount; } // pin definitions. We have wired up four different 8x8 LED matrices to // The AtMega. I have kept the anodes and cathodes contiguous, so that // For each array, the anodes and the cathodes use a sequential number of // Pins. The way I have set up my logical pin numbers, Pins 0..7 are PORTB // Pins 8..15 are PORTD, and then the rest are PORTC. These arrays store // The anode or cathode sequence starts for each of the 4 matrices. const uint8_t cmap[4] = { 21,9, 7,17}; const uint8_t amap[4] = { 12,1,15, 4}; // I didn't know which anode/cathode was which when I wired up the arrays. // LED matrix pinouts can be idiosyncratic like that. However, I did wire up // each of the arrays in a consistent manner. So, I can fix this by applying // a permutation in software. These arrays store the pin permuations for // the anodes and cathodes. const uint8_t aperm[N] = {0,2,3,1,7,4,6,5}; const uint8_t cperm[N] = {4,3,1,5,0,6,7,2}; // This function handles the display scanning -- it is called from a timer // interrupt. The variable scanI keeps track of which light we're currently // displaying. The variable PWM keeps track of state so that we can turn some // lights on longer than others. Each time a timer interrupt occurs, this // code changes which light is displayed. Lights are only shown one at a time. // The timer interrupt changes them fast enough that they appear to be all // Illuminated simultaneously. volatile uint8_t scanI = 0; volatile uint8_t pwm = 0; ISR(TIMER0_COMPA_vect) { // PWM would allow us to vary the brightness by leaving some lights // on longer. Here, I just use it to correct for a problem with PORTC. // For some reason LEDs on PORTC are more dim than they should be. This // is probably because I am driving the LEDs without current limiting // resistors, and so LEDs on other ports are drawing more current than // I expected ( more than 40mA ). Thus, these LEDs are brighter than the // ones driven using PORTC. It may have something to do with PORTC also // being capable of analog input? Anyway, its unclear if this is bad but // this little PWM script seems to fix it. Also, I intentionally waste // CPU cycles using a delay loop so that the PWM branch takes as long // as the light-scanning branch -- this is so that the fraction of time // taken by the display scanning interrupt routine is roughtly constant. // This is important because if I returned early from the PWM branch, // The extra CPU cycles would be used by the game logic and the game // frame rate would vary. A more correct way to do this is to wait after // each frame of the game of life has been computer, based on timer // interrupts. But just adding the delay here was easier for me. if (pwm) { pwm--; delay(110); return; } // We advance to the next light. If for some reason all of the lights are // off we return immediately. Technically, there are race conditions // with the flipBuffers() function, but the errors are not catestrophic // We only focus on lights that are on, and keep track of how many lights // are on in the "ligted" variable. scanI++; if (!lighted) return; scanI%=lighted; // We look up which light should be on, which is stored in the lightList. // The lower 4 bits contain the column index, and the upper four bits // contain the row index. Our display consists of 4 8x8 arrays. These are // laid out with a charlieplexing pattern. So, we do a test to see which // array our light at row, columb (r,c) should be in -- that is what the // variable 'b' stored. Then we can lookup which anode and cathode we // should use to turn the light on, now that we know which array to use. uint8_t light = lightList[scanI]; uint8_t r = light>>4; uint8_t c = light&0x0f; uint8_t b = (r<8?0:1)+(c<8?0:2); // Looking up which anode and cathode to use seems strange at first. // For each array, I've wired up the anodes and cathodes to be contiguous // So that, for example, the fourth array, the cathodes will start at // logical pin 17, and proceed to logical pin 25. Except there are only // 21 pins, so it wraps around to the beginnign again rather than counting // Up to 24. So, we get the starting in, an count up from there, and use // Modulo to wrap around to the beginning again. // Finally, I did not know which cathode or anode was which when I wired // up the arrays -- LED matrix pinouts can be rather idiosyncratic like // that. So! The anodes and cathods were all out of order. So I have to // look up a permutation to get the right one for our specific row and // column. uint8_t an = (amap[b]+aperm[r%8]+21)%22; uint8_t ct = (cmap[b]+cperm[c%8]+21)%22; // Now that we know which pins to use to turn on the light, we can // actually set the pin state to achieve this. First we turn all the // pins to high impedence ("Off" or "input mode"). This is because, to // set the right pin, we have to changes pins in PORTA, PORTB, and PORTC. // As far as I know, there is no way to change all three of these // simultanously -- you have to do them one at a time. This means that // in the process of changing the pin states we might accidentally turn on // some lights we didn't mean to. To work around this, first turn off all // the pins, then set the pin state, then turn back on only the pins that // we need to use setDDR(0); setPort(1UL<<an); setDDR((1UL<<an)|(1UL<<ct)); // If we are driving the anodes using PORTC, we use a brightness correction if (an>=16) pwm = 1; } int main() { // I happen to be using the internal RC oscillator, which has an unknown // frequency. Setting OSCCAL to 0xff means "run the internal RC oscillator // "FAST". OSCCAL is supposed to be used for calirating the RC oscillator // so that it runs at a known frequency, but here I just max out the // calibration variable. Another way to do this is to change the fuses so // that // the RC oscillator runs faster -- but this works too. OSCCAL=0xFF; // I want to configure a timer interrupt to chan the display. // I determined these values using the AtMega datasheet, and don't exactly // remember what they all mean. // I know that we turn on timer interrupt 0 and set the prescaler // (in TCCR0B) to something -- probably "as fast as you can". // Then, we set it to "compare to counter" mode. This means that the // counter will incremement, and when it gets to OCR0A ( set here to 180 ) // it will call our display scanning code. This lets you tweak how often // the display is scanned. If it too slow, you will see flickering. If // it is too fast, there will not be enough CPU cycles left over to run // the game logic. TIMSK0 = 2; // Timer CompA interupt 1 TCCR0B = 2; // speed TCCR0A = 2; // CTC mode OCR0A = 180;// period // Initialize the game to a random state, and update the lightList to // reflect this. uint8_t r,c; for (r=0;r<16;r++) buff[r] = rintn(); flipBuffers(); sei(); // Run the Game of Life // There are some tedious optimizations here. // To compute the next frame in the Game of Life, one has to sum up // the numbr of "live" or "on" neighbors around each cell. // To optimize this, we keep a running count. // When we want to count the number of "live" cells at position (r,c), // We look at how many cells were alive around position (r,c-1). Then, we // Subtract the cells from column c-2 and add the cells from column c+1. // One could also keep a running count along the columns, but this // would require more intermediate state and the additional memory lookups // consume the benefit in this application. // As we update the game, we also keep track of whetehr a cell changes. // If cells are not changing, we make note of this, and if the game stays // stuck for a bit, then we add in new life-forms to keep things // interesting. // One neat thing about double-buffering the game state is that the // state from TWO frames ago is available in the output buffer, at least, // until we write the next frame over it. So we can take advantage of this // and also detect when the game gets stuck in a 2-cycle. while (1) { uint8_t changed = 0; uint8_t k=0; for (r=0; r<N; r++) { uint8_t previous = columnCount(r,N-1); uint8_t current = columnCount(r,0); uint8_t neighbor = previous+current; for (c=0; c<N; c++) { uint8_t cell = getLife(r,c); uint8_t upcoming = columnCount(r,next(c)); neighbor += upcoming; uint8_t new = cell? (neighbor+1>>1)==2:neighbor==3; neighbor -= previous; previous = current ; current = upcoming; changed |= new!=cell && new!=get(buff,rc2i(r,c)); k += new; setLife(r,c,new); } } uint8_t l=0; if (!(k&&rintn())) l=genesis; if (!changed && shownFor++>TIMEOUT) l=genesis; if (l) { uint8_t r = rintn(); uint8_t q = rintn(); uint8_t a = rintn()&1; uint8_t b = rintn()&1; uint8_t i,j; for (i=0;i<3;i++) { uint8_t c = q; for (j=0;j<3;j++) { setLife(r,c,(l&0x80)>>7); l <<= 1; c = a?next(c):prev(c); } r = b?next(r):prev(r); } shownFor = 0; } flipBuffers(); } } Thanks for sharing this technique.I am interested to see the source code for your game of life also,can you post it Excellent article. As Manos wrote I'd be very interested in seeing some source for the implementation of a simple matrix if possible. Saw your article on Hackaday. This is a really beautiful way of visualizing essentially a constrained linear algebra problem problem and definitely an awesome way to teach the concept of charlieplexing. Nice job! Hi Manos and Jared, I've commented and added the source code example to the end of the post. Also, much thanks Hackaday for the attention! I hope this helps people build many excellent gadgets with way too many LEDs. Could you use two buttons with diodes for multiple inputs? yes. Found very cool and unique info here in this blog. This is a great addition in my favorite blog list. MSI - 15.6" Laptop - 16GB Memory - 1TB Hard Drive + 128GB Solid State Drive - Black I see no action on this site for many years, wanted to chat more about a complex charlieplex problem with RGB's! thought you might be the one to have a great conversation about this! Wonderful blog! I truly love how it’s easy on my eyes as well as the info are well written. led scoreboard
http://wealoneonearth.blogspot.com/2013/03/design-note-charlieplexing-led-matrices.html
CC-MAIN-2016-40
refinedweb
5,445
69.21
In mockups related to bug 449691 ( improved message reader ) we have been using an Archive button for "processing" or moving messages from the Inbox to an archive folder. To make this action a reality we need the backend bits implemented. I've included the wiki page with the Archive designs. Initial implementation should * Have a default Archive folder selected on the remote system * create the Archive folder upon the first use of the Archive button. * Provide at least a status bar message notification of the message move I think our first use, where the folder is created, might require an extra explanation to the user of what is happening vs. routine usage of the archive button. I'm not sure what the best method for notification of the first usage should be, however it is probably the optimum time to do something. xref bug 93094. In my own usage, a more typical scenario to archive mail from an arbitrary folder which is the target of a filter, i.e. not from inbox folder, and I wouldn't want that mail to archive where inbox gets archived. I think initial versions of the Archive will likely just be simple moving mail from the Inbox to an Archive folder. Once we've settled the user experience issues that come along with the simple end we can add in filtering / scripting to the archive button such that it becomes more of a "process mail" button than just archive. This should work well for people who want to archive from any folder or archive mail into mail specific folders. And it looks like we should have someone lined up to work on this very soon, hopefully he'll make a comment or two about his approach. I am interested in working on this project. Initially I plan on doing what Bryan suggested with the simple moving of the mail and add more complexity in future iterations. Consider the people that are using a strong folder structure under inbox or such. Out of view doesn't mean out of structure .. Archive should remember that in order to be useful to them or they'll not use it. Either by reproducing the folder structure under it or by having some metadata/tag, which may lead to same thing.. I do not use that much so I cannot give clear scenario and wish, but you know many people use that. [Or this idea may just be the opposite of the archive concept you propose ..] An idea I had discussed a week ago or so was that by using Gloda we can know where the rest of a conversation exists even though it's buried in folders. So if a person files one message in a certain folder we can implement the archive in such a way that it places the next message in that conversation in the same folder. Could possibly solve this problem. We'll have to figure out a way to inform the user of where the message will go when they archive it. Some suggestions were something like this: ( Archive ) /to Inbox->Biz->Mozilla/ Essentially providing some subtle text about where the Archive action will send your message. Of course the initial version of Archive will have to stick to simply moving any message to a single folder. Once the simple implementation is done we can move toward advanced setups. - updating platform flag - Bartosz: any progress so far? Feel free to email me with questions Created attachment 347601 [details] Account-Settings-Copies-Folders.png Here's a screenshot of my initial WIP patch that should be coming Created attachment 347602 [details] [diff] [review] WIP-ao.patch Here's the patch. This adds initial support for the Archives folder Account Settings option. Things that are left to do: * Rename the msg flag from Unused3 to Archives (easy) * Continue changing the msgDBFolder to follow the code paths for "drafts" (difficult) Shouldn't that be "Archive" without the s? > Shouldn't that be "Archive" without the s? Ah, yes that should drop the trailing 's'. good catch! To clarify the last comment after OOB chat w/ bryan: the flag name should be Archive, but the parent folder is supposed to be Archives. Created attachment 348935 [details] [diff] [review] WIP patch for archiving behavior itself This WIP adds an Archive menuitem to the Message menu, and an "archive" button to the message reader. They both work. This patch ignores bryan's patch, and just puts stuff in a toplevel Archives folder based on the first message. The two patches should be merged at some point. A few things to note before I forget: 0) I don't currently do anything on "first archive", but it should be relatively easy to handle that, as long as we know what it is we want to do. I'd suggest we defer that discussion until the Activity Manager & super status bar has landed. 1) this patch should be tweaked to chunk up patches based on server as well as month, in case the set of selected messages spans servers. 2) this patch doesn't deal well with IMAP servers for which every folder needs to be a child of INBOX unless the IMAP personal namespace is set (bienvenu seemed to think this was a bug that should be handled at a lower level. 3) I deliberately didn't use the "traditional" SetNextMessageAfterDelete() mechanism the "standard" way because that mechanism doesn't deal well with single UI operations that result in several IMAP moves. Specifically, if multiple messages spanning multiple destination archive folders were selected, then the DBview was telling the front-end to select messages that the next batch was already moving away, resulting in error dialogs. Also, it was slowing things down a lot. The approach I used here is to call SetNextMessageAfterDelete() to figure out what message we want, then reset that global (ugh) so that the DBview doesn't result in any selection updates, and then do the selection setting myself at the end of the last copy operation. That last bit needs to be changed to be done at the end of _all_ copy operations, as I wouldn't be surprised if the last copy operation started isn't necessary the last one to finish. This makes archiving quite responsive compared to the alternative -- I'd like to know what problems aren't handled, given that I'm deliberately bypassing an existing mechanism which appears horribly tricky. 4) I don't set the Archive bit on newly created Archive folder. TBD. 5) the structure of the archives folder (figured out with various people in mountain view) is: Archives/2008/2008-04 (for april 2008, for example). The reasons for this were: - to not end up with neither too small nor too huge folders, for IMAP health as well as for MSF performance. Monthly seems a reasonable best guess. - to sort well on disk To note about this directory structure in particular: - the plan is to localize the presentation of the archives folder, not its structure on disk. So it will say April 2008 in en-US, Avril 2008 in fr-FR, etc. - the plan is to leverage the JS folder pane to provide archive-specific UI for those folders, particularly suited to the tasks that people do when managing their archives. These last two points should likely be the topic of another bug having to do with the UI of the archive folder. - we need to figure out a way to properly treat Archive-flagged folders so that they get synced appropriately for IMAP -- we're archiving messages in folders corresponding to the From header of the message, and so it is possible to archive a message that's been sitting in an inbox for months in an "old" folder. At the same time, we want other Thunderbird installations pointing at the same IMAP server to detect the new messages, but we don't want Thunderbird to auto-sync every archive folder too frequently. Oh, and I should add that something that I expect to do at some point is to open my 100,000 Archive folder, select all and hit A. It'd be good to test that before I (or anyone else) does it with real mail. =) Does BatchMessageMover want to be its own service or JS module, rather than living directly in the chrome? (In reply to comment #15) > Does BatchMessageMover want to be its own service or JS module, rather than > living directly in the chrome? Good idea. One thing that could make sense is to split the stuff that interacts with the view (figuring out selected messages, managing selection when done) from the creation of batch moves. I'll need to do that anyway when implementing archive on conversations. In general, I think we need to do a higher level review of the APIs having to do with the view & message handling. There's way too much tying together of logic with view stuff. I'll drive this into the tree, as it were. One thing Davida pointed out over IRC - we probably want to treat archive in GMail accounts specially - they shouldn't create the per-month archive folders, and should just do whatever gmail does when you archive a message, or the imap equivalent thereof. Right, for GMail actually want to delete the message, without moving it to the trash. This will remove it from the Inbox but the message remains in [GMail]/All Mail. See the GMail IMAP actions table for other actions: I've un-bitrotted this patch, and started to make the initial imap folder creation work. I'll be fixing some core issues this patch has brought up, including bug 470011, and the fact that creating an imap folder at the root level doesn't pay attention to the personal namespace (e.g., make the folder a child of the INBOX for servers where the personal namespace is "INBOX.") we seem to be creating a different folder for every hour of the day, which seems a bit excessive :-) I've gotten the two patches to work together, such that we use the identity's idea of the archive folder. But I believe we really want to archive imap messages in the imap account instead of using the default local folders account, by default. I'm having a lot of fun with the folders not showing up in the UI until a restart. This feature is quite the stress test on a bunch of different code :-) Created attachment 353616 [details] [diff] [review] wip this is what I have so far - it contains some diffs that are in patches in separate spin-off bugs, which I'll land first. this should get into b2 (In reply to comment #20) > I've gotten the two patches to work together, such that we use the identity's > idea of the archive folder. But I believe we really want to archive imap > messages in the imap account instead of using the default local folders > account, by default. Yes, this is just a fault of my not understanding all the code for the Drafts folder implementation. We really do want to default to the IMAP account instead of the Local Folders. Also, just to note that I think we can handle the GMail case in a follow up patch. This is a large enough change that I think it's important that we get some good testing started ASAP. For GMail users that are testing they will get some labels created that they don't want but no harm will really be done. it's a bit tricky to default to a non-existent folder on a server (we don't have any defaults that behave that way now), though I'm sure I can figure out a way. I also need to make it so the Archives folder name is displayed localized, though I think I'll make the folder name on the server be "Archives". Created attachment 354888 [details] [diff] [review] add archives folder flag, archives folder property to identity, and localized Archives folder name this is some plumbing work to support an Archives folder.. none of this code should currently get exercised, until more of this work lands. (In reply to comment #26) >. I thought Drafts, Templates, Sent, Trash and Junk always defaulted to the server, not local folders. I guess someone must set them up during account creation? Created attachment 355059 [details] [diff] [review] snapshotting current work yes, the account wizard and copies dialog both seem to do that: So that's an alternative to what I've done - I didn't know about/remember the allows_specialfolders_usage server attribute Comment on attachment 354888 [details] [diff] [review] add archives folder flag, archives folder property to identity, and localized Archives folder name oh, yes, the reason I did it this way is so that existing profiles will automatically get their archives folder on the imap server. Also, at least for TB, the account wizard is getting replaced, so that would be one less piece of logic I'd need to redo for the new account wizard. So I think I'll just tweak the nsMsgIdentity::getFolderPref code to check that allows_specialfolders_usage server attribute. Created attachment 355157 [details] [diff] [review] use GetDefaultCopiesAndFoldersPrefsToServer Comment on attachment 355157 [details] [diff] [review] use GetDefaultCopiesAndFoldersPrefsToServer >+archiveFolderName=Archives This was just the most obvious example of the archive/archives mix but you've been horribly inconsistent throughout this patch; pick one and stick to it! > PRUnichar *nsMsgDBFolder::kLocalizedUnsentName; > PRUnichar *nsMsgDBFolder::kLocalizedJunkName; > PRUnichar *nsMsgDBFolder::kLocalizedBrandShortName; >+PRUnichar *nsMsgDBFolder::kLocalizedArchivesName; Nit: Brand should come last, or better still, separated with a blank line. (Same goes for the NS_Free section; the init code is already separated.) >+ nsCOMPtr<nsISupportsArray> servers; >+ rv = accountManager->GetServersForIdentity(this, getter_AddRefs(servers)); >+ NS_ENSURE_SUCCESS(rv,rv); >+ PRUint32 cnt = 0; >+ servers->Count(&cnt); >+ if (cnt > 0) >+ { >+ nsCOMPtr<nsIMsgIncomingServer> server(do_QueryElementAt(servers, 0, &rv)); >+ if (NS_SUCCEEDED(rv)) You probably don't have to count them first, as this will fail anyway. [And you didn't check the rv for Count ;-) ] >+ retval.Append("/"); >+ retval.Append(folderName); Is it worth changing the macro to prepend the "/" automatically i.e. rv = getFolderPref(_prefname, folderPref, "/" _foldername, _flag); \ [Otherwise use retval.Append('/'); instead] re Archive vs. Archives - that was a decision that I inherited, not one that I originated. The decision was to call the folder flag "Archive", but the folder "Archives". Perhaps I should go back and edit all the patch to call all the vars "Archive" and leave the folder name "Archives" so that the only inconsistency would be the display name. (In reply to comment #13) > 5) the structure of the archives folder (figured out with various people in > mountain view) is: > > Archives/2008/2008-04). Month basis can be need for the most users, not deletes mails with multimedia. I see a lot of "folder is larger 2 gb size" problem for less than a year. I am using mail archiving, and not use month level - but I remove all large attachements. Maybe, there can be an option, and archiver can propose more optimal way depending on inbox size and message count? I dare say if you need to archive over 2 or 4 GB of mail per month, you're mailing habits are highly unusual. Of all the bugs re the max 4GB / folder I don't recall anyone ever complaining about the limit for folders - except for the Inbox. (And Trash, when people don't know they must compact folder once in a while.) If it's about the "never throw away anything" policy Gmail tried, even Gmail had to add the delete button. Big surprise deletion *is* on of the most powerful labeling mechanisms, especially with the amount of junk (non-spam) you get... I didn't say about "2 GIG per month", I said about "per year". But have 2-3 gig in one file os not comfortable. This issue created for help users, that not toss mail by boxes. This issue created as a decision for people who not keep in mind that inbox can have any limits, who don't know about email really have a volume, and inbox and trash need to be purged time to time. I often fix broken mail systems of that people, and please, don't tell to **me**, how to **right** use email. Tell it to all email users of all ages - from 5 to 85 years. Computer must work without any harrasements to users, without any user-made "housekeeping". This issue is one more step to computers that "just works", and should perform this task. (In reply to comment #36) >). The primary criterion for picking a monthly folder structure was that we'll need to periodically open the corresponding MSF files for autosync, and it really hurts to open huge MSF files. Also, Bryan and I felt that years and months are concepts that people understand really well, and which correspond to common searches, meaning that the file structure will likely map normal organizational patterns. Archive folders are intended to be displayed with custom logic, which can take into account l10n issues. It makes sense for me to use numbers on the server, as long as the UI uses appropriate l10n names. the time it takes to open a .msf file is miniscule compared to the time it takes to do an imap sync of a large folder - I don't think the .msf opening time is really an issue. (In reply to comment #42) > the time it takes to open a .msf file is miniscule compared to the time it > takes to do an imap sync of a large folder - I don't think the .msf opening > time is really an issue. I knew i had my argument for keeping file sizes down wrong. thanks for correcting the record. Created attachment 355672 [details] [diff] [review] add prefs ui to pick an archive folder. this adds the archive folder to the copies sheet - I'm assuming that SeaMonkey is going to want some sort of Archive feature, though perhaps not exactly the same as TB, so I've left this in SM. Let me know if I should #ifdef MOZ_THUNDERBIRD this... Created attachment 355674 [details] [diff] [review] TB front end archive work this is the TB front end work to make the archive command work, and to add an archive button to the message header area. I think all the work is now in patches attached to this bug. (In reply to comment #10) > Shouldn't that be "Archive" without the s? I disagree. Drafts and Templates have an s, and so should Archives. As a result of the mix up, attachment 355672 [details] [diff] [review] has entity name mismatches! Comment on attachment 355672 [details] [diff] [review] add prefs ui to pick an archive folder. >+ SaveFolderSettings( gArchiveRadioElemChoice, >+ "messageArchive", >+ gArchiveFolderWithDelim, >+ "msgArchiveAccountPicker", This was the worst spot for copied trailing spaces, but git-apply claims there are 18 whitespace errors in all. >+ <label value="&keepArchive.label;" control="messageArchive"/> Archives. >++ Archives. Archives! </rant> A single message in a drafts folder is a draft. Is a single message in an Archive folder an archive? I'm happy to make it all Archives other than the folder flag and if someone doesn't like that, they can change it themselves :-) Comment on attachment 355157 [details] [diff] [review] use GetDefaultCopiesAndFoldersPrefsToServer >@@ -102,6 +102,7 @@ > attribute ACString fccFolderPickerMode; > attribute boolean fccReplyFollowsParent; > attribute ACString draftsFolderPickerMode; >+ attribute ACString archivesFolderPickerMode; > attribute ACString tmplFolderPickerMode; I think it would be worth adding some documentation (just one-liners probably) as to what these folder picker modes relate to. It certainly took me a bit of digging to realise. > attribute ACString draftFolder; >+ attribute ACString archiveFolder; > attribute ACString stationeryFolder; Again, this needs a little documentation I think just to say it will set/return the name of the folder to use for the identity. >diff --git a/mailnews/base/public/nsMsgFolderFlags.idl b/mailnews/base/public/nsMsgFolderFlags.idl >--- a/mailnews/base/public/nsMsgFolderFlags.idl >+++ b/mailnews/base/public/nsMsgFolderFlags.idl >@@ -98,8 +98,8 @@ > const nsMsgFolderFlagType Inbox = 0x00001000; > /// Whether this folder on online IMAP > const nsMsgFolderFlagType ImapBox = 0x00002000; >- /// Used to be for category container >- const nsMsgFolderFlagType Unused3 = 0x00004000; >+ /// Whether this is an archive folder >+ const nsMsgFolderFlagType Archive = 0x00004000; > /// This is a virtual newsgroup > const nsMsgFolderFlagType ProfileGroup = 0x00008000; This file should probably have a uuid bump r=me with those fixed. Comment on attachment 355672 [details] [diff] [review] add prefs ui to pick an archive folder. Something is causing the achiveFolderPickerMode not to be save or restored - it always comes up on "Other" whenever I open the account settings dialog. The archive folder pref does seem to be set correctly though. >+ SaveFolderSettings( gArchiveRadioElemChoice, >+ "messageArchive", >+ gArchiveFolderWithDelim, >+ "msgArchiveAccountPicker", >+ "msgArchiveFolderPicker", >+ "identity.archiveFolder", >+ "identity.archiveFolderPickerMode" ); >+ nit: some of these lines of blank space on the end, and the last line has whitespace on it when it doesn't need to (ditto with other lines you've added). >+ <hbox align="center"> >+ <label value="&keepArchive.label;" control="messageArchive"/> >+ </hbox> This doesn't match the strings. >+ <radio id="archive_selectAccount" >+++ nor do these two. >+ <menulist id="msgArchiveAccountPicker" >+ <menulist id="msgArchiveFolderPicker" There's a tab on these lines. Comment on attachment 355157 [details] [diff] [review] use GetDefaultCopiesAndFoldersPrefsToServer >+++ b/mail/locales/en-US/chrome/messenger/messenger.properties >+archiveFolderName=Archives >+ bundle->GetStringFromName(NS_LITERAL_STRING("archivesFolderName").get(), >+ &kLocalizedArchivesName); >+++ b/suite/locales/en-US/chrome/mailnews/messenger.properties >+archiveFolderName=Archives I've just tested all these patches together. These don't match, and so we then crash (because kLocalizedArchivesName is null and nsDependentString doesn't like that). Comment on attachment 355674 [details] [diff] [review] TB front end archive work messenger.properties didn't seem to apply, but I expect that's because its diff is already in one of the other patches. Should Bryan be doing ui-review on this patch and the account manager? Probably follow-up bugs, but I'll mention them here, please make sure they get filed if you aren't addressing them: - IMAP folders don't get tagged for offline use when they are created. Is that expected, should that happen? - No archive option in context menu (especially useful/expected for multiple messages) - Should the archive button/menu option really be displayed/enabled when you are viewing a message in an archive folder? - Archive button is displayed for RSS messages, but does nothing. >diff --git a/mail/base/content/mailWidgets.xml b/mail/base/content/mailWidgets.xml >--- a/mail/base/content/mailWidgets.xml >+++ b/mail/base/content/mailWidgets.xml >@@ -2098,7 +2098,10 @@ > <xul:button >- <xul:button+ <xul:button++ Seeing as you're observing/setting up button_archive, why not goDoCommand('button_archive') as well? >+ <xul:button anonid="hdrJunkButton" label="&junkButton.label;" nit: no need to change this line (indent is now wrong). >+ // subtle: >+ SetNextMessageAfterDelete(); // we're just pretending >+ this.messageToSelectAfterWereDone = gNextMessageViewIndexAfterDelete; >+ gNextMessageViewIndexAfterDelete = -2; >+ nit: whitespace on blank lines again. >+ let msgHdr = messenger.msgHdrFromURI(selectedMsgUris[i]); >+ >+ let rootFolder = msgHdr.folder.server.rootFolder; >+ //if (rootFolder instanceof Components.interfaces.nsIMsgFolder) >+ //dump("Found root folder for archiving: " + rootFolder); >+ >+ let msgDate = new Date(msgHdr.date / 1000); // convert date to JS date object >+ //dump("msgDate = " + msgDate.toString() + '\n'); >+ let msgYear = msgDate.getFullYear().toString(); >+ //dump("msgYear = " + msgYear + '\n'); >+ let monthFolderName = msgDate.toLocaleFormat("%Y-%m") >+ //dump("monthFolderName= " + monthFolderName + '\n'); >+ let dstFolderName = monthFolderName; >+ //dump("dstFolderName= " + dstFolderName + '\n'); I think we can probably remove these commented out lines (in multiple places) >+ if (!subfolder.containsChildNamed(dstFolderName)) >+ { >+ //dump("Creating month folder\n"); >+ subfolder = subfolder.addSubfolder(dstFolderName); >+ dump("create folder " + subfolder.URI + '\n'); we shouldn't really need this now should we? >+ OnStopCopy: function(aStatus) >+ { >+ try { ... >+ } catch (e) { >+ dump("Exc: " + e + '\n'); >+ } Why do we need this try/catch? I'd prefer if it wasn't there or at least not over the whole function - it is very easy to mask errors otherwise. (In reply to comment #52) > - No archive option in context menu (especially useful/expected for multiple > messages) And in the context menus of folders? (e.g., for archiving a completed project) Created attachment 356010 [details] [diff] [review] cumulative fix this accumulates the various patches into one, for review. I've addressed most of your comments, except for a couple: I don't believe we need to change uuids for new constants Using go_doCommand('button_archive') does not work - there's a downstream error that I don't quite understand, but the code that's there does work :-) Re the bugs you noticed, I'll file those, but I'd like to get the basic stuff in sooner rather than later. The one that worries me a bit more is not configuring the archive for offline - I think I know why that is, and it should be easy to fix. Created attachment 356339 [details] [diff] [review] configure new archive folders for offline download this makes new archive folders get configured for offline use, by default. Comment on attachment 356010 [details] [diff] [review] cumulative fix nit: there are still a few whitespace issues () >+ // URI for the fcc (Sent) folder > attribute ACString fccFolder; nit: doxygen requires /// for single-line comments. >+ // these attributes control whether the special folder pickers for >+ // fcc, drafts,archives, and templates are set to pick between servers >+ // (e.g., Sent on accountName) or to pick any folder on any account. >+ // "0" means choose between servers; "1" means use the full folder picker. > attribute ACString fccFolderPickerMode; >- attribute boolean fccReplyFollowsParent; > attribute ACString draftsFolderPickerMode; >+ attribute ACString archivesFolderPickerMode; > attribute ACString tmplFolderPickerMode; nit: if you make this: /** * @{ * <the comments> */ attribute attribute ... /** @} */ Doxygen can then pick this up as a group comment and will apply it to all of the attributes This also applies to the special folder attributes. r=me with those fixed. fix checked in - I'll file followup bugs on these: - No archive option in context menu (especially useful/expected for multiple messages) (though I don't know why anyone would use a context menu when there's a single key shortcut available) - Hide or disable the archive button when viewing a message in an archive folder. - Either fix or hide the Archive button for RSS messages Bug 473212 is the tracking bug for remaining issues.
https://bugzilla.mozilla.org/show_bug.cgi?id=451995
CC-MAIN-2016-26
refinedweb
4,348
60.65
14 January 2008 08:05 [Source: ICIS news] SINGAPORE (ICIS news)--Hanwha Chemical, a South Korean chemicals maker, plans to build a won (W) 360bn ($384.2m) polyvinyl chloride plant (PVC) in eastern China for start-up at the end of 2010, a spokesman from its parent company said on Monday. The project in ?xml:namespace> Feedstock units producing 500,000 tonnes of ethylene dichloride (EDC) and 300,000 tonnes of vinyl chloride monomer (VCM) would also be built at the Daxie economic development zone, the spokesman said. Ethylene feedstock will be exported from its joint venture Yeochun NCC (YNCC) in Although It was also easier to get chlorine in Hanwha was still in talks with its potential partner in ($1=W937
http://www.icis.com/Articles/2008/01/14/9092425/hanwha-chem-to-build-384m-china-pvc-plant.html
CC-MAIN-2014-49
refinedweb
122
56.79
Re: Passing Structure to a function From: Niklas Borson (niklasb_at_microsoft.com) Date: 11/13/03 - ] Date: 12 Nov 2003 15:17:02 -0800 "kazack" <kazack@talon.net> wrote in message news:<GAmsb.6713$Bv6.2039282@news1.epix.net>... > [snip] > > #include <string> > #include <iostream> > #include <fstream> > using namespace std; > > int Menu(); > void Menu_Selection(int,struct phonerec phone); > void Input_New_Record(struct phonerec phone); > void Write_To_File(struct phonerec phone); You don't need the 'struct' keyword to refer to a structure type, only to declare/define it. I suspect the only reason you used the 'struct' keyword above is because otherwise you got compiler errors. The reason for the errors is that phonerec hasn't been declared or defined yet. You should probably move the structure defintion (below) so that it precedes the function declarations, and then remove the 'struct' keyword from the function declarations. What you have actually done is essentially equivalent to this: struct phonerec; void Menu_Selection(int, phonerec phone); void Input_New_Record(phonerec phone); void Write_To_File(phonerec phone); The first line above declares (but does not define) the phonerec structure. A structure declaration merely says that a structure exists but not what its members are. Some uses of a type require its defintion (e.g., creating an instance of the type), but others require only its declaration (e.g., creating a pointer or reference to the type). A declaration like the one above is called a "forward declaration" because it declares a struct which will defined later. This is sometimes necessary. For example, if struct A contains a member of type B* and struct B contains a member of type A*, then either A or B must be forward declared. It is also possible for a struct to be declared but not defined at all, or at least not publicly. This is called an "opaque struct". The FILE structure in the C runtime library is an example of this. Windows handles are another example. Yet another is the "Pimpl idiom" (Google is your friend). > struct phonerec > { > string fname; > string lname; > string number; > }; > > > int main() > { > phonerec phone; > int Menu_Choice; > Menu_Choice = Menu(); I recommend using an enum rather than an int for Menu_Choice. Then you can use meaningful names instead raw numbers like 1, 2, 3. I also like function names to be verbs and type names to be nouns. Menu would be a good name for a class that represented a menu. A better name for your function in my opinion would be Show_Menu. Note that you can also declare and initialize a variable in one step, and this is usually preferred in C++, e.g.: MenuChoice choice = Show_Menu(); > > if(Menu_Choice != 3) > { > Menu_Selection(Menu_Choice,phone); > main(); > } Note that you're passing phone by value to Menu_Selection. This means a copy of phone is passed to the function. Anything the function does with phone will only modify its copy. The phone object in main will be untouched. Also, you probably just want to have a loop here rather than calling main recursively: for (MenuChoice choice = Show_Menu(); choice != QuitMenuItem; choice = Show_Menu()) { Process_Command(choice, &phone); } > return 0; > } > > > void Menu_Selection(int Menu_Choice,struct phonerec phone) > { > switch(Menu_Choice) > { > case 1: > { > Input_Phone_Record(phone); > break; > } > case 2: > { > //Reserved For Menu Option 2 to search for record > // When this feature is set up it will input one record at > // a time into the struct and check to see if search is equal > // and will do this for all records. I know this is not the > //most efficient way but it lets me know if I am using > //structs properly. > break; > } > } > } Again, I would choose a more verb-like name for the above function (e.g., ProcessCommand) and use an enum instead of raw integers to represent the menu selection. Also, phone is passed by value throughout your program, which means if any function modifies phone it changes only its own copy. I would probably use something more like the following function declarations: void Process_Command(MenuChoice choice, phonerec* phone); phonerec Input_Phone_Record(); void Write_Phone_Record(const phonerec& phone); In the first function, phone is an "in/out" parameter so it is declared as a pointer (alternatively it could be declared as a non-const reference). The second function does not use the value of the existing phone record but simply returns a new one. In the third function, phone is an "in" parameter; it could be passed by value but it is more efficient to declare it as a const reference. > void Input_New_Record(struct phonerec phone) > { > cout << "Enter The First Name: "; > cin >> phone.fname; > cout << endl << "Enter The Last Name: "; > cin >> phone.lname; > cout << endl << "Enter The Phone Number: "; > cin >> phone.number; > Write_To_File(phone); > } > > void Write_To_File(struct phonerec phone) > { > ofstream outdata; > outdata.open("phonebook.dat",ios::app); > outdata << phone.fname; > outdata << ","; > outdata << phone.lname; > outdata << ","; > outdata << phone.number; > outdata << endl; > outdata.close(); > } The following function is essentially equivalent to the one above but is, I think, a little more concise and readable. Also the parameter is declared as a const reference which reduces unnecessary copying of the phonerec structure. void Write_Phone_Record(const phonerec& phone) { ofstream outdata("phonebook.dat", ios::app); outdata << phone.fname << ',' << phone.lname << ',' << phone.number << endl; } > int Menu() > { > int choice; > while(choice != 1 && choice !=2 && choice !=3) > { > cout << endl << endl << endl; > cout << "1. Input New Record" << endl; > cout << "2. Search For A Record" << endl; > cout << "3. Quit Program" << endl; > cout << "Please Enter A Choice: "; > cin >> choice; > } > return choice; > } > > Thank you once again. And also how valuable are unions? They have their place, but for the most part they're dangerous and evil. > From what I have > glanced at all it is is a renamed structure or something along that line. There's a crucial difference. All the members of a union share the same storage. So if you have a union of, say, an int, a long, and a char*, only one of those members is actually valid at any given time -- and it's up to you the programmer to know which. It looks like you've picked a good learning excercise. Good luck! - ]
http://coding.derkeiler.com/Archive/C_CPP/comp.lang.cpp/2003-11/1417.html
crawl-002
refinedweb
1,004
65.12
domoticz motion(type)sensors don't show battery level hello. i build an motion sensors that works great but if i select sensor type on domoticz like "motion sensor", the battery level from "devices" disappear. That only happens on "motion sensor type", if i select other like on/off type ,the level appears but than i can't use the "disable after x seconds" feature present only on motion sensor type. any one have this problem? i can't find if its an domoticz bug or mysensors , or what what happens code is bellow but i think it's ok because if i select other type of sensor ,on domoticz, battery status work good. .thanks. void setup() { pinMode(DI_SENSOR1, INPUT); //pinMode(DI_SENSOR2, INPUT); // sets the motion sensor digital pin as input analogReference(INTERNAL); } void presentation() { // Send the sketch version information to the gateway and Controller sendSketchInfo("Motion Sensor", "1.0"); // Register all sensors to gw (they will be created as child devices) present(CHILD_ID, S_MOTION); } void loop() { int sensorValue = analogRead(BATTERY_SENSE_PIN); float vBat = static_cast<float>(sensorValue * (8.2/1023)); #ifdef MY_DEBUG Serial.print("A0: "); Serial.println(sensorValue); Serial.print("Battery Voltage: "); Serial.println(vBat); #endif delay(500); int batteryPcnt = static_cast<int>(((vBat-6)/(8.4-6))*100.); delay(500); // ((1e3+150)/150)*1.1 = Vmax = 8.43 Volts // 8.43/1023 = Volts per bit = ~0.00804 #ifdef MY_DEBUG Serial.print("Battery percent: "); Serial.print(batteryPcnt); Serial.println(" %"); #endif if (oldBatteryPcnt != batteryPcnt) { // Power up radio after sleep sendBatteryLevel(batteryPcnt); oldBatteryPcnt = batteryPcnt; } //motion bool tripped = digitalRead(DI_SENSOR1) == HIGH; Serial.println(tripped); send(msg.set(tripped?"1":"0")); sleep(digitalPinToInterrupt(DI_SENSOR1), RISING, 0); } I have 2 motion sensors on Domoticz, and they both show the battery level. Maybe it is because your level doesn't get sent often enough. I do send a battery level every 30 minutes even if the value hasn't changed (which is way too often. But, I am still experimenting with these nodes.) Or, maybe it has to do with the Domoticz version. My Domoticz version is 2020.2 My version it's V4.11207 .I can't upgrade more without upgrade Os from "strecht"to new raspbian Os. Shouldn't be the sensor update frequency because if i go to domoticz now and just change sensor type to" on/off switch" ,battery level just appears there on debices. I think that i have to upgrade everyting...Os and domoticz but its a pain,because i have to pair zwave devices from shutters again...and probably new bugs appear.... My thought is;linux that work...don't touch I know what you mean. I have several Pi's. I upgraded them from Stretch to Buster using instructions found here I only got the courage to ugrade my domoticz server after having upgraded 3 others first with no problems. But it did work. On a new card i updated OS to Raspian Buster and installed latest domoticz V 2.2020. BUT the problem still the same . no battery value present soon as this sensor report a new "data" AND it's as motion sensor and not as any other type of sensor. If it works to others i really don't understand what happens...
https://forum.mysensors.org/topic/11529/domoticz-motion-type-sensors-don-t-show-battery-level/5
CC-MAIN-2021-10
refinedweb
535
59.3
Hey, I'm trying to overload the assignment operator '+' to add two objects. I need to add throttle sample2 and throttle sample3. I've tried several things and keep getting errors. Here is what I am working on... Code://Operator fxn outside class #include <iostream> #include <cstdlib> using namespace std; class throttle { public: throttle(); //default constructor function throttle(int size);//other constructor throttle(throttle ©);//copy constructor throttle operator+(throttle& temp, throttle& temp2); int get_pos(){return position;} int get_max(){return max;} void shut_off(); void shift(int amount); double flow() const; bool is_on() const; private: int position; int max; }; throttle::throttle() { max=1; position=0; } throttle::throttle(int size) { max=size; position=0; } throttle::throttle(throttle ©) { max=copy.max; position=copy.position; } //operator fxn declaration outside of class void throttle::shut_off() {position=0; } void throttle::shift(int amount) { position += amount; if(position<0) position=0; else if (position>max) position=max; } double throttle::flow()const { return position/6.0; } bool throttle::is_on() const { return (flow()>0); } int main() { throttle total; throttle sample(10); sample.shift(5); throttle sample2(sample); throttle sample3(sample); int user_input; cout << "I have 2 throttles with 10 positions." << endl; cout << "Where would you like to set the throttle?" << endl; cout << "Please type a number 0 to 10: "; cin >> user_input; sample2.shut_off(); sample2.shift(user_input); cout << "Second Throttle." << endl; cout << "Where would you like to set the throttle?" << endl; cout << "Please type a number 0 to 10: "; cin >> user_input; sample3.shut_off(); sample3.shift(user_input); while (sample2.is_on()) { cout << "The flow for throttle one is now " << sample2.flow() << endl; sample2.shift(-1); } cout << "The flow is now off" << endl; while (sample3.is_on()) { cout << "The flow for throttle two is now " << sample3.flow() << endl; sample3.shift(-1); } cout << "The flow is not off" << endl; //adding two throttles return EXIT_SUCCESS; }
http://cboard.cprogramming.com/cplusplus-programming/44544-operatorplus-overloading.html
CC-MAIN-2016-18
refinedweb
298
50.73
How to Transpose a Collection in Scala [Snippets] How to Transpose a Collection in Scala [Snippets] These quick snippets will teach you how to transpose a Map of Lists into a List of Maps and how to transpose a List of Lists. Join the DZone community and get the full member experience.Join For Free The CMS developers love. Open Source, API-first and Enterprise-grade. Try BloomReach CMS for free. Goal You want to transpose a Map of Lists to a List of maps. Solution def main(args: Array[String]) { val m = Map( "breakfast" -> List("cereals", "omelet", "fruits"), "lunch" -> List("sandwich", "salad", "steak"), "dinner" -> List("pasta", "taco", "soup")) val dietList = m.map { case (k, vs) => vs.map(k -> _) }.toList.transpose.map(_.toMap) print(dietList) Output List( Map(breakfast -> cereals, lunch -> sandwich, dinner -> pasta), Map(breakfast -> omelet, lunch -> salad, dinner -> taco), Map(breakfast -> fruits, lunch -> steak, dinner -> soup) ) Goal You want to transpose a List of Lists. Solution def main(args: Array[String]) { val list = List(List("a1", "a2", "a3", "a4"), List("b1", "b2", "b3", "b4"), List("c1", "c2", "c3", "c4")) val transposedList = list.transpose println(transposedList) } Output List( List(a1, b1, c1), List(a2, b2, c2), List(a3, b3, c3), List(a4, b4, c4) ) }}
https://dzone.com/articles/how-to-transpose-a-collection-in-scala?fromrel=true
CC-MAIN-2018-43
refinedweb
207
63.7
How can I create a game timer? Hello all! I've been working on a monopoly clone in Python, and I was hoping to be able to add a stopwatch kind of thing, and whenever the game hits the 30-40 minute mark the game will end, and whoever has the most money wins. I'm not that great at Python yet, so I don't know how to make one myself. Would the time module have some sort of timer or stopwatch command? Thanks in advance! Voters RhinoRunner (692) time.perf_counter() might work. import time length_of_game = 0 while True: turn_start = time.perf_counter() #time at start #put the game loop stuff for playing monopoly here turn_end = time.perf_counter() #time at end how_long = int(turn_end) - int(turn_start) #amount of time in between, in seconds as an integer length_of_game += how_long if length_of_game >= 2100: break #ends loop if the time is >= 35 minutes here's a link. It'll help.
https://replit.com/talk/ask/How-can-I-create-a-game-timer/127825
CC-MAIN-2021-17
refinedweb
157
82.04
Hi Antony, As of v8 of the RISC-V QEMU target patch series, you can now define the reset vector in your CPU initializer: Michael. On Fri, Jan 5, 2018 at 6:53 AM, Antony Pavlov <antonynpav...@gmail.com> wrote: > On Thu, 4 Jan 2018 20:33:57 +1300 > Michael Clark <m...@sifive.com> wrote: > > > On Thu, Jan 4, 2018 at 7:47 PM, Antony Pavlov <antonynpav...@gmail.com> > > wrote: > > > > > On Wed, 3 Jan 2018 13:44:07 +1300 > > > Michael Clark <m...@sifive.com> wrote: > > > > > > > Add CPU state header, CPU definitions and initialization routines > > > > > > > > Signed-off-by: Michael Clark <m...@sifive.com> > > > > --- > > > > target/riscv/cpu.c | 338 ++++++++++++++++++++++++++++++ > +++++++++ > > > > target/riscv/cpu.h | 363 ++++++++++++++++++++++++++++++ > > > ++++++++++++ > > > > target/riscv/cpu_bits.h | 411 ++++++++++++++++++++++++++++++ > > > ++++++++++++++++++ > > > > 3 files changed, 1112 insertions(+) > > > > create mode 100644 target/riscv/cpu.c > > > > create mode 100644 target/riscv/cpu.h > > > > create mode 100644 target/riscv/cpu_bits.h > > > > > > > > diff --git a/target/riscv/cpu.c b/target/riscv/cpu.c > > > > > > ... > > > > > > > +static void riscv_cpu_reset(CPUState *cs) > > > > +{ > > > > + RISCVCPU *cpu = RISCV_CPU(cs); > > > > + RISCVCPUClass *mcc = RISCV_CPU_GET_CLASS(cpu); > > > > + CPURISCVState *env = &cpu->env; > > > > + > > > > + mcc->parent_reset(cs); > > > > +#ifndef CONFIG_USER_ONLY > > > > + tlb_flush(cs); > > > > + env->priv = PRV_M; > > > > + env->mtvec = DEFAULT_MTVEC; > > > > +#endif > > > > + env->pc = DEFAULT_RSTVEC; > > > > > > The RISC-V Privileged Architecture Manual v1.10 states that > > > > > > The pc is set to an implementation-defined reset vector. > > > > > > But hard-coded DEFAULT_RSTVEC leaves no chance for changing reset > vector. > > > > > > Can we add a mechanism for changing reset vector? > > > > > > > That can be added very easily at some point when necessary. > > > > All 5 RISC-V machines in the QEMU port currently have their emulated Mask > > ROMs at 0x1000 so its not necessary until we add a machine that needs a > > different value. I certainly wouldn't reject a patch that adds that > > functionality if we had a machine with a different reset vector, although > > given we have 5 machines using the same vector, it may remain a sensible > > default. I would think twice about adding a property that no machines > sets, > > or duplicate code and have all machines set their reset vector even when > > they are all the same? Shall we add the functionality when we need it? > > Actually it is me who needs this functionality. > > At the moment my board code needs this dirty hack: > > > bfc8221d89b9bb828f3742f17eb89d8513a75aae#diff- > 429448b1b26e0bc4256cc290758c0ab5 > > > > > I'd categorise this as a feature request. #define DEFAULT_RSTVEC > 0x00001000 > > is the "implementation-defined reset vector" > > > > Folk on the RISC-V mailing list are actually seeking guidance on the > blanks > > in the RISC-V specification so it may be that a de-facto standard emerges > > for some of these "implementation defined" blanks, in which case it may > > become part of a platform spec (vs the ISA spec). > > > > E.g. there is the "reset-hivecs" property in the ARM emulation code > > > so SoC-specific code can change reset vector. > > -- > Best regards, > Antony Pavlov >
https://www.mail-archive.com/qemu-devel@nongnu.org/msg518504.html
CC-MAIN-2018-39
refinedweb
461
64.71
I am trying to write a python script that will create a new object attribute containing the parcel area for any number of parcels I’ve selected in the scene. I know I need to use Export (Reporting) python script to fetch the value of a rule attribute. Proposed method: - Select the desired parcels in the scene - Run a python script that assigns the CGA rule “calculateParcelArea.cga” to each of the parcels, generates the models using “calculateParcelArea.cga”, and reports the area in the Parcel_Area row, under the sum column. - The python script then fetches the reports for each of the parcels, creates a new object attribute named ‘parcelArea’ for each parcel, and assigns the reported value. So far I’ve written a regular python (Module: Main) script that assigns the “calculateParcelArea.cga” to the selected parcels, generates the models with areas saved to rule attribute ‘parcelArea_Calc’, and reports the value. I’m having difficulty with the Export (Reporting) python module. Can someone help me make sense of this? How do I bring the existing script into the Export (Reporting) python module to complete the task? Thanks! Python script and CGA rule below: _____________________________________________________________________________________ ''' Created on 2017-07-26 @author: bcbd ''' from scripting import * # get a CityEngine instance ce = CE() def parcelArea(): shapes = ce.getObjectsFrom(ce.selection, ce.isShape) for shape in shapes: ce.setRuleFile(ce.selection(), 'calculateParcelArea.cga') # assign CGA rule calcParcelArea ce.setStartRule(ce.selection(), 'Lot') ce.generateModels(ce.selection()) if __name__ == '__main__': parcelArea() pass _____________________________________________________________________________________ /** * File: calculateParcelArea.cga */ version “2017.0” attr parcelArea_Calc = geometry.area Lot --> report("Parcel_Area", parcelArea_Calc) print("Parcel_Area: " + parcelArea_Calc) _____________________________________________________________________________________ I don't think you want to try to get the rule attribute. In Python, you could either get the initial value set in the cga file for this attribute or the user set value (e.g. if you want to get the value the user sets in the Inspector), but you don't want either of these values, and instead you want a value that is calculated within a rule. Therefore, I think you want to get the reported value for the parcel area. For each parcel shape, you can get the reported value for parcel area and then assign this to an object attribute of the parcel shape. To do this, create a Python Main script and a Python Export script (right click on scripts -> New -> Python Module). The following code assumes that a cga rule that reports the parcel area to "ParcelArea" has been applied to the selected parcel shapes. The script reads the value for "ParcelArea" and sets an object attribute called "parcelArea" to have this value. In your Python Main script, run the export script on your desired set of shapes. In your Python Export script (called exportScript.py in above code), you only need to add two lines (8 and 11) to the end of the finishModel() method. Beware that if you change your parcel shapes (e.g. resize them), then the object attribute won't have the correct parcel area anymore, which also means that your buildings will not be receiving the correct parcel area, and you'll have to rerun the python script to update the object attribute.
https://community.esri.com/thread/199022-using-python-to-create-an-object-attribute-from-a-rule-attribute
CC-MAIN-2018-43
refinedweb
533
63.59
I want to make a pine cone with its natural form using python scripting. Anybody working on the same problem? you might want to read through The Algorithmic Beauty of Plants, it covers cones in chapter 4 together with a good tutorial video from which you might get this as a starting point: import Rhino import scriptcontext import rhinoscriptsyntax as rs import math def Phyllotaxis(): c = 4 pts = [] for n in xrange(1,1000): a = n * math.radians(137.5) r = c * math.sqrt(n) x = r * math.cos(a) y = r * math.sin(a) pt = Rhino.Geometry.Point3d(x,y,0) pts.append(pt) rs.AddPointCloud(pts) Phyllotaxis() _ c. @clement Thank you for your reply. I already got inspiration from Daniel’s video on YouTube. But now I want to create Pine structure and nor able to write the script. It would be helpful for me if you could explain a = n * math.radians(137.5) code of line. I am not getting how are you multiplying angel with for loop iteration. Regards Kuldeep Hi @kggadhavi, this line just multiplies the step angle for each loop. Since the formula works using a circular measure in radians, the angle is converted from degree to radians. I guess that the conversion can also happen outside of the loop, but the multiplication with n (the loop counter) must remain in the loop. btw. changing the angle has significant impact on the result. You probably found that already, here is a video what changes if the angle is modified during the loop… _ c.
https://discourse.mcneel.com/t/cone-with-phyllotaxis-structure/52661
CC-MAIN-2022-21
refinedweb
262
67.25
libssh2_channel_read_ex - read data from a channel stream #include <libssh2.h> ssize_t libssh2_channel_read_ex(LIBSSH2_CHANNEL *channel, int stream_id, char *buf, size_t buflen); ssize_t libssh2_channel_read(LIBSSH2_CHANNEL *channel, char *buf, size_t buflen); ssize_t libssh2_channel_read_stderr(LIBSSH2_CHANNEL *channel, char *buf, size_t buflen); Attempt to read data from an active. channel - active channel stream to read from. stream_id - substream ID number (e.g. 0 or SSH_EXTENDED_DATA_STDERR) buf - pointer to storage buffer to read data into buflen - size of the buf storage libssh2_channel_read and libssh2_channel_read_stderr are macros. Actual number of bytes read or negative on failure. It returns LIBSSH2_ERROR_EAGAIN when it would otherwise block. While LIBSSH2_ERROR_EAGAIN is a negative number, it isn't really a failure per se. Note that a return value of zero (0) can in fact be a legitimate value and only signals that no payload data was read. It is not an error. LIBSSH2_ERROR_SOCKET_SEND - Unable to send data on socket. LIBSSH2_ERROR_CHANNEL_CLOSED - The channel has been closed. libssh2_poll_channel_read This HTML page was made with roffit.
https://libssh2.org/libssh2_channel_read_ex.html
CC-MAIN-2021-43
refinedweb
160
51.04
Components is the basic building blocks of React UI. Every React project consist of different type of components which can communicate each other, manage its own state and they are reusable. There two types components, functional components and class components. We are focusing on the first in this post. A functional component is a JavaScript functions which return some web element such as <Div> or it can be any HTML element. Lets create our first functional component Create a React project from scratch and locate the App.js file under src folder and delete everything within <div className = “App” > If you don’t know how to start a React Project here is the Guide for you. Create functional component Create new folder named components under src folder and create a file called Message.js with following content. (You can do this easily with VS Code and ES7 React extension by using rfce command) import React from 'react' .... function Message() { return (<div> <h1 > Hellow < /h1> </div>) } The component simply return a Hello message. In App.js which is the main component , we can use inside the App Div as import Message from './components/Message' ..... .... function App() { return ( < div </div> ); Run the project using npm start Props or properties What about passing some values to the component which make it more dynamic. With the help props we can pass some values to the component like <Message person='Chris'/> We have to modify the component as import React from 'react' .... function Message(props) { return (<div> <h1 > Hellow {props.person} < /h1> </div>) } Child components May be you already noticed that component inside <Message> <p>This is a functional component </p> </Message> didn’t show up yet. For this we have specify the props children ( variable always specified inside the { } , curly braces in React. ). import React from 'react' .... function Message(props) { return (<div> <h1 > Hellow {props.person} < /h1> {props.children} </div>) } Now you know how to create a functional component in React. It can be a piece of input box with awesome styles or it can be simple box, it us up to you , the developer
https://developerm.dev/2020/11/21/create-react-functional-component/
CC-MAIN-2021-17
refinedweb
351
64.3
Classes are the basic units of programming in the object-oriented programming. In this Java tutorial, learn to write classes and how to create objects in Java. 1. Difference between a Class and an Object In Java, objects are containers like data structure which have state and behavior. Objects represent the actors in the system or the application. For example, in a Human Resource application, the main actors are Employee, Manager, Department, or Reports, etc. An object is an instance of a class. The classes are the template that describes the state and behavior of its objects. A class can be used to create multiple objects. which are similar in structure but can have different states. 2. How to declare a Class The general syntax for declaring a class in Java is: <<modifiers>> class <<class name>> { // fields and members of the class } - A class declaration may have zero or more modifiers. - The keyword classis used to declare a class. - The <<class name>> is a user-defined name of the class, which should be a valid identifier. - Each class has a body, which is specified inside a pair of braces ({ … }). - The body of a class contains its different components, for example, fields, methods, etc. For example, public class Main { // Empty body for now; Write we own } Types of Classes In Java, we can have two types of classes. - Abstract class – These classes are abstract. These are incomplete classes. It means you cannot create an instance of this class. You can only extend these classes to complete their specification. - Non-abstract class – These classes define their full state and behavior. They are complete classes. You can create objects of this class. 3. Ingradiants of Java Classes In Java, classes are used as templates to create objects. A class in Java may consist of five primary components. i.e. - Fields - Methods - Constructors - Static initializers - Instance initializers Fields and methods are also known as class members. Constructors and both initializers are used to during initialization of class i.e. creating objects using class template. Constructors are used for creating objects of a class. we must have at least one constructor for a class (if we don’t declare explicitly then JVM inject default constructor for us). Initializers are used to initialize fields of a class. We can have zero or more initializers of static or instance types. Fields Fields of a class represent properties (also called state attributes) of objects of that class. The fields are declared inside the body of the class. The general syntax to declare a field in a class is: public class Main // A field declaration <<modifiers>> <<data type>> <<field name>> = <<initial value>>; } Suppose every object of the ‘Human’ class has two properties: a name and a gender. The human class should include declarations of two fields: one to represent the name and one to express gender. public class Human { String name; String gender; } Here the Human class declares two fields: name and gender. Both fields are of the String type. Every instance (or object) of the Human class will have a copy of these two fields. Methods or Functions A Java method is a collection of statements that are grouped together to operate. Methods are generally used to modify the state of class fields. Methods also can be used to delegate tasks by calling methods in other objects. In Java, methods may – - accept zero or more arguments - return void or a single value - be overloaded – means we can define more than one method with same name but different syntax - be overrided – means we can define methods with same syntax in parent and child classes public class Human { String name; String gender; public void eat() { System.out.println("I am eating"); } } Constructors A constructor is a named block of code that is used to initialize an object of a class immediately after the object is created. The general syntax for a constructor declaration is: <<Modifiers>> <<Constructor Name>>(<<parameters list>>) throws <<Exceptions list>> { // Body of constructor goes here } - A constructor can have its access modifier as public, private, protected, or package-level (no modifier). - The constructor name is the same as the simple name of the class. - The constructor name is followed by a pair of opening and closing parentheses, which may include parameters. - Optionally, the closing parenthesis may be followed by the keyword throws, which in turn is followed by a comma-separated list of exceptions. - Unlike a method, a constructor does not have a return type. - We cannot even specify void as a return type for a constructor. If there is any return type, then it is a method. - Remember that if the name of a construct is the same as the simple name of the class, it could be a method or a constructor. If it specifies a return type, it is a method. If it does not specify a return type, it is a constructor. Instance Initialization Block We saw that a constructor is used to initialize an instance of a class. An instance initialization block, also called instance initializer, is also used to initialize objects of a class. An instance initializer is simply a block of code inside the body of a class, but outside of any methods or constructors. An instance initializer does not have a name. Its code is simply placed inside an opening brace and a closing brace. Note that an instance initializer is executed in instance context, and the keyword this is available inside the instance initializer. public class Main { { //instance initializer block } } - we can have multiple instance initializers for a class. - All initializers are executed automatically in textual order for every object we create. - Code for all instance initializers are executed before any constructor. - An instance initializer cannot have a return statement. - It cannot throw checked exceptions unless all declared constructors list those checked exceptions in their throws clause. public class Main { //instance initializer { System.out.println("Inside instance initializer"); } //constructor public Main() { System.out.println("Inside constructor"); } public static void main(String[] args) { new Main(); } } Output: Inside instance initializer Inside constructor Static Initialization Block - A static initialization block is also known as a static initializer. - It is similar to an instance initialization block except it is used to initialize a class. - An instance initializer is executed once per object whereas a static initializer is executed only once for a class when the class definition is loaded into JVM. - To differentiate it from an instance initializer, we need to use the statickeyword in the beginning of its declaration. - we can have multiple static initializers in a class. - All static initializers are executed in textual order in which they appear, and execute before any instance initializers. A static initializer cannot throw checked exceptions. It cannot have a return statement. public class Main { //static initializer static { System.out.println("Inside static initializer"); } //constructor public Main() { System.out.println("Inside constructor"); } public static void main(String[] args) { new Main(); } } Output: Inside static initializer Inside constructor How to Create Java Objects In Java, to create an object from a class, use new keyword along with one of its constructors. <<Class>> <<variable>> = new <<Call to Class Constructor>>; //e.g. Human human = new Human(); Remember, when we do not add a constructor to a class, the Java compiler adds one for us. The constructor that is added by the Java compiler is called a default constructor. The default constructor accepts no arguments. The name of the constructor of a class is the same as the class name. The new operator is followed by a call to the constructor of the class whose instance is being created. The new operator creates an instance of a class by allocating the memory in a heap. The ‘null’ Reference Type Java has a special reference type called null type. It has no name. Therefore, we cannot define a variable of the null reference type. The null reference type has only one value defined by Java, which is the null literal. It is simply null. The null reference type is assignment compatible with any other reference type. That is, we can assign a null value to a variable of any reference type. Practically, a null value stored in a reference type variable means that the reference variable is referring to no object. // Assign the null value to john Human john = null; // john is not referring to any object john = new Human(); // Now, john is referring to a valid Human object Note that null is a literal of the null type. We cannot assign null to a primitive type variable, and that’s why the Java compiler does not allow us to compare a primitive value to a null value. That’s all for this very basic tutorial about creating classes in java. Happy Learning !!
https://howtodoinjava.com/java/basics/java-classes-objects/
CC-MAIN-2022-27
refinedweb
1,462
56.15
The reliability is a Siemens standard but now they have simplicity with the SIMATIC IOT2000 series. The industrial gateway of choice in factories and institutions exploring the SIMATIC IOT2000 series harmonizes, analyzes, and forwards data efficiently with common protocols like MQTT and Modbus. Based on a Yocto Linux, the SIMATIC IOT2000 series includes the IoT2020 and IoT2040 models which can manage its own automation systems. This incredible gateway harmonizes the communication between various data sources effectively over long distances and in electrically noisy environments, analyses it, and forwards it to the corresponding recipients, offering a solution that can be easily implemented and perfect for retrofitting. Available in two versions, the IoT 2020 designed for educational institutions and public spaces while the IoT 2040 is optimized for Industrial environments. If you'd like to learn more check out the SIMATIC IOT 2000 support and forums. In this guide we detail the integration of the Siemens SIMATIC IOT 2000 with Ubidots, using an external device serial communicated through RS-485 interface with the SIMATIC IOT 2000 and configuring a flow in Node-RED to transmit the data obtained to Ubidots over MQTT. Requirements - Ethernet cable - SD Card - 24V power supply - Ubidots account - Educational License - Business License Setting up the SIMATIC IOT2000 First, you must register with or have access to Siemens Support Portal to download all initial configurations. This portal will also provide troubleshooting and support from Siemens on any hardware related inquires. The entire IOT2000 series is setup the same way, please follow this tutorial for any devices in the series. Setup: - Burn and Install the SD-Card - First commissioning of the SIMATIC IOT2000 - Hardware Setup - Visualizing your data in Ubidots Burn and Install the SD-Card Example Image I: Burn and Install the SD-Card 1. Begin by burning the SD-Card with the image provided by the Siemens Industry Online Support page. Please, download and save Example_Image_V2.1.3 for later. 2. Insert the microSD-Card into the SD-Card slot of your computer (an adaptor may be needed). 3. Unzip the downloaded image and burn it to the SD-Card. Microsoft users click here for how to burn images to your SD-Card. Linux users please continue reading. IMPORTANT NOTE: Make sure the SD-Card is formatted before burn the image into it. - Linux: 1. Open your computer terminal and go to the folder where the zip file was. downloaded using the cd command, i.e.: I downloaded the file into the "Downloads" directory: cd Downloads 2. Unzip the downloaded file running the command below: sudo unzip 109741799_Example_Image_V2.1.3.zip Once the zip file was properly unzipped you will see a file named example-V2.1.3.wic as is shown above. NOTE: If you get an error running the command above verify if the name of the file downloaded is the same one, if not replace it with the correct one. 3. Verify the location of the SD-card to unmount it and burn the image. Run the command below to verify the location: df -h The SD-card should be located it the directory /dev/...; in my case the sd card is located in the following directory /dev/mmcblk0 4. Umount the SD-Card running the command below: umount /dev/mmcblk0 5. To burn the image, replace the name of the file unzipped and the location of the SD-Card; the structure of the command is as follows: sudo dd bs=1M if={name_of_the_image} of={SD_location} Once the parameters are replaced with the correct ones, the command should look similar to the following: sudo dd bs=1M if=example-V2.1.3.wic of=/dev/mmcblk0 NOTE: Running this command make take a couple minutes, please be patient. Install your SD-Card Connect your SD-Card into your hardware. Below we have installed the SD-Card into the SIMATIC 2040 where indicated. II: First commissioning of the SIMATIC IOT2000 The following steps show how to access the SIMATIC IOT2040 using the static IP to setup the gateway's network. At this point is important to mention that the SIMATIC IOT 2040 brings DHCP Address by default in the Ethernet Port - X2P1, if your desire you can access directly using the IP address assigned. 1. Power off and Connect one end of the Ethernet Cable to your computer and the other to the Ethernet Port- X1P1 of the SIMATIC IOT2000 device. CAUTION: Only use a DC 9...36V power supply! 2. Once the SIMATIC IOT2000 is powered on, you will see the following behavior on the LEDs of the gateway: - PWR: Solid; device turned ON - SD: Intermittent.... then Solid turned OFF - USB: Solid; device turned ON The SD LED will be intermittent because is resizing the SD card with the image, wait until the SD LED change it status to Solid turned OFF to access to the gateway. 3. The SIMATIC IOT2000 lets you access to via Serial, SSH or Telnet; this guide uses the SSH connection. The SIMATIC IOT2000 has a static IP address by default -> 192.168.200.1 . To establish a SSH connection, your computer have the same subnet as the SIMATIC IOT2000. If you are working with Microsoft, please reference this getting started guide for how to access the gateway. Linux users please continue with the following steps. 4. Once the network of your computer is configured on the same subnet of the SIMATIC IOT2000, verify its connectivity with a ping: ping 192.168.200.1 Expected result: PING 192.168.200.1 (192.168.200.1) 56(84) bytes of data. 64 bytes from 192.168.200.1: icmp_seq=1 ttl=64 time=1.04 ms 64 bytes from 192.168.200.1: icmp_seq=2 ttl=64 time=1.03 ms 64 bytes from 192.168.200.1: icmp_seq=3 ttl=64 time=1.00 ms If you receive the expected result the SIMATIC IOT2000 is properly connected. 5. Access to the gateway running the command below: ssh root@192.168.200.1 Upon first accessing the Gateway you will be prompted to approve the security message. Send the command yes and press enter to approve and continue. Once access is properly established you will see the following root in your terminal: root@iot2000:~# 6. As mentioned above, the static IP address of the SIMATIC IOT2000 is set to 192.168.200.1 . Thus, if another static IP address or DHCP address is required, this can be set in the "interfaces" file in the "/etc/network" directory. To do this, enter to the directory specified with the command below: cd /etc/network/ Open the interfaces file using nano editor running the following command: nano interfaces The content of the interfaces file by default be the same as below. # /etc/network/interfaces -- configuration file for ifup(8), ifdown(8) # The loopback interface auto lo iface lo inet loopback # Wired interfaces auto eth0 iface eth0 inet static address 192.168.200.1 netmask 255.255.255.0 auto eth1 iface eth1 inet dhcp As mentioned above, If you are working with the SIMATIC IOT2040 the DHCP Address is configure by default on the second port (X2 P1LAN). Ensure your Ethernet cable is connected to the second Ethernet port and reboot the gateway. If you are working with the SIMATIC IOT2020 and desire to setup DHCP Address, you must modify the interfaces file as is shown below, then reboot the gateway: # /etc/network/interfaces -- configuration file for ifup(8), ifdown(8) # The loopback interface auto lo iface lo inet loopback # Wired interfaces auto eth0 iface eth0 inet dhcp Once the DHCP Address is configured you can use a network scanner app to know the new ip address assigned to the SIMATIC 2000, we highly recommend you use fing which is easy to use and is available in both Google's Play Store and Apple's App Store. III. Hardware Setup SIMATIC IOT2000 with Arduino (external device) Based on your environment and technical requirements, choose the best device to complete your project. Make sure you device is transmitting data through RS485. Our project calls for a Arduino UNO using a RS485 shield with an humidity sensor to transmit it values to Ubidots. - Hardware Setup: Fly-out Rule: To avoid any hardware issue please make sure that the SIEMENS IOT2000 is turned OFF before make the connections: Arduino connections 1. First attach the Arduino Grove Shield to the Arduino UNO and then attach the RS485 shield. 2. Connect the Humidity Sensor to A0 pinout of the Grove Shield using a grove cable. Once everything is properly attached your Arduino will look similar to below. 3. Verify if the headers of the RS485 shield are properly assigned with the configuration below: - P1 -> 5V - P2 -> TX_CTRL - D2 -> TX - D3 -> RX RS485 connections: Click here for more detailed information about the SIMATIC IOT 2000 operating instructions: 1. The X30 COM and X31 COM allow you work with RS232/RS422/RS485 interfaces; in this case we are going to work with the X30 COM - RS485. Connector Pinout: 2. Follow the table below to make the connection between the Arduino RS485 shield and the SIMATIC IOT2000: - Firmware Upload: 1. Open Arduino IDE. 2. Select the Arduino UNO from Tools > Board menu 3. Connect the Arduino UNO to your computer and select the port COM assigned from Tools > Port > Arduino UNO.. 4. Now with everything configured, copy and paste the code below in the Arduino IDE. #include <SoftwareSerial.h> int sensor = A0; SoftwareSerial mySerial(3,2); void setup() { mySerial.begin (9600); Serial.begin(9600); pinMode(sensor, INPUT); } void loop() { int sensor_value = analogRead(sensor); mySerial.println (sensor_value); Serial.println(sensor_value); delay(1000); } 5. Verify and upload the code choosing the "check mark" icon and then the "right-arrow" icon beside the check mark icon. Now your Arduino UNO is sending data to the Siemens SIMATIC IOT 2000 properly. SIMATIC IOT2000 with Node-RED Before starting with the Node-RED flow, we must establish some configurations in the SIMATIC IOT2000. Please, follow the steps below carefully to ensure the right functionality: Package manager: 1. Go to the opkg directory: cd /etc/opkg 2. Edit the opkg.conf file adding the lines below at the end of the file: src iotdk-all src iotdk-i586 src iotdk-quark src iotdk-x86 3. Next, edit the arch.conf file adding the lines below at the end of the file: arch i586 12 arch quark 13 arch x86 14 4. Update the configurations made with: opkg update 5. Write iot2000setup to open the setup interface and configure the X30 COM as RS-485. To do this, select Peripherals > Configure External COM Port > X30 > RS485: 6. Assign the baud-rate to the port with the command below: stty -F /dev/ttyS2 9600 7. Reboot the SIMATIC to save the changes with the command reboot: Node-RED: - Write the command below "in your computer's terminal" to enter to the Node-RED directory: cd /usr/lib/node_modules/ 2. Then install the node required by writing the following command: npm install -g node-red-contrib-modbus This process will take a couple of minutes so please be patient. NOTE: If you get an issue installing the node, see the following tips and tricks to troubleshoot. To start Node-RED type the command below: node /usr/lib/node_modules/node-red/red & Once the Node-RED started properly, you should see the behavior below in your SIMATIC IOT2000, this will take a couple of minutes: 3. Once the Node-RED is started, open a web-browser (firefox, preferably) and write the IP Address of the SIMATIC IOT2000 and the port 1880 (i.e.) to open the Node-RED web interface 4. Now click on Node-RED menu in the upper right corner, then “Import” -> “Clipboard” and paste the code below: [{"id":"38e1405b.5796d","type":"serial in","z":"c88a5f47.16d498","name":"rs-485","serial":"8bf5451a.2fb14","x":170.5,"y":223,"wires":[["f7937636.d26448","ae2f3a52.32f23"]]},{"id":"f7937636.d26448","type":"debug","z":"c88a5f47.16d498","name":"","active":true,"console":"false","complete":"false","x":377.5,"y":121,"wires":[]},{"id":"ae2f3a52.32f23","type":"function","z":"c88a5f47.16d498","name":"parse function","func":"var response = {};\nresponse.payload = {\"humidity\": msg.payload};\nresponse.topic = \"/v1.6/devices/siemens\";\nreturn response;","outputs":1,"noerr":0,"x":374.5,"y":223,"wires":[["51bcbd87.0af04c"]]},{"id":"51bcbd87.0af04c","type":"mqtt out","z":"c88a5f47.16d498","name":"","topic":"","qos":"","retain":"","broker":"cefb900f.f02ca8","x":605.5,"y":222,"wires":[]},{"id":"8bf5451a.2fb14","type":"serial-port","z":"","serialport":"/dev/ttyS2","serialbaud":"9600","databits":"8","parity":"none","stopbits":"1","newline":"\\n","bin":"false","out":"char","addchar":false},{"id":"cefb900f.f02ca8","type":"mqtt-broker","z":"","broker":"things.ubidots.com","port":"1883","clientid":"","usetls":false,"compatmode":true,"keepalive":"60","cleansession":true,"willTopic":"","willQos":"0","willPayload":"","birthTopic":"","birthQos":"0","birthPayload":""}] 5. Assign your Ubidots TOKEN as username in the security tab of the MQTT-broker node. If you don't know how to get your Ubidots TOKEN see this guide. Once the Ubidots TOKEN is assigned, press Deploy and the status of the serial and mqtt node should appear as connected. Also, if you wish to visualize the sensor value received, just press the debug tab: IV. Visualizing your data in Ubidots Go to the device section of your Ubidots account and see a new device created: Enter to the device and you will see the variable created with the real-time data of the sensor connected: If your desire to modify the name of the device and the variables, edit the parse function created in the Node-RED flow: Results In what felt like too easy of a process for hardware, we just integrated the SIMATIC IOT2000. We built this integration with starter equipment and simple know-how, with the right devices for your environment, you will be able to launch industrial applications in a matter of days instead of months. Now its time to create Ubidots Dashboards to visualize and interpret your data to control and monitoring your machines and environments remotely and keeping your clients happy and productions at its peak.
https://create.arduino.cc/projecthub/74113/connect-your-siemens-simatic-iot2000-to-ubidots-nodered-0fcae6
CC-MAIN-2020-29
refinedweb
2,345
53.81
java int tostring example is a java int tostring document that shows the process of designing java int tostring format. A well designed java int tostring example can help design java int tostring example with unified style and layout. java int tostring example basics When designing java int tostring document, it is important to use style settings and tools. Microsoft Office provide a powerful style tool to help you manage your java int tostring int tostring styles may help you quickly set java int tostring titles, java int tostring subheadings, java int tostring section headings apart from one another by giving them unique fonts, font characteristics, and sizes. By grouping these characteristics into styles, you can create java int tostring documents that have a consistent look without having to manually format each section header. Instead you set the style and you can control every heading set as that style from central location. you also need to consider different variations: convert int tostring java, convert int tostring java word, java class tostring, java class tostring word, java string tostring, java string tostring word, java long tostring, java long tostring word Microsoft Office also has many predefined styles you can use. you can apply Microsoft Word styles to any text in the java int tostring int tostring documents, You can also make the styles your own by changing how they look in Microsoft Word. During the process of java int tostring style design, it is important to consider different variations, for example, java int array tostring, java int array tostring word, javascript int tostring, javascript int tostring word, override tostring java, override tostring java word, java double tostring, java double tostring word. java int tostring example java what are the alternative methods for converting and integer to a string tostring your int value and concatenates both of them. example if you want to convert some number to string in loop then you can use new name java convert int to string example integer to string conversion is a basic task in many java projects. there are download the source code of this example inttostringtest.zip. converting between numbers and strings the java tutorials the number subclasses that wrap primitive numeric types byte , integer the tostringdemo example uses the tostring method to convert a number to a string java integer to string examples . another alternative method is to create an instance of integer class and then invoke int to string example this int to string java example shows how to convert int to string in java. int i . . to convert int to string, use. tostring int i . method of integer convert integer to java string object convert integer object to string object this example shows how a integer new integer use tostring method of integer class to conver integer into string. java java tostring method learning java in simple and easy steps a beginners example public class test public static void main string args integer x java lang integer tostring method java.lang.integer.tostring int i, int radix method example learning java.lang packages in simple and easy steps a beginners tutorial containing complete convert int to string convert language basics java convert int to string public class convertinttostring public static void main string args int aint string astring integer.tostring aint java integer tostring int i int radix method example java.lang.integer tostring int i, int radix . description this java tutorial shows how to use the tostring int i, int radix method of integer class
http://www.slipbay.com/java-int-tostring-example/
CC-MAIN-2017-17
refinedweb
585
54.46
SpreadsheetML is the XML vocabulary included with Excel 2003 as well as Excel XP. It consists of tags that can describe all aspects of an Excel spreadsheet. Just as you can with WordprocessingML, you can write the SpreadsheetML from scratch in an XML or text editor, or you can allow Excel 2003 or XP to generate the content for you automatically. SpreadsheetML documents start with an XML declaration and processing instruction. The root node <Workbook> includes references to a number of namespaces. < XML document has the following structure: <DocumentProperties> <!-- information about document properties --> </DocumentProperties> <ExcelWorkbook> <!-- information about the Excel workbook --> </ExcelWorkbook> <Styles> <!-- information about the styles --> </Styles> <Worksheet> <Table> <!-- multiple Column tags --> <Column /> <!-- multiple Row blocks --> <Row> <Cell> <!-- Cell data type and contents --> </Cell> <!-- multiple Cell tags --> </Row> </Table> <WorksheetOptions> <!-- information about the Worksheet options --> </WorksheetOptions> <Sorting> <!-- information about sorting --> </Sorting> </Worksheet> The contents of the Excel worksheet are contained within the <Table> element. The element contains two attributes, ExpandedColumnCount and ExpandedRowCount , which indicate the table size . The <Table> element contains a number of <Row> elements, which in turn contain <Cell> elements. A <Data> child element contains the content of each cell. It has an attribute Type , which indicates the datatype of the contents. Its also possible for a <Cell> to include a Formula attribute that reflects the Excel formula used to generate the data. When Excel opens a SpreadsheetML document, it wont prompt you about how to open the document. It opens the document natively, as if it was an Excel workbook. This is one of the advantages of working with SpreadsheetML documents. When you work with other XML documents, Excel prompts about how the file should be opened. If youre using Excel to generate XML content for Flash, you may find the structure of a SpreadsheetML document a little unwieldy. It contains formatting information that youre unlikely to need, and all of the content for inclusion within Flash will be in the <Row> and child <Cell> elements. Youd be better off exporting the XML content from Excel using an XML map to refine the document structure.
https://flylib.com/books/en/1.350.1.54/1/
CC-MAIN-2021-39
refinedweb
348
58.38
flutter_shogi_board 0.0.3 flutter_shogi_board # A shogi board widget for Flutter. This widget can be used to render static game board positions, tsume problems or shogi castles. Shogi (将棋) is a two-player strategy board game native to Japan, belonging to the same family as chess and xiangqi. Getting Started # Import the package # To import this package, simply add flutter_shogi_board as a dependency in pubspec.yaml dependencies: flutter: sdk: flutter flutter_shogi_board: Note that this package requires dart >= 2.3.0. Example # import 'package:flutter/material.dart'; import 'package:flutter_shogi_board/flutter_shogi_board.dart'; import 'package:shogi/shogi.dart'; void main() { runApp( MaterialApp( home: Scaffold( body: Padding( padding: const EdgeInsets.all(8.0), child: Center( child: ShogiBoard( boardPieces: ShogiUtils.initialBoard, ), ), ), ), ), ); } For more information, see the Flutter app in the example directory. Game Board Parameters # The widget is designed to be used in portrait mode, and fills the board size to match it's parents width. The board pieces are rendered as text. # This package grew out of my desired to visualize shogi castles in Flutter, and with no game board widget or even a shogi engine available, I decided to roll my own. The package shogi contains the initial business logic from this package and will be simultaneously developed upon. For the future I would like to utilize this widget not just for displaying static game boards, but also for tsume problems, thus user interaction may be considered. Moreover, presently the numbers 1-9 and 一, 二, 三, 四, 五, 六, 七, 八, 九 are not displayed to mark cell positions, this is something that could be offered as an optional boolean defaulting to true. Raising Issues and Contributing # Please report bugs and issues, and raise feature requests on GitHub. To contribute, submit a PR with a detailed description and tests, if applicable. [0.0.3] - 13/10/2019 - Moved business logic components from this package to new shogi package. [0.0.2] - 06/10/2019 - Fixed meta package version conflict ^1.1.7 with Flutter: 1.7.8+hotfix.4. [0.0.1] - 06/10/2019 - Initial release of flutter_shogi_board package for Flutter. example/README.md example # A Flutter project which demonstrates the flutter_shogi_board package. Getting Started # For help getting started with Flutter, view the online documentation, which offers tutorials, samples, guidance on mobile development, and a full API reference. Use this package as a library 1. Depend on it Add this to your package's pubspec.yaml file: dependencies: flutter_shogi_board: _shogi_board/flutter_shogi_board.dart'; We analyzed this package on Oct/utils/package_utils.dart. Run flutter format to format lib/src/utils/package_utils.dart. Format lib/src/widgets/board_cell.dart. Run flutter format to format lib/src/widgets/board_cell.dart. Format lib/src/widgets/shogi_board.dart. Run flutter format to format lib/src/widgets/shogi_board.dart. Maintenance issues and suggestions Use constrained dependencies. (-20 points) The pubspec.yaml contains 1 dependency without version constraints. Specify version ranges for the following dependencies: shogi. Package is pre-v0.1 release. (-10 points) While nothing is inherently wrong with versions of 0.0.*, it might mean that the author is still experimenting with the general direction of the API.
https://pub.dev/packages/flutter_shogi_board
CC-MAIN-2019-43
refinedweb
523
51.24
None 0 Points Jun 10, 2009 08:59 AM|anders@businessanalyze.no|LINK I am currently reviewing the use of SSRS 2008 and Report Builder 2.0 in our custom application as a supplement to our custom report engine. When rendering reports with the ReportViewer webcontrol in Local Mode I get the error: The report definition is not valid. Details: The report definition has an invalid target namespace '' which cannot be upgraded. The reason why I get this error is that VS 2008 only supports the SSRS 2005 schema, but I was informed that support for SSRS 2008 would be supported in VS 2010. Today I downloaded VS 2010 Beta 1 to test out this feature. I updated my references to Microsoft.ReportViewer.WebForm/Common version 10.0.0.0 but I still get the above error. Does anyone know if VS 2010 has implemented this feature in the Beta release or if the release version will support it? ssrs 2008 Visual Studio 2010 All-Star 28635 Points Jun 17, 2009 04:16 AM|Jian Kang - MSFT|LINK Hi, From your description, I think the issue is not related to the Visual Studio IDE but the SQL Server. What version of SQL Server do you have? I think it should be SQL Server 2005, right? In Visual Studio, when we work with SQL Server Reporting Services (SSRS) in local mode, we actually use the report processing engine which is installed with SQL Server. If we work with SSRS 2008, we need SQL Server 2008. We cannot downgrade a SSRS 2008 project to SSRS 2005. For more information, please refer to the links below: If there are few reports, I think we can re-design them with SSRS 2008. Otherwise, I would suggest you download and install SQL Server 2008 Express with Advanced Services from the following link: Related document: How to: Install SQL Server 2008 (Setup) 1 reply Last post Jun 17, 2009 04:16 AM by Jian Kang - MSFT
https://forums.asp.net/t/1433651.aspx
CC-MAIN-2020-29
refinedweb
330
63.29
Wiki Challenge11 / gdlog GDLog Usage Notes This is a short set of notes on the use of Oleg Babul's gdlog - they exist mainly so that I don't forget things! For simplicity, we'll assume that we are given a prime p, a generator g of ZZp and a value t in ZZp for which we wish to calculate an x such that t = gx mod p. Note: - in all time based outputs to gdlog, etis the estimated time to completion and, unless post-fixed with h, all timings are displayed in seconds - gdlog appears to require both its sieving polynomials to have 1 < degree <= 3 (which might limit its ability to be used to post-process relations collected by other NFS implementations?) - for the challenge: - average of 39 cores used over a 6 week period - phase 1 produced approximately 12 million relations within 3 weeks - phase 3 produced (after the challenge's submission deadline) the incorrect result of 10 607833 713671 622331 958593 898979 290746 974713 429220 998127 451286 349297 232203 445447 007724 535020 385315 291415 382670 421464, for t = 57 862149 747092 325030 167062 717207 431168 694932 216310 538267 343292 342318 477158 898286 092297 346029 386203 435452 141910 116025. - following the challenge, it appears that I have introduced a copying error in moving code from my commodity machines to the Huddersfield HPC. This mistake messed up the sieved relations with ensuing chaos! A fresh rerun of gdlog (on 16 cores) produced the following results: - phase 1 produced approximately 3.2 millions relations within 1 week (see ??) - phase 2 produced a log base within 3 weeks (see ??) - phase 3 required ? weeks and ? solution attempts in order to produce a correct answer of ??. Phase 1: Sieving This stage of the algorithm is embarrassingly parallel and aims at building a sufficiently large collection of relations and ideals. In order to do this, a pair of polynomials are first selected. The choice of these polynomials is critical to the runtime of this algorithm. The reader is referred to: - Polynomial Selection for the Number Field Sieve Integer Factorisation Algorithm by B.A.Murphy - Polynomial Selection for the Number Field Sieve by S.Bai - and Projections for GNFS polynomials for further information on these issues. For discrete logarithms in large prime fields (that are safe), you'll almost certainly need to manually choose your own polynomials, as the default choices can lead to very long run times. Here, we'll assume that: - p = 2q + 1, for q a prime - f0 and f1 are our two polynomials over ZZ[X] - and that m in ZZp is such that f0(m) = 0 mod p and f1(m) = 0 mod p. With a gdlog job file setup to (for example) contain (here: lc0Fact is the factorisation of the most significant coefficient of the f0 polynomial; and p1Fact is the factorisation of p-1): p: 64871953055083132442586738160300545132676055315639670194672701161688976212780255925431194294264487036940900075456699 q: g: 28874886502820635270988382873765249080724636489175670968600351015660554179871058627909746857890394896866174667024027 f0:[ -350341802863515235428874094709894204855 17716971180757166540477367604139645968 441472165546405738919812033359164963440 ] f1:[ 64 -99 -30 1 ] m: 39954570559566723571719449282650117197915782766741932890919455166435188457869286321758554960521414441796342496308655 lc0Fact: [2 2 2 2 5 7 9533 7866136993862153 10512940372551401] p1Fact: [2] job: gdlog we first need to generate a factor base for the interval of numbers over which we wish to sieve out relations and ideals. We do this via (this is a single threaded task): def gen_factor_base(start, cpus): end = start + cpus*1000000 p = subprocess.Popen("gdlg_sieve -q0" + start + " -q1" + end + " -fb -of gdlog.fb gdlog") return p.wait() Next, we perform lattice sieving to generate a collection of relation files. The following python function achieves this (here, this is a multi-process task): def lattice_sieve(start, cpus): sieveprocs = [] for cpu in range(0, cpus): start_slice = start + cpu*1000000 end_slice = start + cpu*1000000 p = subprocess.Popen("gdlg_sieve -tlattice -q0" + start_slice + " -q1" + end_slice + " -j gdlog.f -of gdlog_" + start_slice + "_" + end_slice + ".rel -if gdlog.fb gdlog") sieveprocs.append(p) for cpu in range(0, cpus): if sieveprocs[i].wait() != 0: sys.exit(1) You should now have a large collection of *.rel files. Please note that, with large integer intervals, this number of files can exceed the number of files allowed as arguments on the bash command line or similar (you can deal with this by cat'ing the results together!). It is essential to ensure that this set of files are properly formatted, or else time will be lost in performing the calculation (latter stages of the algorithm have not been coded as defensively as one might like!). Each line of a *.rel file should match the following EBNF: <int> <int>; [<int>]+; [<int>]+; The first two numbers are the numbers a and b (these specify a relation), and are such that gcd(a, b) = 1. The remaining number sequences specify the prime factorisations for two ideals I0 and I1. These numbers are such that: - bd(f0)*f0(a/b) = I0 mod p - and bd(f1)*f1(a/b) = I1 mod p where d(fi) is the degree of the polynomial fi (i = 0 or 1). By exploiting computing clusters (e.g. using 70 odd cores), one can generate sufficiently large sets of relations within about 1-2 weeks here. Phase 2: Building the Logbase This phase has parts that are multi-threaded. For computing clusters, the gdlog code really needs to be rewritten to take advantage of openmpi or similar. However, we found that by using the existing code on 48 core clusters, our speeds were tolerable (i.e 1-2 weeks). Should errors be thrown at this stage (e.g. Incorrect norm factorization), you'll need to stop the algorithm and deal with them (e.g. by locating the offending entry in gdlog.f and deleting it). Each line of the fact.bak file (generated by this phase), has the following EBNF format: <number of entries> (<number> <number>)+ <max int> 0 (<number> <number>)+ <max int> 0 here, <max int> is typically the value 2147483647 and each entry is a pair of integers. It is essential that each line of fact.bak be of the correct length and contain two <max int> record separators. Failure to ensure this means that the subsequent parsing of this file will generate incorrect results (which are typically reported during the parsing of fsys.bak!). Each line of fsys.bak file is such that: - the first line is the value m (see phase 1) - the second line has the number of relations followed by the distinct number of ideals present within the file - and all remaining lines match the EBNF <number of entries> (<number> <number>)+- these lines are generated from correspondingly indexed lines in fact.bak. The following python code is used to generate these files and the resulting logbase: def logbase(cpus): p = subprocess.Popen("gdlg_sys -d3 -useBackup -useGauss -th" + cpus + " -if gdlog.f -of gdlog.logbase gdlog") return p.wait() The generation of the wnSeq.bak file (produced by the Block Wiedemann algorithm) can be quite lengthy (on computing clusters, our jobs had to operate in 48 hour windows). Fortunately, the code (generating wnSeq.bak) is robust enough to correctly restart following a job termination. The generation of this file, and the checking of its solution, appear to be the computational bottlenecks in phase 2? Phase 3: Calculating a Discrete Logarithm Having generated our logbase, we may at long last attempt to perform a discrete logarithm calculation (this stage of the algorithm appears to be single-threaded and only took at most 2 days for our challenge scenario). If we have not generated a sufficiently large enough collection of relations in phase 1, then this phase may well fail, forcing us to generate more relations! Before the logarithm is actually calculated, a collection of virtual logarithms are first validated - whilst this check may be skipped, it doesn't take too long. It appears that this phase of the algorithm often terminates with an incorrect result. To cope with this, we run this phase multiple times (with the number we wish to calculate a discrete logarithm for multiplied by a known skew value). The following python code will hopefully(?) deliver your results (this code can obviously better exploit parallelism within multiple_dlog!): def dlog(t): p = subprocess.Popen("gdlg_dlog -t" + t + " -if gdlog.logbase -of gdlog.new.logbase." + t + " gdlog") return p.wait() def multiple_dlog(t, g, p, n): for i in range(0, n): k = randint(0, p) alt_t = (power_mod(g, k, p) * t) % p print "Skew value is g ^ " + k + " (subtract this number from a *valid* result in order to obtain log_g(t))" return dlog(alt_t) Updated
https://bitbucket.org/carlpulley/challenge11/wiki/gdlog
CC-MAIN-2019-13
refinedweb
1,409
62.07
Schema Scuffles and Namespace Painsby Edd Dumbill May 30, 2001 Leigh Dodds, after a well-deserved vacation, will be returning next week. Meanwhile, after the latest bout of XML conferences, I have the pleasure of casting the XML-Deviant's eye over some of May's developments in the XML developer community. Schema Scuffles The W3C XML Schema Definition Language was released as a Recommendation at the beginning of May, at the Tenth International World Wide Web Conference. After collective sighs of relief were heaved, it would be unrealistic to expect silence to descend on the topic. Kohsuke Kawaguchi posted a reference to an article, XML Schema Dos and Don'ts, which gives his best practice for keeping XML Schemas simple. His rather direct introduction states. For them, XML Schema is a new favorite toy. There has to be a different document. A document for those who use XML Schema for business --- for those who are at a loss how to use it. Kawaguchi's document provoked a considered response from Martin Gudgin, a member of the Schema Working Group, who disagreed over which features from XML Schema were disposable. One note of dissent in particular concerned the use of namespaces (what else?). Regarding local declarations. I have to take issue with your assertion that<foo:person xmlns: <familyName> KAWAGUCHI </familyName> <lastName> Kohsuke </lastName> </foo:person> is 'bad use of XML namespaces'. I have lots and lots of places where I use *exactly* that approach and it works very nicely for what I do. I don't think you can call this one way or the other. Neither approach is *wrong*, they're just different This complaint was the start of an extended debate on proper namespace usage. Kawaguchi's assertion is that the child elements inside the foo:person element should also be in the same namespace. Gudgin's counter was that there is more than one way to use namespaces, and his was equally valid, and indeed is used in the SOAP specification. Gudgin appealed to the notion that his way was more natural for data-oriented XML applications and more directly mirrored the approach a programming language takes to scoping names. public class Person { String lastName; String firstName; }... The debate bounced back and forth between the two protagonists, until Jonathan Borden intervened with a simpler solution. This argument seems hopelessly complicated. The most reasonable way to define a person name structure is:<person.name <given>Martin</given> <family>Gudgin</family> </person.name> why would anyone want to complicate this with different namespaces for each element of the structure? The central point of the debate is that child elements do not inherit their namespaces from a parent element. This seems relatively straightforward, but Gudgin pointed out that XML Schema allows types like <complexType name='person'> <sequence> <element name='given' type='string' /> <element name='family' type='string' /> </sequence> </complexType> Given an XML Schema for a document, then, it is possible to know that the child elements do in some sense belong to their parent, in a way which is not apparent simply from the XML instance. Observing this, Simon St.Laurent offered a comment.. As the debate continued, Tim Bray, one of the editors of the Namespaces in XML specification, weighed in on the side of fully qualifying child elements. I was reading through this thread with interest, and could see both sides of the argument, but find myself swinging more and more strongly one way. At one level, what's going on in the following is pretty obvious and natural ... I'm sure there are large classes of applications that will Do The Right Thing. But the more I think about this, the more I believe that this is probably pretty bad practice. Bray proceeded to explain that Gudgin's style of markup breaks in the scenario when it is mixed with names from another namespace. He concluded that the "admirable simplicity" of Gudgin's example wasn't quite "pleasing enough to justify the cost, which is considerable." There's only been room for a small section of the entire debate here. If you have the time, read the thread in the XML-DEV archives. Not only is it instructive, but it also exemplifies the lively flavor of XML-DEV debates. Expectations for XML Schema 1.1 In response to a message that implied "co-constraints" will be introduced as a feature in XML Schema 1.1 or 2.0, Rick Jelliffe seemed doubtful such functionality would be in XML Schema 1.1. Co-constraints are constraints on instances where the permissible values of one element depend on the value of a different element.. Little else has been said publicly about what XML Schema 1.1 may or may not contain, but it seems likely that consolidation and perhaps simplification are in the cards. Namespace Pains, Again If you thought Namespaces in XML had caused enough pain for a lifetime, then perhaps it's time to find a different job. Rumors from multiple areas of the XML world indicate that the W3C may be planning to reopen the can of namespace worms, in an attempt to resolve issues with the specification. While such attention to detail seems admirable, the potential for further confusion and delay make a compelling case for the W3C to leave Namespaces in XML alone. Given this, and the experience of the XML-URI firestorm last year, one can only conclude that the W3C must have a very strong reason to revive this debate. Got a viewpoint on XML Schema or Namespaces? Join the fray in our forum. (* You must be a member of XML.com to use this feature.) Comment on this Article - Before I run back to DTDs ... 2001-10-10 09:16:40 Steve Cohen [Reply] A relative newbie to these matters, I am trying to define a set of constraints for a series of XML data packets for a particular application. Understanding DTDs, I naturally started out on this march using them. And being a good citizen of cyberspace, I'd always absorbed the pain of using namespaces in my DTDs. But in order to impress the client, I thought I'd like to try to convert these to schemas to "show off the new technology". My first effort involved using the DTD->Schema converter in XMLSpy. Not good - it created a document that it's validator wouldn't accept. So much for "simple-to-use" tools. All right then, let's eschew the "easy way out" and go for understanding. And since XMLSpy is wont to crash on my system, let's investigate TurboXML as well. So I painstakingly hand-crafted schemas with both tools and then tried to create instance documents. What I find is most disturbing. The schema-namespace coeexistence is anything but peaceful. The assumptions made by the tools lead me into blind alleys that there is no way out of and no way of knowing, in fact, how faithful any of these tools are to the specs. I read the Kawaguchi-Gudgin debate and it only deepens my frustration. Most of the textbooks show you how to write a schema, sometimes in great detail. What they don't show you is what sorts of instance documents you are contrained to/from using based on the choices made in the schema. I am going to give this one more crack. If I can't get beyond this soon, I am going to run as fast as I can back to DTDs. The fact that DTDs are NOT xml is beginning to look like a real advantage instead of the disadvantage everyone says it is. Meantime, if anyone has any advice for me, I'd love to hear it. - namespaces 2001-08-07 23:13:53 Marc Portier [Reply] I just read the article at xml.com: (so this comes totally out of the blue...) I found the reasoning behind: public class Person { String lastName; String firstName; } as being a logic reason for having: <foo:person xmlns: <familyName> KAWAGUCHI </familyName> <lastName> Kohsuke </lastName> </foo:person> not very satisfying... in the java space (see example) person functions as a type, while the familyName and lastName ar members (best practice would be to call them m_whatever :-)) at best the so called 'logical/natural' serialization would lead to: <person> <string name="familyName"> KAWAGUCHI </string> <string name="lastName"> Kohsuke </string> </foo:person> which I would never state as being nice xml... so even before we delve into discussions on the namespaces-mess we should understand that it's no good to try and argument in this discussion by referring to other namespacing techniques in other languages or address spaces with totally different purposes (java packages, dns naming, ...) Elements, subelements and attributes do not [ever] map 'naturally' onto classes, instances, types, members etc. etc. (ask the JAXB guys about this: they needed to invent some additional mapping language) XML tries to service both the data and document audience, so it's fairly normal Having said that, it would be nice that someone _could_ finally explain what the default namespace actually is :-) as far as diambiguity is concerned, I'm definately +1 for prefixing all elements... only it kind of blows up the whole idea of having namespaces in the first place :-) and it's surely not what the vim and notepad xml authors are waiting for... -marc= mpo@outerthought.org
http://www.xml.com/pub/a/2001/05/30/deviant.html
crawl-002
refinedweb
1,567
61.77
From the R Documentation... ‘rule of thumb’, Silverman (1986, page 48, eqn (3.31)) unless the quartiles coincide when a positive result will be guaranteed. np.arange(1,401) def nrd0_python(x): X = min(np.std(x), np.percentile(x,25)) top = 0.9*X bottom = 1.34*len(x)**(-0.2) return top/bottom The precedence of operators in an English sentence is ambiguous. Here's an implementation that returns the value you expect: In [201]: x = np.arange(1, 401) In [202]: 0.9*min(np.std(x, ddof=1), (np.percentile(x, 75) - np.percentile(x, 25))/1.349)*len(x)**(-0.2) Out[202]: 31.393668650034652 I don't have the Silverman reference. I found that in (p. 21).
https://codedump.io/share/7w9zUJPvkKdQ/1/is-there-a-scipynumpy-alternative-to-r39s-nrd0
CC-MAIN-2017-17
refinedweb
123
65.49
Agenda See also: IRC log <scribe> ScribeNick: ArtB <scribe> Scribe: Art Date: 8 February 2011 AB: I posted a draft agenda yesterday ( ). I intend to merge topics #4 and #6 since they both are about Use Cases. Any change requests? AB: Working Groups handle issues differently: embed the issues in the spec, use W3C's tracker, Bugzilla, etc. Let's briefly talk about how we want to handle issues. ... anyone have comments or feedback re issue tracking DS: my preference is to use Tracker (W3C tool) ... it has a nice integration with IRC ... less cluttered with Bugzilla AB: also has nice integration with e-mail DS: from the WebEvents page, look for issues <shepazu> DS: there is only one action now ... and no issues ... Action-1 is still open ... and I'll take care of it ... Tracker is easy to use <shepazu> issue-1? <trackbot> ISSUE-1 does not exist <shepazu> action-1? <trackbot> ACTION-1 -- Arthur Barstow to work with Doug on a voice conference time of day that works for most people -- due 2010-12-15 -- CLOSED <trackbot> DS: has some macros that trackbot understands and acts on ... to add issues, may need to copy text from an email to tracker issue ... so a bit of a pain ... to both edit the spec and to do issue tracking ... As such, if someone wants to volunteer to help with issue tracking that would be very welcome ... Requires monitoring the list and then adding issues to Tracker ... One email may have more than one issue AB: is anyone willing to volunteer to lead the issue tracking MB: I will tend the issue tracker DS: this is good and a nice way to ease into the editing ... Think the spec should include credit for people that take on big tasks like Issue tracking and Test suite work, etc. AB: I think that's a great idea SM: I just added two issues DS: that's great ... we can have a 3-way call and go through some of the tasks <scribe> ACTION: doug set up a conf call with Matt and Sangwhan re issue tracking and editing [recorded in] <trackbot> Created ACTION-6 - Set up a conf call with Matt and Sangwhan re issue tracking and editing [on Doug Schepers - due 2011-02-15]. RESOLUTION: the WG agrees to use Tracker for issue tracking (and action tracking) AB: thanks guys! DS: an advantage Bugzilla has is that anyone in the Public create Issues; whereas, only WG members can create issues via Tracker MB: so if Joe Public wants to create/raise an Issue, they must use the list? DS: yes <timeless> [of note, bugzilla can be configured to have similar restrictions ] AB: PPK read Doug's first ED and submitted some comments ( ) DS: does anyone have comments SM: re his comments about radiusXandY ... physical units create probs for mobile browsers ... pixels make much more sense ... than something like centimeters DS: I agree ... would be good if we could convert but think screen pixels is reqd ... Someone else raised an issue about radiusxy ... It may disappear OP: re altKey, etc., what about Pens? DS: some Pens do have keys ... I talked to at least one engr at Wacom ... they have >=1 buttons on the pens ... and they can be configured <timeless> [ ] <timeless> [ Wacom ] s/Wacom/Wacom/ SM: we should add Meta key MB: PPK links to Apple Safari doc DS: I created a blog ( ) ... after reading PPK's blog, I went thru point-by-point and cleaned up the spec to address most of his points ... Sangwhan, perhaps you could add the Meta key ... I think I addressed ontouch move ... I still have questions about time stamp ... Units for radiusXY will need some work ... Unit of force: defined it as 0 to 1 as relative due to device <Sangwhan_Moon> ACTION: Add meta key for the TouchPoint interface [recorded in] <trackbot> Sorry, couldn't find user - Add DS: touch cancel event - I'm not sure what this could be needs some work <mbrubeck> hg log of shepazu's spec changes: <timeless> [ ] <Sangwhan_Moon> DS: fyi, I created a twitter account for webevents <shepazu> twitter feed @w3cwebevents DS: I intend to push spec changes to @w3cwebevents SM: is it branch aware? DS: not sure ... we want to be able to tweet directly rather than going thru a 3-rd party service as I do now AB: excellent ... anything else on PPK's comments? AB: Google's Andrew Grieve submitted some comment regarding use cases ( ) <mbrubeck> might work AB: so far, no one has responded DS: I will respond to Andrew ... it's encouraging that we already have comments so early in the spec process AB: yes, I agree DS: I prefer to take other topics and come back to Andrew's email if we have time AB: Use Case and Reqs wiki was created ( ) and it needs some work. I don't think we need to be overly prescriptive on how the UCs and Reqs are documented and there is significant variability in the way WGs have documented them. DS: I would like to work on these but I don't have the time ... pointing to some examples would be good <scribe> ACTION: barstow send to the list some examples of WGs' documenting UCs and Reqs [recorded in] <trackbot> Created ACTION-8 - Send to the list some examples of WGs' documenting UCs and Reqs [on Arthur Barstow - due 2011-02-15]. <Sangwhan_Moon> It should be possible to start off from previous use cases that Cathy wrote up AB: is anyone interested in leading or contributing to that process of UCs and Reqs? ... Cathy did some work <timeless> i'd suggest tweeting asking for people to add to the wiki :) AB: anything else on UCs and Requs for today? SM: do we have any Web developers in the WG? ... it would be good to get their input DS: good point ... and Timeless has a good point too ... asking web devs and tweeting could help; that's kinda' what I did with PPK ... So there is an Action for Everyone to tweet for UCs and Reqs SM: I've found that browser developers aren't particularly good at writing UCs <timeless> s/particuarly/particularly/ AB: strictly speaking, a WG is not required to create test cases until a spec enters the Candidate Recommendation phase. In some cases, WGs try to work on test cases much earlier. Ideally, a comprehensive test suite would exist before a spec enters Last Call WD but in practice, I think they are rarely created that early. ... there is also a significant amount of variability in test suites from WG to WG and in some cases e.g. WebApps WG, there is variability from spec to spec. DS: if tests aren't developed early ... ... when the spec gets to CR and test case are then started, some people will have already left the WG or become inactive ... and when test cases are written, realize the spec has a hole but the CR means people will start implementing ... that ends up tying the hands of the WG ... would be good to stay in the ED state until we have some test cases ... that is, don't publish a WD until test cases exist ... this would be more stringent then what is required ... but this restriction could help us advance the spec more quickly <timeless> shepazu: so you're holding the WD ransom against implementers providing testcases? DS: Naturally, we need volunteers to write the test cases ... and intend to include a section in the spec that points to the test suite and give an attribution to whomever leads the test suite work MB: PPK has a lot of experience with test suites DS: I asked him but he can't make the commitment ... Does anyone here have experience writing tests? Or no experience writing tests? OP: how does adding TCs to the TS acutally work? ... because they all need to be reviewed <timeless> of note, some WGs have published test suites with poor quality tests OP: are TCs added to bugzilla <timeless> which lead to problems <timeless> i think that's SVG/HTML/CSS (?) OP: it is too easy to write Invalid tests DS: agree; but a hard problem to solve SM: we could create a mirror e.g. bitbucket for prelim work <timeless> the general suggestion is a reviewer. DS: would prefer to use W3C services <timeless> at the risk of volunteering for work, i could probably help out here SM: must have a W3C account to fork DS: what about just to pull? <timeless> cloning is possible w/ public repositories <timeless> but the issue is informing the owner of the w3 repo that your changes are available SM: need to differentiate merging and just making a clone <timeless> in theory one could again use twitter :) DS: think we should have a call about sysadmin type stuff <timeless> (please include me for this call/topic) <timeless> the general suggestion was since it provides for pull requests DS: if a large number of people aren't interested in infra type discussions we could use this call <timeless> there aren't to my knowledge many hg hosts which do it DS: how about we dedicate next week's call to infra/sysadmin? AB: WFM MB: OK <Sangwhan_Moon> AB: coming back to Doug's proposasl, I'm a little uneasy with making test case availability be a block for FPWD ... would make more sense as a block for LCWD <timeless> art: i think that there might be enough web dev demand that we can remind the web that they won't be able to play with this stuff unless they help provide test cases <mbrubeck> As vendors like Mozilla implement the spec, we will be writing test cases for our own use... <timeless> personally, i think we do need to block some *WD on having thoroughly reviewed the test suite DS: I think people need to speak up, even if you don't care AB: if anyone has comments about Doug's test case proposal, please speak up now MB: I don't think I know enough about W3C process to make an informed opinion ... we are already getting comments DS: we aren't lacking any visibility ... it's too easy to slip into a mode where we are not creating TCs ... will help us narrow down the scope of the spec <mbrubeck> Is there a standard test harness / library / tool for W3C specs, or should we just create any old web page that runs scripts and displays the results? <timeless> mbrubeck: there are a couple of harnesses used by different WGs <timeless> each WG can choose from them or use a new one AB: I think some people won't review the spec until there is a FPWD <timeless> iirc some of the recent WG / Specs have tended toward certain harnesses, but i can't recall which DS: the spec is relatively small ... and don't expect a huge number of TCs AB: I'd like a little time to think about this; see some clear advantages to the proposal JS: I think implementors at Moz will write test cases as they implement ... so, if they can easily contribute their TCs, it will help ... I don't think most implementors will distinguish between ED and WD ... they are going to follow the EDs anyway ... Do implementors have a way to namespace-protect their early implementations? <mbrubeck> The global namespace is rather polluted in this space already. :( DS: there is a way in D3E ... eg -moz-touchstart <mbrubeck> Mozilla currently implements MozTouchDown, MozTouchMove, MozTouchUp - DS: I will add something to the spec about adding prefixes <mbrubeck> If the spec continues to follow WebKit in a mostly backward-compatible way, then I'm not sure prefixes are useful LG: this will be tricky with WebKit i.e. to state pre-spec and post-spec state ... WK already has some TCS <mbrubeck> We never prefixed things like <canvas> that followed existing implementations LG: WG may be able to use them ... We need to think about how to automate the testing ... The WK tests cases have some platform specific parts DS: automation is not a requirement ... I can work with you Laszlo re if we can re-use WK tests ... Do, you know Art if we can use WK tests? <scribe> ACTION: barstow work with Doug and Laszlo re if we can re-use Webkit tests [recorded in] <trackbot> Created ACTION-10 - Work with Doug and Laszlo re if we can re-use Webkit tests [on Arthur Barstow - due 2011-02-15]. <timeless> lgombos noted that the webkit tests tend to be platform specific AB: does anyone object to Doug's proposal that test cases be required before we publish a FPWD? [ None ] <mbrubeck> no objection, but I'll read more about process and see if I have any further comments AB: so, let's give everyone a week to think about Doug's proposal <timeless> I guess w3 process doesn't require test cases not be limited to a specific platform/device/impl? AB: Doug, do you have an Estimated Time of Arrival (ETA) for an Editor's Draft of the high-level intentional spec? DS: I think it is weeks away ... I need to work with other people on that spec <Sangwhan_Moon> DS: I hope to get it out before March 1 <mbrubeck> "Uncontacted tribe in Amazon rain forest announces W3C membership, plans to support HTML5" AB: we will have a call next week; primary topics are infrastructure and sysadmin ... meeting adjourned This is scribe.perl Revision: 1.135 of Date: 2009/03/02 03:52:20 Check for newer version at Guessing input format: RRSAgent_Text_Format (score 1.00) Succeeded: s/thru/through/ Succeeded: s/Qualcomm/Wacom/ FAILED: s/Qualcomm/Wacom/ Succeeded: s/Qualcomm/Wacom/ Succeeded: s/use case that/use cases that/ Succeeded: s/deverlopers/developers/ Succeeded: s/particuarly/particularly/ FAILED: s/particuarly/particularly/ Succeeded: s/Call WG/Call WD/ Succeeded: s/left the WG/left the WG or become inactive/ Succeeded: s/cases/suite/ Succeeded: s/commentns/comments/ Succeeded: s/intensional/intentional/ Found ScribeNick: ArtB Found Scribe: Art Default Present: +1.781.534.aaaa, +1.206.792.aabb, Shepazu, Matt_Brubeck, Josh_Soref, Art_Barstow, Laszlo_Gombos, Olli_Pettay, Sangwhan_Moon Present: Art_Barstow Josh_Soref Matt_Brubeck Doug_Schepers Laszlo_Gombos Sangwhan_Moon Olli_Pettay Agenda: Found Date: 08 Feb 2011 Guessing minutes URL: People with action items: add barstow doug send[End of scribe.perl diagnostic output]
http://www.w3.org/2011/02/08-webevents-minutes.html
CC-MAIN-2015-11
refinedweb
2,411
67.89
Initially named “Boston”, Visual Studio has gone through a number of transformations in the last two decades. Right from its Visual Basic and Interdev days, Visual Studio has evolved with every release to address new markets and provide improved experiences across multiple platforms and devices. Visual Studio 2017 (VS 2017) is the 11th version of Visual Studio with a focus on improving experiences around mobile apps, cloud services and devops. New IDE features like interactive code suggestions (intellisense), easy code navigation, debugging, fast builds and quick deployment are some of the productivity and performance enhancements in VS 2017. This article explains some of the most important features of VS 2017 which are useful for boosting developer productivity. Visual Studio 2017 can be downloaded from this link.. Assuming you have downloaded VS 2017, run the setup for a new installation experience, as shown in the following image: The installation allows you to choose and install just the features which you need; which makes the installation faster. The Workloads tab provides installation options which are grouped to represent common frameworks, languages and platforms. The main advantage of grouping is that a developer can easily choose a feature set to be installed based on their needs e.g. only Windows Features or Web and Cloud features etc. These group are as follows: If you don’t want to go the Workloads route, no worries! The Individual components tab allows you to pick the components you require, as shown in the following image: Some options in Individual components are listed here: The advantage of the new setup experience is that, now one can choose only those features which are needed for his/her development. Individual components can be used by advanced developers to further customize these features of Visual Studio. The Language packs allows you to choose the language for Visual Studio. The VS installer, by default, tries to match the language of the OS when it runs for the first time. The following command can be used to force an installer to run in the selected language: vs_installer.exe -locale The following language token are supported by the installer: en-Us, zh-cn, zh-tw, cs-cz, fr-fr, de-de, it-it, ja-jp, ko-kr, pl-pl, pt-br, ru-, u, tr-tr, Once VS 2017 installs and is launched, the start page is displayed as shown in the following image: The start page shows options like Recent and Open, which are similar to the previous version of Visual Studio e.g. VS 2015, but a new feature worth observing is to create a New project using the Search project templates search box or the Create new project link. A new project can be created by entering the project category in the search box as shown in the following image: Once the project category (e.g. Web Ap) is entered in the textbox, all matching project templates are searched and displayed. Once the project template is searched and the name of the template is clicked, the New Project window will be opened. The same New Project window will also open on clicking the Create new project link. Note: If this is not a fresh installation and you have already created projects using VS 2017, then before you start searching for project templates, the recently used project templates are listed. Once we create a solution, it will be added in the Recent solution list. The solution may contain several projects in it, which increases the solution loading time. When the solution is clicked from the Recent list (or else File > Open > Project/Solution), by default, it will be opened with all projects in it. However it is not necessary that the developer will be working on all projects at the same time, so Visual Studio can now be configured to load the solution in a lesser time using Tools > Options > Projects and selecting Lightweight Solution Load option as shown in the following image: The Enable option decrease time for loading the solution. This option also results in some limitations e.g. projects will still be loaded as needed when first accessed (directly or indirectly) and in this case, features like edit and continue won’t work. Step 1: Create a Console Application of the name ‘CS_NavigationFeatures’. In the project, add a new class file called Employee.cs and add the following code in it: namespace CS_NavigationFeatures { public class Employee { public int EmpNo { get; set; } public string EmpName { get; set; } public int Salary { get; set; } public string DeptName { get; set; } public string Designation { get; set;} } } Open Program.cs and create an instance of the Employee class. VS 2017 has enhanced navigation experiences for developers to move from one point to another. For e.g. a developer can easily navigate all Employee declarations that matches with the word entered in the search box, which can be opened using a short-cut key Ctrl+T. Using the shortcut brings up a navigation pop-down dialog on the top-right corner of the Visual Studio as shown in the following image: Enter Emp word in the search textbox of the dialog box, which will show all references matching the word Emp as shown in the following image: Here a developer can select where to navigate to e.g. to an Employee class, Employee.cs file or other Emp references e.g. members. All this facilitates an easier code navigation, with less distractions. One of the important features of this dialog is the icon-menu-bar on the top. This icon-menu-bar provides options for selection of code navigation e.g. File, Class, member, etc. The following image explains it in details. For e.g: to navigate to a file, File Navigation > Symbol is ‘f’ ..which shows files starting with the matching search criteria: Type Navigation (applied to class, interface) > Symbol is ‘t’ ..shows classes matching with the search criteria: Member Navigation > Symbol is ‘m’ ..shows all members matching the search criteria: While writing code, developers creates several code files and refer to various types at various places for defining instances e.g. Employee references in various files. In Visual Studio 2017, these references can be easily searched using an improved reference window. In the project, add two new class files of name Manager.cs and Payroll.cs and add the following code in it: Manager.cs namespace CS_NavigationFeatures { public class Manager { public Employee emp { get; set; } public int TravelAllowance { get; set; } public int HouseRentAllowance { get; set; } } } Payroll.cs namespace CS_NavigationFeatures { public class Payroll { Employee emp; Manager mgr; public Payroll() { emp = new Employee(); mgr = new Manager(); } } } Program.cs is as shown in the following code: namespace CS_NavigationFeatures { class Program { static void Main(string[] args) { Employee emp = new Employee(); Console.ReadLine(); } } } In the three code files we just saw, an Employee object is used for instance creation and property declaration. Now it is easily possible to find out all the Employee references for the current project. Select Employee declaration in Program.cs as shown in the following image: Now select Shift+F12, and the ‘Employee’ references window will be displayed as shown here: This window will list all Employee references in all the file names. Just by clicking on the reference, the file can be opened in the VS Editor. The type reference details (in this case Employee) can be seen just by moving the mouse cursor on a specific line or reference it as shown in the following image: For e.g. in the above image, a reference of an Employee in Payroll.cs is displayed in the tooltip. In VS 2015, it was possible to find all references on a class or property and there was no option to filter it. But in VS 2017, these references can be filtered as shown in the following image: The references can also be grouped as shown in the following image: The references window also provides a facility to search from the references using the search textbox on the top-right corner of the window, as shown in the following image. The search can be based on the File name, Column number as well as the Line number. This shows all Employee references from Program.cs file. The Keep Results toggle button in the references window will make sure that all the references will be saved. The advantage of this feature is that, when new references are searched; instead of overwriting previous references, the new references will be shown in a new tab of the reference window as shown here: The above image shows references for Manager and Employee. As a developer, when some code is added in the application, sometime it happens that the developer knows the class to be used in the code, but the name of the package from which this class is used, is not known. In this case, a developer sometimes searches online for help but such help is not always helpful (pun intended). For e.g. a developer who wants to use the DbContext class or a JObject class but does not know which NuGet package needs to be installed for the project. In VS 2017 (also in VS2015.3), there is an option available for Suggest usings for types in NuGet packages in the Tools > Options > Text Editor > C# > Advanced as shown in the following image: The checkbox for Suggest usings for types in NuGet packages is not checked by default, please check it and restart VS 2017. Open Program.cs and try to use DbContext class, select this class name and press Ctrl+. Doing so brings up the quick action menu with suggestion for installing EntityFramework package as shown in the following image: Once the Install package ‘EntityFramework’ option is selected, the package will be installed and its status will be shown in the VS 2017. I hope you too realize what a cool feature this is! When the code file contains several classes and a class contains several lines of code with several programming constructs (if...else statements, for loops, etc.), while scrolling down in the VS editor, it is at times difficult to track the scope of the current statement. In VS 2017, the code contains dotted lines between curly braces to identify the scope. When the mouse is moved over the dotted lines, the current scope is displayed as shown here: This is another cool feature of VS 2017. This feature provides suggestion for defining variable name in a class/function as well as input parameters to the function. This helps to follow naming standard for variables/parameters in the application. To experience this feature, add a CalculateSalary() method in the Payroll class in Payroll.cs file. Define the Employee object as an input parameter for this method. VS 2017 will provide name suggestion for the input parameter as shown in the following image: In the Payroll class, try to declare a Manager object. VS 2017 will show the suggested name for the declaration of object, as well as for methods too. This helps to keep coding standards in check. There are some more suggestions settings provided by VS 2017 for validations and coding styles. These suggestions can be set using Tools > Options > Text Editor > C# > Code Style as shown in the following image: For e.g. in the above image for ‘var’ preferences, the For built-in types is set to value for Preference as Prefer explicit type and Severity as Suggestion. In this case, if the code variable contains declaration as shown here.. ..then the var declaration has dots below it, which means that there is a suggestion available for the declaration. Press Ctrl+. on var, and a quick action menu will display suggestions for the var declaration: Here an explicit type can be selected instead of a var declaration. Likewise, there are several suggestions provided in the options windows which can be helpful to provide a better coding experience. I would encourage you to explore them all. Code refactoring is a major activity that developers must perform while writing code. This makes the code maintainable and readable. In VS 2017, there are some features which provide some great Code-refactoring experiences. Here are some of them: Object Initialization C# 3.0 already provided a new syntax for object initialization, but consider this code where object properties are initialized in a manner as shown here: To change the above code using the Auto-Initialized syntax of C# 3.0, VS 2017 provides a new feature. Observe the underlined dots below the new keyword for object creation. Now move your mouse cursor on the new keyword, to bring up a pop-up that shows the message Object initialization can be simplified: Click on the down-arrow of the quick action menu, to bring up the new object initialization refactoring suggestions as shown in the following image: Select Object initialization can be simplified and you will find that the code will be refactored as below: How convenient! We could change the object declaration/initialization in a jiffy! Managing null value check for the reference of input parameters of method When a method accepts a reference type (e.g. Employee object) as an input parameter, then while accessing that method, it is important to check for a non-nullable value for the input parameter, before passing it to the method. Alternatively, the method must have code for checking for a null value. In VS 2017, this feature is provided so that a method can be added with the required null check. In the Payroll class in Payroll.cs file, add the CalculateSalary() method as shown in the following code: public void CalculateSalary(Employee emp) { } To check the null value for the emp object, right-click on emp and select Quick action and Refactorings option from the context menu as shown in the following image: This will bring up the Add null check option as shown here: Once this option is selected, the method will be added with a null check condition: Likewise, if the method accepts a string parameter, the code can be refactored to generate conditions for string.IsNullOrEmpty and string.IsNullOrWhiteSpace check in the method. This useful feature helps developers to reduce logical errors in the code. Changing the method signature When a method having various input parameters in a specific order needs to changed either by removing some parameters or changing order of parameters, then it will definitely result in to a compilation error. If the method is called at various places in code, the Developer would need to manually keep track of changes in the method and update the code accordingly. This is a time-consuming task! In VS 2017, the signature of the method can be easily changed and these changes can be reflected at all places where this method is called. This saves the developer some precious time and makes the code error-free. Consider the following PrintName() method in the program class of the Program.cs file. class Program { static void Main(string[] args) { PrintName("Mahesh","Sabnis"); Console.ReadLine(); } static void PrintName(string fname, string lname) { Console.WriteLine($"First Name {fname} Last Name {lname}"); } } The PrintName() method accept two string parameters fname and lname. This method is called in the Main() method with the values set for fname and lname as Mahesh and Sabnis respectively. If we need to change an order of fname and lname in the PrintName() method, then in the Main() method, values for these parameters needs to be changed manually. In VS 2017, this can be done easily by refactoring the method. Right-click on the method name and select Quick action and Refactorings option from the context menu. Doing so will show the Quick Action menu with a Change signature option as shown in the following image: Clicking on the Change signature option will show a Change signature window. Using this window, the order of parameters in a method can be changed or they can be removed altogether. In the image you just saw, click on the button with the downward arrow and move the fname parameter below the lname parameter. Now click on the Ok button, and you will see that the method signature and its call will be updated. Once the PrintName() method signature is updated, the PrintName() method call with its parameter values is also updated. The advantage of this feature is that it reduces potential errors which a developer can make while updating the method definition in the application. Once the code has been written, it is important for a developer to debug the code to ensure that the code is logically working and has been diagnosed for exceptions, if any. In VS 2017, there are some improvements made for debugging and exceptions management. Debugging Run to Click In previous versions of Visual Studio, when breakpoints were applied on various lines, it was necessary for developers to press F5 to skip lines in between two breakpoints, to continue debugging from next breakpoint. Or, for the developer to skip the current breakpoint and continue debugging ahead, it was necessary to put additional breakpoints. In this case, it was necessary for the developer to keep track of all breakpoints (imagine a for/foreach loop occuring in between the code). To get rid of this, in VS 2017, a new feature known as Run to Click is added (similar to Run to cursor feature of the previous version), which allows the developer to skip the lines in between breakpoints and start executing code from the desired line. Consider the following image. A breakpoint is applied on the PrintName() method, so the debugger will stop at this method. If the developer does not want to stop an execution at the PrintName() method and wants to continue execution directly from the Reverse() method call, just move the mouse cursor adjacent to the Reverse() method, and a Run Execution to here symbol will be displayed as shown in the following image: Click on this symbol, and all the lines of code in between PrintName() call to Reverse() method calls will run past it, and the Reverse() method call will be highlighted as shown in the following image: This means that an execution is continued from the Reverse() method call, hence there is no need to apply a breakpoint at the Reverse() method call. The New Exception Information Helper Dealing with exception is a common developer problem irrespective of the technology. Figuring out the reason for an exception is one of the most frustrating experiences. In previous Visual Studio versions, exception information messages used to be displayed as shown here: In this case, it was challenging for the developer to find out the exact exception and it was necessary to see the View Details and Inner Exception to find out what is the reason behind the exception. In VS 2017, a new non-modal exception handling helper is provided as shown here: This helper shows an exception message and provides the reason behind the exception. In this case the Object reference is not set to an instance of an object exception is fired and the cause of the exception is also displayed as m as null. This helps developers to understand what is the reason behind an exception and how to handle it. The main advantage here is that, earlier it was required for the developer to see the Inner Exception in the View details dialog; however in the VS 2017, the in-detail exception information is seamlessly provided to the developer. Apart from all the above features discussed, there is one more important enterprise feature provided in VS 2017, and that is Live Unit Testing. This feature encourages Test Driven Development (TDD) and helps in developing better quality code and code coverage. You can read more about Live Unit Testing at. Visual Studio 2017 is packed with improvements and new features that increase productivity. This all-new IDE released by Microsoft helps developers to build stunning apps on Windows and other platforms. I hope this article served its purpose and introduced you to these productivity features which will help you simplify your most common tasks, and ultimately boost your productivity. This article was technically reviewed by Damir Arh and Suprotim Agarwal.
https://www.dotnetcurry.com/visualstudio/1399/visual-studio-2017-new-features
CC-MAIN-2018-43
refinedweb
3,373
58.72
NAME spu_create - create a new spu context SYNOPSIS #include <sys/types.h> #include <sys/spu.h> int spu_create(const char *pathname, int flags, mode_t mode); int spu_create(const char *pathname, int flags, mode_t mode, int neighbor_fd); DESCRIPTION non-existing contexts,. SPU_CREATE_ISOLATE Create an isolated SPU context. Isolated contexts are protected from some PPE (PowerPC Processing Element) operations, such as access to the SPU local store and the NPC register. Creating SPU_CREATE_ISOLATE contexts also requires the SPU_CREATE_NOSCHED flag. SPU_CREATE_AFFINITY_SPU the permissions used for creating the new directory in spufs. See stat(2) for a full list of the possible mode values. RETURN VALUE On success, spu_create() returns a new file descriptor. On error, -1 is returned, and errno is set to one of the error codes listed below. ERRORS EACCES The current user does not have write access to the spufs(7) mount point. EEXIST An SPU context already exists at the given path name. contexts has been reached. ENOSYS The functionality is not provided by the current system, because either the hardware does not provide SPUs or the spufs module is not loaded. ENOTDIR A part of pathname is not a directory. EPERM The SPU_CREATE_NOSCHED flag has been given, but the user does not have the CAP_SYS_NICE capability. FILES. Programs using this system call are not portable. NOTES. EXAMPLE See spu_run(2) for an example of the use of spu_create() SEE ALSO close(2), spu_run(2), capabilities(7), spufs(7) COLOPHON This page is part of release 2.77 of the Linux man-pages project. A description of the project, and information about reporting bugs, can be found at.
http://manpages.ubuntu.com/manpages/hardy/en/man2/spu_create.2.html
CC-MAIN-2014-42
refinedweb
269
58.58
FastText is one of the popular name in Word Embedding these days . In short , It is created by FaceBook . Still FastText is open source . You may use FastText in many ways like test classification and text representation etc . While under this article , We will only explore the text representation . Basically for any Machine Learning algorithms on Text , You need to convert them into numbers vectors .Lets understand How to create word embedding using FastText ? Using FastText own Implementation – Yes ! FastText has its own implementation for word embedding . Here I am sharing the official link for FastText own implementation for word embedding . Here you can use FastText pre train model as well as you may train your own model of embedding with fastText algorithms . For implementation prospective I will suggest you to visit the official FastText tutorial on embeddings . Gensim for FastText Implementation – Gensim provide the another way to apply FastText Algorithms and create word embedding .Here is the simple code example – from gensim.models import FastText from gensim.test.utils import common_texts model_FastText = FastText(size=4, window=3, min_count=1) model_FastText .train(sentences=common_texts, total_examples=len(common_texts), epochs=10) The above example is of 4 line implementation . Lets understand one by one – - Import required modules . - You need some corpus for training . Here the corpus must be list of lists of tokens . Regular text must contains sentence . you need to create the tokens out of it . Hence every element of the list will be a sentence tokens .Now any text data must contains multiple sentence . So there will be a corresponding list for each sentence . So the final data structure will be list of lists . - Create the object for FastText with require parameters .Here size is numbers of feature or embedding dimensions . For more clarification 4 represents that each words will be represented in 4 columns . For more details , Please have look here – create word embedding using FastText paramters 4. This line gives the last train command syntax for FastText . Fast Text Pre Trained Model – When you read this title , you must have a question . Embedding on your training data or FastText Pre trained Model . Actually this is one of the big question point for every data scientist . Actually There is very clear line between these two . Lets understand them one by one . See FastText is not a model , Its an algorithm or Library which we use to train sentence embedding . However Pre train Fast Text Models are the ready made solution ( models ) on some large corpus . This is only beneficiary for generalize data itself . See Training on large data involves heavy computation cost . Also any deep learning model like FastText etc needs too much of data . Conclusion – Friends how did you find this article – How to create word embedding using FastText ? Please write your views on this topic . Apart from this article , There are some other key terms which you should understand when it comes to word embedding . Word Embedding is very vast and hot research topic . So keep on reading related latest content on this . Please refer the below article for reference and basic understanding – Word Embedding in Python : Different Approaches Prediction Based Word Embedding Techniques Which is the Best Word Embedding Technique with Domain Data ? Join our list Subscribe to our mailing list and get interesting stuff and updates to your email inbox.
https://www.datasciencelearner.com/how-to-create-word-embedding-using-fasttext/
CC-MAIN-2020-50
refinedweb
555
60.01
$ cnpm install @fabiosantoscode/uglify-es A JavaScript parser, mangler/compressor and beautifier toolkit for ES6+. uglify-esis API/CLI compatible with uglify-js@3. uglify-esis not backwards compatible with uglify-js@2. First make sure you have installed the latest version of node.js (You may need to restart your computer after this step). From NPM for use as a command line app: npm install uglify-es -g From NPM for programmatic use: npm install uglify-es uglifyjs [input files] [options] UglifyJS can take multiple input files. It's recommended that you pass the input files first, then pass the options. UglifyJS will parse input files in sequence and apply any compression options. The files are parsed in the same global scope, that is, a reference from a file to some variable/function declared in another file will be matched properly. If. --ie8 Support non-standard Internet Explorer 8. Equivalent to setting `ie8: true` in `minify()` for `compress`, `mangle` and `output` options. By default UglifyJS `uglify-es` will not work around Safari 10/11 bugs. - UglifyJS assumes HTTP X-SourceMap is being used and will omit the //# sourceMappingURL= directive. For example: uglifyjs (default false) -- mangle names declared in the top level scope. eval (default false) -- mangle names visible in scopes where eval or with are used. var x = { baz_: 0, foo_: 1, calc: function() { return this.foo_ + this.baz_; } }; x.bar_ = 2; x["baz_"] = 3; console.log(x.calc()); Mangle all properties (except for JavaScript builtins): $ uglifyjs example.js -c -m --mangle-props var x={o:0,_:1,l:function(){return this._+this.o}};x.t=2,x.o=3,console.log(x.l()); Mangle all properties except for reserved properties: $ uglifyjs example.js -c -m --mangle-props reserved=[foo_,bar_] var x={o:0,foo_:1,_:function(){return this.foo_+this.o}};x.bar_=2,x.o=3,console.log(x._()); Mangle all properties matching a regex: $ uglifyjs example.js -c -m --mangle-props regex=/_$/ var x={o:0,_:1,calc:function(){return this._+this.o}};x.l=2,x.o=3,console.log(x.calc()); Combining mangle properties options: $ uglifyjs); $ uglifyjs stuff.js --mangle-props keep_quoted -c -m var o={foo:1,o:3};o.foo+=o.o,console.log(o.foo); = require("uglify-es");.minify(code); console.log(result.error); // runtime error, or `undefined` if no error console.log(result.code); //.minify(code, options); console.log(result.code); // console.log(3+7); The nameCache option: var options = { mangle: { toplevel: true, }, nameCache: {} }; var result1 = UglifyJS.minify({ "file1.js": "function add(first, second) { return first + second; }" }, options); var result2 = UglifyJS", UglifyJS.minify({ "file1.js": fs.readFileSync("file1.js", "utf8"), "file2.js": fs.readFileSync("file2.js", "utf8") }, options).code, "utf8"); fs.writeFileSync("part2.js", UglifyJS }, output: { beautify: false, preamble: "/* uglified */" } }; var result = UglifyJS.minify(code, options); console.log(result.code); // /* uglified */ // alert(10);" To produce warnings: var code = "function f(){ var u; return 2 + 3; }"; var options = { warnings: true }; var result = UglifyJS.minify(code, options); console.log(result.error); // runtime error, `undefined` in this case console.log(result.warnings); // [ 'Dropping unused variable u [0:1,18]' ] console.log(result.code); // function f(){return 5} An error example: var result = UglifyJS.minify({"foo.js" : "if (0) else console.log(1);"}); console.log(JSON.stringify(result.error)); // {"message":"Unexpected token: keyword (else)","filename":"foo.js","line":1,"col":7,"pos":7} Note: unlike uglify-js@2.x, the 3.x API does not throw errors. To achieve a similar effect one could do the following: var result = UglifyJS.minify(code, options); if (result.error) throw result.error; ecma (default undefined) - pass 5, 6, 7 or 8 to override parse, compress and output options. compress or mangle is enabled then the toplevel option will be enabled.. nameCache (default null) - pass an empty object {} or a previously used nameCache object true to support IE8. keep_classnames (default: undefined) - pass true to prevent discarding or mangling of class names. keep_fnames (default: false) - pass true to prevent discarding or mangling of function names. Useful for code relying on Function.prototype.name. If the top level minify option keep_classnames is undefined it will be overriden with the value of the top level minify option keep_fnames. safari10 (default: false) - pass true to work around Safari 10/11 bugs in loop scoping and await. See safari10 options in mangle and output for details. { parse: { // parse options }, compress: { // compress options }, mangle: { // mangle options properties: { // mangle property options } }, output: { // output options }, sourceMap: { // source map options }, ecma: 5, // specify one of: 5, 6, 7 or 8 keep_classnames: false, keep_fnames: false, ie8: false, module: false, nameCache: null, // or specify a name cache object safari10: false, toplevel: false, warnings: false, } To generate a source map: var result = UglifyJS.minify({"file1.js": "var a = function() {};"}, { sourceMap: { filename: "out.js", url: "out.js.map" } }); console.log(result.code); // minified output console.log(result.map); //.minify({"file1.js": "var a = function() {};"}, { sourceMap: { root: "", url: "out.js.map" } }); If you're compressing compiled JavaScript and have a source map for it, you can use sourceMap.content: var result = UglifyJS.minify({"compiled.js": "compiled code"}, { sourceMap: { content: "content from compiled.js.map", url: "minified.js.map" } }); // same as before, it returns `code` and `map` If you're using the X-SourceMap header instead, you can just omit sourceMap.url. bare_returns (default false) -- support top level return statements ecma (default: 8) -- specify one of 5, 6, 7 or 8. Note: this setting is not presently enforced except for ES8 optional trailing commas in function parameter lists and calls with ecma 8. html5_comments (default true) shebang (default true) -- support #!command as the first line arrows (default: true) -- Converts ()=>{return x} to ()=>x. Class and object literal methods will also be converted to arrow expressions if the resultant code is shorter: m(){return x} becomes m:()=>x. This transform requires that the ecma compress option is set to 6 or greater. booleans (default: true) -- various optimizations for boolean context, for example !!a ? b : c → a ? b : drop_console (default: false) -- Pass true to discard calls to console.* functions. If you wish to drop a specific function call such as console.info and/or retain side effects from function arguments after dropping the function call then use pure_funcs instead. drop_debugger (default: true) -- remove debugger; statements ecma (default: 5) -- Pass 6 or greater to enable compress options that will transform ES5 code into smaller ES6+ equivalent forms. evaluate (default: true) -- attempt to evaluate constant expressions expression (default: false) -- Pass true to works best with mangle enabled, the compress option passes set to 2 or higher, and the compress option toplevel enabled. hoist_vars (default: false) -- hoist var declarations (this is false by default because it seems to increase the size of the output in general) if_return (default: true) -- optimizations for if/return and if/continue inline (default: true) -- inline calls to function with simple/ return statement: false-- same as 0 0-- disabled inlining 1-- inline simple functions 2-- inline functions with arguments 3-- inline functions with arguments and variables true-- same as 3 join_vars (default: true) -- join consecutive var statements keep_classnames (default: false) -- Pass true to prevent the compressor from discarding class names. See also: the keep_classnames mangle option.. keep_infinity (default: false) -- Pass true to prevent Infinity from being compressed into 1/0, which may cause performance issues on Chrome. loops (default: true) -- optimizations for do, while and for loops when we can statically determine the condition. module (default false) -- Pass true when compressing an ES6 module. Strict mode is implied and the toplevel option for this, UglifyJS will assume that object property access (e.g. foo.bar or foo["bar"]) doesn't have any side effects. Specify "strict" to treat foo.bar as side-effect-free only when foo is certain to not throw, i.e. not null or undefined. reduce_funcs (default: true) -- Allows single-use functions to be inlined as function expressions when permissible allowing further optimization. Enabled by default. Option depends on reduce_vars being enabled. Some code runs faster in the Chrome V8 engine if this option is disabled. Does not negatively impact other major browsers.. side_effects (default: true) -- Pass false to disable potentially dropping functions marked as "pure". A function call is marked as "pure" if a comment annotation /*@__PURE__*/ or /*#__PURE__*/ immediately precedes the call. For example: /*@__PURE__*/foo(); switches (default: true) -- de-duplicate and remove unreachable switch branches toplevel (default: false) -- drop unreferenced functions ( "funcs") and/or variables ( "vars") in the top level scope ( false by default, true to drop both unreferenced functions and variables) top_retain (default: null) -- prevent specific toplevel functions and variables from unused removal (can be array, comma-separated, RegExp or function. Implies toplevel) typeofs (default: true) -- Transforms typeof foo == "undefined" into foo === void 0. Note: recommend to set this value to false for IE10 and earlier versions due to known issues. unsafe (default: false) -- apply "unsafe" transformations (discussion below)ma compress option is set to 6 or greater. unsafe_comps (default:_Function (default: false) -- compress and mangle Function(args, code) when both args and code are string literals. unsafe_math (default: false) -- optimize numerical expressions like 2 * x * 3 into 6 * x, which may give imprecise floating point results. unsafe_methods (default: false) -- Converts { m: function(){} } to { m(){} }. ecma must be set to 6 or greater to enable this transform. If unsafe_methods is a RegExp then key/value pairs with keys matching the RegExp will be converted to concise methods. Note: if enabled there is a risk of getting a " <method name> is not a constructor" TypeError should any code try to new the former function. unsafe_proto (default: false) -- optimize expressions like Array.prototype.slice.call(a) into [].slice.call(a) unsafe_regexp (default: false) -- enable substitutions of variables with RegExp values the same way as if they are constants. unsafe_undefined (default: false) -- substitute void 0 if there is a variable named undefined. eval (default false) -- Pass true to mangle names visible in scopes where eval or with are used. keep_classnames (default false) -- Pass true to not mangle class names. See also: the keep_classnames compress option. keep_fnames (default false) -- Pass true to not mangle function names. Useful for code relying on Function.prototype.name. See also: the keep_fnames compress option. module (default false) -- Pass true an ES6 modules, where the toplevel scope is not the global scope. Implies toplevel. reserved (default []) -- Pass an array of identifiers that should be excluded from mangling. Example: ["foo", "bar"]. toplevel (default false) -- Pass true to mangle names declared in the top level scope. safari10 (default false) -- Pass true to work around the Safari 10 loop iterator bug "Cannot declare a let variable twice". See also: the safari10 output option. Examples: // test.js var globalVar; function funcName(firstLongName, anotherLongName) { var myVariable = firstLongName + anotherLongName; } var code = fs.readFileSync("test.js", "utf8"); UglifyJS.minify(code).code; // 'function funcName(a,n){}var globalVar;' UglifyJS.minify(code, { mangle: { reserved: ['firstLongName'] } }).code; // 'function funcName(firstLongName,a){}var globalVar;' UglifyJS.minify(code, { mangle: { toplevel: true } }).code; // 'function n(n,a){}var a;' builtins (default: false) -- Use true to. regex (default: null) -— Pass a RegExp literal to only mangle property names matching the regular expression. reserved (default: []) -- Do not mangle property names listed in the reserved array. will set this to true, but you might need to pass -b even when you want to generate minified code, in order to specify additional arguments, so you can use -b beautify=false to override it. braces (default false) -- always insert braces in if, for, do, while or with statements, even if their body is a single statement. false) -- pass true or "all" to preserve all comments, "some" to preserve some comments, a regular expression string (e.g. /^!/) or a function. ecma (default 5) -- set output printing mode. Set ecma to 6 or greater to emit shorthand object properties - i.e.: {a} instead of {a: a}. The ecma option will only change the output in direct control of the beautifier. Non-compatible features in the abstract syntax tree will still be output as is. For example: an ecma setting of 5 will true to preserve lines, but it only works if beautify is set to false. quote_keys (default false) -- pass true to true to work around the Safari 10/11 await bug. See also: the safari10 mangle option. semicolons (default true) -- separate statements with semicolons. If you pass false then whenever possible we will use a newline instead of a semicolon, leading to more readable output of ugl true to wrap immediately invoked function expressions. See #640 for more details. You can pass --comments to retain certain comments in the output. By default it will keep JSDoc-style comments that contain "@preserve", "@license" or "@cc_on" (conditional compilation for IE). You can pass --comments all to keep all the comments, or a valid JavaScript regexp to keep only comments that match this regexp. For example Note, however, that there might be situations where comments are lost. For example: function f() { /** @preserve Foo Bar */ function g() { // this function is never called } return something(); }. unsafe compress) { console.log("debug stuff"); } You can specify nested constants in the form of --define env.DEBUG=false..minify(fs.readFileSync("input.js", "utf8"), { compress: { dead_code: true, global_defs: { DEBUG: false } } }); To replace an identifier with an arbitrary non-constant expression it is necessary to prefix the global_defs key with "@" to instruct UglifyJS to parse the value as an expression: UglifyJS.minify("alert('hello');", { compress: { global_defs: { "@alert": "console.log" } } }).code; // returns: 'console.log("hello");' Otherwise it would be replaced as string literal: UglifyJS.minify("alert('hello');", { compress: { global_defs: { "alert": "console.log" } } }).code; // returns: '"console.log"("hello");' minify() // example: parse only, produce native Uglify AST var result = UglifyJS.minify(code, { parse: {}, compress: false, mangle: false, output: { ast: true, code: false // optional - faster if false } }); // result.ast contains native Uglify AST // example: accept native Uglify AST input and then compress and mangle // to produce both code and native AST. var result = UglifyJS.minify(ast, { compress: {}, mangle: {}, output: { ast: true, code: true // optional - faster if false } }); // result.ast contains native Uglify AST // result.code contains the minified code in string form. Transversal and transformation of the native AST can be performed through TreeWalker and TreeTransformer respectively. UglifyJS .minify(code, { compress: false, mangle: true }); Uglify compress option and just use mangle.. Function.prototype.toString()or Error.prototype.stackto be anything in particular. .watch()or Proxy). Object.defineProperty(), Object.defineProperties(), Object.freeze(), Object.preventExtensions()or Object.seal()).
https://developer.aliyun.com/mirror/npm/package/@fabiosantoscode/uglify-es
CC-MAIN-2020-24
refinedweb
2,395
50.53
I'm using PB kernel (see below) in an AIR / Flex application to speed up some calculations. The data I supply is a Vector.<Number> of floating point precision pixels. Every pixel is stored as three consecutive Numbers respectively for R,G,B channels, which corresponds to image3 and pixel3 data types (well, if you forget the conversion between IEEE 754 double and float). I only need to store the result of my calculation on G-channel which I chose for luminance. However, only the first four pixels are computed correctly. Starting from the 5th one there seem to be a problem with incorrect offsets of the channels, I suppose. To make matters worse, after removing the last division "... / div" from my kernel this partial result is fine. Identical code in AS3 works as expected. Here's a sample output of both methods: The kernel: <languageVersion : 1.0;> kernel Foobar < namespace : "Your Namespace"; vendor : "Your Vendor"; version : 1; description : "your description"; > { input image3 src; output pixel3 dst; parameter float avgY; parameter float maxY; parameter float exp; parameter float div; void evaluatePixel() { pixel3 p = sampleNearest(src,outCoord()); float Y = p.g / avgY; p.g = (log(Y + 1.0) / log(2.0 + pow(Y / maxY, exp) * 8.0)) / div; dst = p; } } Equivalent ActionScript 3 code: for (i = 1; i < data.length; i += 3) { var Y:Number = data[i] / avgY; data[i] = (Math.log(Y + 1) / Math.log(2 + Math.pow(Y / maxY, exp) * 8)) / div; } Further analysis revealed classic symptoms of the buffer overflow error. First of all, using a literal value rather than parameter for avgY yields correct results. Adding a dummy variable results in a shift of the intermediate values. Declaring yet more variables leads to overwriting one of the channels with the given dummy value (example below). At first I thought it might be due to erroneous PB compiler so I disassembled the kernel code using haXe () and Tinic's Uro C++ tool (). However, I carefully scrutinized the assembly code and have to admit it's perfectly fine. Perhaps the problem lies with the implementation of Shader class within Flash? Or maybe I'm utterly wrong? Desperately looking for a solution. Example:
https://forums.adobe.com/thread/602339
CC-MAIN-2017-47
refinedweb
363
58.99
Hello, I want to ask why this code does not work: /*jshint browser:true */ /*global $, console, alert */ (function () { "use strict"; /* hook up event handlers */ function register_event_handlers() { /* button #revBtn */ $(document).on("click", "#revBtn", function (evt) { var canvas = document.getElementById("map-div"), m; var latlng = new google.maps.LatLng(51.4975941, -0.0803232); var options = { center: latlng, zoom: 11, mapTypeId: google.maps.MapTypeId.ROADMAP }; m = new google.maps.Map(m, options); }); } document.addEventListener("app.Ready", register_event_handlers, false); })(); The above code is from my index_user_scripts.js This is what I got from JSHint log: 16 'google' is not defined. (W117) var latlng = new google.maps.LatLng(51.4975941, -0.0803232); 21 'google' is not defined. (W117) mapTypeId: google.maps.MapTypeId.ROADMAP 24 'google' is not defined. (W117) m = new google.maps.Map(m, options); The map supposed to change to the given latitude and longitude values. I am using Intel XDK version 3240, using Standard HTML5 Only by designer. Any idea how do I resolve this? Link Copied JSHint simply doesn't know about the 'google' namespace. That doesn't necessarily mean there is an actual error. Do you have the inclusion to the google maps API in your HTML? If using the App Designer google maps widget you should. If you do, then you could add 'google' to the global listing in index_user_scripts.js to remove the JSHint warning. I'm not sure your code is supposed to change the Lat/Lng. The map object should already be initialized in google_maps.js on startup, and in the Properties of the Google Map you can set the initial center location and zoom. Your code is initializing a _new_ map object, which should not be needed. Take a look at google_maps.js (which should be bound into your project). You'll see that window.googleMaps is an array of all the maps set up for your app. So googleMaps[0] should be your Google Map. To affect it, use the Google Maps API. For example: googleMaps[0].setCenter(new google.maps.LatLng(37.4419, -122.1419), 13); will change the center point of the map. For more information on the Google Maps API see Hope this helps, Chris
https://community.intel.com/t5/Software-Archive/GoogleMaps-JavaScript-API-Problem/m-p/1111449/highlight/true
CC-MAIN-2021-43
refinedweb
364
79.26
14 January 2010 05:59 [Source: ICIS news] SINGAPORE (ICIS news)--Shares of petrochemical companies in Thailand gained Thursday on expectations of better first-quarter earnings on the back of rising product prices and improving demand. At 13.32 hours ?xml:namespace> “In the first quarter, there might be some surprise on the upside for petrochemical earnings,” said Suttichai Kumworachai, a Bangkok-based analyst at brokerage KGI Securities, citing wider overall spread on chemical products. “There seems to be very surprising strong demand and the market is very tight due to [plant] shutdowns,” he said. Fourth-quarter 2009 earnings for the companies may just be the same as the third quarter’s results if not softer due to weak spreads but investors have been looking past this judging from the strong share prices of petrochemical stocks, he said. Issues about the stalled petrochemical projects of these companies in Mab Ta Phut, Rayong province were temporarily set aside. Overall sentiment in the country’s equities market, meanwhile, has remained subdued and appetite for new listings may be muted in the first quarter. Indorama Ventures, the parent of polyethylene terephthalate (PET) producer Indorama Polymers, has plans to do an initial public offering (IPO) of 931m shares at Thai baht (Bht) 10.20-12.60 each on the Thai bourse. KGI Securities was projecting only a very limited upside to the benchmark stock index in the first three months of the year to 760 points, said Suttichai. Topping the list of concerns in the country was its shaky politics, said the analyst. Concerns about the strength of the global economic recovery and the timing of the withdrawal of fiscal and monetary support across economies, meanwhile, continued to hound the market, he said. Sentiment and market conditions may get better in the second half as the global economic picture gets clearer, Suttichai said. “For this year, we have a target of 850, which means we have a 15% upside for the SET index,” he added. ($1 = Bht33
http://www.icis.com/Articles/2010/01/14/9325571/thai-petchem-stocks-gain-on-rosy-q1-results-outlook.html
CC-MAIN-2015-11
refinedweb
333
54.86
- Change a node's text - Reversed each loop over a store? - Row Grid height Dynamically increases/Decreases in ExtJS 4 - Date picker - CDN Network - Is it possible to open a .ppt on a window? - Enable/Disabling row in a Grid in extjs4 - Combo Box Dirty Field Indicator - Multiselect combo with typeahead - Ext.define instances extraParams being set on all subsequent instances - Grid Drag and Drop - About Merging the two folder structure CodeIgniter and Sencha - How to render checkbox, textFiled,selectbox etc in a single grid column - changing width of columns messes up the width of the grid - sync grid scrolling positions - ComboBox Display Edit Values Show [object, Object] in RowEditing Grid - Error Occurs when attempting to Load Data into an XMLStore in Architect 2 on 4.1.X - change row color in a grid according to a value - Chart/draw sprites being written with hidden="false" in IE9 - Extjs 4.1.1 When init Grid bbr catch error! - Application halts if writing to IE console. - PagingToolbar in store of 'memory' proxy type - MVC, store proxy response on Controller, Good code solution, Full site building ... - add dynamic options to dropdown - Include Google Earth api to extjs - Integration tests with ExtJS 4.1.1 and capybara-webkit: * is not a constructor - Grid rownumberer always displaying '1' for all the newly added records in grid - How to replace one panel by another in Ext.Windows - How to make window draggable by body? - Panel afterExpand\afterCollapse events - How can i split js file - Unable to upload files - Creating sub menu using ExtJS 4.1 - How to render HTML in Ext.MessageBox? - Find center co-ordinates of browser / Viewport - how to have a dynamic extend? - Disabling the some checkboxselectionmodel based on the condition - Customer Exception Using ASP.Net - Binding of static store to treepanel - Extjs 4 grid checkbox column - Text Area change event in extjs4.1 - How to define functions I could call from everywhere in application ? - Date picker - Example of Ext.direct.PollingProvider with url being a direct function? - MVC matters : How to link ExtJS to a database (PostGreSQL) ? - Non-Legend Chart Line Style Disappears on Panel Expand - Selection CheckboxModel doesn't fire events - create JSB3 file from url that can only be accessible by signing in - Infinite Scrolling / Lazy scrolling in ExtJS - Appending a Store instead of Updating/Overwriting It - How to process images then display them in canvas - store sync cannot obtain response in failure listener... - How to designate convert function in metadata? - Tree nodes displaying extra charaters in IE . - Tree Selection Model in Extjs not picking up children recursively - what to include for Row editing - in extjs4, when tabpanel change, tabpanel's showing have problem! - Are Stores sharing the same Model objects? - Tabbar at bottom - Multiple checkbox columns in a grid panel in extjs 4.1 - Resizable Ext JS 4 Chart Tip? - Ext.ux.grid.ComboColumn renders without comboboxes arrow. - Tooltip not fitting to content IE - Spaces in textsprites - Resizable Ext JS 4 Chart on mobile devices - How To Use Two Or More Features In Grid - [ FORM ] Basic ExtDirect api load with data set to null - Row Edit grid onload function in extjs4.1 - Store With Parameters - Showing popup menu on onmouseover - XML and xPath using Ext.DomQuery - display help icon next to button - Waiting message while removing records of a grid - MessageBox problem, see image? - TimeField Slider Editor in Window/Floating Panel - Changing title of graph produces error - How to get cell index (or dataIndex) of the cell that triggered itemcontextmenu ? - Grid Height should dynamically Grow/Shrink based on records in Extjs 4.1 - Applying Css for Button control - On click of enter button inside the text area cursor not moving to new line Extjs 4 - Problem while doing a clearValue in a combo box - How to Error message in store sync callback - Loading a view into an existing panel by replacing an existing one - POST form data and get file - Store doesn't raise load event - Using childEls in header of a window - How to update checkbox box label - Ext.tab.Panel Tools Configuration - Ability to load a store from another store - RowExpander grid into grid - Use other components (buttons etc) in View component? - combobox typeahead and forceselection problem - cellEditing plugin with autosync not working - pass variable - Ext.tree.panel, conditionally render node text and type - how do i reset the filter properties on the store - formpanel with other formpanels inside, submit problem. - Opening popup window on grid.Panel cell click - How to handle Browser Vertical and Horizontal Scrollbar as GridPanel Scrollbar - Ext.Window - autocomplete textfield data from webservice - tabpanel without tabs showing... - EXTJS MVC sending data from one view to another - Ext.flash.Component : Install flash if it is not installed - store proxy extraparams issue - How to avoid that an event executes its action - How to remove white corners? - actioncolumn to use text instead of icons - JSP MVC IN EXT JS 4 - form how to knwo invalid fields ? - Grid and Form Panel in a Window - How to know if a store is loaded? - extjs4 and virtual keyboard - grid pane with row expander plugin: unable to showing text from the record - Column lock stoping cellclick of the grid - Setting Grid the Row height Manually in extjs 4 - Creating Label and TextBox over the window - Auto Population of Current Time - how to word-wrap a node text in Ext.tree.Panel. in extjs 4.1 - How to enable the icon after the textfield - Expand/Collapse buttons issue in grouping grid with Buffered store - Typeahead in Ext.picker.Time - Tree Panel : auto collapse of an expanded tree node... - viewport with vbox layout - add row in grouped grid - Refresh RowNumberer after store.insert() ? - Datepicker - choose initial date - Trouble uploading files in Opera - Dragging list of valuesinto target panel - Extjs file size is so big. Anyone can help me on this - about Categorized Items in a menu panel - Data for Combo Box from Database - How to Load mask to a window/store before loading ? - Problem with converted field - Expandable Panel - how to use expressInstaller - How to start an automatic file download after a dblclick event on a button? - Every action over the grid resizes the width columns. - Java script error when using proxy url config in Store - textfield selected text - Rebinding Grid from Menu click - minify - Integrate EXTJS MVC with Portlets(Run on Portal Server) - DataIndex of grid in ExtJS 4.1 - Choosing config of base layout for application - how to add record dynamically to a grid - Sharing '0.parentNode' is null or not an object - Sorting not proper when grouping - Finding records of similar type - need help export/import - Datefield Y/m bug in EXTJS ? - Possible bug using getEditor to dynamically set a combobox - request.xhr.readyState undefined for some AJAX calls - Remove added sprite from chart surface - How to load a url in extjs4.1 - ext window visibility issue in IE & Firefox - Hyperlink - Extjs 4.1.0 MVC - Grid continously shows loading mask while store has reloaded - model/store field setter/getter - extjs 4.1 doc example code "cell editing" is not working - Dropdown column in a grid panel. - wizard functionality in a tab panel - How to programatically select an item in Ext.view.View - Applying TdCls styles dynamically for textarea in extjs4.1 - Ext.ux.GMapPanel with markers takern from server? - What's the difference between model and store? - ExtJs 4.1 - Uncaught Error - Cannot read property "items" of undefined. - paste plaintext using htmleditor - ExtJs4.1 - Form data not being submitted to server - Grid menu sort . What listener shoud I use - Problem in dynamic tooltip - Empty an array - row count - Display icons in Ext.form.ComboBox items - GRID: Sort on load doesn't show sorting arrows on columns. - Enter Key si not working inside text area in IE8 and IE9 - Combobox autocomplete to search the whole string in local mode - Removing the splitter when a panel collapses - Tree/TreeStore mixing checkboxes and radio buttons - Ext.js is undefined in Chrome - How to change background color/image of a tab? - How to get auto completion for EXTJS 4.1 in Eclipse Juno???? - bind store error - WTF??? - How to add Extra textbox in RowEditor - EXT JS 4 MVC - call from controller a click event on a div - Hide Ckeditor in some scenarios - Column Editor which is having panel doent get values - Vbox Vertical Scroll Issue - Cannot get button by find field and name - Apply background color to selected row.. - difference - TypeError: Ext.getCmp("DetailsForm").getForm is not a function - Alignment of icon next to textfield control - How to create One file for multiple stores? - Extjs - 4.1.1 - Moving between views in an Extjs app - GroupingSummary + XMLStore + remoteRoot ? - ExtJS 4.1 + Spring REST Simple Form Submission Example ? - default button change with image in extjs - [ FORM ] Html Editor - Ext Direct - Bug while setting value while collapsed - Unset a value in multiselect combo - Drag and drop from outside Ext JS application - Input text and Button within Menu - How to see object properties ? - How to get hold over JSON object while using HTTPProxy? - how to arrange an textfield and a button to one line horizontally? - Creating Menu items dynamically - How to get TextField value from the Grid - How to handle "HTTP Error 302" in Extjs & PHP? - Extjs 4.1 - Getting Java script error when submitting the Field Container Editable Row - form submit upload file via ext.direct api submit - how do i Clear all selections in Ext.tree.Panel? Ext JS 4.1 - Do we have the chance to achieve the 4.1.2 - parameter field or property in remote filter with grid and store - Ext.DomQuery not working with XML namespaces - Failure code in Firefox: 0x805e0006 - Infinite scroll table dont work. - Check duplicate rows in ExtJs Grid - RowEditing how to enabled via record settings. - Combobox: hide selected value from dropdown list - refresh grid/store after data changed in store - ExtJS 4 or 4.1 MessageBox Custom Buttons - Ext.grid.RowEditor: grid header above the editor - Grid Drag to Group? - How can I insert new record to a store? - Calculated field in model - upload file with api extdirect error - Grid with multiple views - Why the pagingToolbar's Next Buttons is Disabled ? - Controller Refs Selector Problem 2 - File Upload response Bug - ExtJS form submission ? - why php $_FILES is empty whe uploading form via api ?? - Change cursor for click event - graphing problem with multiple node XML data and unix timestamps - Text Field in the header of a column - Cannot read property "fields" of undefined - Setting Text Area height to 5 rows by default inside row edit grid - Current Edit row data not visible in extjs4.1 grid - Applying different Css styles in extjs4.1 - Reorder Store after move columns - rowexpand and rezise grid height - ExtJS Webtop with 'Desktop Switcher'? - TabReorderer plugin's reordering does not work properly if there are many tabs - Add New Row To Grid Panel With RowEditing Plugin - Adding node to a treestore doesn't use Model - MVC design
https://www.sencha.com/forum/archive/index.php/f-87-p-34.html?s=aa6962fe5093c8f150fedc953cdcc6f1
CC-MAIN-2020-16
refinedweb
1,815
54.63
Python/C API: Reference Counting 5th semester is finally over and let’s just say I have been to the dark side. Moving on. The most important aspect of Python is memory management. As mentioned in the earlier post of this series, PyObject* is a pointer to a weird data type representing an arbitrary Python object. All Python objects have a “type” and a “reference count” and they live on heap so you don’t screw with them and only pointer variables cab be declared. I had skipped the part of referencing. In this post, I’ll talk about Memory Management in Python and Reference Counts. So What is Reference Counting? Python’s memory management is based on reference counting. Every Python object has a count of the number of references to the object. When the count becomes zero, the object can be destroyed and its memory reclaimed. Reference counts are always manipulated explicitly using macros Py_INCREF() to increment the reference count and Py_DECREF to decrement it by one. The decref macro is considerably more complex than the incref one, since it must check whether the reference count becomes zero and then cause the object’s deallocator, which is a function pointer contained in the object’s type structure. Background: PyObject: Python objects are structures allocated on the heap. Accessed through pointers of type PyObject* An object has a reference count that is increased or decreased when a pointer to the object is copied or deleted. When the reference count reaches zero there are no references to the object left and it can be removed from the heap. Py_INCREF() and Py_DECREF(): The macros Py_INCREF(op) and Py_DECREF(op) are used to increment or decrement reference counts. Py_DECREF() also calls the object’s deallocator function; for objects that don’t contain references to other objects or heap memory this can be the standard function free() The argument shouldn’t be a NIL pointer. To prevent Memory Leaks, corresponding to each call to Py_INCREF(), there must be a call to Py_DECREF(). Owned vs Borrowed: Every PyObject pointer is either owned or borrowed. An owned reference means you are responsible for correctly disposing of the reference. Objects are not owned, they are all shared. It’s the references to the objects that are owned or borrowed. A borrowed reference implies that some other piece of code(function) owns the the reference, because the code’s interest started before yours, and will end before yours. So you must not deallocate the pointer or decrease the reference. Otherwise, crash! A caller must have a reference to the arguments it passes into a called function, so arguments are almost always borrowed. Acquiring Owned References: There are two ways to get an owned reference: Accept a return value from a C function that returns a PyObject. Most C API functions that return PyObject return a new reference, but not all. Some return the borrowed reference. Read the docs carefully. Python/C API functions that borrow references - StackOverflow. Use Py_INCREF on a borrowed PyObject pointer you already have. This increments the reference count on the object, and obligates you to dispose of it properly. Discarding Owned References: Once you have an owned reference, you have to discard it properly. There are three ways. Return it to the caller of your function. This transfers the ownership from you to your caller. Now they have an owned reference. Use Py_DECREF() to decrement the reference count. Store it with PyTuple_SetItem() or PyList_SetItem(), which are unusual among C API functions: they steal ownership of their item argument. Python/C API functions that steal reference - StackOverflow. Code Example: So I have been working on my pointer skills and created a simple selection sort to sort a list of integers. Here’s the code. Include Libraries: #include <Python.h> #include <stdio.h> #include <stdlib.h> C Function: PyArg_ParseTuple works like scanf and returns 1 if successful. So, here I’m trying to check whether the passed argument(one argument only) is a PyObject (list) or not and similar to scanf, storing the value of the argument in list (PyObject*). PyObject* py_selectionSort(PyObject* self, PyObject* args) { PyObject* list; if (!PyArg_ParseTuple(args, "O", &list)) { printf("Not a listn"); return NULL; } // continued } NOTE: list is an object we pull out of the args with PyArg_ParseTuple. Since args is borrowed, we can borrow value out of it, so list is also borrowed. Create array from list: I am creating an integer array from the Python list. PyObject* py_selectionSort(PyObject* self, PyObject* args) { // continued.. PyObject* list_item; Py_ssize_t i, len; len = PyList_Size(list); long* list_array = (long*) malloc(len*(sizeof(long))); /* create array from list */ for(i=0; i<len; i++) { list_item = PyList_GetItem(list, i); if PyInt_Check(list_item) { *list_array = PyInt_AsLong(list_item); list_array++; } // Py_DECREF(list_item); No need to decrease the reference count // as PyList_GetItem returns a borrowed reference. } list_array-=len; // continued.. } @franksmit pointed out the mistake with borrowed reference. Here list_item is an owned reference, so it is your responsibility to discard it properly using Py_DECREF. Sorting: This is just C part. You can skip this part if you know how to sort stuff. PyObject* py_selectionSort(PyObject* self, PyObject* args) { // continued.. int min = *list_array; int index = 0; int l; int min_element, temp_element; for (j=0; j<len; j++) { list_array+=j; min = *list_array; index = j; for (k=j; k<len; k++) { if (*list_array < min) { min = *list_array; index = k; } list_array++; } list_array = list_array - len; if (index != j) { temp_element = *(list_array + j); *(list_array + j) = *(list_array+ index); *(list_array + index) = temp_element; } } // continued .. } Create list from the sorted array: After sorting the integer array, I want a list (PyObject*) which I can return. PyObject* py_selectionSort(PyObject* self, PyObject* args) { // continued.. /* create list from sorted array */ PyObject* flist = PyList_New(len); for (i=0; i<len; i++) { list_item = PyInt_FromLong(*list_array); PyList_SetItem(flist, i, list_item); list_array++; //Py_DECREF(list_item); /* PyList_SetItem steals the reference */ } list_array-=len; // continued .. } NOTE:Here we’re not to use Py_DECREF to decrement the reference count of list_item because PyList_SetItems() steals the reference. Cleaning Up and Return: Memory management is very important in any Python program hence you need to clean up to avoid memory leaks and crashes. PyObject* py_selectionSort(PyObject* self, PyObject* args) { // continued .. /* make sure that list_array points to the first allocated block of the array * else, free() will cause a segmentation fault. */ free(list_array); /* list is an object we pull out of the args with PyArg_ParseTuple. * Since args is borrowed, we can borrow value out of it, * so list is also borrowed. */ //Py_DECREF(list); return flist; } NOTE: list is an object we pull out of the args with PyArg_ParseTuple. Since args is borrowed, we can borrow value out of it, so list is also borrowed. list_array must point to the first allocated block of the array while using free() to deallocate it. Afterpart: Declare PyMethodDef and the module. PyMethodDef methods[] = { {"selectionSort",(PyCFunction)py_selectionSort, METH_VARARGS, NULL}, {NULL, NULL,0,NULL}, }; PyMODINIT_FUNC initselectionSort(void) { Py_InitModule3("selectionSort", methods, "Extension module example!"); } You can find/fork code on my GitHub. References: Python/C API docs A Whirlwind Excursion through Python C Extensions - Ned Batchelder Ed’s Eclectic Science Page Numerous StackOverlfow questions. P.S. Winter break is on. I need to speed things up and start with Mahotas and other Computer Vision work. I have to make some notes, presentation slides and gather all my CV work for the next semester. Playing around with Android UI Articles focusing on Android UI - playing around with ViewPagers, CoordinatorLayout, meaningful motions and animations, implementing difficult customized views, etc.
https://jayrambhia.com/blog/pythonc-api-reference-counting
CC-MAIN-2022-05
refinedweb
1,243
56.55
Runs an external program under the context of a different user and pauses script execution until the program finishes. RunAsWait ( "username", "domain", "password", logon_flag, "program" [, "workingdir" [, show_flag [, opt_flag]]] ) Paths with spaces need to be enclosed in quotation marks. It is important to specify a working directory the user you are running as has access to, otherwise the function will fail. It is recommended that you only load the user's profile is you are sure you need it. There is a small chance a profile can be stuck in memory under the right conditions. If a script using RunAs() happens to be running as the SYSTEM account (for example, if the script is running as a service) and the user's profile is loaded, then you must take care that the script remains running until the child process closes. When running as an administrator, the Secondary Logon (RunAs()) service must be enabled or this function will fail. This does not apply when running as the SYSTEM account. After running the requested program the script pauses until the program terminates. To run a program and then immediately continue script execution use the RunAs() function instead. Some programs will appear to return immediately even though they are still running; these programs spawn another process - you may be able to use the ProcessWaitClose() function to handle these cases. The "load profile" and "network credentials only" options are incompatible. Using both will produce undefined results. There is an issue in the Windows XP generation of Windows which prevents STDIO redirection and the show flag from working. See Microsoft Knowledge Base article KB818858 for more information about which versions are affected as well as a hotfix for the issue. Users running Windows XP SP2 or later, or Windows Vista or later are not affected. ProcessWait, ProcessWaitClose, Run, RunAs, RunWait, ShellExecute, ShellExecuteWait #include <AutoItConstants.au3> #include <MsgBoxConstants.au3> Example() Func Example() ; Change the username and password to the appropriate values for your system. Local $sUserName = "Username" Local $sPassword = "Password" ; Run Notepad and wait for the Notepad process to close. Notepad is run under the user previously specified. Local $iReturn = RunAsWait($sUserName, @ComputerName, $sPassword, $RUN_LOGON_NOPROFILE, "notepad.exe") ; Display the return code of the Notepad process. MsgBox($MB_SYSTEMMODAL, "", "The return code from Notepad was: " & $iReturn) EndFunc ;==>Example
https://www.autoitscript.com/autoit3/docs/functions/RunAsWait.htm
CC-MAIN-2016-07
refinedweb
379
55.74