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
Join the community to find out what other Atlassian users are discussing, debating and creating. Today I started using the Rapid Boards for the first time in our team. And I was quickly struck by something that seemed weird - our story point estimates on subtasks wasn't aggregated up to the parent story, hence I get the "error message" that I haven't estimates issue X, Y and Z when I select "Start sprint". This was obviously wrong, but I assumed it had something to do with a configuration missing than anything else. A couple of hours later I'm quite baffled. It seems that estimates in story points on subtasks are ignored by GH. It only cares about story points on the parent issue. Hours on the other hand can be included if the user configures this for the specific board, but story points are ignored. After further reading the blog () I understood that this was intentional, and that Atlassian doesn't seem to have any plan to include aggregation for story points in the future. The team I work with is a product team. We have a big backlog, and we do not estimate the user stories when they are added to the backlog. The backlog is used as just that, a backlog, and we plan the sprints based on what is most important for the business at all times. So how do we plan the sprints? Before every sprint planning, the product owner and I sit down with the backlog and prioritize the issues using business value. Some issues have been estimated before, but moved back to the backlog, while other issues are "clean" in regards to estimates. So we add a "decent" amount and await the sprint planning result. During the sprint planning the team breaks down all user stories into sub-tasks and estimate them in story points. To make sure we are relatively sure of the estimates, we do not allow for a larger estimate than 8 story points. And btw - story points are only considered in regards to complexity not 1 sp = X hours. After the sprint planning I sit down with the product owner again and consider the total estimate for the sprint vs. the velocity. If there are big gaps, we remove the issues that are the least important to the business. And we end up with a sprint the team can commit to. This has worked quite fine for several years now. But it seems that Atlassian doesn't want to support this way anymore - I have to do something else. It seems that it all comes down to estimate vs. tracking? E.g. that the user story should be estimated in regards to other user stories (e.g. user stories and complexity, 1 being bigger than the other), and that sub-tasks just as well can be estimated in hours (something we have been moving away from for 3.5 years now). Am I completely misunderstanding something here? Wouldn't it be great if the tool did not dictate how we run our teams. It seems like a logical feature to have sub task aggregate up to a story. Forcing teams to use hours in order for the burn down to work is illogical. JIRA is supposed to be a tool, not an Agile Methodology cop. Can this be really true that it is so complex just to add a feature being able to customize the rapidboard. to show what is required for the given project or customer. I think there is a misunderstanding of how estimating and planning should work in an agile evironment. User stories are a feature. "As a user, I should be able to create sub-tasks for user stories." This is the "card" that moves across the board. When doing high-level planning (say for an epic, the quarter, the year, etc...) you should as quickly as practical assign story points to the stories. These should be an estimate of relative size: 2 is twice the size as 1, 10 is twice as large as 5, etc... This should be enough information to establish velocity over several sprints and allow you to schedule several or many sprints into the future. During iteration planning (start of a sprint) the team adds all the relevant sub-tasks to that story and estimate each of them in hours. This book did a very good job of helping my understanding of best practices for Scrum: Hello, I have made a workaround I did a little something its not perfect at all should any of you do better just put it here. - It add a button left of PLAN mode - It work only for certain user since it can create a load on the isntance (get the issues data in rest) It add the sum of subtask instead of story point/time estimate when you click on it. Also add a custom field (we have another kind of priority system). You can use it to add story point or time, its like you want easy to edit. Add this code into the Announcement banner <script type='text/javascript'> AJS.$(document).ready(function () { var username = AJS.$('#header-details-user-fullname').attr('data-username'); console.log(username); if (username == 'name1' || username == 'name2') { var path = window.location.pathname; console.log (path); if (path.substring(path.lastIndexOf('/') + 1).indexOf('RapidBoard') > -1) { AJS.$('#ghx-modes').before('<button class="aui-button" id="add-ubi">Show CF and Aggregate Time</center>'); AJS.$('.add-ubi').on('click', function () { $('add-ubi').trigger("click"); }); AJS.$("#add-ubi").click(function () { //AJS.$("#add-ubi").toggleClass("active"); //AJS.$("#add-ubi").remove(); AJS.$('.ghx-issues > div').each(function () { try { console.log('Found issue list in sprints'); var row = this; var issueKey = AJS.$(this).attr("data-issue-key"); //console.log('Found issuekey' + issueKey); if (issueKey) { AJS.$.getJSON(AJS.contextPath() + '/rest/api/latest/issue/' + issueKey, function (data) { console.log('Got data for - ' + issueKey); if (data.fields.customfield_10222 || data.fields.customfield_10222 != null) { var value = data.fields.customfield_10222.value; if (value.lenght) {) { var value2 = data.fields.aggregatetimeoriginalestimate / 60 / 60 / 8; var actions2 = AJS.$(row).find('.ghx-end .aui-badge'); AJS.$(actions2).html(value2.toFixed(2).replace(/[.,]00$/, "") + "d"); } }); } } catch (ex) { console.log ("ERROR"); } }); AJS.$('.js-issue-list > div').each(function () { try { console.log('Found issue list in backlog'); var row = this; var issueKey = AJS.$(this).attr("data-issue-key"); if (issueKey) { console.log('Found issuekey' + issueKey); AJS.$.getJSON(AJS.contextPath() + '/rest/api/latest/issue/' + issueKey, function (data) { console.log('Got data for - ' + issueKey); if (data.fields.customfield_10222 || data.fields.customfield_10222 != null) { var value = data.fields.customfield_10222.value; console.log("we are inside of value" +issueKey) != null || data.fields.aggregatetimeoriginalestimate != 'undefined' || data.fields.aggregatetimeoriginalestimate != "" || data.fields.aggregatetimeoriginalestimate.lenght != 0) { var value2 = data.fields.aggregatetimeoriginalestimate / 60 / 60 / 8; var actions2 = AJS.$(row).find('.ghx-end .aui-badge'); AJS.$(actions2).html(value2.toFixed(2).replace(/[.,]00$/, "") + "d"); } }); } } catch (ex) { console.log ("ERROR"); } }); }); } } }); </script> Working with support from Arsenale Dataplane, we are now able to view a report that includes epics, the stories in those epics, and the subtasks for those stories. Though we are using Dataplane (a paid addon), the scheme for setting up a scripted field that can be used to "segment by" epics is still useful without it. How Dataplane solved the problem for me: import com.atlassian.jira.component.ComponentAccessor; import com.atlassian.jira.issue.CustomFieldManager; import com.atlassian.jira.issue.fields.CustomField; import com.atlassian.jira.issue.Issue; CustomFieldManager fieldManager = ComponentAccessor.getCustomFieldManager(); CustomField epicLinkField = fieldManager.getCustomFieldObjectByName("Epic Link"); CustomField epicNameField = fieldManager.getCustomFieldObjectByName("Epic Name"); if (issue.isSubTask()) { issue = issue.getParentObject(); } Issue epicIssue = (issue.getIssueTypeObject().getName().equals("Epic")) ? issue : issue.getCustomFieldValue(epicLinkField); return (epicIssue != null ? epicIssue.getCustomFieldValue(epicNameField) : null); I'm having a similar issue – the teams I'm now helping use main stories and subtasks. In addition to not having the subtask points "add up" and total in the main story, there's also the resource tracking problem. You know those nice resource tiles at the top of each sprint in backlog view and you can expland it and see where all your people are working? it won't read subtasks. So I've had to resort to manually putting everything in excel. I work in a very large team - about 24 devs including a handful of QAs (I know, we're trying to figure out how to break them out into smaller teams). If I could get them to only use Epics as their "main story" and instead of subtasks link the stories together the world would be a better place. But they're resisting, big time, so I'm researching. Hi Ivar Planning the sprints will rely on your business rules, every client can plan the sprint differently, but they will always have to use issues for it. Regarding story points and sub-tasks, as you already stated GreenHopper will not sum the sub-tasks in the task and also, you will not be able to finish a task in the sprint if the sub-tasks aren't all completed. We reccomend you creating one task instead of sub-task and create a epic label, that way you can keep track of all the tasks that belong to the same "task force". Please refer to this documentation regarding epics: You can take-off tasks from the already started sprint, but agile methods don't reccommend it. Just right click at the issue and select remove from sprint. Hope it helps. Ricardo Carracedo. Ricardo, I'm sorry to say that your answer didn't really give me anything. Of course a user story (task) isn't complete before all sub-tasks are resolved. And we are already using epics today to link things together - however, we are using regular "link issue" because we haven't started to use rapid boards yet. My main concern is that rapid boards doesn't sum the amount of story points on the sub-tasks. But it does for estimate in hours. Something that doesn't add up for me. Why choose one estimate type but not the other? If we are going to start using rapid boads, which I guess we have to if we want to continue to use Jira as the classical boards will die sometime in the future, we will either have to change our development process and introduce an "immediate estimate from the team lead" once an issue has been added to the backlog and then double up on the number of story points per sprint (the original guestimate from the team lead + the number of story points for the sub-tasks once estimated in the sprint planning), or we change estimate technique and start estimate sub-tasks in hours instead. For the second part, the burn down for story points will look bad as you will (potentially) have 0 story points resolved for the first days, and then get big jumps when the user stories gets resolved - in this case I guess it is only the burndown of hours that will indicate if we will hit the target or not. For the other part, if we double up the story points I guess we will get a burn down that behaves better, but I'm still not sure it will be better for us. Thing is - this has been working just fine for years, now rapid boards changes everything (at least, it seems). Hours on the other hand can be included if the user configures this for the specific board, but story points are ignored. I'm not seeing hours rolling up in GH either. Unit of tasks by definition has nothing to do with unit of user stories. It is a common practices to use story points for user stories and for tasks. But these are different story points just like one's team story points are different than other's team story points. They are incomparable as story points given to user stories are given with less knowledge than task points. It is your choice not to estimate stories (omit this step) and go straight to task estimation. Task estimation is done only during sprint planning meeting to judge whether something can fit into a sprint. Guess which story points are used to calculate the velocity of the team.... It's the PB story points..
https://community.atlassian.com/t5/Jira-questions/Rapid-Board-Story-Points-and-sub-tasks-Aggregate-Estimates-quot/qaq-p/212283
CC-MAIN-2019-22
refinedweb
2,053
56.66
Download source code for 9 simple steps to run your first Azure Table Program Introduction What will we do in this article? Step 1:- Ensure you have things at place Step 2:- Create a web role project Step 3:- Specify the connection string Step 4:- Reference namespaces and create classes Step 5:- Define partition and row key Step 6:- Create your ‘datacontext’ class Step 8:- Code your client Step 9:- Run your application Azure has provided 4 kinds of data storages blobs, tables, queues and SQL azure. In this section we will see how to insert a simple customer record with code and name property in Azure tables.In case you are complete fresher and like me you can download my two azure basic videos which explain what azure is all about Azure FAQ Part 1 :- Video1 Azure FAQ Part 2 :- Video2.Please feel free to download my free 500 question and answer eBook which covers .NET , ASP.NET , SQL Server , WCF , WPF , WWF , Silver light ,-requisite at place. You can read the below article to get the basic prerequisite . The next step is to select the cloud service template, add the web role project and create your solution. The ‘connectionstring’. We also need to specify where the storage location is , so select the value and select ‘Use development storage’ as shown in the below figure. Development storage means your local PC currently where you Azure fabric is installed. If you open the ‘ServiceConfiguration.cscfg’ file you can see the setting added to the file. In order to do Azure storage operation we need to add reference to ‘System.Data.Services.Client’ dll. Once the dlls are referred, let’s refer. The next step is to create your data context class which will insert the customer entity in to. In the same data context we have created an ‘AddCustomer’ method which takes in the customer entity object and call’s the ‘AddObject’ method of the data context to insert the customer entity data in to Azure tables. table’s structure. in to the table. //Loop through the records to see if the customer entity is inserted in the tabless foreach (clsCustomer obj in customerContext.Customers) { Response.Write(obj.CustomerCode + " " + obj.CustomerName + "<br>"); } It’s time to enjoy your hard work, so run the application and enjoy your success. You can get the source code from top of this article. Latest Articles Latest Articles from Questpond Login to post response
http://www.dotnetfunda.com/articles/show/766/9-simple-steps-to-run-your-first-azure-table-program
CC-MAIN-2017-04
refinedweb
409
60.95
Regula Falsi Method in Python Regula Falsi Method in Python In this, you will learn Regula Falsi Methon implementation in Python Programming. First of all, we discuss Regula falsi method and try to understand the concept of Regula Falsi. In the next part you will learn how to write code in Python. Regula falsi method or method of false position Regula falsi method or method of false position is a numerical method to solve an unknown equation. This is very similar to the bisection method algorithm and is one of the oldest methods. The bisection method was developed so that it converges at a very slow speed. The process of convergence in the bisection method is very slow. It depends on the choice of end points of the interval [a, b]. The f (x) function has no role in finding point C (which is the point between a and b). It can only be used to determine the next short interval [a, c] or [c, b]. C can be better estimated by taking a straight line L connecting the points (a, f (a)) and (b, f (b)) that meet the x-axis. To obtain the value of c we can equate the two expressions of the slope m of the L line. This method is an improvement over the slow convergence of the bisection method. To find the source, the input consists of a search interval [a, b], followed by a tangent joining (a, f (a)) & (b, f (b)). The point at which the tangent touches the x-axis is an interesting point. Steps: The continuous function f (x) is given at intervals [a, b] such as F (a) * f (b) <0 c = (a * f (b) - b * f (a)) / (f (b) - f (a)) f (a) * f (c) <0 if b = c else a = c Example 1: Write a Program to find and print roots of the given equation x**3-x**2+2 by Regula Falsi Method Python code: max_iter=100000 def func(x): return x**3-x**2+2 a = -100 b = 200 def regulafalsi(a,b): if func(a)*func(b)>=0: print("a and b are not rightly assumed") return 1 c = a for i in range(max_iter): c = (a*func(b)-(b*func(a)))/(func(b)-func(a)) if func(c)==0: break elif func(a)*func(c)<0: b = c else: a = c print("root of equation is:",c) regulafalsi(a,b) Output: root of equation is: -1.0000028705371073 Example 2: To print the root of equation x**3+x**2+x+7 and plot its graph from pylab import * import math def f(x): y = x**3+x**2+x+7 return y x = linspace(-3,3,100) xa = -1 xb = -3 xc = (xa*f(xb)-(xb*f(xa)))/(f(xb)-f(xa)) while abs(f(xc))>0.001:+x**2+x+7") grid(True) show() Output: The root is: -2.104817327832827 Example 3: To print roots of x3-2x+1 and plot its graph from pylab import * import math def f(x): y = x**3+2*x+1 return y x = linspace(-3,3,100) xa = -1 xb = -2 xc = (xa*f(xb)-(xb*f(xa)))/(f(xb)-f(xa)) while abs(f(xc))>0.01:+2*x+1") grid(True) show() output: The root is: -0.4564692206092183
https://www.epythonguru.com/2020/10/regula-falsi-method-in-python.html
CC-MAIN-2021-31
refinedweb
555
65.35
why you should implement or emulate remotes in your projects (there is really no need to write down any reasons, but the things is, I really like lists): - if you need to hide your project someplace and need to operate it covertly like spy devices. - if project will be installed in some inaccessible or high reaching place like DIY overhead projector, bird house water supply, etc... - if you need to remove all those ugly buttons on your project enclosure. - if you want to control your remote-controlled devices like TV with an Arduino or Raspberry Pi. - if you want to survive the singularity (earn brownie points with Skynet while you still have a chance) - because remotes are cool In this instructable, I'll show you how to: (Warning: Another list follows) - Using Arduino: - read remote signals using interrupts, so you can do other stuff on your Arduino while waiting for someone to press that button. Also interrupts will get the most accurate timing data. - decode remote codes to identify individual buttons without overflowing your memory. Usually saving a few button's IR codes will fill up your Arduino's memory... - recreate IR signals for any of your remote's button super easily. Control your TV with an Arduino! - read IR signals and implement it in your Python scripts. Play games with remotes! - recreate IR signal using Raspberry Pi. Make a universal remote control. Note: Since posting this instructable, I've discovered Shirriff's IR library for Arduino and I suggest that for the Arduino part of this instructable as it's extremely easy to use. But if you want to understand how IR really works on those remotes, the instructable will provide a good read. Maybe if I get some free time, I'll add steps for Shirriff's IR library: Step 1: Go Get Stuff What you need depends on what all you want to do. Still the list is quite short: - IR sensor (adafruit link) - IR LED (adafruit link) - Arduino or Raspberry Pi - NPN Transistor PN2222 - 1K ohm resistors - 220 ohm resistor - Some connecting wires - Of course, a remote control Step 2: IR Basics There are already very detailed instructions on how to read and recreate IR codes from a remote. I'll try to build upon ladyada's IR tutorial. I'll explain the basics and give a brief overview, but I'll keep linking to ladyada's tutorial's pages for detailed instructions. IR stands for Infra-Red. This is a part of the spectrum that goes beyond the red color and invisible to us. IR can be better called as heat waves. Whenever something radiates heat, be it a bulb, fire or sun, it radiates infrared rays. Even something that is not glowing(like a hot-plate) will be emitting IR. The IR we work with is generated by an IR LED. The IR is very weak and you will not feel its heat, but it is very useful for sending invisible focused rays to transfer data. Tip: Your average digital camera(even mobile camera) can view some amount of IR. Take a look at your remote's IR LED through your camera. IR remotes use a technique called modulation to reduce noise and data loss. They take a frequency(38kHz is most commonly used for remotes) and turns the IR LED on and off at that frequency. The IR LED's cycle will be 1/38000 seconds = 0.0000263 seconds = 0.0263 milliseconds = 26.3 microseconds long. So the LED will turn on for half of that duration, i.e. 26.3/2 = 13.15 microseconds, followed by being off for the same duration, and this goes on over and over again. Data is read/sent by measuring how long we keep turning the IR LED on-off at 38kHz. A simple IR code might be: blinking/modulating IR LED at 38kHz for 1500 microseconds, then keeping the IR LED off for 50 microseconds, then again modulating IR LED for 1500 microseconds, followed by finally turning off the LED until user presses a button again. The IR receiver is a 38kHz demodulator. It can only read remotes using that frequency to modulate signals. It will remain in HIGH state if you simply connect an IR LED to battery and shine on it. It will only give a LOW on its Vout pin when 38kHz modulated IR light falls on it. Create this simple circuit by ladyada to test your IR sensor. If we used a remote to shine the above simple IR code on the IR receiver, we will get a LOW on Vout for 1500 microseconds, then HIGH for 500 microseconds, then 1500 microseconds LOW, and finally HIGH indefinitely. Step 3: Reading IR Codes Using Arduino Now let's get to the interesting stuff. Connect your IR sensor to Arduino as shown in the image. I soldered some longer wires to my IR sensor and covered the joint with heat shrink. Make sure of the pinout of your sensor from its datasheet. Connect Arduino to PC and open up Arduino IDE. I modified the code from this tutorial by ladyada to read a remote's IR codes so that it uses interrupts. Upload it to your Arduino. The .ino file is attached to this step. As I mentioned in the previous step, the remote code is nothing but how long the modulated signal was being sent and how long it was not. On your Arduino IDE's serial monitor, you'll get a series of OFF-ON duration. This is the raw data sent by the remote. If we had a remote sending the example IR code we used in the previous step, we'd have something like this: Ready to decode IR!!! Received: OFF ON 1234 usec, 1500 usec 500 usec, 1500 usec int IRsignal[] = { // ON, OFF(in 10's of microseconds) 150, 50, 150, 0} The first block of codes is the raw time values in microseconds, the second is the same values divided by 10 and presented in the form of a C array, so we can directly use it in our Arduino code(we'll use it while recreating the IR signal). Notice that raw value columns are OFF-ON and the formatted values are ON-OFF. The first raw data value (1234 usec) is useless as it is the measure of time there was no signal(OFF) before we started receiving the first ON signal (so doesn't appear in formatted values). In the values formatted as an array, last value will always be 0 as the last OFF duration will only end when you press a remote button again. Step 4: Decoding IR Signal Manually - Part I Decoding IR signal implies mapping a different number to each button. So you can easily recognize the button by comparing the integer value representing that button instead of storing long IR codes for each button and comparing each value. To do this, we will process the IR timing values we got in the last step for each button. This step varies a lot from remote to remote. There are hundreds of remote protocols out there. This instructable aims to provide a basic understanding to cover most remotes, but the technique and codes can be modified to suit a complex one as well. There will be a starting signal to your timing data. The starting signal is a unique ON-OFF pair value at the beginning to identify a remote. For my remote, it was: 8400, 4160. For some remotes, it might be more than a single ON-OFF value pair. Rest of the values(except starting code) can be usually grouped under 2 categories(about 20% difference is acceptable). All the values(besides start values) lies near to either 55 or 167 for my remote. If the starting code appears multiple times and the code which follows is always the same, then that means your remote is sending the same code over and over and you can remove the repetitive data. Now pick a spreadsheet editor of your choice. You can use excel or any similar software. I chose LibreOffice(free & open source!). Write down the button names for all your buttons in the column headings. Copy-paste the value for your first button IR code into the spreadsheet. You can use the delimit function to separate the ON-OFF values. Remember to delimit using commas and spaces so there are no leading or trailing spaces to your values, else they will be interpreted as text instead of numbers. Place the OFF values below the ON value in the same column after a gap of one row. Do the same for the next button. Look closely and bold those values in column-2 which vary from those in column-1 for the same row. A difference of less than about 15-20% can be ignored. Do this for 3-4 more buttons. Usually, all the values that change from one button to another will lie in the ON list or the OFF list. We only need the values that change from button to button since that is the data. Mine were in the OFF list, so I removed all the ON values from the spreadsheet. Then I laboriously copy-pasted the OFF values for all the buttons. Remember to bold the values that differ from the previous column. In this way, we'll be able to easily visualize in which range all the data lies. My bold values(i.e. data) lies in the index 17-24 and 25-32. There is no data for index 24 and 32 as the number of buttons easily fit within 7 bits and so the 8th bit is unused, but I'll include it in my range as well. Step 5: Decoding IR Signal Manually - Part II You'll need to have a basic understanding of binary numbering system for this step, since the data being sent will be decoded in binary. Create a new sheet and copy the rows with data(i.e. ones with bold values). I replaced all the values nearby 50 to 0 and those near 150 to 1. You can choose the reverse as well. I used a simple formula: =FLOOR(B3/100, 1) to convert all values below 100 to 0 and all above to 1. Each row is a single bit in the byte data for the button. It is clearly visible in the image that values in range 3-10 are the complement of those in 12-19 for my remote, i.e. wherever there is a 0 in 3-10, the corresponding value in 12-19 is 1 and vice-versa. So the remote is sending the same data for each button press twice, one being the complement of the other. Generally, there will be less than 8 bits of data per button. 8 bits(= 1 byte) is enough to represent 256 buttons uniquely. Choose one of these ranges. I chose the range 3-10 as this yielded smaller values, but that doesn't make much difference. Convert the collective value in your range for each button to form a binary value. You can do it manually if you find formulas confusing. I used this formula to concatenate all the bits and form a binary number in row-21: =CONCATENATE(B10,B9,B8,B7,B6,B5,B4,B3) Convert this binary to decimal. You can do it using a scientific calculator or use this formula in row 22: =BIN2DEC(B21) This final value you get is the decoded value for that button. Step 6: Decoding Value Using Arduino Code Use the attached code to decode the value in your program. A few modifications have to be made in the variables on top. DATA_LOC : set this to 0 if the data values(which we highlighted in bold) are in OFF list, else 1 for ON list LOW_VAL : the value you are taking as 0 for decoding HIGH_VAL : similarly, the value you are taking as 1 for decoding START_ON : the value for the start code under ON START_OFF: similarly, the value for the start code under OFF RANGE1_START : where to start reading values for decoding for the first range. Do not use the excel row number. The first row is 0, next is 1 and so on... RANGE1_END: similarly, where does the last value for decoding liefor range 1? RANGE2_START : if your values are duplicated, then where does the duplicated values begin? RANGE1_END: similarly, where do they end? RANGE2_INVERTED: are the duplicated values in range 2 the complement of values in range 1? // IR DEFINITIONS #define IRpin_PIN PIND // Pins for IR sensor (do not change) #define IRpin 2 // Pin number for IR sensor (do not change) #define DATA_LOC 0 // Data located in which list? 0: OFF, 1: ON #define LOW_VAL 550 // Value to interpret as 0 #define HIGH_VAL 1560 // Value to interpret as 1 #define START_ON 8500 // Start code's ON value #define START_OFF 4200 // Start code's OFF value #define RANGE1_START 17 // From which index to start decoding? #define RANGE1_END 24 // Till where to decode? #define RANGE2_START 25 // comment this #define if you do not have repeated data #define RANGE2_END 32 // comment this #define if you do not have repeated data #define RANGE2_INVERTED 1 // is range2 inverse/complement of range1? 1: yes, 0: no #define MAXPULSE 65000 // the maximum pulse we'll listen for - 65 ms #define MAX_PULSE_PAIRS 60 // maximum number of pulse pairs to store #define FUZZINESS 5 // What percent variation is allowed: 2 = 50%, 3 = 33.3%, 4 = 25%. 5 = 20% Why are we using the 2 ranges if they are the same, or just complement of each other? It's just an extra check to see if both matches. Comment out #define for RANGE2_START if you do not have a range 2 or don't want to use the extra check. When you press a button on your remote, it will provide the decoded value for that button in the serial monitor. Now your Arduino can know which button is being pressed. You can now assign different tasks to different buttons, such as turning an LED on and off with the power button, increasing/decreasing brightness with volume buttons, speeding up/slowing down blink speed with channel up/down buttons, etc. Step 7: Emulating IR Signals Using Arduino You can also send the IR signals using Arduino instead of using a remote. I modified ladyada's code so you can send code for any button by just providing its decoded value. This code will send the IR signal on reset and then after every minute. To setup your own remote, choose any button from your remote and get the formatted C-array for it provided by the IR-reading Arduino code in Step-3. Replace the values assigned to uint16_t IRsignal[] array with the formatted array you got. Now you can code it to send different IR signal by calling EncodeData() with the decoded value of the button you want to send as a parameter, and then calling SendIRCode(). For example you want to send IR signal for button whose decoded value is 2, call EncodeData(2) followed by calling SendIRCode(). As simple as that! The attached arduino sketch waits for you to send the decoded value of the button you want to emulate and sends the IR signal for it. Remember to set line ending in serial monitor as 'Newline'. Step 8: Reading IR Using Raspberry Pi Reading and decoding IR signals using Raspberry Pi is extremely easy. We only have to use LIRC (Linux Infrared Remote Control) and it will handle the most of the heavy lifting work for us. So let's get started... Connect an IR receiver to your Raspberry Pi as shown. IR sensor needs to be connected to 3.3V instead of 5V. We are connecting the data pin of IR sensor to Pin-18 of Raspberrty Pi. Power up your Raspi, make sure you have internet connected. Upgrade RPi2 firmware to newest version using these commands in order: sudo apt-get update sudo apt-get upgrade sudo rpi-update sudo reboot After reboot, type the following command to install LIRC: sudo apt-get install lirc Open the /etc/modules file: sudo nano /etc/modules and add these lines at the end to make LIRC start up on boot and set the IR sensor pin to Pin-18 and IR LED pin(for later) to Pin-17: lirc_dev lirc_rpi gpio_in_pin=18 gpio_out_pin=17 To save, press Ctrl+X -> y -> Enter Now we need to edit the LIRC hardware configuration file. Open it using: sudo nano /etc/lirc/hardware.conf Change the following lines: DRIVER="default" DEVICE="/dev/lirc0" MODULES="lirc_rpi" That's it! To make it work, you need to reboot your Raspi once: sudo reboot Note: buda.suyasa found out that to make LIRC work on Raspberry Pi 2, you need to edit /boot/config.txt using: sudo nano /boot/config.txt add the following line to it: dtoverlay=lirc-rpi,gpio_in_pin=18,gpio_out_pin=17,gpio_in_pull=up Step 9: Reading and Recording IR Signals Using Raspi To check if your Raspberry Pi is reading IR sensor properly, you need to first stop the LIRC daemon(don't worry. There's no demon, it's just a fancy linux name for a background running process): sudo /etc/init.d/lirc stop To run a program to get the IR signal timings(similar to our IR-reading Arduino code), use: mode2 -d /dev/lirc0 Now point your remote at the IR sensor and it should spit out a series of pulse-space(aka ON-OFF) IR timing values. This means everything is working perfectly. Let's record the button values. The daemon needs to be in stopped state for this to work as well. First, get the list of allowed button names using: irrecord --list-namespace Run the below command to start recording IR signals for each button and assigning an allowed name to it: irrecord -d /dev/lirc0 ~/lircd.conf It will take you through some weird but detailed instructions. Follow them and you will end up with a config file storing IR signals for each button. You can view it using: sudo nano lircd.conf It's best if you replace the name field value in the header with something relevant (I chose samsungTV). Replace the default blank config file with your remote's new config file: sudo cp lircd.conf /etc/lirc/lircd.conf We're done with recording. To test it out, start the LIRC daemon: sudo /etc/init.d/lirc start Run the following command to get the button's assigned name whenever you press that remote button: irw Note: If you are getting multiple output per button press, you can add suppress_repeat 2 in the /etc/lirc/lircd.conf file so it ignores the next 2 repeat values. Step 10: LIRC With Python - Part I Using LIRC with python is extremely easy. We'll use the bundled slidepuzzle python game to demonstrate. I'll use the arrow keys on my remote to move the tiles in game. I'll provide the finished file along with the simulate game I modified to play with remote as well. Firstly, we'll need to make licrc config file. This file contains information on what string to send to python when a particular button is pressed. Create and open a file using: sudo nano /etc/lirc/lircrc Paste the following lines: begin button = KEY_UP prog = slidepuzzle config = up end begin button = KEY_DOWN prog = slidepuzzle config = down end begin button = KEY_LEFT prog = slidepuzzle config = left end begin button = KEY_RIGHT prog = slidepuzzle config = right end Between each begin and end, button is assigned the button name, prog is the program name and config is the string to be sent. So when a button is pressed, LIRC sends config string to prog program. You have to change the button names with 4 buttons names you assigned to your remote. Step 11: LIRC With Python - Part II To use LIRC with python, we need to import lirc module first. Open IDLE and open slidepuzzle.py. It should be in /home/pi/python_games. At the top with the other imports, add import lirc We need to create a connection to LIRC. For that, write the below line of code just before the main game loop starts: sockid = lirc.init("slidepuzzle", blocking = False) LIRC matches the first parameter(slidepuzzle) with the prog value in lircrc and only returns button matches for them. the second parameter(blocking = False) tells LIRC that it should not stop the python code execution to wait for the button press. Just before we go into the event handling loop, write: codeIR = lirc.nextcode() if codeIR and isValidMove(mainBoard, codeIR[0]): slideTo = codeIR[0] LIRC stores the button presses in a queue. lirc.nextcode() removes the next value from queue and return it. So if we pressed the remote button assigned to KEY_UP, we will get a list containing the string up i.e. codeIR will be ['up']. In the next line, we check if codeIR isn't empty and that the move we are trying to make is a valid one. If yes, we set slideTo to the returned string in codeIR. Since slidepuzzle assigns up, down, left, right strings to slideTo to make the blocks move, we directly assigned that string saved in lircrc's conf to make it move. That's all. I've done the same with simulate.py python game and attached both of them. Enjoy the games with a remote! Step 12: Recreating IR Signals With Raspi LIRC allows you to send the IR signals as well. If you have set up lircd.conf as instructed in Step-9, you can send IR signal for one of the recorded buttons using LIRC very easily. All you have to do is run the command: irsend SEND_ONCE samsungTV KEY_VOLUMEUP Here, replace samsungTV with the name of the remote you set in header of lircd.conf. KEY_VOLUMEUP has to be replaced by the name of the button you want to send. If you wish to send the IR signal using Python, just import at the top: import os Now wherever you want to send IR signal, just call: os.system("irsend SEND_ONCE samsungTV KEY_VOLUMEUP") 4 People Made This Project! MuhammadI221 made it! Sword_xx made it! buda.suyasa made it! ravijmca made it! 82 Discussions 3 months ago Hello again! I just did this project for the second time and I had trouble figuring out where to put the 'suppress repeat 2' in the lircd.conf file. I keep getting multiple repeats when i push my remote buttons. Can you help me? 3 months ago It would have been good to know that IR_Reading.ino only works with pin 2 or 3 (Arduino nano) beacuse of the attachInterrupt() command. 6 months ago hi I followed the steps for Raspberry Pi. to control my ONIDA AC using lirc , but it cannot control my ac . What might be the problem ?? plz suggest any one to control my AC , how to send my IR signal to the AC ,and send any code link . if i record the AC remote after that code found is in lircd.conf file is begin remote name /home/pi/lircd.conf flags RAW_CODES eps 30 aeps 100 gap 20016 begin raw_codes name KEY_power 8914 4551 624 1676 623 1678 625 596 585 621 575 627 576 1701 622 602 585 619 578 625 576 632 571 1700 624 1676 623 601 600 1677 624 602 605 1672 627 597 601 604 599 604 599 603 600 603 600 1681 631 1663 637 589 601 602 601 602 601 602 601 603 600 1694 610 596 602 1676 624 600 602 602 593 1686 621 606 585 name KEY_POWER 8558 4929 596 1684 621 1697 597 607 580 1717 599 627 559 1699 617 610 576 651 551 651 552 652 551 1701 is this code is correct or not and if correct then how to send the code ir transmitter suggest any What might be the problem ?? 11 months ago I could follow your instructions at Raspbian Jessie (8) on Noobs 4.2.2 When I updated to the latest Raspbian released on Dec 2017 at Noobs 4.2.4, some instructions did not work (sudo /etc/init.d/lirc stop) and I could not send irsend. Also, when I record the IR it requested the remote name and lot's of other things did not match your instructions. If you could make another instruction it would be great! 1 year ago hi I followed your tutorial and working great with arduino but it's not working on Raspberry with Raspbian Stretch, tried several times with fresh OS installs but no luck, I get stuck when i run: $ sudo /etc/init.d/lirc stop I get "command not found" but it seems to work when i run: $ sudo /etc/init.d/lircd stop [....] Stopping lircd (via systemctl): lircd.serviceWarning: Stopping lircd.service, but it can still be activated by: lircd.socket . ok When I run mode2 I always get "Partial read 8 bytes", $ mode2 -d /dev/lirc0 Using driver devinput on device /dev/lirc0 Trying device: /dev/lirc0 Using device: /dev/lirc0 Partial read 8 bytes on /dev/lirc0 Any help would be appreciated, I've been stuck for a few days ^^ Reply 1 year ago EDIT: LIRC is not working on Raspbian Stretch, use Jessie if you have similar issues. Reply 1 year ago Since you've followed a few tutorials, there might be a hotch-potch of settings clashing with each other. I suggest you to try with fresh install of Raspbian either on this card or another one. Then, follow the instruction in Step-8 and 9 closely(especially the raspbian update and upgrade). If after following it till end of Step-9 and things still don't work, you can try buda.suyasa's trick mentioned at the end of Step-8. Reply 1 year ago That's weird. Are you using Rapsberry Pi 3? As you say, could be a Raspbian Stretch problem. You can try with Jessie and see if it works. The archived firmwares are here and I guess this is the latest Jessie release. Reply 1 year ago Hey Antzy! Finally had time to test a little more. LIRC works on Wheezy and Jessie but not working on Stretch, might be good to indicate it on your tutorial (tested on both RPI3 and RZero). After install it seems like Stretch doesnt have a valid hardware.conf file. Looked around but couldn't find it anywhere. Won't work even after creating it myself. I'm back onto Jessie ^^ 1 year ago I'm using Ubuntu MATE on my Rasperry PI, and when I try to run the slidepuzzle game, it just says "no module named lirc". It seems I haven't installed lirc for python, so does anyone know the command I can use to get it? Thanks, Dr Reply 1 year ago Start from Step-8 and follow each step to install and setup lirc for using with python. Also, make sure you are using IDLE and not IDLE-3. Reply 1 year ago thanks, I was using idle3. This is a great instructable antzy! Thanks! 1 year ago In my case it doesnt work. The decoder works perfectly but im not able to emitt. Everything else works. I suppose it to be to slow. can anyone help me? 1 year ago using the Pi 2. After following the instructions exactly several times, I get the following after trying to install LIRC: No valid /etc/lirc/lircd.conf has been found Remote control support has been disabled Reconfigure LIRC or manually replace /etc/lirc/lircd.conf to enable.... What did I miss? Thanks Tom Reply 1 year ago Which command is giving you this error? Is it sudo apt-get install lirc? Did you update your raspi before installing LIRC? Reply 1 year ago Antzy: Which version of the Raspberry Pi were you using when you wrote this? Reply 1 year ago I was using Raspberry Pi B at the time. But that shouldn't be the problem as many people have reproduced the steps on later versions as well. Did you check whether /etc/lirc/lircd.conf exists or not? I saw a comment here with the same problem and giving the solution: I was having the same problems as Taavi. When I ran "mode2 -d /dev/lirc0" I got a permission denied error and when I added sudo I just got nothing. Turns out I had the IR receiver wired backwards. I probably misinterpreted your schematic (I'm pretty new at all this) but I think you have the VCC and OUT pins reversed (Also using a TSOP38238). So basically I had the software side working properly, just a couple crossed wires on the hardware side. So please check your connections as well if you have anything connected to GPIO. Or remove everything and try once. 1 year ago I did all that then tried to install the lirc. The errors appear after the "apt-get install lirc" completes it's run. Thanks for the help!
https://www.instructables.com/id/How-To-Useemulate-remotes-with-Arduino-and-Raspber/
CC-MAIN-2018-51
refinedweb
4,893
72.05
Wolfgang Jeltsch <g9ks157k at acme.softbase.org> wrote: > The Yampa people and I (the Grapefruit maintainer) already agreed to > introduce a top-level FRP namespace instead of putting FRP under > Control or whatever.. I do understand that hierarchical classification is inherently problematic, and will never quite fit the ways we think of our modules. But the alternative being proposed here is neither more descriptive, nor more logical. In fact, it is an abandonment of description, in favour of arbitrary naming. A package called foo-1.0 containing a module hierarchy rooted at "Foo." tells me precisely nothing about its contents. It it were rooted at Military.Secret.Foo, at least I would have some clue about what it does, even if the category is inadequate or slightly misleading in certain circumstances. You may argue that only novices are disadvantaged by arbitrary names - once you learn the referent of the name, it is no longer confusing. However, I strongly believe that even experienced users are helped by the continuous re-inforcement of visual links between name and concept. After all, if you are collaboratively building a software artifact that depends on large numbers of library packages, it may not be so easy to keep your internal dictionary of the mapping between names and functionality up-to-date, and in sync with your colleagues. Being just a little bit more explicit in the hierarchy is a one-time cost at time of writing, that reaps perceptual benefits long into the future for yourself, and those maintainers who will follow you. Regards, Malcolm
http://www.haskell.org/pipermail/haskell/2009-June/021422.html
CC-MAIN-2014-23
refinedweb
260
53.41
how to access metadata server when we use neutron provider network Hi all, When we use neutron provider network and use a external Router. We do not need L3 agent function in Openstack. But the NAT rules for 169.254.169.254 is done in add router and delete router. What ever I know that I can add NAT in the external Router, but I still want this is done in Openstack . The only way I can think out is that set route for 169.254.169.254 via dhcp addr in VM. And manually to modify the NAT rules in dhcp namespace. Any way to solve this problem in Openstack? Thanks so much.
https://ask.openstack.org/en/question/14264/how-to-access-metadata-server-when-we-use-neutron-provider-network/
CC-MAIN-2019-51
refinedweb
114
94.35
Google Starts to Detail Dart 219 MrSeb writes "After waiting for more than a month, Google has unveiled its mysterious Dart programming language... and you're going to kick yourself for getting so preemptively excited. Dart is a new programming language that looks like Java, acts a lot like Java, runs inside a virtual machine like Java... but ominously, it also has a tool that converts Dart code into JavaScript.." Could be really cool in about 5 years or so. (Score:2, Insightful) When and if every browser on the market supports it. Until then it is just interesting. Re: (Score:3) Re: (Score:3) There are several dozen languages that can be cross-compiled to JavaScript today. So far, none of them have become popular as replacement for JS in the browser. Re: (Score:2) Because all of those were never ment to run directly in the browser. Can you explain how a language is designed any differently if it is meant to run directly in the browser? And what precludes, say, Python or Lua from being used that way? With dart there is hope that one day browsers will support it without compilation Good luck waiting for IE and Safari to do that. yup. it's like the internet is dying (Score:2) because of all the shitty languages used to develop it. it's going the way of Sun . . . just losing tons of users every day. Re: (Score:2) Which Google will add to Chrome once enough cross-compiled apps are out there. Then they get a huge speed boost and it forces everyone else to add a dart runtime to their browsers or lose the benchmark wars. Re: (Score:2) Except that the browser benchmarks will be written in JS. Very few people will be willing to take the performance hit that the cross compile might cause. If it is any slower they will keep living with JS for a good long time. Re: (Score:2) Re: (Score:2) Doesn't CoffeeScript already do cross-compile from native to JavaScript, with quite a few proponents and examples of complex usage working fine? No idea as CoffeeScript is something on my to-look-at list, and seems to be difficult to use on Windows. Re: (Score:2) That's partially true. In fact you can write JS style coffeescript and the js output of the compiler is just about as long as cs input. However coffeescript adds some nice syntax sugar that can translate into more complicated javascript. List comprehensions is a good example of this. The generated code isn't very complex and you could write it yourself with a little bit of effort but you don't have to. That's the main selling point of coffeescript. It takes a simpler syntax and translates it to the co Re: (Score:2) And you really think google would make it so you have to tweak it for IE? Re: (Score:2) Enlighten me (Score:2) .... but ominously, it also has a tool that converts Dart code into JavaScript. Sounds pretty mundane to me- What's so ominous about converting to JS? Re: (Score:2) Re: (Score:2) Re: (Score:3) In the worst case, this could lead to everybody having to implement Dart, and the new de-facto standard scripting language being controlled by Google, who, running several of the world's most popular websites, can hardly be considered neutral. Re: (Score:2) Dart->JS might be slower than Dart, but I don't see any reason to expect that it'll be an order of magnitude slower than just writing it in JS would be, since much of it won't be replacing stuff that would be handcrafted in JS, but stuff that would be built on several abstraction Re: (Score:2) I don't think anyone has yet suggested writing "Dart-only websites." From the blog: "We plan to explore this option" could be interpreted in that light, but I take it to mean that they're still in a pl Re: (Score:2) Writing stuff that will work an order of magnitude slower on JS browsers could seem like a sensible lazy solution to many well, that's possible if they happen to do a terrible implementation of the compiler, but the intent would that it's faster as it can output optimized JS code. It's not a bad thing (Score:5, Informative) The world actually needs more "enterprisey" languages. If you want experimental, fun languages, your choices are actually very good, what with ruby, python, and a ton of functional languages. In terms of safe and good for scalable, risk-averse environments, there's pretty much just Java and C#. Java seems to have accumulated so much inertia, it doesn't add new features anymore. As for C#, the problems dealing with Microsoft are well-known to the slashdot community already. A little more competition in that arena would do the industry some good. Re: (Score:3) Exactly. In terms of "heavy enterprise", meaning the real back ends of big financial companies, airline conglomerates and insurances...They only let you touch their valuable cobol systems through java, mostly 1.3 (1.4 if you're lucky). The java 5 route (and thus 6, 7, 8) is too risky because of Oracle. Any new development in that sector is good news. Although some java integration is necessary (mostly connectors and MQ systems), because these are tested for 10+ years and that counts more than anything else. Re: (Score:2) If by "risk averse", you mean "will only use what at least 1/4 of the rest of the people doing the same thing are using because it needs to be 'established'", then you'll never have more than a couple of options at best. If you mean any other sense of "risk averse", well, you can probably add Erlang to that risk, and several other things. In any case, it'll take quite somet time before any newly-created lan Re: (Score:2) Re:It's not a bad thing (Score:4, Interesting) Take Python. I love its syntax, the plethora of libraries available, the ability to rapidly prototype and see immediate results. All the things that make it "fun" really do make it productive (shorter time to a final, correctly coded solution). It's a great language. However, it doesn't run as fast as C/C++ code, for obvious reasons (interpreted, dynamic typing, etc.). There are ways to make it faster (rewriting critical subsections in C/C++, using fast libraries intelligently, various optimizers and pseudo-compilers exist, etc.). But everyone (or at least me) would love to code using Python syntax but have the code run as fast as C/C++. Best of both worlds. In other words, what I would love to see is tons of effort put into making toolchains for making Python (or other "fun" languages) faster (and probably by association more enterprisey in terms of being type-safe, etc.). I'm not saying doing this would be easy, but there are various proofs-of-principle for compiling Python code or automatically converting it to C/C++ code and whatnot. It could be done and would allow programmers to use the clean syntax of Python to more rapidly code a project without feeling bad about the performance not being up to scratch. Again, I'm aware of the alternatives (rewrite bottlenecks in a fast external, etc.). But it seems to me that we've learned a lot about what makes for a nice high-level syntax, so we should automate the grunt-work of converting that syntax into fast low-level code. (Yes, I'm aware of gotchas such as dynamic typing preventing full compiling in some cases, but something like adding type hints to a high-level language would surely be less onerous for programmers than going to a lower abstraction level wholesale. Even type hints could be automatically inferred by a parser in a lot of cases, with a programmer checking that they make sense...) Re: (Score:2) And why must "fun" and "enterprisey" be exclusive? If your definition for enterprisey is scalable and risk-averse, why can't a language that is pleasant to use meet those requirements? I maintain hope for a language, compiler/runtime, and library that allows me to easily communicate my solution without being distracted by the language implementation (fun), while offering good performance and scalability. As for being risk-averse, there are never any guarantees there and I doubt you'll find that the great s Re: (Score:2) If you want experimental, fun languages, your choices are actually very good, what with ruby, python, and a ton of functional languages. In terms of safe and good for scalable, risk-averse environments, there's pretty much just Java and C#. Do you have any idea how much financial code is written in Python? I take that back, because it's obvious you do not. Re: (Score:2) I got excited? (Score:2) I would describe it more as "a funny feeling". There shall be puns (Score:2) Still no confirmation whether the object declaration will go something like: objet d'art(foobar) { } Bad article and summary (Score:3) Both the article and the summary don't seem to get it. This sounds like C#.NET take two, with the added trick that until browser support for the real Dart is there, you can deploy by translating your client side Dart code to JavaScript. Re: (Score:2, Interesting) just great... Java took at the 'best' ideas of C++ and then mangled it into something pretty nasty - a memory and resource hog with poor performance, especially for GUIs, and added non-deterministic finalisation (eventually - the original didn't even have that!) with verbose OO code everywhere. The only good thing it gives is a huge set of libraries. C# took that and did even more to it, so much so that you require an IDE to write code. So what does Google do? Take these languages and builds on top of them ev Re: (Score:2) Why don't they go back to the source, learn the mistakes that Java made ... and create a language initially based on C++ with the good bits of that included. let me guess. c++ developer? Re: (Score:2) You cannot take C++ and mangle anything since C++ is a Frankenstein language to begin with. Only it's inventor and the deranged could possibly love it. As for memory hogging, there are plenty of C++ apps that are memory hogs. And please, poor performance in Java? Java is one of the fastest languages on the planet. The only languages that even compete with it are C and C++. Apparently you get your information from the 1990's. Oh, and last I checked...the vast majority of C++ developers use an IDE. Re: (Score:2) The only way you could "learn the mistakes that Java made" and then "create a language initially based on C++" is if the purposes of learning Java's mistakes was so that you could repeat them. Modern C++ may good for some things, but they don't seem to be the things Dart i Re: (Score:2) C# doesn't need an IDE to write code. It's plenty easy to write and compile projects outside of the IDE. All it requires is a little research, but you can't honestly decry that with a straight face now can you? Or were you born with the knowledge required to compile C/C++ projects at the command line? Microsoft even provides a shortcut to the visual studio command line environment when you install it for christ sake. Just because they give you the tools doesn't mean you are forced to use them (not that I kno Re: (Score:2) I disagree about the ceremony of C++, C++ is a lot lower level and library code is pretty direct. C# on the other hand does like you to create classes all over the place (I'm thinking especially of XAML where you can only bind a gadget to a variable via an object which has properties - the equivalent in C++ would be 2 lines of code, and one of those would be the variable declaration). I wouldn't like to resolve those namespaces or the horrendously long method names that most style guides expect you to use w Re: (Score:2) Comparing C# and C++ as languages to write meaningful code in without an IDE strikes me as very similar to comparing a cantalope and an apple as a tool to drive nails. It might be easier (even much easier) to use one than the other, but either is far from a good choice for the role. Re: (Score:2) Dylan is an example of a practical, approachable, well-designed, strongly typed language that compiles well and scales well. It took Lisp and Scheme concepts, added a few of its own, and employs a nice, traditional Algol-ish syntax. It works well with C code. It w Re: (Score:2) That's actually very good! (Score:3, Insightful) Even mono is not open enough to allow usage in many embedded devices (read: game consoles) without paying royalties, due to the GPL license. A replacement for those that is portable, can be used everywhere, is easy to migrate to and is distributed by the very permissive licenses Google always utilizes sounds extremely good in my view, so I think the negative tone of the summary is misplaced.. Whoa there (Score:5, Insightful) The main problem of Java and C# is that they are controlled by Oracle and Microsoft respectively But Dart is controlled WHOLLY by Google. Why is that really any different or better? The reality for Java is much better, it's controlled by a community standards body (the JCP). Oracle can provide direction but they are NOT in control the way Microsoft and Google are. Re: (Score:2) Re: (Score:3) That's what Microsoft did with C# and the CLI, too. Either we believe that our open standards bodies are real, and that standards are indeed standards, or we believe that they are corruptible by corporations and nothing is actually standard, or we believe that somehow Google is an incorruptible paragon of holy perfection. I understand the reasoning behind the first two. I think the third might indicate substance abuse. Re: (Score:2) Microsoft did standardize C#, but actual development of the language and tools moves so fast that non-MS implementations always lag. And MS only supports Windows (by design). Time will tell, but I think we can expect Google to actively support all of the platforms Chrome runs on, and to release full source code under a fairly permissive license. An open standard plus an open source, multi-platform reference implementation will be truly open in a way that C# isn't and Microsoft doesn't want it to be. Embrace, extent, extinguish (Score:2) Re:Whoa there (Score:5, Informative) The difference is that Google have pretty much a clean track record when it comes to open source software. I don't think so. Chrome was marketed as an open source browser, yet from the very first release they added in proprietary bits without source code. It's nice that it is almost open source, and that Chromium exists, but it's important to note they compromised on open source principles. This continues now with Android, with Google releasing Honeycomb for their partners without releasing the corresponding source code. I don't care what excuses Google gave for that, no source code is no source code. Google cannot be trusted. They are a big corporation looking out for their own interests. Sure, they play nice for the most part, but many times they don't. Re: (Score:2) Google cannot be trusted. sure they can. they can be trusted to always act in a way that maximizes their profits. in fact, that's all any corporation will ever do, by definition. if you can't stand that, stop using any OSS project that consumes corporate resources in some way or another. that would rule out so many of the OSS projects that you'd be forced to start using non-OSS software in its place. Re: (Score:2) Re: (Score:2) Google is still pretty young, you haven't given them enough time to become utter bastards yet. Microsoft? (Score:2) Re: (Score:2) In the world of programming, you choose your poison and insist to everyone that you are feeling fine. Re: (Score:2) Why is JS compiling ominous? (Score:3) but ominously, it also has a tool that converts Dart code into JavaScript No, that's an excellent feature. Allows us to start developing sites with this new language without having to wait for all browsers to upgrade or to have plugins installed. How else would you get any sort of main stream takeup of a javascript replacement? Re: (Score:2) Yes and no. Unless Dart is "much better" why take the time to learn a new language where support will depend on two codebases. You will have your Dart code and your js translation of your Dart code? If you know JS your going to keep developing in JS until Dart support is proven and universal. Even then you will probably keep using JS unless you start a new project. Re: (Score:2) I don't see why this is any worse than a compiled language (Java, C# etc.), it's not going to be hard to manage your sourcecode and the JS output if you've got an automated build of your web project set up. Having done a lot of big projects in JS for me it has a lot of shortcomings and it would be great to have a replacement language that is backwards compatible. Sure I wouldn't do anything enterprise level for a year or so while Dart proves itsself, but I would happily use it for large projects before wides Re: (Score:2) It comes down to time for most developers. For instance I need to filter a large text file a few weeks ago. I have been thinking about learning Python because it seems pretty interesting. Time ticks buy as I am reading and setting up things and then I think, " if I used perl I would have been done". So I write the four line perl script and I am done. A tool just needs to be a lot better to be worth the time sink. A lot of the time Good enough is just that good enough. Re: (Score:2) To a degree, but if everyone stuck to this mindset then everyone would still only be using the first language they ever learnt. It's like saying that no-one will ever use Java or C# because they know PHP and it's "good enough". Dart has many nice features that would be very useful for large multi-developer projects (typing, static checking etc.) which would easily offset the time for developers to familiarise (one of the design goals of Dart is that it is easy to learn from a javascript background anyway). Re: (Score:2) Ahh but PHP isn't good enough for desktop applications. To change tools it must be much better or you have no other choice. Re: (Score:2) " if I used perl I would have been done". And if they would have spent this time, effort, and money on Parrot... You, the Python coder, the Lua coder, and the insert Parrot supported language [parrot.org] coder would have been done. Re: (Score:2) Well, it should be obvious, but I'm saying anyway: Wait to learn Python when you have a problem that isn't The One Thing one of the languages you know shines at. When you need to filter a text file, please do it in Perl*, not Python. That is good advice even for Python programmers. * Or Haskel. It is amazing how good Haskel is for filtering text. But, of course, you need a completely different mindset than you'd use with Perl. Re: (Score:2) True which is why I picked Perl. To me scripting languages like Perl and Python are the tools I use for simple one off programs like filtering a text file. I do not do much web stuff right now but I could see me using Python along with Perl and PHP. For anything more complex on the desktop I would use Java, C++ or ObjectiveC. If I need to do anything with or very old dos codebase I would breakout FreePascal. You see it is a need to learn thing. Now Haskel does interest me but when I have looked at it my head hur Re: (Score:2) I find that Python is quite usefull for writting any kind of fancy UI. It is simlper to write in than C++ (or Java, how can a garbage collected language be harder to write in than C++?), and yet, it doesn't collapse at its own weight like Perl or PHP. I guess that is some of your more complex stuff, so I'd recomend you learn python next time you go out to use QT or do web development (or more complex UIs, like what you can do with PyGame or 3D modellers). PHP by its turn, I now consider defunct. I looked at H Re: (Score:2) I am just not a big fan of C++ but I mostly used it on Windows so that may have tainted it for me. Java+Netbeans makes writing GUI software really easy for me. I also find Java's tread support very robust. It could just be that it fits my style. Perl I do agree is good for programs under 100 lines long and that you will never touch again. However for plowing though a bunch of data it is a great tool. I really like ObjectiveC. It seems far less like a Hack to me than C++. Re: (Score:2) The key here is I'm willing to believe Dart can be 'much better', because really, being 'much better' than Javascript is a pretty low bar. Re: (Score:2) Yawn, we've seen this before with GWT for Java. Wake me up when it has code to convert Dart into Bacon Sandwiches. Re: (Score:2) It's becoming obvious that browsers need to support a runtime like LLVM in addition to or instead of javascript. That way, the developer could use their language of choice and just compile to LLVM byte code instead of to javascript. I would think it should be easier to optimize performance for LLVM byte code that for javascript. Would there be any downsides except for the fact that it does not exist already? If only Google would have thought of that! (Score:2) Yes. It is. [googlecode.com] Closed platforms (Score:3) The ominous part of that memo is "The cyclone of innovation is increasingly moving off the web onto iOS and other closed platforms." By which they mean iPhone and Android "apps". "Apps" are not a very good environment, and many of them are just web pages with delusions of grandeur. But that they have a payment model, DRM, and give the app distributor absolute control. It's all about screwing the end user. "You're the product, not the customer". As a language, Dash looks mediocre, as the article points out. "Optional typing", an idea that started with Visual Basic is usually a lose in language design. Statically typed languages have been successful, and dynamically typed languages have been successful, but optional typing is usually an afterthought bolted on to increase performance at the cost of programmer confusion. There's a typed Python variant, for example; PyPy is written in it. It's rarely put in a language from the beginning. A few languages have tried a form of soft typing, where you have, essentially,"integer", "real", "boolean", etc., and arrays of same, plus "object". That way you get efficient code for machine arithmetic, which means you can do codecs and graphics in the language. Objects have to be dispatched anyway, so a performance penalty there isn't so severe. Re: (Score:2) sorry, but did this, But that they have a payment model, DRM, and give the app distributor absolute control. and this It's all about screwing the end user. go together? having a payment model doesn't screw the user, it gives the developer a way to feed their family. as to the user, it's up to them if they want to pay or not. nobody is screwed. at least on android, there's nothing special in the platform that forwards DRM. android does have a "license verification" API that allows developers to validate that users actually purchased the app. see point above about feeding the family. on android, the "distributor", by which i guess you me Re: (Score:2) at least on android, there's nothing special in the platform that forwards DRM. android does have a "license verification" API that allows developers to validate that users actually purchased the app. Actually, any serious pretense to verify the legitimacy of copying a bunch of bits to the device can only be done with a technology that amounts to DRM, requiring device lockdown all the way down to the bootloader. So either Android is claiming their verification to be more than it is, or it forwards DRM. Quick! Everyone start converting your code! (Score:2) I have this idea of a new language that is 100% Javascript-compatible. It would require no code conversion whatsoever, works with your existing tool chain, and requires no new learning. It started out from an Ada-like project, and I dubbed it "New ADA", or "NADA". It's evolved quite a bit and doesn't look like Ada anymore. In fact, it looks exactly like Javascript. But it's new! I recommend that everyone start using Nada as soon as possible to open a whole new world of possibilities. go (Score:2) Re: (Score:2) I thought Go was just a project of some Google engineers and not an official product. Standard library (Score:2) The corelib looks very sparse: [dartlang.org] The thing I like about jquery and dojo is that you actually get a reasonable standard library, which JS sorely lacks. It would be nice if dart included a better standard library. The end game for GWT (Score:2) GWT rocks - don't expect it to go easily into that good night. Consider the following scenario: o Convert the compiler to accept Dart instead of "pure" Java. Remember, GWT does not implement the entire language, only a subset of the run-time. This conversion can easily be implemented as a rolling replacement to the compiler. o There's absolutely no reason now for GWT to support Java 7+ o The Google Plugin for Eclipse will easily convert to Dart, keeping the developer mind-share o Keeps all those nifty 3rd party MIT licensed anylanguageVM (Score:3) If Google would have spent time and effort on Parrot or helped to release a VM that interprets multiple languages under the MIT license, I would be loving Google. Another scripting language and VM doesn't make me warm, fuzzy, or even remotely interested. Re: (Score:2) Look up PNaCl. To be honest, I'm somewhat disappointed that this Dart thingy isn't running on top of that. Re: (Score:2) Salt, Pepper, Pinnacle are for pluggins and JIT'd C. I want a virtual machine designed to efficiently compile and execute bytecode for dynamic languages [parrot.org] built into the browser instead of a JavaScriptVM. Re: (Score:2) If you have a low-level VM (such as LLVM, which is what PNaCl uses), you can always build something higher-level on top of that - be it bytecode interpreter, JIT compiler or whatnot. You could take Clang and compile Parrot to LLVM bytecode for example. On the other hand, it also lets one use compiled languages. It's all about having more options. Re: (Score:2) "It lets one use compiled languages." Yes, LLVM absolutely does. I love it. It also allows one to create JIT's for high level languages. Jade, Crack, Rubinius, etc... are all done with LLVM. However, a JIT for a language is far from an anylanguageVM. I would call it an HLVM but that name was taken then absorbed back into LLVM. What I'm talking about is an interpreter that interprets more than JavaScript not a JIT for each language. There is a huge difference. Yes, one could use LLVM to build one. The real reason for Dart (Score:2) Remember, Dalvik bytecode is not Java bytecode. Android only uses the Java language, not its v Re: (Score:2) Remember, Dalvik bytecode is not Java bytecode. Android only uses the Java language, not its virtual machine, which is why Oracle mistakenly believes they can sue Google over its use. Changing the source language removes the perceived violation without breaking existing software. Mistakenly? I'm pretty sure they *are* suing Google over its use. Re: (Score:2) You've got some faulty assumptions. One of the reasons Oracle is suing Google is over the Dalvik implementation and patents: [wikipedia.org] Interfaces = Meh (Score:2) I was really hoping that they included something like Ruby's mixins. I'm sorry, Google, but I'm not interested. Re: (Score:2) Interfaces are useful for static checking, since they express an implementation-free contract; this makes them important for Dart. Mixins might be useful in addition to interfaces, but don't fill the same role. Its also early in the game for Dart, unless there is a philosophical opposition to having mixins, they could well be added in. Maybe you should recommend that on the forum on the dartlang.org website? Re: (Score:2) Re: (Score:2) Re: (Score:2) Java with first-class functions and opt-in dynamic typing is called C#. ~ Re: (Score:2) Its java. With optional typing. So, more like groovy. Re: (Score:2) No, no, no -- it's most definitely not java. Google are being sued by Oracle over their use of Java in Android, don't you know. Any new language from Google is not java, not at all. Any superficial similarity you think you see is a mistake, so don't you go mentioning it Larry Ellison. Re: (Score:3, Informative) JavaScript = Dynamically typed language with first class functions with prototypal based inheritance, some runtime safety Dart = Dynamically typed language with first classes functions, but with some support for static types & classical inheritance, still runtime safety/error checking, no compiling etc. Dart is more like JavaScript than Java. It's been touted as a JavaScript replacement, no Re: (Score:2) First class functions? Dynamic typing with optional static typing? Its not really very much like Java. It is more like the love child of JavaScript and C#. Looking at the spec, it looks like it has some of the best features of both and I'm looking forward to getting my hands on it. Re: (Score:2) Actually, looking at the spec, this seems to be mostly C#, except that it defaults to "dynamic" type (it's even named the same!) when you don't specify it. Frankly, I think it's more trouble than it's worth, particularly in cases where C# would infer the type instead (e.g. "var", or non-type-annotated lambdas). Aside from that, and a few minor deviations such as no method overloading (but named constructors), I really don't see what this brings to the table compared to C# 4.0+ (the one that has "dynamic") - Re: (Score:2) They've made pretty clear what their exit strategy for Android is: move things to the browser, merge with ChromeOS, and do everything as browser-based apps (not necessarily web-apps in the traditional sense, as Chrome supports browser based apps that can be fully offline, and which can include native code.) So, insofar as this is this intends to replace JavaScript as the main Re: (Score:3) Seems to me DART is meant to replace the ubiquitous PHP/Javascript combination. Think about it: quick prototypes with untyped code, moving to static typechecking wherever wanted, Server-side and client-side execution, built-in HTML5 DOM library. Its features may be unexciting, but they could provide an easy escape from PHP/Javascript hell without too much learning curve. If that is Google's primary target with DART, it may prove to be a very strategic move. Re: (Score:3) Its designed to run both client-side and server-side. Re: (Score:2) If DART catches on I bet you'll see something like PhoneGap or Titanium eventually. Re: (Score:2) Screw it... just use perl. Sorry, its not on The List [github.com] Supposedly you can compile scheme, ruby, or basic into JS. Never tried it, don't know. I transitioned from Perl to Ruby probably about 6 years ago, it was fairly painless, would advise if you feel you're "stuck" on perl to try ruby. Re: (Score:2) awk Erlang (Score:2)
http://developers.slashdot.org/story/11/10/10/1454238/google-starts-to-detail-dart?sdsrc=rel
CC-MAIN-2015-06
refinedweb
5,580
71.34
Created on 2013-06-07 15:31 by brett.cannon, last changed 2017-08-18 16:16 by brett.cannon.! I'd like to ping this channel. I post a question on to ask if it is possible to directly get the attribute from AttributeError, which leads me here. > try: > cls.meth() > except AttributeError as exc: > if exc.attr != 'meth': > raise What if cls.__getattr__('meth') calls a completly unrelated function which also raises AttributeError(attr='meth') but on a different object? I would also expect an "obj" attribute, a reference to the object which doesn't have attribute. But AttributeError can be raised manually without setting attr and/or obj attribute. So the best test would look to something like: if exc.obj is cls and exc.attr is not None and exc.attr != 'meth': raise The test is much more complex than expected :-/ Maybe it's simpler to split the code to first get the bounded method? try: meth = cls.meth except AttributeError: ... meth() Or check first if cls has the attribute 'meth' with hasattr(cls, 'meth')? -- About attr/obj attribute not set, an alternative is to add a new BetterAttributeError(obj, attr) exception which requires obj and attr to be set, it inherits from AttributeError. class BetterAttributeError(AttributeError): def __init__(self, obj, attr): super().__init__('%r has no attribute %r' % (obj, attr) self.obj = obj self.attr = attr It would allow a smoother transition from "legacy" AttributeError to the new BetterAttributeError. The major issue with keeping a strong reference to the object is that Python 3 introduced Exception.__traceback__ which can create a reference cycle if an exception is stored in a local variable somewhere in the traceback. It's a major pain point in asyncio. In asyncio, the problem is more likely since exceptions are stored in Future objects to be used later. The concerns mentioned by haypo seems to have existed in PEP473.
https://bugs.python.org/issue18156
CC-MAIN-2021-21
refinedweb
318
60.31
Use Batch Apex Learning Objectives Batch Apex Batch Apex is used to run large jobs (think thousands or millions of records!) that would exceed normal processing limits. Using Batch Apex, you can process records asynchronously in batches (hence the name, “Batch Apex”) to stay within platform limits. If you have a lot of records to process, for example, data cleansing or archiving, Batch Apex is probably your best solution. - Every transaction starts with a new set of governor limits, making it easier to ensure that your code stays within the governor execution limits. - If one batch fails to process successfully, all other successful batch transactions aren’t rolled back. Batch Apex Syntax To write a Batch Apex class, your class must implement the Database.Batchable interface and include the following three methods:start Used to collect the records or objects to be passed to the interface method execute for processing. This method is called once at the beginning of a Batch Apex job and returns either a Database.QueryLocator object or an Iterable that contains the records or objects passed to the job. Most of the time a QueryLocator does the trick with a simple SOQL query to generate the scope of objects in the batch job. But if you need to do something crazy like loop through the results of an API call or pre-process records before being passed to the execute method, you might want to check out the Custom Iterators link in the Resources section. With the QueryLocator object, the governor limit for the total number of records retrieved by SOQL queries is bypassed and you can query up to 50 million records. However, with an Iterable, the governor limit for the total number of records retrieved by SOQL queries is still enforced.execute Performs the actual processing for each chunk or “batch” of data passed to the method. The default batch size is 200 records., use the returned list. Here’s what the skeleton of a Batch Apex class looks like: public class MyBatchClass implements Database.Batchable<sObject> { public (Database.QueryLocator | Iterable<sObject>) start(Database.BatchableContext bc) { // collect the batches of records or objects to be passed to execute } public void execute(Database.BatchableContext bc, List<P> records){ // process each batch of records } public void finish(Database.BatchableContext bc){ // execute any post-processing operations } } Invoking a Batch Class To invoke a batch class, simply instantiate it and then call Database.executeBatch with the instance: MyBatchClass myBatchObject = new MyBatchClass(); Id batchId = Database.executeBatch(myBatchObject); You can also optionally pass a second scope parameter to specify the number of records that should be passed into the execute method for each batch. Pro tip: you might want to limit this batch size if you are running into governor limits. Id batchId = Database.executeBatch(myBatchObject, 100); Each batch Apex invocation creates an AsyncApexJob record so that you can track the job’s progress. You can view the progress via SOQL or manage your job in the Apex Job Queue. We’ll talk about the Job Queue shortly. AsyncApexJob job = [SELECT Id, Status, JobItemsProcessed, TotalJobItems, NumberOfErrors FROM AsyncApexJob WHERE ID = :batchId ]; Using State in Batch Apex Batch Apex is typically stateless. Each execution of a batch Apex job is considered a discrete transaction. For example, a batch Apex job that contains 1,000 records and uses the default batch size is considered five transactions of 200 records each. If you specify Database.Stateful in the class definition, you can maintain state across all transactions. When using Database.Stateful, only instance member variables retain their values between transactions. Maintaining state is useful for counting or summarizing records as they’re processed. In our next example, we’ll be updating contact records in our batch job and want to keep track of the total records affected so we can include it in the notification email. Sample Batch Apex Code Now that you know how to write a Batch Apex class, let’s see a practical example. Let’s say you have a business requirement that states that all contacts for companies in the USA must have their parent company’s billing address as their mailing address. Unfortunately, users are entering new contacts without the correct addresses! Will users never learn?! Write a Batch Apex class that ensures that this requirement is enforced. The following sample class finds all account records that are passed in by the start() method using a QueryLocator and updates the associated contacts with their account’s mailing address. Finally, it sends off an email with the results of the bulk job and, since we are using Database.Stateful to track state, the number of records updated. public class UpdateContactAddresses implements Database.Batchable<sObject>, Database.Stateful { // instance member to retain state across transactions public Integer recordsProcessed = 0; public Database.QueryLocator start(Database.BatchableContext bc) { return Database.getQueryLocator( 'SELECT ID, BillingStreet, BillingCity, BillingState, ' + 'BillingPostalCode, (SELECT ID, MailingStreet, MailingCity, ' + 'MailingState, MailingPostalCode FROM Contacts) FROM Account ' + 'Where BillingCountry = \'USA\'' ); } public void execute(Database.BatchableContext bc, List<Account> scope){ // process each batch of records List<Contact> contacts = new List<Contact>(); for (Account account : scope) { for (Contact contact : account.contacts) { contact.MailingStreet = account.BillingStreet; contact.MailingCity = account.BillingCity; contact.MailingState = account.BillingState; contact.MailingPostalCode = account.BillingPostalCode; // add contact to list to be updated contacts.add(contact); // increment the instance member counter recordsProcessed = recordsProcessed + 1; } } update contacts; } public void finish(Database.BatchableContext bc){ System.debug(recordsProcessed + ' records processed. Shazam!'); AsyncApexJob job = [SELECT Id, Status, NumberOfErrors, JobItemsProcessed, TotalJobItems, CreatedBy.Email FROM AsyncApexJob WHERE Id = :bc.getJobId()]; // call some utility to send email EmailUtils.sendMessage(job, recordsProcessed); } } - The start method provides the collection of all records that the execute method will process in individual batches. It returns the list of records to be processed by calling Database.getQueryLocator with a SOQL query. In this case we are simply querying for all Account records with a Billing Country of ‘USA’. - Each batch of 200 records is passed in the second parameter of the execute method. The execute method sets each contact’s mailing address to the accounts’ billing address and increments recordsProcessed to track the number of records processed. - When the job is complete, the finish method performs a query on the AsyncApexJob object (a table that lists information about batch jobs) to get the status of the job, the submitter’s email address, and some other information. It then sends a notification email to the job submitter that includes the job info and number of contacts updated. Testing Batch Apex Since Apex development and testing go hand in hand, here’s how we test the above batch class. In a nutshell, we insert some records, call the Batch Apex class and then assert that the records were updated properly with the correct address. @isTest private class UpdateContactAddressesTest { @testSetup static void setup() { List<Account> accounts = new List<Account>(); List<Contact> contacts = new List<Contact>(); // insert 10 accounts for (Integer i=0;i<10;i++) { accounts.add(new Account(name='Account '+i, billingcity='New York', billingcountry='USA')); } insert accounts; // find the account just inserted. add contact for each for (Account account : [select id from account]) { contacts.add(new Contact(firstname='first', lastname='last', accountId=account.id)); } insert contacts; } @isTest static void test() { Test.startTest(); UpdateContactAddresses uca = new UpdateContactAddresses(); Id batchId = Database.executeBatch(uca); Test.stopTest(); // after the testing stops, assert records were updated properly System.assertEquals(10, [select count() from contact where MailingCity = 'New York']); } } The setup method inserts 10 account records with the billing city of ‘New York’ and the billing country of ‘USA’. Then for each account, it creates an associated contact record. This data is used by the batch class. In the test method, the UpdateContactAddresses batch class is instantiated, invoked by calling Database.executeBatch and passing it the instance of the batch class. The call to Database.executeBatch is included within the Test.startTest and Test.stopTest block. This is where all of the magic happens. The job executes after the call to Test.stopTest. Any asynchronous code included within Test.startTest and Test.stopTest is executed synchronously after Test.stopTest. Finally, the test verifies that all contact records were updated correctly by checking that the number of contact records with the billing city of ‘New York’ matches the number of records inserted (i.e., 10). Best Practices - Only use Batch Apex if you have more than one batch of records. If you don't have enough records to run more than one batch, you are probably better off using Queueable Apex. - Tune any SOQL query to gather the records to execute as quickly as possible. - Minimize the number of asynchronous requests created to minimize the chance of delays. - Use extreme care if you are planning to invoke a batch job from a trigger. You must be able to guarantee that the trigger won’t add more batch jobs than the limit.
https://trailhead.salesforce.com/en/content/learn/v/modules/asynchronous_apex/async_apex_batch
CC-MAIN-2021-10
refinedweb
1,477
56.96
Use hubs in SignalR for ASP.NET Core By Rachel Appel and Kevin Griffin View or download sample code (how to download) What is a SignalR hub The SignalR Hubs API enables you to call methods on connected clients from the server. In the server code, you define methods that are called by client. In the client code, you define methods that are called from the server. SignalR takes care of everything behind the scenes that makes real-time client-to-server and server-to-client communications possible. Configure SignalR hubs The SignalR middleware requires some services, which are configured by calling services.AddSignalR. services.AddSignalR(); When adding SignalR functionality to an ASP.NET Core app, setup SignalR routes by calling app.UseSignalR in the Startup.Configure method. app.UseSignalR(route => { route.MapHub<ChatHub>("/chathub"); }); Create and use hubs Create a hub by declaring a class that inherits from Hub, and add public methods to it. Clients can call methods that are defined as public. public class ChatHub : Hub { public Task SendMessage(string user, string message) { return Clients.All.SendAsync("ReceiveMessage", user, message); } } You can specify a return type and parameters, including complex types and arrays, as you would in any C# method. SignalR handles the serialization and deserialization of complex objects and arrays in your parameters and return values. Note Hubs are transient: - Don't store state in a property on the hub class. Every hub method call is executed on a new hub instance. - Use awaitwhen calling asynchronous methods that depend on the hub staying alive. For example, a method such as Clients.All.SendAsync(...)can fail if it's called without awaitand the hub method completes before SendAsyncfinishes. The Context object The Hub class has a Context property that contains the following properties with information about the connection: Hub.Context also contains the following methods: The Clients object The Hub class has a Clients property that contains the following properties for communication between server and client: Hub.Clients also contains the following methods: Each property or method in the preceding tables returns an object with a SendAsync method. The SendAsync method allows you to supply the name and parameters of the client method to call. Send messages to clients To make calls to specific clients, use the properties of the Clients object. In the following example, there are three Hub methods: SendMessagesends a message to all connected clients, using Clients.All. SendMessageToCallersends a message back to the caller, using Clients.Caller. SendMessageToGroupssends a message to all clients in the SignalR Usersgroup. public Task SendMessage(string user, string message) { return Clients.All.SendAsync("ReceiveMessage", user, message); } public Task SendMessageToCaller(string message) { return Clients.Caller.SendAsync("ReceiveMessage", message); } public Task SendMessageToGroup(string message) { return Clients.Group("SignalR Users").SendAsync("ReceiveMessage", message); } Strongly typed hubs A drawback of using SendAsync is that it relies on a magic string to specify the client method to be called. This leaves code open to runtime errors if the method name is misspelled or missing from the client. An alternative to using SendAsync is to strongly type the Hub with Hub<T>. In the following example, the ChatHub client methods have been extracted out into an interface called IChatClient. public interface IChatClient { Task ReceiveMessage(string user, string message); Task ReceiveMessage(string message); } This interface can be used to refactor the preceding ChatHub example. public class StronglyTypedChatHub : Hub<IChatClient> { public async Task SendMessage(string user, string message) { await Clients.All.ReceiveMessage(user, message); } public Task SendMessageToCaller(string message) { return Clients.Caller.ReceiveMessage(message); } } Using Hub<IChatClient> enables compile-time checking of the client methods. This prevents issues caused by using magic strings, since Hub<T> can only provide access to the methods defined in the interface. Using a strongly typed Hub<T> disables the ability to use SendAsync. Any methods defined on the interface can still be defined as asynchronous. In fact, each of these methods should return a Task. Since it's an interface, don't use the async keyword. For example: public interface IClient { Task ClientMethod(); } Note The Async suffix isn't stripped from the method name. Unless your client method is defined with .on('MyMethodAsync'), you shouldn't use MyMethodAsync as a name. Change the name of a hub method By default, a server hub method name is the name of the .NET method. However, you can use the HubMethodName attribute to change this default and manually specify a name for the method. The client should use this name, instead of the .NET method name, when invoking the method. [HubMethodName("SendMessageToUser")] public Task DirectMessage(string user, string message) { return Clients.User(user).SendAsync("ReceiveMessage", message); } Handle events for a connection The SignalR Hubs API provides the OnConnectedAsync and OnDisconnectedAsync virtual methods to manage and track connections. Override the OnConnectedAsync virtual method to perform actions when a client connects to the Hub, such as adding it to a group. public override async Task OnConnectedAsync() { await Groups.AddToGroupAsync(Context.ConnectionId, "SignalR Users"); await base.OnConnectedAsync(); } Override the OnDisconnectedAsync virtual method to perform actions when a client disconnects. If the client disconnects intentionally (by calling connection.stop(), for example), the exception parameter will be null. However, if the client is disconnected due to an error (such as a network failure), the exception parameter will contain an exception describing the failure. public override async Task OnDisconnectedAsync(Exception exception) { await Groups.RemoveFromGroupAsync(Context.ConnectionId, "SignalR Users"); await base.OnDisconnectedAsync(exception); } Handle errors Exceptions thrown in your hub methods are sent to the client that invoked the method. On the JavaScript client, the invoke method returns a JavaScript Promise. When the client receives an error with a handler attached to the promise using catch, it's invoked and passed as a JavaScript Error object. connection.invoke("SendMessage", user, message).catch(err => console.error(err)); If your Hub throws an exception, connections aren't closed. By default, SignalR returns a generic error message to the client. For example: Microsoft.AspNetCore.SignalR.HubException: An unexpected error occurred invoking 'MethodName' on the server. Unexpected exceptions often contain sensitive information, such as the name of a database server in an exception triggered when the database connection fails. SignalR doesn't expose these detailed error messages by default as a security measure. See the Security considerations article for more information on why exception details are suppressed. If you have an exceptional condition you do want to propagate to the client, you can use the HubException class. If you throw a HubException from your hub method, SignalR will send the entire message to the client, unmodified. public Task ThrowException() { throw new HubException("This error will be sent to the client!"); } Note SignalR only sends the Message property of the exception to the client. The stack trace and other properties on the exception aren't available to the client. Related resources Feedback Send feedback about:
https://docs.microsoft.com/en-us/aspnet/core/signalr/hubs?view=aspnetcore-2.2
CC-MAIN-2019-22
refinedweb
1,140
57.87
On Tue, 14 Apr 2009 22:21:14 +0200Andrea Righi <righi.andrea@gmail.com> wrote:> Subject: [PATCH 3/9] bio-cgroup controllerSorry, but I have to register extreme distress at the name of this. The term "bio" is well-established in the kernel and here we have a newdefinition for the same term: "block I/O"."bio" was a fine term for you to have chosen from the user'sperspective, but from the kernel developer perspective it is quitehorrid. The patch adds a vast number of new symbols all into theexisting "bio_" namespace, many of which aren't related to `struct bio'at all.At least, I think that's what's happening. Perhaps the controllerreally _is_ designed to track `struct bio'? If so, that's an odd thingto tell userspace about.> The controller bio-cgroup is used by io-throttle to track writeback IO> and for properly apply throttling.Presumably it tracks all forms of block-based I/O and not just delayedwriteback.
http://lkml.org/lkml/2009/4/16/379
CC-MAIN-2015-06
refinedweb
164
65.52
[ ] Uwe Schindler updated LUCENE-4463: ---------------------------------- Attachment: LUCENE-4463.patch Here is a trivial patch doing this (it uses a for-loop of <antcall/>). The reason why doing this is: - The naive approach is to simple use project.executeTarget(), but on the second run of the same target, junit4 complains about properties set from the previous run. - This approach unfortunately runs all dependencies over and over, as <antcall/> internally creates a "sub-project", inherits all properties currently set and then executes the target in this isolated environment. No way around that :( - This patch works everywhere where you can call "ant test" (except top-level as it does not import common-build.xml. >
http://mail-archives.apache.org/mod_mbox/lucene-dev/201210.mbox/%3C969393797.3273.1349476083838.JavaMail.jiratomcat@arcas%3E
CC-MAIN-2015-27
refinedweb
111
54.22
Destroy a window group. #include <screen/screen.h> int screen_destroy_group(screen_group_t grp) The window group to be destroyed. The group must have been created with screen_create_group(). Function Type: Flushing Execution This function destroys a window group given a screen_group_t instance. When a window group is destroyed, all windows that belonged to the group are no longer associated with the group. You must destroy each screen_group_t after it is no longer needed. 0 if the window group was destroyed, or -1 if an error occurred (errno is set; refer to /usr/include/errno.h for more details). Note that the error may also have been caused by any delayed execution function that's just been flushed.
http://www.qnx.com/developers/docs/6.6.0.update/com.qnx.doc.screen/topic/screen_destroy_group.html
CC-MAIN-2018-13
refinedweb
115
67.76
The WinSSH communicator is built specifically for the Windows native port of OpenSSH. It does not rely on a POSIX-like environment which removes the requirement of extra software installation (like cygwin) for proper functionality. NOTE: The Windows native port of OpenSSH is still considered "pre-release" and is non-production ready. For more information, see the Win32-OpenSSH project page. The WinSSH communicator uses the same connection configuration options as the SSH communicator. These settings provide the information for the communicator to establish a connection to the VM. Config namespace: config.ssh The settings within config.ssh relate to configuring how Vagrant will access your machine over SSH. As with most Vagrant settings, the defaults are typically fine, but you can fine tune whatever you would like. config.ssh.username - This sets the username that Vagrant will SSH as by default. Providers are free to override this if they detect a more appropriate user. By default this is "vagrant," since that is what most public boxes are made as. config.ssh.password - is true. config.ssh.host - The hostname or IP to SSH into. By default this is empty, because the provider usually figures this out for you. config.ssh.port - The port to SSH into. By default this is port 22. config.ssh.guest_port -.private_key_path -.insert_key - If true, Vagrant will automatically insert a keypair to use for SSH, replacing Vagrant's default insecure key inside the machine if detected. By default, this is true. This only has an effect if you do not already use private keys for authentication or if you are relying on the default insecure key. If you do not have to care about security in your project and want to keep using the default insecure key, set this to false. config.ssh.keys_only - Only use Vagrant-provided SSH private keys (do not use any keys stored in ssh-agent). The default value is true.` config.ssh.paranoid - Perform strict host-key verification. The default value is false. The configuration options below are specific to the WinSSH communicator. Config namespace: config.winssh config.winssh.forward_agent - If true, agent forwarding over SSH connections is enabled. Defaults to false. config.winssh.forward_env - An array of host environment variables to forward to the guest. If you are familiar with OpenSSH, this corresponds to the SendEnv parameter. config.winssh.forward_env = ["CUSTOM_VAR"] config.winssh.proxy_command - A command-line command to execute that receives the data to send to SSH on stdin. This can be used to proxy the SSH connection. %h in the command is replaced with the host and %p is replaced with the port. config.winssh.keep_alive If true, this setting SSH will send keep-alive packets every 5 seconds by default to keep connections alive. config.winssh.shell - The shell to use when executing SSH commands from Vagrant. By default this is cmd. Valid values are "cmd" or "powershell". Note that this has no effect on the shell you get when you run vagrant ssh. This configuration option only affects the shell to use when executing commands internally in Vagrant. config.winssh.export_command_template - The template used to generate exported environment variables in the active session. This can be useful when using a Bourne incompatible shell like C shell. The template supports two variables which are replaced with the desired environment variable key and environment variable value: %ENV_KEY% and %ENV_VALUE%. The default template for a cmd configured shell is: config.winssh.export_command_template = 'set %ENV_KEY%="%ENV_VALUE%"' The default template for a powershell configured shell is: config.winssh.export_command_template = '$env:%ENV_KEY%="%ENV_VALUE%"' config.winssh.sudo_command - The command to use when executing a command with sudo. This defaults to %c (assumes vagrant user is an administator and needs no escalation). The %c will be replaced by the command that is being executed. config.winssh.upload_directory - The upload directory used on the guest to store scripts for execute. This is set to C:\Windows\Temp by default. © 2010–2017 Mitchell Hashimoto Licensed under the MPL 2.0 License.
http://docs.w3cub.com/vagrant/vagrantfile/winssh_settings/
CC-MAIN-2018-51
refinedweb
666
51.55
OpenGLTutorial1 From HaskellWiki This tutorial was copied with permission from [1] After having failed following the googled tutorial in HOpenGL programming, I thought I’d write down the steps I actually can get to work in a tutorial-like fashion. It may be a good idea to read this in parallell to the tutorial linked, since Panitz actually brings a lot of good explanations, even though his syntax isn’t up to speed with the latest HOpenGL at all points. Hello World First of all, we’ll want to load the OpenGL libraries, throw up a window, and generally get to grips with what needs to be done to get a program running at all. import Graphics.Rendering.OpenGL import Graphics.UI.GLUT main = do (progname, _) <- getArgsAndInitialize createWindow "Hello World" mainLoop Note: GHCI has problems running this simple program on some platforms. However, as a skeleton, it is profoundly worthless. It doesn’t even redraw the window, so we should definitely make sure to have a function that takes care of that in there somewhere. Telling the OpenGL-system what to do is done by using state variables, and these, in turn are handled by the datatype Data.IORef. So we modify our code to the following: import Graphics.Rendering.OpenGL import Graphics.UI.GLUT main = do (progname, _) <- getArgsAndInitialize createWindow "Hello World" displayCallback $= clear [ ColorBuffer ] mainLoop This sets the global state variable carrying the callback function responsible for drawing the window to be the function that clears the color state. Save this to the HelloWorld.hs, recompile, and rerun. This program no longer carries the original pixels along, but rather clears everything out. The displayCallback is a globally defined IORef, which can be accessed through a host of functions defined in Data.IORef. However, deep within the OpenGL code, there are a couple of definition providing the interface functions $= and get to fascilitate interactions with these. Thus we can do things like: height = newIORef 1.0 currentheight <- get height height $= 1.5extract: Triangles Each three coordinates following each other define a triangle. The last n mod 3 coordinates are ignored. Keyword Triangles Triangle strips Triangles are drawn according to a “moving window” of size three, so the two last coordinates in the previous triangle become the two first in the next triangle. Keyword TriangleStrip Triangle fans Triangle fans have the first given coordinate as a basepoint, and takes each pair of subsequent coordinates to define a triangle together with the first coordinate. Keyword TriangleFan Lines Each pair of coordinates define a line. Keyword Lines Line loops With line loops, each further coordinate defines a line together with the last coordinate used. Once all coordinates are used up, an additional line is drawn back to the beginning. Keyword LineLoop Line strips Line strips are like line loops, only without the last link added. Keyword LineStrip Quadrangles For the Quads keyword, each four coordinates given define a quadrangle. Keyword Quads. Keyword QuadStrip reshapeCallback. Similarily,.). Summary So, in conclusion, so far we can display a window, post basic callbacks to get the windowhandling to run smoothly, and draw in our window. Next installment of the tutorial will bring you 3d drawing, keyboard and mouse interactions, the incredible power of matrices and the ability to rotate 3d objects for your leisure. Possibly, we’ll even look into animations.
http://www.haskell.org/haskellwiki/index.php?title=OpenGLTutorial1&oldid=21651
CC-MAIN-2014-35
refinedweb
556
53.92
On accessing chains of potentially null properties Raise your hand if you’ve ever written code looking like this: var result = default(int); if (fubar != null) { var foo = fubar.Foo; if (foo != null) { var bar = foo.Bar; if (bar != null) { result = bar.Baz; } } } We’ve all done that, and it’s just sad. There seems to be a law of the Universe that says that if your code looks like a wedge, like the code above, then something is wrong with that code, or with the language it’s expressed in. It illustrates one of the reasons why Tony Hoare, inventor of Quicksort, called the null reference his “billion-dollar mistake”. One can mitigate this to a degree, and use ternary operators, to make the code a little bit less horrible (but not that much): var foo = fubar == null ? null : fubar.Foo; var bar = foo == null ? null : foo.Bar; var result = bar == null ? default(int) : bar.Baz; Or maybe you’ve just given up, just call fubar.Foo.Bar.Baz and accept the null ref exceptions. Why don’t you also wear sweat pants while you’re at it? Of course, the more theoretically-oriented of you will have immediately objected that for our code to attempt to reach deep into the object graph and grab Baz is in direct violation of the Law of Demeter. Right. But in reality, we deal with DOMs, JSON payloads, and other deep graphs that are designed to be traversed, all the time, and it would be impractical to be too dogmatic about this. Ideally, we would have language support for this, and it seems like we will, in the next version of C#: fubar?.Foo?.Bar?.Baz In the meantime, what can we do? Don’t we have a language construct that enables us to express code without immediately executing it? Well, yes we do: Lambdas and expression trees! I’ve built a little helper that takes an expression tree, and evaluates it on an object, but doing null checks on the way. Using it is as simple as this: var result = fubar.Get(f => f.Foo.Bar.Baz); If you don’t even know if the fubar object is null, you can use it as a static method: var result = NotNull.Get(fubar, f => f.Foo.Bar.Baz); Here is the source code for the helper: using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Reflection; namespace Bleroy.Helpers { public static class NotNull { public static TProp Get<TSource, TProp>( this TSource source, Expression<Func<TSource, TProp>> property) where TSource : class { if (source == null) return default(TProp); var current = property.Body; var properties = new List<PropertyInfo>(); while (!(current is ParameterExpression)) { var memberExpression = current as MemberExpression; if (memberExpression == null || !(memberExpression.Member is PropertyInfo)) { throw new InvalidOperationException("All members in the expression must be properties."); } properties.Add((PropertyInfo) memberExpression.Member); current = memberExpression.Expression; } properties.Reverse(); object currentValue = source; foreach (var propertyInfo in properties) { if (currentValue == null) return default(TProp); currentValue = propertyInfo.GetValue(currentValue); } return (TProp) currentValue; } } } I’ve also posted this on Github as a Gist: Of course, the code in this post comes with no guarantee of anything whatsoever, especially performance and I don’t recommend anybody use it. It’s a fun experiment, is what it is. I’d love to read your thoughts about it in the comments section. Note: in Clay, we’ve copied Ruby’s Nil behavior, and it is possible to safely access deep properties without caring too much about them being null. This is nice, but doesn’t help you much if you’re using regular C# objects. Update: I'm being pointed to Monads.Net, that is a set of monad-driven helpers, one of which addresses the same problem with a similar solution. With Monads.Net, you'd write: var result = fubar.With(f => f.Foo).With(f => f.Bar).With(f => f.Baz); I prefer my version, because I don't need to use one method call and one Lambda per property, but can instead use one big deep Lambda. It's nice too see others come to the same kind of solution however. Update 2: Ian Griffiths was there years ago: his version rewrites the expression tree.
http://weblogs.asp.net/bleroy/on-accessing-chains-of-potentially-null-properties
CC-MAIN-2015-18
refinedweb
706
57.67
view raw I just extracted a .csv file from a scope, which shows how a signal changes in the time duration of 6 seconds. Problem is that I can't come up with a proper way of plotting this signal, without things getting mushed together. Mushed together like this: The .csv file is here. The signal goes through four stages, which I want to show with the plot, without it being to mushed together? How do I plot it? More info about the signal: The signal is a PWM signal that changes frequency. Either plotting the PWM signal vs. time, or the frequency of the PWM signal vs time, would be plot representation I would be /seeking for. As a rudimentary analysis, you could do the following using a deque to process a sliding window of values: from collections import deque import csv import matplotlib import matplotlib.pyplot as plt maxlen = 20 window = deque(maxlen=maxlen) with open('12a6-data_extracted_2.csv') as f_input: csv_input = csv.reader(f_input, skipinitialspace=True) header = next(csv_input) freq = [] x = [] for v1, v2 in csv_input: v1 = float(v1) window.append(v1) if len(window) == maxlen: x.append(v1) freq.append(maxlen / ((window[-1] - window[0]))) plt.plot(x, freq) plt.show() This would give you an output looking like:
https://codedump.io/share/zPjK2jZUp3Ew/1/how-do-i-properly-plot-data-extracted-from-a-scope-as-csv-file
CC-MAIN-2017-22
refinedweb
213
69.28
Explanation of Pointers in C++Hello everyone, in this article we are going to see the pointers in C++. We will see the purpose of the pointers and what can we do with pointers with example in QT Console Application. Let's Begin. Declared every variable has an address value on the memory. Normally the developer do not do something with these aderesses. When the program started the variables being located at the memory automatically and CPU reach them via these addresses. Sometimes we developers may be in need of accessing directly these addresses of the variables. In these cases the pointers comes for our help. We use the (&) operator to get the variable address. #include <QCoreApplication> #include <iostream> using namespace std; int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); int var_1; bool var_2; cout << "Address of var_1 is " << &var_1 << endl ; cout << "Address of var_2 is " << &var_2 << endl; return a.exec(); } As you can see below progam output we have the adresses of the varables. Address of var_1 is 0059F990 Address of var_2 is 0059F99B These values will be chenged at every program restarted. Because the program always be writed differant adresses on the memory. So What are pointers? Pointers are a variable types to keep the addresses of the variables. We declare the variables. We use the (*) operator to declare the pointers. Below you will how to declare a pointer: int *p_int_var; //an integer pointer bool *p_bool_var; //a bool pointer You can not assign a variable directly to these pointers even if same variable types. You can only assign the address values. When you try to get value of the pointer you will have the address of the pointer. If you want to get the variable value which assigned to the pointer by address you must use the unary operator(*). You can see the example code below: cout << "Define and use the pointers : " << endl; int *p_int_var; //an integer pointer bool *p_bool_var; //a bool pointer var_1 = 33; var_2 = true; p_int_var = &var_1; p_bool_var = &var_2; cout << "Value of var_1: " << var_1 << ", Adress is : " << p_int_var << endl; cout << "Value of var_2: " << var_2 << ", Adress is : " << p_bool_var << endl; cout << "Address of p_int_var : " << p_int_var << " , value is : " <<*p_int_var << endl; cout << "Address of p_bool_var : " << p_bool_var << " , value is : " <<*p_bool_var << endl; And the output of the program will be like below: Define and use the pointers : Value of var_1: 33, Adress is : 00AFFC48 Value of var_2: 1, Adress is : 00AFFC4F Address of p_int_var : 00AFFC48 , value is : 33 Address of p_bool_var : 00AFFC4F , value is : 1 You can also make some arithmetic operations via pointers. Just need to use pointers with unary operator and make the operations. Lets make a simple example about it. cout << "Arithmetic operations with pointers : " << endl; int num1 = 33, num2 =44; int *p_num1 = &num1; int *p_num2 = &num2; int sum = (*p_num1) + (*p_num2); int multiply = (*p_num1) * (*p_num2); cout << "output of sum is " << sum << " , and multiply is " << multiply << endl; Below you will see the output of the example: Arithmetic operations with pointers : output of sum is 77 , and multiply is 1452 You can reach the example application on Github via : That is all in this article. I wish you all healthy days. Have a good pointing the variables. Burak Hamdi TUFAN
https://thecodeprogram.com/explanation-of-pointers-in-c--
CC-MAIN-2021-31
refinedweb
530
60.24
Hi, i have been trying to place a gameobject on the position of touch on an ImageTarget in unity. I am able to place object on a surface in unity by getting the position from raycasthit. But it is not workin when i try to place the object on the imagetarget. Can anyone help me out? - Sort Posts - 10 replies - Last post Hi, hi kim, i tried accessing the objects i created dynamically from ontrackinglost function and disabled them. I gave a tag to the object im using for instantiating the new objects and used gameObject.FindGameObjectsWithTag for getting the objects . But it is remaining on the screen if the tracking is lost suddenly. It looks as if it is sticking on to the screen when it lost track suddenly. Take a look at the OnTrackingLost method in TrackableScript.cs. This method is called whenever tracking is lost. Currently, it disables the renderer component of all the children of the trackable, so if your objects are attached to the trackable they should be turned off automatically. You can edit the code here to handle other situations, e.g. searching for specific gameobjects to turn on/off. - Kim Hi kim, I tried the above code and it worked fine for me. When i loose track of the imagetarget slowly, all the objects that i placed on the image taget disappears, but, when i loose track suddenly, all the objects that i placed on the image taget remain on the screen as if it is stuck on the screen surface. What should i do to remove it whenever tracking is lost? I can get this to work with the following script, placed on the chips target in the ImageTargets sample project: using UnityEngine; using System.Collections; public class TouchScript : MonoBehaviour { public GUIText message; public Transform teapot; void Update () { Plane targetPlane = new Plane(transform.up, transform.position); foreach (Touch touch in Input.touches) { Ray ray = Camera.main.ScreenPointToRay(touch.position); float dist = 0.0f; targetPlane.Raycast(ray, out dist); Vector3 planePoint = ray.GetPoint(dist); message.text = "Projected point: " + planePoint; Instantiate(teapot, planePoint, Quaternion.identity); } } } I created a GUIText object and attached it to the script, and then I attached the teapot model to the script. The teapot is neither textured nor rotated correctly, but it is created at the correct touch location. Make sure you are tracking off the chips target, in fact you may want to delete the stones target just to be safe. - Kim Hi Kim, I tried doing that. Im able to get the value for distance ,but it is in terms of E, ie, like 2.3545E+13 . the position i get using Getpoint is also havin the same. I tried creating an object there using the instantiate method giving this as the position , but im not able to see the object. What can be the problem? I might suggest doing a raycast against a Plane object. Create a plane from the transform of your ImageTarget object: Plane targetPlane = new Plane(transform.up, transform.position); That code works for a script attached to the ImageTarget, or you could pass in the ImageTarget object to a script that lives elsewhere. Now do a raycast on the plane, with the current touch: Ray ray = Camera.main.ScreenPointToRay(touch.position); float dist = 0.0f; targetPlane.Raycast(ray, out dist); Vector3 planePoint = ray.GetPoint(dist); Try that and let me know if it helps. - Kim Delete Message Are you sure you want to delete this message? Delete Conversation Are you sure you want to delete this conversation? You will probably want to set the parent of your newly instantiated object to the trackable it is attached to. This will ensure its renderer is turned off when that trackable is lost. See the TrackableScript.cs OnTrackingLost function for more details. - Kim
https://developer.vuforia.com/forum/unity-extension-technical-discussion/placing-object-position-click-imagetarget
CC-MAIN-2019-51
refinedweb
637
66.33
The memcpy() function in C/C++ is used to copy data from one memory location to another. This is a common way of copying data using pointers. Let’s understand how we can use this function in this article. Syntax The memcpy() function takes in two memory address locations (src and dst) as arguments, along with the number of bytes (n) to be copied. Since C/C++ typically uses a void* pointer to denote memory location addresses, the invocation for the source and destination addresses are void* src and void* dst. The function returns a pointer to the destination memory address dst, but in practice, we do not usually capture the return value. (Since we already have the pointer with us) Format: #include <string.h> void* memcpy(void* dst, const void* src, size_t n) The header file <string.h> is necessary to load this library function. Arguments: dst-> Pointer to the destination address src-> Pointer to the source address n-> Number of bytes to be copied Return Value This returns the pointer to the destination location ( dst). NOTE: To avoid any kind of overflow, the size of the arrays pointed to by both the destination and source arguments must be at least n bytes and cannot overlap. Let’s understand the function using some examples. Some Examples Here is an example which copies a string from one location to another using memcpy(). #include <stdio.h> #include <string.h> int main () { // This is constant, since memcpy() will not modify this const char src[50] = "JournalDev"; char dest[50]; strcpy(dest, "Sample"); printf("Before memcpy(), dest: %s\n", dest); // It is strlen(src) + 1 since we also copy the null terminator '\0' memcpy(dest, src, strlen(src)+1); printf("After memcpy(), dest: %s\n", dest); return(0); } Output Before memcpy(), dest: Sample After memcpy(), dest: JournalDev Here is another example which appends a string using memcpy() using appropriate offsets. #include <stdio.h> #include <string.h> int main() { // This is constant, since memcpy() will not modify this const char src[100] = "This is a JournalDev article."; char dst[100] = "memcpy"; printf("Before memcpy(), dst is: %s\n", dst); // Set offsets for both src and dst size_t offset_src = 0, offset_dst = 0; offset_src += 4; offset_dst += strlen(dst); memcpy(dst + offset_dst, src + offset_src, strlen(src)); printf("After memcpy(), dst is: %s\n", dst); return 0; } The output will be the destination string appended with ” is a JournalDev article“. Output Before memcpy(), dst is: memcpy After memcpy(), dst is: memcpy is a JournalDev article. A Simple memcpy() Implementation Here is a simple implementation of memcpy() in C/C++ which tries to replicate some of the mechanisms of the function. We first typecast src and dst to char* pointers, since we cannot de-reference a void* pointer. void* pointers are only used to transfer data across functions, threads, but not access them. Now we can directly copy the data byte by byte and return the void* destination address. void* memcpy_usr(void* dst, const void* src, size_t n) { // Copies n bytes from src to dst // Since we cannot dereference a void* ptr, // we first typecast it to a char* ptr // and then do the copying byte by byte, // since a char* ptr references a single byte char* char_dst = (char*) dst; char* char_src = (char*) src; for (int i=0; i<n; i++) { *char_dst++ = *char_src++; } return dst; } You can verify that by replacing memcpy() with our new function, we will get the same output. Conclusion In this article, we learned about the memcpy() library function in C/C++, which is useful to copy data from a source address to a destination address.
https://www.journaldev.com/34452/c-memcpy-copy-across-memory-locations
CC-MAIN-2021-25
refinedweb
601
57.1
Published 4 months ago by thc1967 I've finally bumped into a spot in my project that I can no longer use an in-memory sqlite database for my unit tests. It was cool while it lasted but, alas, I need to do some stuff that sqlite simply doesn't support. And I want to keep using unit testing. I'm pretty stoked that I have hundreds of tests with thousands of assertions. I've found it helps tremendously with everything I do. And I refuse to design my code around shortcomings in the testing setup I've elected to use. My code needs to be right and the tests should support and verify that; not the other way around. So now I face the prospect of running my unit tests against a real, "on-disk" database like mysql (same thing I'm using for production). With a sqlite memory database, I didn't have to worry or care about exactly how the tests would run the migration and the tiny little seeder I set up. If it ran them before each test class or even each function, that wouldn't be a big deal. It's all in memory. That won't be the case any longer. How, using Laravel 5.5, do I ensure that my PHPUnit tests run my migration and seed just once before running all the test classes & methods? Thanks for the advice! I've been running my tests in an on disk mySQL database since I started, I'll tell you how I did it. First, you create an alternate database called something like appName_test. Then, you want to go to your config/database and add a test connection to the list, like this: // Note the env() variables, they are specific to the test database. 'mysql_test' => [ 'driver' => 'mysql', 'host' => env('DB_TEST_HOST', '127.0.0.1'), 'port' => env('DB_TEST_PORT', '3306'), 'database' => env('DB_TEST_DATABASE', 'forge'), 'username' => env('DB_TEST_USERNAME', 'forge'), 'password' => env('DB_TEST_PASSWORD', ''), 'unix_socket' => env('DB_TEST_SOCKET', ''), 'charset' => 'utf8mb4', 'collation' => 'utf8mb4_unicode_ci', 'prefix' => '', 'strict' => true, 'engine' => null, ], Of course, you have to define those env variables in your .env file. Then you need to setup your phpunit.xml to use the testing database during testing, like this: <php> <env name="APP_ENV" value="testing"/> <env name="CACHE_DRIVER" value="array"/> <env name="SESSION_DRIVER" value="array"/> <env name="QUEUE_DRIVER" value="sync"/> <!-- Add this line, this is the connection name we defined before. --> <env name="DB_CONNECTION" value="mysql_test"/> </php> Your testing database is empty though, run migrate on it: php artisan migrate --database mysql_test You can also run seed on it, if your tests need to have some data in the database. Mine inserted all the data during fixture setup. Now, if your TestCases are using the DatabaseTransactions trait. Each test will run inside a different transaction that will be automatically rolled back at the end of the test, undoing any change to the database made during the test. Because of that, I only need to run migrate again when I create new migrations. Dont forget to clear your config cache before running phpunit! Good luck, tell me how it goes. That's a cool idea. Unfortunately, transactions do not seem like they're going to work because of the context switch when testing controllers with objects that have relationships. I'm creating the related objects in my test case, but those relations don't carry through into the controller when I call it with something like $this->post($route, $params). Therefore, I bomb out on referential integrity constraints in my controller. Maybe if I do it without transactions. Do a migrate:fresh --seed before each run of my full test suite and just let the tests load up the database. Doesn't matter; it's a test database, right? The problem with not cleaning the database after each test is that the data left behind by one test could affect the result of the next test. I'm not sure I understand what context switch you mean, or what's happening to your related models. It'd be nice to see one of the tests that's not working with the transactions. $item = make(Comment::class); // Creates a Post behind the scenes. $this->post('/comments/store', $item->toArray()); // Touches the Post The $this->post() results in a 500 error, which comes back as a referential integrity constraint violation because the Post that the Comment created doesn't exist within the context of the controller. I think that's because I'm running the transaction within the Test object, which is a different memory space than the Controller, so the Controller isn't aware of the transaction... Unfortunately, I'm distracted with other things so I've had to stop digging. Will be back to it later this weekend hopefully. I think I get it. Your call to make(Comment::class) makes a Comment without persisting it to DB because you want to store it in the Controller logic. But, since Comment belongs to Post, you are also making a post. Now if the post you're making isn't persisted to database, I can see why that would cause trouble. Is that the case? If so, try to actually persist the post to DB during the fixture setup and see what happens. Actually, the make(Comment::class) calls create(Post::class) which does persist it to the database... ...but it doesn't because it's all transacted because I'm using the transaction trait in my test. So my theory is that the the data created during the transaction that started in my test class isn't able to be seen in my controller, which I'm almost certain is running in a separate process from my test class. I extract the DatabaseTransactions into my own trait to gain control over it: <?php namespace Tests; trait DatabaseTransactions { /** * Handle database transactions on the specified connections. */ public function beginDatabaseTransaction() { $database = $this->app->make('db'); foreach ($this->connectionsToTransact() as $name) { $database->connection($name)->beginTransaction(); } $this->beforeApplicationDestroyed(function () use ($database) { foreach ($this->connectionsToTransact() as $name) { $database->connection($name)->rollBack(); } }); } /** * The database connections that should have transactions. * * @return array */ protected function connectionsToTransact() { return property_exists($this, 'connectionsToTransact') ? $this->connectionsToTransact : [null]; } } If you try to use the DatabaseTransactions trait that comes with Laravel, it will be registered with the test runner and this will not work. In my TestCase class, I do the following: <?php namespace Tests; use Tests\DatabaseTransactions; use Illuminate\Foundation\Testing\TestCase as BaseTestCase; abstract class TestCase extends BaseTestCase { use CreatesApplication, DatabaseTransactions; /** * If true, setup has run at least once. * * @var boolean */ protected static $setUpRun = false; /** * Set up the test. */ public function setUp() { parent::setUp(); if (!static::$setUpRun) { \Artisan::call('migrate:refresh'); \Artisan::call('db:seed', ['--class' => 'TestDatabaseSeeder']); static::$setUpRun = true; } $this->beginDatabaseTransaction(); } } Basically, if its the first run, we're going to migrate and run a seeder to get everything set up. Otherwise, we'll just start database transactions. @thc1967 If you really can't make it work with with transactions, try the DatabaseMigrations trait instead. It will migrate the database between tests, shoul work. But it'll probably make your tests run too slowly. If you're sure that your tests don't care about any data left by a previous test then @zachleigh 's anwer is perfectly fine. It will avoid filling up the database too much by running the tests over and over. And it wont make the tests run too slowly. As for the transactions... If you're using the trait, your entire test runs inside the same transaction. Both the call to make() and the call to $this->post(). Try this, just to make sure. $item = make(Comment::class); // Creates a Post behind the scenes. // These should NOT fail. If make() is persisting the models. Comment::findOrFail($item->id); Post::finOrFail($item->post_id); $this->post('/comments/store', $item->toArray()); // Touches the Post There are three things that seem weird to me. I'm not saying they're wrong, because I don't know how your app works. But they jump at me. First, your function is called make(), which to me implies the item isn't persisted to dabase. Factories make that distinction between make() and create(). Second, you're telling me you're sending a comment that's already in database to the store route (which is supposed to store in database). Third, you're sending $item->toArray(). toArray will serialize the model and the related models that are loaded. If your route is only expecting data about the comment you could try $item->getAttributes(). I think I have it working with the Laravel DatabaseTransactions trait... mostly. MySQL behaves differently than Sqlite when using transactions. The biggest change seems to be that when we consume an autonumber in MySQL, that autonumber stays consumed. This invalidates tests like ensuring I've redirected to a specific record ( $this->assertRedirect(route('posts.show', 1))). The ID of the record would only be 1 for the very first test that I run that creates the object. This is more proper database behavior, of course, but it means I need to rethink my test cases a little bit. Please sign in or create an account to participate in this conversation.
https://laracasts.com/discuss/channels/testing/migrate-seed-only-once
CC-MAIN-2018-09
refinedweb
1,536
64.81
Below is the code I tried to test but it keeps telling me Line 3: error: <identifier> expected. I'm confused since this code is almost the same as solution. or Error : Line 3: error: illegal start of type. Anyone can help find the problem? I am using java. public class Solution { public vector<int> twoSum(vector<int>& numbers, int target){ int low = 0, high = numbers.size()-1; while(low< high){ int sum= numbers[low]+ numbers[high]; if(sum == target){ return {low+1, high+1}; } else if(sum< target){ ++low; }else{ --high; } } return {-1,-1}; } } I believe binary search is still applicable to this question. I read some existing posts. Most of them used binary search for one value, and their algorithm could be described as following: for(i = 0; i < nums; i++) num1 = nums[i]; num2 = target - num1; binary search num2 in nums[i:], if found, return the index of num1, num2 Their approach actually takes O(nlogn) time. The worst case is num1 and num2 is the center. It takes log(n-1)+log(n-2)+..log(n/2) ~ nlogn My idea is using binary search with only one loop. The worst case is: - the input arry contains same values, or - num1 and num2 is in the center is then every time we move the cursor by 1, which takes O(n). In other cases my approach is faster than linear scan. We could start with left = 0, right = nums.size()-1, and mid = left+right. Since the input vector is sorted, we know nums[left] < nums[mid] < nums[right], so that: nums[left] + nums[mid] < nums[left] + nums[right] < nums[mid] + nums[right]. If nums[left] + nums[mid] > target, the 2 number we are looking for must be within nums[left:mid-1]. Similarly, if nums[right] + nums[mid] < target, the 2 number we are looking for must be within nums[mid+1:right]. Following is an accepted C++ implemetaion. class Solution { public: vector<int> twoSum(vector<int>& numbers, int target) { int left = 0, right = numbers.size()-1; vector<int> ret; while (left < right){ int mid = left + (right-left)/2; int sum = numbers[left] + numbers[right]; if (sum == target){ ret.push_back(left+1); ret.push_back(right+1); break; } else if (sum < target){ left = (numbers[mid] + numbers[right] < target)?mid:left+1; }else{ right = (numbers[mid] + numbers[left] > target)?mid:right-1; } } return ret; } }; You have to consider overflow case. Doesn't work for a test case of numbers={1, 2, 3, 2147483647}, target=3. This logic yields time error in Python. I implemented binary search in Python which has O(nlogn) complexity: class Solution(object): def twoSum(self, numbers, target): """ :type numbers: List[int] :type target: int :rtype: List[int] """ i = 0 for i in range(0, len(numbers)): num1 = numbers[i] target_new = target - num1 j = i + 1 k = len(numbers) - 1 while j <= k: if numbers[j] == target_new: return [i+1 ,j+1] elif k - j == 1: if numbers[k] == target_new: return [i+1, k+1] else: break else: middle = int((j + k)/2) if target_new < numbers[middle]: k = middle elif target_new > numbers[middle]: j = middle else: return [i+1, middle+1] Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.
https://discuss.leetcode.com/topic/43/two-sum-ii-input-array-is-sorted
CC-MAIN-2018-13
refinedweb
542
63.9
Gantry::Plugins::SOAP::RPC - RPC style SOAP support In your GEN module: use Your::App::BaseModule qw( -PluginNamespace=YourApp SOAP::RPC ); # this will export these into your package: # soap_in # soap_out # do_main # do_wsdl # return_error sub get_soap_ops { my $self = shift; return { soap_name => 'Kids', location => $self->location, namespace_base => 'localhost', operations => [ { name => 'get_count', expects => [ { name => 'table_name', type => 'xsd:string' }, ], returns => [ { name => 'count', type => 'xsd:int' }, ], }, ], }; } Add as many operations as you need. In your stub: use Your::GEN::Module; sub get_count { my $self = shift; my $data = shift; return { ... }; } Your data will have whatever was in your client's soap request. You are responsible for diagnosing all errors and for returning the correct structure (it should match the returns list). But feel free to just die when you spot an error, this module traps those and uses its return_error method which sends valid SOAP fault messages. This plugin is for rpc style SOAP requests only. If you need document style requests, you should use Gantry::Plugins::SOAP::Doc. Bigtop can help a lot with the use of this plugin. Below is what you need to do manually, should you choose that route. But first, I'll explain what is happening from overhead. For each SOAP handler in your app, there should be one controller (or a stub/GEN controller pair) placed on a location in your httpd conf. If you do the normal thing, the GEN module (or controller if you don't have a GEN) uses this module and accepts all the exports (the list is mainly for documentation, since all of them are exported by default). Two of the exports are Gantry handlers: do_main and do_wsdl. This means that the caller will look for the service itself at the location from httpd.conf, while they will add /wsdl to get the WSDL file. For example, suppose you have this in your httpd.conf: <Location /appname/SOAP> SetHandler perl-script PerlHandler YourApp::YourSoapStub </Location> Then users will hit /appname/SOAP to get the service and /appname/SOAP/wsdl to get the WSDL file. This module registers a pre_init callback which steals all of the body of the POST from the client. Then it lets Gantry do its normal work. So your stub methods will be called through a site object. All SOAP requests are handled by do_main, which this module exports. It uses the internal soap_in method to parse the input. You must import soap_in, so it will be in the site object. It fishes the client's desired action out of the incoming SOAP request and calls the method of the same name in the stub module. That method receives the SOAP request as parsed by XML::Simple's XMLin function. It must return the structure which will be returned to the client. The action method's structure is then fed to soap_out (which you must also import) and the result is returned as a plain text/xml SOAP message to the client. SOAP::Lite's SOAP::Data and SOAP::Serializer are used to the hard work of making output. Here are the details of what your need to implement. You need a namespace method which returns the same name as the -PluginNamespace. You also need a get_soap_ops method which returns a hash describing your WSDL file. See the SYNOPSIS for an example. Here's what the keys do: This is used whenever SOAP requires a name. Prefixes and suffices are appended to it, as in NAME_Binding. Normally, you should make this <$self-location>>, so that all requests come to the same SOAP controller which produced the WSDL file. This should be everything after http:// and before <$self-app_rootp>> in the URL of the SOAP service. Usually that is just the domain. An array reference of hashes describing the services you offer. Each element is a hash with these keys: The name of the action method in your stub controller, which will handle the request. An array reference of parameters the method expects. These have two keys: name and type. They type can be any valid xsd: type or any other type in your WSDL file. If you need to define types, see WSDL TYPES below. An array exactly like expects, except that it represents your promise to the client of what will be in the SOAP response. Called by Gantry's import method to register the callbacks for this module. Gantry ships with wsdl.tt which it uses by default to construct the WSDL file from the result of get_soap_ops. If you need to define types, simply copy that template into your own root path and add the types you need. If you want to supply your own data to the template, just implement your own get_soap_ops and return whatever your template expects. All of these are exported by default. You may supply your own, or accept the imports. Failure to do one of those two is fatal. Doing both will earn you a subroutine redefinition warning. Steals the body of the POST request before Gantry's engine can get to it. This method must be registered to work. Do that by using the plugin as you use your base module: use Your::App qw( -PluginNamespace=module_name SOAP::RPC ); Note that you don't have to do this in the same place as you load the engine. In fact, that probably isn't a great idea, since it could lead you down the primrose path to all of your modules using the plugin's steal_post_body, leaving you without form data. Then, you must also implement a method called namespace which returns the same string as the -PluginNamespace. This method delegates its work to consume_post_body, which is exported by each engine. The SOAP service. Fishes the POST body with get_post_body parses it using soap_in, dispatches to your action method, makes the SOAP response with soap_out, and returns it. Uses wsdl.tt to return a WSDL file for your service to the client. It uses get_soap_ops to know what to put in the WSDL file. Its template is wsdl.tt. You must call yours that, but feel free to copy the standard one to an earlier element of the root template path and edit it. For internal use. Uses XML::Simple to parse the incoming SOAP request. For internal use. Forms a valid (though simple) SOAP response. Note that this module may not be able to handle your complex types. It uses SOAP::Lite's SOAP::Data and SOAP::Serializer modules to generate the XML response. Returns a valid SOAP fault response. You must either accept this method in your imports or write one yourself. The standard error is not SOAP aware. Phil Crow, <crow.phil@gmail.com> This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself, either Perl version 5.8.6 or, at your option, any later version of Perl 5 you may have available.
http://search.cpan.org/dist/Gantry/lib/Gantry/Plugins/SOAP/RPC.pm
CC-MAIN-2018-13
refinedweb
1,154
73.98
Using Dockerized Consul as dnsmasq backend My internal network for development and staging has a lot of moving pieces, most of which is managed with Saltstack, and deployed on VMs and in a local DC/OS cluster, and the lingering challenge was how to dynamically update internal DNS so I don’t have to update mappings in dnsmasq as I add and remove, or just reboot or rebuild, VMs and containerized services. Since I rely on commercial DNS and provisioning tooling from my various cloud providers, and in the case of hardware I manage directly, automation tooling like Fabric, this was not required in my production environments, so I allowed myself some latitude to slap something together, but also take an opportunity improve this as well. The approach I landed on, as my environment grew, and my needs got a little more involved, was: - On my DNS server (itself a containerized service), I run a service intended to identify and set as the network address pushed through Consul the address for the network I’d actually be accessing (not always simple when many hosts may have multiple interfaces that don’t require exposure, etc. and this is a neater, more canonical way of selecting the address actually assigned and used on the network bound to that host): - When this address and the system hostname is pushed to Consul, this updates the backend used by dnsmasq, and adding the mapping to the zone for my internal domain (for example, $HOST.boulder.gourmet.yoga) Since all of my network VMs also run Docker (as managed through Salt, many requirements in most state files are served in the form of Docker images, rather than packages from an apt-repo, etc.), Consul will be no exception. On my DNS host, I run two containers, the primary Consul instance, and the IP address ID service (a very simple Ruby application): jmarhee@tonyhawkproskater2 ~/return_ip $ docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES b5b4dd6d86dc progrium/consul "/bin/start -server -" 3 seconds ago Up 2 seconds 10.0.1.13:8300-8302->8300-8302/tcp, 10.0.1.13:8400->8400/tcp, 53/tcp, 172.17.0.1:53->53/udp, 10.0.1.13:8500->8500/tcp, 10.0.1.13:8301-8302->8301-8302/udp consul0 return_ip registry.boulder.gourmeta.yoga/return_ip "/bin/sh -c 'ruby /ro" 2 minutes ago Up 2 minutes 0.0.0.0:80->4567/tcp return_ip I deploy Consul on the DNS node using a command like the following: docker run --restart=unless-stopped -d -h consul0 --name consul0 -v /mnt/consul:/data -p 10.0.1.13:8300:8300 -p 10.0.1.13:8301:8301 -p 10.0.1.13:8301:8301/udp -p 10.0.1.13:8302:8302 -p 10.0.1.13:8302:8302/udp -p 10.0.1.13:8400:8400 -p 10.0.1.13:8500:8500 -p 172.17.0.1:53:53/udp progrium/consul -domain gourmet.yoga -dc=boulder -server -advertise 10.0.1.13 -bootstrap-expect 12 and something like this on the client nodes: docker run --restart=unless-stopped -d -h consul-$(hostname) --name consul-$(hostname) -v /mnt:/data -p $(curl -s 10.0.1.13):8300:8300 -p $(curl -s 10.0.1.13):8301:8301 -p $(curl -s 10.0.1.13):8301:8301/udp -p $(curl -s 10.0.1.13):8302:8302 -p $(curl -s 10.0.1.13):8302:8302/udp -p $(curl -s 10.0.1.13):8400:8400 -p $(curl -s 10.0.1.13):8500:8500 -p 172.17.0.1:53:53/udp progrium/consul -domain gourmet.yoga -dc=boulder -server -advertise $(curl -s 10.0.1.13) -join 10.0.1.13 where the curl commands are calling out to test connectivity, but also verify the advertisement address. I specified the datacenter and domain parameters to override the dc1.consul formatted-default behavior to match my naming scheme boulder.gourmet.yoga . To make use of the DNS feature, a service must be defined, and in this case, since I’m looking to basically namespace a development environment, I’m just going to declare (without a port definition) a service called dev and register the service: A service can be registered either by providing a service definition or by making the appropriate calls to the HTTP API… For example, I connected my workstation (`iampizza`) to this network, and when I check the members output from Consul, I see the following: jmarhee@tonyhawkproskater2 ~/return_ip $ docker exec -it consul0 consul members Node Address Status Type Build Protocol DC consul-iampizza 10.0.1.10:8301 alive server 0.5.2 2 boulder consul0 10.0.1.13:8301 alive server 0.5.2 2 boulder So, as a result of adding this member, using the above dc and domain specification, it should come out to consul-iampizza.$SERVICE.boulder.gourmet.yoga (for example) when I go to query for the address through my DNS server. Hooking this up to dnsmasq as a useful backend is a little more straightforward; I rebuilt my dnsmasq container with the addition of a link to the consul0 container. From this point, the configuration on the DNS server side (if, for example, you use BIND and not dnsmasq), follows the documentation as one might if running Consul locally, and not in a container:
https://medium.com/@jmarhee/using-dockerized-consul-as-dnsmasq-backend-42e09d52e0d0?source=rss-d532e3e97d0f------2
CC-MAIN-2017-26
refinedweb
898
54.42
Converting date from one timezone to another in groovy Hi, In my recent grails project, i came across the situation where i needed to convert the date in given timezone to the date in another timezone. I searched a lot about it and got many solutions for this problem and then i came out with a simple way to do so. Lets i have a date in TimeZone say oldTimeZone and i want to convert it to another timeZone say newTimeZone, so to convert it to another timezone, i wrote the method given below. public Date convertToNewTimeZone(Date date, TimeZone oldTimeZone, TimeZone newTimeZone){ long oldDateinMilliSeconds=date.time - oldtimeZone.rawOffset // oldtimeZone.rawOffset returns the difference(in milliSeconds) of time in that timezone with the time in GMT // date.time returns the milliseconds of the date Date dateInGMT=new Date(oldDateinMilliSeconds) long convertedDateInMilliSeconds = dateInGMT.time + newTimeZone.rawOffset Date convertedDate = new Date(convertedDateInMilliSeconds) return convertedDate } This Works for me. Hope it helps. Cheers..!!! Vishal Sahu vishal@intelligrape.com I am in similar situation. I am trying to convert my dateTime groovy object (EST) from DB to PST. But my results are not right using your solution. Thank You! Hi Har, Yes this code wont work for DST. If you want to cover DST also, then replace the “rawOffset” with “getOffset((new Date()).time)” So the modified code would be:- Date date=new Date() long oldDateinMilliSeconds=date.time – oldtimeZone.getOffset(date.time) Date dateInGMT=new Date(oldDateinMilliSeconds) long convertedDateInMilliSeconds = dateInGMT.time + newTimeZone.getOffset(date.time) Date convertedDate = new Date(convertedDateInMilliSeconds) Thanks. This doesn’t cover the daylight savings. giving me the wrong output. Thanks dude, it helped Hi Lari, thanks for sharing the code. Code provided by me is helpful when you know the date and its timezone as well. In my scenario i wanted to convert the date that is stored in some other timezone on my machine, i know the date and its timezone and thus converted it by using this code and it works fine for me. I think this code is in-correct for most users. The internals of java.util.Date is always UTC. You should just format the date in another TimeZone instead. The same thing applies for parsing dates (set the TimeZone on the DateFormat used for parsing). Example code: import java.text.* dateformat=DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL) dateformat.setTimeZone(TimeZone.getTimeZone(‘America/Los_Angeles’)) dateformat.format(new Date())
https://www.tothenew.com/blog/converting-date-from-one-timezone-to-another-in-groovy/?replytocom=40647
CC-MAIN-2020-34
refinedweb
403
50.02
The Java EE 7 Tutorial 23.9 Giving Beans EL Names To make a bean accessible through the EL, use the @Named built-in qualifier: import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.inject.Named; @Named @RequestScoped public class Printer { @Inject @Informal Greeting greeting; ... } The @Named qualifier allows you to access the bean by using the bean name, with the first letter in lowercase. For example, a Facelets page would refer to the bean as printer. You can specify an argument to the @Named qualifier to use a nondefault name: @Named("MyPrinter") With this annotation, the Facelets page would refer to the bean as MyPrinter.
http://docs.oracle.com/javaee/7/tutorial/doc/cdi-basic009.htm
CC-MAIN-2014-42
refinedweb
108
50.53
table of contents other versions - wheezy 3.44-1 - jessie 3.74-1 - jessie-backports 4.10-2~bpo8+1 - testing 4.10-2 - unstable 4.10-2 NAME¶setns - reassociate thread with a namespace SYNOPSIS¶ #define _GNU_SOURCE /* See feature_test_macros(7) */ #include <sched.h>int setns(int fd, int nstype);int setns(int fd, int nstype); DESCRIPTION¶Given a file descriptor referring to a namespace, reassociate the calling thread with that namespace. - 0 - Allow any type of namespace to be joined. - CLONE_NEWIPC - fd must refer to an IPC namespace. - CLONE_NEWNET - fd must refer to a network namespace. - CLONE_NEWUTS - fd must refer to a UTS namespace. RETURN VALUE¶On success, setns() returns 0. On failure, -1 is returned and errno is set to indicate the error. ERRORS¶ -.
https://manpages.debian.org/wheezy/manpages-dev/setns.2.en.html
CC-MAIN-2022-40
refinedweb
126
63.36
Random Forests in Python http likes 249 Random forest is a highly versatile machine learning method with numerous applications ranging from marketing to healthcare and insurance. This is a post about random forests using Python.. Random forest is a highly versatile machine learning method with numerous applications ranging from marketing to healthcare and insurance. It can be used to model the impact of marketing on customer acquisition, retention, and churn or to predict disease risk and susceptibility in patients. Random forest is capable of regression and classification. It can handle a large number of features, and it's helpful for estimating which Classification able. Alright let's write some code. We'll be writing our Python code in Yhat's very own interactive environment built for analyzing data, Rodeo. You can download Rodeo for Mac, Windows or Linux [here](). First, create some fake data and add a little noise. import numpy as np import pylab as pl x = np.random.uniform(1, 100, 1000) y = np.log(x) + np.random.normal(0, .3, 1000) pl.scatter(x, y, s=1, label="log(x) with noise") pl.plot(np.arange(1, 100), np.log(np.arange(1, 100)), c="b", label="log(x) true function") pl.xlabel("x") pl.ylabel("f(x) = log(x)") pl.legend(loc="best") pl.title("A Basic Log Function") pl.show() We'll be doing our Python analysis and visualization in Rodeo, Yhat's open source data science environment. Want to follow along? You can download Yhat's Python IDE for Mac, Windows or Linux here. Following along in Rodeo? Here's what you should see. Let's take a closer look at that plot.products of trying lots of decision tree variations is that you can examine which variables are working best/worst in each tree. When a certain tree uses parallelize fitting your random forest based on the number of cores you want to use. Here's a great presentation by scikit-learn contributor Olivier Grisel where he talks about training a random forest on a 20 node EC2 cluster. from sklearn.datasets import load_iris from sklearn.ensemble import RandomForestClassifier import pandas as pd import numpy as np iris = load_iris() df = pd.DataFrame(iris.data, columns=iris.feature_names) df['is_train'] = np.random.uniform(0, 1, len(df)) <= .75 df['species'] = pd.Categorical.from_codes(iris.target, iris.target_names) df.head() train, test = df[df['is_train']==True], df[df['is_train']==False] features = df.columns[:4] clf = RandomForestClassifier(n_jobs=2) y, _ = pd.factorize(train['species']) clf.fit(train[features], y) preds = iris.target_names[clf.predict(test[features])] pd.crosstab(test['species'], preds, rownames=['actual'], colnames=['preds']) Following along? Here's what you should see(ish). We're using *randomly* selected data, so your exact values will differ each time. Final Thoughts Random forests are remarkably easy to use given how advanced they are. As with any modeling, be wary of overfitting. If you're interested in getting started with random forest in R, check out the randomForest package. - Berkley Resources - Kaggle blogpost - Andy Mueller's blog (scikit-learn contributor) - Random Forest Guide - Olivier Grisel's website Original. Reposted with permission. Related:
https://www.kdnuggets.com/2016/12/random-forests-python.html
CC-MAIN-2019-18
refinedweb
525
52.97
Dist: Ubuntu 14.04, Unity. POL: 4.2.2 I didn't want to put this in the POL forum because it's more a Steam problem than POL(I believe), I just figured someone here would know more as it is running the game with a POL shortcut. I recently got Swordsman working in POL, everything is fine it launches with the shortcut "/usr/share/playonlinux/playonlinux --run "Swordsman" %F" as expected, but I can't seem to launch it in Steam. I have searched around and have tried adding the .desktop file with a script as explained > When I run the game from Steam, Steam shows it launch for about half a second then stops, and the game doesn't even launch. It seems that Steam tries to run it but fails somewhere and it doesn't even get to POL, otherwise I'd at least get the game pop up. My Swordsman.desktop file; [Desktop Entry] Type=Application Name=Swordsman Exec=/home/mattio/Documents/Swordsman.sh Icon=/home/mattio/.PlayOnLinux/wineprefix/Arc/drive_c/Program Files/Perfect World Entertainment/Swordsman_en/patcher/myicon.ico Terminal=false /home/mattio/Documents/Swordsman.sh #!/bin/bash /usr/share/playonlinux/playonlinux --run "Swordsman" %F Any help would be great, hopefully I haven't missed something blatently obvious, I just want to have Steams overlay ready for when the game arrives :P Awesome! I can't wait to play Swordsman and make a PlayOnLinux guide. What are your computer specs? I'm sure you knew that the Arc client will run Swordsman as well... Arc runs beautifully in PlayOnLinux, so try downloading and installing from it. It's a great game! Definitely recommend trying it. I'll tell you what happened with POL. I managed to get Swordsman running by it's files only, without Arc(I downloaded on a windows machine a while back and to save time I copied them over). So I could run it directly and I was happy with that, but that was before closed beta release. Just before release they release a patch! Broke my damn setup and wouldn't launch the game lol. I have a Windows partition so I ran on that because it released and was eager to play :P. I found the last Swordsman patch forces you to run the game through Arc, which really sucked(for me), so I haven't had chance to try fix it for Linux, so I'll try again soon(maybe end of closed beta) or awaite a guide. My main specs are i5 2500 (4ghz), GTX 660Ti, 8GB GSkill RipjawX RAM, OCZ Agility SSD. Ubuntu 14.04. I did the same thing with Neverwinter while it was beta. Ran fine without Arc, but when it went live I had to install Arc. Good thing is, Arc runs just fine in PlayOnLinux. Check out this Guide on installing Arc for Neverwinter: Neverwinter Guide Just get Arc running and then install Swordsman and do the patching/updating. I wonder if you could speed up the process by moving the beta game folders to the same place Arc install Swordsman? So its out of beta? I'm going to have to try it! Star Trek Online and Neverwinter run just fine, so I bet its the same engine! Hey Mattio, I finally started testing World of Swordsman and am having problems as well. I have successfully gotten Arc to install and download the entire game, but when I launch there is a Swordsman logo, some strange buggy animation and then CRASH. I tried several versions of Wine: 1.6.2 1.7.19 1.7.21 I tried windows versions: 7 & XP I also installed the following libraries: I can post the debug, but there isn't anything significant that I can see. Maybe its just the intro video that is causing problems, but the debug has some codec PNG fixme outputs. Not sure what is up with that. i've tried to install, with no luck.. with 1.7.19 , i get "Sorry, your client resources are incomplete." and if i click verify i get "Verification Interrupted!".. with wine 1.7.10 it works fine but after the book image, the game crashes, with older versions i get buggy text and images and it crashes on the book aswell, i've tried to open directly, or trought arc, i've tried installing on a windows machine and then copy it, but i got allways the same results Thanks for replying TeraJL, I'm glad that I am not the only one with these problems. I get the exact same errors no matter how I launch it. I even checked the Arc support forums and many Windows people are having the same problems. Guess we will be waiting for the next update. Please post your results as you keep testing. I really want to play Swordsman in Linux!!! I actually got to the Blue Book by copying the Swordsman_en folder to a new virtual drive and installing Arc again. But of course, it crashes. By the way, Swordsman isn't even available on Steam... so are you using Arc? I will continue launching Swordsman everday to see if there is an update. I'm thinking about testing Swordsman again. Has anyone had any recent success with newer versions of Wine? I got ARC & SWORDSMAN working in POL Distribution: Slackware 14.1 x86_64, multilib enabled POL : 4.2.5, WINE 1.9.10 (x86) update: WINE 1.9.10-staging (x86) works, CSMT for enhanced video also works, but CSMT eats up more RAM & CPU cycles, up to 30%-40% memory & 50% cpu cycles, it's faster when running single client (xajh.exe), but slower when running multiple instances, all depends on the hardware available (hyperthreading & extra RAM) here are the steps: gecko (to install when prompted in "Configure WINE", or use POL "Install components")mono (to install when prompted in "Configure WINE") Configure WINEWinXP (windows version)VIDEO RAM, set according to GPU hardware POL "Install Components"d3dx9 msvc80 msvc90 msvc100 vcrun2008 vcrun2010 PROBLEMS: - character BAG don't display fonts properly, the quantity of items in a stack is unreadable (update: found the simple fix for unreadable fonts, change game resolution to aspect ratio 16:9) - game may crash during screen loading, maybe 2 out of 5 times, but the game will run properly once loaded - if game turns into a crash loop/stuck/no response, kill SWORDSMAN client (patcher.exe) and click PLAY again in ARC, pause for 1-2 mins before clicking START - some distributions may need libtxc-dxtn (32bit package) also (if you found a solution, please post here, thank you) 2 methods to install SWORDSMAN 1ST METHOD (normal way) install ARC, update install SWORDSMAN via ARC launch SWORDSMAN by clicking PLAY 2ND METHOD (copying old SWORDSMAN folder, then edit registry) install ARC (uncheck all 3 boxes at the end, DO NOT LAUNCH ARC!) if using 32-bit windows or WINE copy old Swordsman_en folder into "Program Files" prepare the following registry file, save as SMO_32BIT_COPY.reg Windows Registry Editor Version 5.00 [HKEY_LOCAL_MACHINE\SOFTWARE\Perfect World Entertainment\Core] [HKEY_LOCAL_MACHINE\SOFTWARE\Perfect World Entertainment\Core\30en] "INSTALL_PATH"="C:\\Program Files\\Swordsman_en\\" "CLIENT_PATH"="C:\\Program Files\\Swordsman_en\\patcher\\patcher.exe" "APP_ABBR"="swm" "installed"=dword:00000001 launch POL Registry Editor import Registry file SMO_32BIT_COPY.reg quit POL Registry Editor Launch POL, run ArcLauncher.exe located in your ARC folder SWORDSMAN will be listed as installed, just click PLAY if using 64-bit windows or WINE copy old Swordsman_en folder into "Program Files (x86)" prepare the following registry file, save as SMO_64BIT_COPY.reg Windows Registry Editor Version 5.00 [HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Perfect World Entertainment\Core] [HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Perfect World Entertainment\Core\30en] "INSTALL_PATH"="C:\\Program Files (x86)\\Swordsman_en\\" "CLIENT_PATH"="C:\\Program Files (x86)\\Swordsman_en\\patcher\\patcher.exe" "APP_ABBR"="swm" "installed"=dword:00000001 launch POL Registry Editor import Registry file SMO_64BIT_COPY.reg quit POL Registry Editor Enjoy! Edited by pokipokipxorn Awesome! Thanks for posting all of your findings. I'll definitely check out Swordsman again and test it on my machine. Do you know if there is a download/installer for Swordsman so you don't have to use ARC? They have one for Neverwinter, Star Trek Online and Champions Online Not that I know of, but once u installed the game via ARC, u can just copy and folder Swordsman_en and edit registry (see 2nd METHOD in post above) I'm looking for the equivalent of hotkeynet in linux, it's a multiboxing app that sends the same keystroke to 3 different game windows simultaneously. Any recommendations? thks I can't even get ARC installed
https://www.playonmac.com/en/topic-12026-NonSteam_game_with_POL.html
CC-MAIN-2020-24
refinedweb
1,446
63.09
eternal navigation using bumper sensor Hi all, today I wanted to make my turtle bot move about the room forever without stopping, when something touches, the front bumper sensor, it goes back a bit, turns and keeps moving forward, if hit from the left, turns right and keeps moving forward. If its hit from the right, turns left and keeps going forward ... I have successfully implemented the direction methods and each works fine independently in the call back, however, after a while I get bad call back error. Below is the call back function logic which listens to bumper events. How should i improve it to get the above described behavior? Thanks. def on_bump_event(self, data): if data.state == BumperEvent.PRESSED: bumped = True else bumped = False if data.bumper == 1: # should go backwards, turn and then go forwards self.move(speed, distance, direction) # direction is either forwards or backwards - a boolean #it never turns/reaches this point self.rotate(angular_velocity, radians, direction) # direction is either clockwise or anticlockwise # turn right x radians, and then keep on going forward till collides again if data.bumper == 2: for(i in range(0, 1): self.rotate(0.2, x, True) # after rotating i get a bad callback, shows that bumper still is 2 then rotates again self.bumpData = 5 if data.bumper == 0: for(i in range(0, 1): self.rotate(0.2, x, True) # after rotating i get a bad callback, shows that bumper still is 0 then rotates again self.bumpData = 5 if self.bumpdata = 5 self.move(speed, 100000, direction) # should just move forever till bumps again - but not happening Then in the initialisation method: def __init__(self): self.bumpData = 5 # initialise rospy.init('node', anonymous=True) rospy.on_shutdown(self.shutdown) #initialise publishers and subscribers ... r = rospy-Rate(20) r.Sleep() while not rospy.is_shutdown(): # just wait for the bumper to be touched. do nothing def shutdown(self): #do shutdown stuff here: if __name__ == '__main__': try: node() rospy.spin() except # get interruption Error UPDATE Got rid of the while loop as suggested in the comment but the problem persists. Also, the turtlebot2 starts with the move forward action, but when interrupted, instead of smoothly moving backwards, it first gives a weird sound, and shakes about, as if trying to both move forward and backwards at the same time. To stop it is it not sufficient to simply set the linear velocity of the robot to zero and then publish the velocity message? Not sure this is the answer, but: don't run infinite while-loops in your constructor (never a good idea). you don't even need to do that, as you have a blocking rospy.spin()in your __main__. oh alright. I will get rid of the while loop then. I also dont think it will solve it too either. I suspect the problem might be a ros logic related one. I'm not super familiar with Python, but is it possible the bumper switch bounces and you end up with multiple threads running different versions of the callback issuing conflicting commands? @billy it is very possible - infact i suspected that too. how can I test/avoid that? I would test it with a print in the callback with a unique identifier (increment a global, print it, run callback, decrement the global) to see if multiple versions are running, but a smarter person than me would google it to see if python inherently prevents this or allows to control the behavior. I tested on a Rasp Pi Zero using a function generator to trigger a python callback and scope to monitor status of callback. Re-triggering event before callback returns doesn't cause re-entrant behavior. No sign of 2 different threads at same time. But it can cause callback to function to behave..... ..... improperly. The callback I used always took > 5 mS (5 - 40ms) to complete when events came in slowly. But if event came in quicker than 40 mS, I could see callback ending in 2 mS on rare occasions. That means it wasn't running the full callback. In one case the program crashed.... ...so I say it's possible that bumper re-triggers could be causing issues, but it's not causing multiple threads to be running concurrently. Adding a debounce time to the trigger fixed it for me. Do you have a debounce time defined? As you back away from wall bumper will retrigger. Prepare for that.
https://answers.ros.org/question/307896/eternal-navigation-using-bumper-sensor/?answer=358879
CC-MAIN-2021-39
refinedweb
743
66.23
Merchant of Venice Test Card Set Information Author: littlepetrie ID: 53001 Filename: Merchant of Venice Test Updated: 2010-12-03 03:47:31 Merchant Venice Shakespeare Bryson Folders: Description: Merchant of Venice Test Review Show Answers: > Flashcards > Print Preview The flashcards below were created by user littlepetrie on FreezingBlue Flashcards . What would you like to do? Get the free Flashcards app for iOS Get the free Flashcards app for Android Learn more What are the 3 "images" that remain of Shakespeare? Chandos Portrait Droeshout Engraving Janssen's Statue at Holy Trinity Church True or False. We don't know exactly how many plays he wrote or in what order he wrote them. True How many words do we have in Shakespeare's hand writing? fourteen words. His name signed 6 times, and the words "by me" on his will. Who was Shakespeare's wife? Anne Hathaway What did Shakespeare leave Anne Hathaway in his will? his second best bed True or False. Shakespeare's sexuality is an unknown mystery True What year was Shakespeare born in? 1564 What day was Shakespeare born? April 23, Saint George's day When was Shakespeare baptized? April 26 On what day did shakespeare die? April 23, 52 years later after his birthday. What calender was Shakespeare born under? What is his "modern day birthdate"? Julian, May 3 How long had Elizabeth been queen when Shakespeare was born? 5 years, would reign for 39 more. What are recusants? Catholics who did not wish to attend Anglican services and paid a fine. What are Church Papist or Cold Statue Protestants? Those who were prepared to support Protestantism so long as it required, but happy or eager to become Catholics again if the circumstances altered How many deaths must be reached for all public performances (besides church going) to be banned in London? 40 What were the two biggest cities in Europe besides London? Paris and Naples What was the life expectancy in London? 35 What city was the largest and busiest place in Europe and headquarters for the English monarch and government? Westminster What stylish new item was making its way into England from France? Starch What are piccadills? increasingly exotic ruffs What is the Royal Exchange? Who built it? One of the world's first shopping malls, Sir Thomas Gresham When was the main meal taken? midday What beverage was drunk copiously? beer Who was Shakespeare's first child? Susanna When was his first child baptized? May of 1583 Who paid a penny or a half penny to see Shakespeare's plays? the groundlings How many people did the Globe theater seat? between 2000-3000 Where did costume changes take place? The Tiring House What is a masque? Entertainment form for high end, dress up in fancy costume and wear mask What were the career levels? Apprentice--> Journeyman--> Master--> Sharer--> Partowner Shakespeare was sharer and partowner of the Globe Who is the eponymous character of Merchant of Venice? Antonio What is a Ghetto? a restricted area in Europe for Jews or other foreigners What is usury? The sin of loaning something and expecting more in return (interest in loans) Sin for Christians and Catholics, but not Jews in medias res to begin in the middle What was the 1290 Edict of Expulsion King Edward I had all Jews expelled from England (Shakespeares audience and himself had no concept of what a Jew was, so they used stereotypes) Where is the first place we see plays broken into acts? Folio What are the rules set up by Portia's father in order to win her hand in marriage? 1) Whoever picks the right casket gets to marry Portia 2) If they choose wrong they must immediately leave and vow to never marry if they are wrong How does Act 1 begin? in medias res Who does Portia hope chooses the wrong casket, because of the color of his skin? Prince of Morroco How much does Bassanio need to borrow in order to impress Portia? 3 thousand ducats What does Shylock hate Antonio? 1) He is a Christian 2) He doesn't charge interest, messes with the rate of usance 3) Antonio hates Jews, and ridicules shylock Where does Shylock work? In the rialto What deal do Antonio and Shylock make? Antonio must pay back the three thousand ducats in three months, Shylock gets to take a pound of his flesh Which casket does the Prince of Morroco choose? gold What does Shylock do before he leaves for the masque? He gives Jessica his keys, and tells her to watch the house and lock the doors. He also tells her to ignore the sounds of the masquerade What does Jessica plan to do? Runaway with Lorenzo and convert, and steal her fathers jewels and riches Which casket does Arragon choose? silver What is inside the gold casket? skull What is inside the silver casket? a blinking idiot What is inside the lead casket? A picture of Portia Who picks the correct casket? Bassanio picks the correct casket (lead) What does Portia give to Bassanio once they are married? a ring that he must never take off Who does Nerissa marry? Gratiano, also gives him a ring What would you like to do? Get the free Flashcards app for iOS Get the free Flashcards app for Android Learn more > Flashcards > Print Preview
https://www.freezingblue.com/flashcards/print_preview.cgi?cardsetID=53001
CC-MAIN-2017-04
refinedweb
894
74.29
Details - Type: Bug - Status: Closed - Priority: Critical - Resolution: Fixed - Affects Version/s: 1.5.7, 1.6-beta-2 - Fix Version/s: 1.6-rc-1, 1.7-beta-1 - Component/s: None - Labels:None Description Run the attached script to see the bug in action. It seems getProperty() and DOMCategory.get() end up in an infinite loop. This is a serious problem for Gant since it means that you basically can't use categories in Gant scripts. Issue Links - relates to GROOVY-3220 CLONE for 1.5.x -StackOverflowError with DOMCategory and missing property - Closed Activity - All - Work Log - History - Activity - Transitions Also affects Subversion Head (aka 1.7-beta-1-SNAPSHOT). Even just this fails, without any property in the gstring: import groovy.xml.dom.DOMCategory use(DOMCategory) { println "foo" } import groovy.xml.dom.DOMCategory use(DOMCategory) { test } was failing too This is fixed in 1.6 and 1.7. But it seems the same fix can't be applied to 1.5 without generating some new test failures. I close this bug as the fix is now in 1.5.8 too Applying this fix breaks the 1.5 build on JDK 1.4. I created GROOVY-3220 as a clone for 1.5.x of this bug. Since it works on 1.7/1.6 it might very well be not really related to the patch, but to a problem uncovered by the patch. Anyway, it may be needed to divert from the path taken for 1.7/1.6 so we should protocol thatin the other issue Merged the changes for GROOVY-3220 into the trunk. Will do for 1.6 if no complaints. Your comment in 3220 didn't sound like a complaint about my change, so I've merged it into 1.6. I just tried the same example with org.codehaus.groovy.runtime.TimeCategory instead and that worked fine, so it looks like a problem with DOMCategory alone.
https://issues.apache.org/jira/browse/GROOVY-3109?focusedCommentId=158666&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel
CC-MAIN-2015-40
refinedweb
326
61.73
This page is a snapshot from the LWG issues list, see the Library Active Issues List for more information and the meaning of NAD status. Section: 15.5.5.5 [member.functions] Status: NAD Submitter: Ville Voutilainen Opened: 2015-11-29 Last modified: 2018-11-13 Priority: 2 View all other issues in [member.functions]. View all issues with NAD status. Discussion: The combination of 15.5.5.5 [member.functions], paragraphs 2 and 3 that LWG 2259 does seems to drop a requirement that any call behaves as if no overloads were added. Paragraph 3 used to say "A call to a member function signature described in the C ++ standard library behaves as if the implementation declares no additional member function signatures." whereas the new wording says "provided that any call to the member function that would select an overload from the set of declarations described in this standard behaves as if that overload were selected."This can be read as meaning that if there's no default constructor specified, like for instance for std::ostream, an implementation is free to add it. It can also be read as meaning that an implementation is free to add any overloads that wouldn't change the overload resolution result of any call expression that would select a specified overload. That's vastly different from allowing extensions that add new functions rather than new overloads. Was this relaxation intentional? [2016-04, Issues Telecon] Ville provides a motivating example. #include <iostream> class my_stream : std::ostream { }; int main() { my_stream ms; } This example is accepted by libstdc++, msvc rejects it, and clang+libc++ segfault on melpon.org/wandbox o_O. An earlier clang+libc++ just accepts it. I don't think the implementation divergence is caused by the acceptance of the referred-to 2259, but it certainly seems to increasingly bless the implementation divergence. [2016-05 Issues Telecon] This is related to issue 2695. [2018-08 Batavia Monday issue discussion] Ville to provide wording. [2018-08 Batavia Monday issue discussion] Ville recommends NAD; because closing this would outlaw conforming extensions. [2018-11 San Diego Thursday night issue processing] Status to NAD Proposed resolution:
https://cplusplus.github.io/LWG/issue2563
CC-MAIN-2019-09
refinedweb
357
54.02
shown in other instead. Run-time Game Launch To launch the game you need to use a little improved system script. That is: - Include a header data/framework/game/game_system.h, which implements the framework system script - Call the Game::init() method in theinit() function - Call the Game::update() method in theupdate() function - Call the Game::shutdown() method in theshutdown() function The example of the Game Framework system script (can be found in the data/framework/game/game_system_script.cpp directory): #include <unigine.h> #include <core/scripts/system/system.h> #include <core/scripts/system/stereo.h> #include <core/scripts/system/wall.h> #include <framework/game/game_system.h> int init() { systemInit(); stereoInit(); wallInit(); Game::init(); return 1; } int shutdown() { systemShutdown(); stereoShutdown(); wallShutdown(); Game::shutdown(); return 1; } int update() { systemUpdate(); stereoUpdate(); Game::update(); return 1; } int render() { stereoRender(); wallRender(); return 1; } To launch the game, specify the [-game file] parameter as a CLI on the engine loading, where file is a name and a path of the game relatively to the data directory. You can also specify the additional parameter, [-game_level index], where index is number of the level to be loaded. If this parameter is not specified, the first level will be loaded. If there is no levels in the game, the game would not be loaded and the corresponding messages will appear in logs. The other way to add game path and game level parameters is to specify them right in the engine configuration file in the following way: <!-- a game path parameter --> <item name="game" type="string">framework/samples/strategy/strategy.game</item> <!-- a start level parameter --> <item name="game_level" type="int">0</item> <!-- a system script path --> <item name="system_script" type="string">framework/game/game_system_script.cpp</item> The system script execution sequence: While framework system script instance initialization, the MasterGame class instance is being created (can be found in thedata/framework/game/master_game.h folder). It controls the framework and the game itself, so it has an information about all the levels, which level is currently running. The level can be loaded or reloaded only through the MasterGame class usage. It is run from the engine initialization till its shutdown. Level Loading and World Script Any .world file has the corresponding .cpp file, where the world script is implemented. Game Framework uses the same .cpp files for each world, containing the only line: #include <framework/game/game_world_script.h> This is enough for the framework to run. The world script execution sequence: Initialization An init() function is used to create a game and initialize all of the necessary resources on the game launch. Initialization starts with all of the game data loading from the XML files to the special class, GameData. After, the standardPlayer class is created in case of the initialization error. Then, theGame class with the specified current loaded world is created. The Game class loads the level logic (if there is any) and the logic of all of the user entities, and put it in the expression with the"EntitiesLogic" namespace. If the user code has the errors and cannot be compiled, the corresponding message will appear in the logs and the game would not be launched. After the user logic is compiled, framework creates the instance of the user class Level, applicable for the current loaded level. If the class could not be created, the corresponding message will appear in the logs and the game would not be launched. The next step is the user code analyzing and checking on the all of the entities properties. All of the user entities are being checked on the presence of the fields. If the fields are found, then the corresponding properties are being checked. If there is any mismatch, the corresponding message will appear in the logs and the game would not be launched. In the end of the Game class initialization, theLevel class is initialized. While the Level class initialization all of the integrated framework systems (a scheduler, the event system, the entity pool) are created. Then framework analyzes all of the level node references and checks if they are entities. If a node reference is an entity, framework creates the user class Entity and assign it a name of the node reference. All of the entities with the assigned names re placed in a special map file, where the entity can be found by a name. If there are two or more entities with the same names, the last entity found during the search will be placed into the map file. At the entity creation, the node of this entity gets the Node::setVariable() function, where variable is an entity instance. Then, while analyzing this node we can assume if this node is an entity or not. After all of the world entities are created, framework sets their fields. In other words, the set() method is called to the each field. The set() method passes the corresponding parameter from the property. Besides, all of the entities are allocated by the update groups: updateable, flushable or renderable entities. Only after that the user entity and Level class onInit() method is called. If the node or entities has been added to the world during the initialization, the engine.world.updateSpatial() function is called. Update, Flush, Render The update() function is the most important in the framework, as the game logic and process are executed in it. The top feature of the framework is providing of the optimal entities update, dynamic and safe update groups exchange, changing of the order or disabling the entities which do not require the update at all. Also framework implements the safe creation and deletion of the entities, puts the deleted entities in the memory pool for them to be used later. It also provides a periodic call of the functions and their automatic time spreading. The framework update() function works in the following way: - The engine calls the world script update() function, which calls the Game classupdate() function. - The Game class calls the currently usedLevel class update() function. The level update is split into several parts: - All the integrated framework systems (a periodic function calls scheduler, profilers etc.) are updated. - The entities, deleted during the last update, are put in the memory pool or completely deleted. - The entities, created during the last update are added into the list.NoticeThe entity will appear in the entity list only at the next update. - The onPreUpdate() function is called for the level. It is required for the user code, implemented before entities update (for example, controls update). - The onUpdate() function is called for all of the updateable entities. - The onPostUpdate() function is called for the level. The render() function is called every time after the update(). Framework calls the render() function for the current Level class, which, in turn, calls theonRender() function for the all renderable entities. Then, theonRender() function is called for the current level. The call of the flush() function is similar to the render(), but takes place in the separate engine thread with the fixed FPS. onUpdate(), onRender() and onFlush() Functions Calls for Entities Each entity has onUpdate(), onRender() andonFlush() virtual functions. These functions calls can be disabled if required for the entity. They can be disabled dynamically by calling thesetUpdateable(), setRendereable(int mode) and setFlushable(int mode) functions or by changing Field values set before. Besides, each entity has the Update Order parameter, which defines the order for entities to be updated. For example, if you need the camera entity to be updated after the character entity, camera entity Update order should be bigger than the character's one. The Update order parameter can be set in the Game Framework editor or dynamically by calling the setUpdateOrder(int order) entity function. It can take up 17 values from0 to 16 inclusive. The default value is 0. It affects the call orders of the onUpdate(), onRender() and onFlush() functions. Callbacks Callbacks or in other words pieces of user code executable by the engine at some convenient time are very important while developing your project. There can be Unigine Widgets callbacks (pressed buttons, unfocused windows), body callbacks (called after collisions), or callbacks caused by Physical or World triggers. While using callbacks you should remember that all of the user's logic is dynamically compiled into the separate expression with its defined namespace (it's name can be returned by calling a Game::getLogicNamespaceName() method). In other words, while setting callback to the engine's object make sure that you have specified namespaces as prefixes to your function. The example of Unigine Widgets usage in the custom Entity class: class MyEntity : Entity { private: WidgetButton button; // button clicked callback void button_clicked() { log.message(“my button clicked\n”); } // button callback redirector void button_callback_redirector( MyEntity entity) { entity.button_clicked(); } public: void onInit() { Gui gui = engine.getGui(); button = new WidgetButton(gui,"Close"); gui.addChild(button,GUI_ALIGN_CENTER); button.setCallback(GUI_CLICKED,game.getLogicNamespaceName() + "::MyEntity::button_callback_redirector",this); } void onShutdown() { // don't forget remove callbacs from widget button.setCallback(GUI_CLICKED,NULL); // or delete widget delete button; } }; At shutdown() you need to unbind all the callbacks from Unigine objects that reference to expressions (at shutdown() the expression along with all user logic is deleted, and if there is a callback binded to the Unigine object, it will reference to the non-existent expression, which may cause an engine crash while calling this callback). Scheduler A scheduler provides the periodic call of a function or group of functions and their automatic time spreading. It can manage the complicated logic, for example, if some operations do not need to be counted every update: the path finding, complicated calculations of the object state or even your C++ plugin call with the database request. The time spreading helps to avoid spikes (the sharp increase of the update time if there are a big amount of objects). The call frequency can vary from 1 to 60 calls per second. The scheduler can call either static or class instance functions. For the function to be called periodically, in a current loaded level call the Level::setPeriodicUpdate(int instance,string function,int frequency,int priority) function. Besides, you can pass up to 4 additional arguments when calling the function periodically. You can safely cancel the function periodic call in any time: in a current loaded level call the Level::removePeriodicUpdate(int instance,string function,int num_args = 0) function. If you want to change the call frequency for your function, call the Level::setPeriodicUpdate(int instance,string function,int frequency,int priority) for this function with the set new frequency. You cannot call the same function with different frequencies. All of the Scheduler functions are divided into groups by the call frequency. When you subscribe to the periodic function update, the function (task), according to its frequency, is automatically moved to the corresponding group. Then the scheduler defines the time for the tick, during which one task is needed to be done. It depends on the number of tasks in the group. For each world update the Scheduler forms the group of tasks that are needed to be performed. If the world update time exceeds the tick time for a group, there will be several tasks from this group in the list. Then the Scheduler sorts the tasks by priority and perform their function calls. Such system provides correct time spreading for complicated tasks and tends to perform tasks with the frequency specified. If the world update time is too big (low FPS), the Scheduler will always perform tasks, but the call frequency for the task will not be guaranteed. If FPS is extremely low, the Scheduler can perform the task more than for one time in one update (in other words, the Scheduler will perform the specified tasks even if there was a hang). The example of calling the "myPeriodicFunction" function of the MyEntity class to be updated 10 times per second, with the 0 priority and one custom int argument: class MyEntity : Entity { public: void onInit() { int my_value = 333; // set periodic update to ”myPeriodicFunction” function with // the frequency 10 times per second, 0 priority and // one custom int argument. level.setPeriodicUpdate(this,”myPeriodicFunction”,10,0,my_value); } void onShutdown() { // remove periodic update level.removePeriodicUpdate(this,”myPeriodicFunction”,0); } void onUpdate() { } void onRender() { } void onFlush() { } void myPeriodicFunction(int some_value) { log.message(“some_value = %i\n”,some_value); } }; If you want the static function, described and compiled in the user code, to be periodically called, do not forget to specify the framework expression namespace in the prefix (you can get its name by calling the Game::getLogicNamespaceName() function in the current game). For example: namespace MyNamespace { void myPeriodicFunction() { log.message(__FUNC__ + “ called\n”); } } class MyEntity : Entity { private: public: void onInit() { level.setPeriodicUpdate(NULL,game.getLogicNamespaceName() + ”::MyNamespace::myPeriodicFunction”,10,0); } void onShutdown() { level.removePeriodicUpdate(NULL,game.getLogicNamespaceName() + ”::MyNamespace::myPeriodicFunction”); } void onUpdate() { } void onRender() { } void onFlush() { } }; Event System The event system is one of the basic parts of every game. It is needed for interaction of game objects or the world with the other objects. Each user class instance can be attached to the event, so when the event occur, the set functions will be called. Framework allows user to create, call, disable or delete events at any time. Besides, specially for entities there is an event call in the specified area. To create the event, in the current level call the Level::createEvent(string name) function, so the system will create an event with this name and you will be able to attach to it. Similarly to the periodic calls scheduler, you can subscribe to the event in the current level by calling the Level::subscribe(string name,int instance,string function) function. You can pass up to 4 user arguments to the function. You can unsubscribe the function by calling the Level::unsubscribe(string name,int instance,string function,int num_args = 0) function. You can call the event for the current level by calling the Level::callEvent(string name) function, so the function will be called to all of the subscribers in the level. There is also a special event call within the specified area. If the subscriber is an Entity class instance, it goes to the special list, for which the call within the specified area is applied. If you call the event by the Level::callEvent(string name,variable p0,variable p1) function, there will be a search depending on thep0 and p1 types through all the nodes (by engine.world.getIntersectionNodes(variable p0, variable p1,int type,int ret_id[]) function). If the node is an entity, the event will be called for it. p0 and p1 parameters types: - vec3 and vec3 — search is performed within the bounding box. Variables set the points of the bounding box minimum and maximum (by x, y, and z axes). - vec3 and float — search is performed within the bounding sphere. Variables set the sphere center and its radius. - mat4 and mat4 — search is performed within the view frustum. Variables set projection and modelview matrices. To enable or disable the event, call the Level::setEventEnabled(string name,int mode) function. You can check if the function is enabled by calling the Level::isEventEnabled(string name) function. You can check if the even exists by calling the Level::isEvent(string name) function. Dynamical Entity Creation And Deletion By means of framework you can dynamically create or delete entities. To delete the entity, in the current level call the Level::removeEntity(Entity entity,int mode = 0) function. There are 3 ways modes of the entity deletion: - REMOVE_ENTITY_MODE_DEFAULT - delete the instance of the user entity - REMOVE_ENTITY_MODE_DELETE_NODE - delete the entity and the node reference connected with it - REMOVE_ENTITY_MODE_POOL - put the entity and its node reference into the memory pool. This way is much easier when creating a new entity, as it is already in the pool. Regardless of the entity deletion mode, the onShutdown() method will be called for it. You should clear your resources, unsubscribe from events and cancel the periodic function call in it. In order to dynamically create a new entity, in the current level call the Level::createEntity(string type,string name = “”) function. The first step on the entity creation is to check the pool on the such entity type and if it exists, take it from there. If it does not exist, the new entity instance and node reference will be created and correspondence between them will be set. After that, all of the fields will be set to the entity. Lastly, theonInit() function will be called for a new entity. There is another feature of the framework: the entity can safely delete itself in any time if the Level::removeEntity(Entity entity,int mode = 0) function is called and the entity itself (entity = this) is passed as an argument. Entities Interaction Besides the event system, there are other ways of entities interaction. As user logic is written in the one expression, you can call the methods of one entity to another. For it you need to find the target entity: - Find an entity by name. Call the Level::getEntity(variable index) function for it. If the entity with this name exists, the entity will be returned; otherwise, NULL will be returned. - Define an entity from the node (the fastest way). You can find a node by calling the engine.world.getIntersectionObjects() function or through the body callbacks. If this node is a root for node reference, connected to the entity, the instance of the required entity can be found through theNode::getVariable(). - Find an entity by index. Call the Level::getEntity(int index) . You can get the amount of entities by calling the Level::getNumEntities() function. - Collect all of the entities. Call the Level::getEntities(Entity ret[],string type = ””,int childs = true) function. When the entity is found, its methods could be called for other entities. Passing Parameters Through Levels As the game logic is located in the world script and is reloaded every time the level is reloaded, common parameter for different levels cannot be hold in the world script. There is an opportunity in Game Framework to hold any user data in the system script and use it on different levels. For example, you can use the results of the game progress or character state in the next level. There are two functions of the current class instance to set or get the parameter: Game::setGameParameter(string name,variable value) andGame::getGameParameter(string name). Furthermore, you can save the parameters values into the file after the end of the game. For it, in the system script after the game initialization (the Game::init(); line), add the required parameters by Game::setGameParameter(string name) function, and after the game is ended (before theGame::shutdown()) get the parameters into a file by calling the Game::getGameParameter(string name) function.
https://developer.unigine.com/en/docs/2.4/code/uniginescript/scripts/game_framework/runtime?rlang=cpp
CC-MAIN-2019-35
refinedweb
3,131
54.42
View Complete Post Downloaded the latest Ribbon Control Library from microsoft. Created a new WPF Ribbon Application, and create a few simple buttons and tabs. Problem: When I navigate away from my Ribbon Window to another app (ie browser), when I come back the the Ribbon Application the Ribbon will sometimes be frozen. I cannot click any buttons or switch tabs, only the application menu is still active. I can fix it my maximizing the window oddly. Is this a know problem? How do I fix it? I can provide a small sample app if needed. Please check into this Microsoft :). Thanks, Kevin <ribbon:RibbonWindow x:Class="Main" xmlns="" xmlns:x="" xmlns:ribbon="clr-namespace:Microsoft.Windows.Controls.Ribbon;assembly=RibbonControlsLibrary" Title="Main" x: <Grid x: <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="*"/> </Grid.RowDefini I've done a fair amount of looking, but I have not found what I am looking for. I would like a ribbon control that I drag from the ribbon to a canvas below. In addition, I would like a combobox resting just below the control that allows me to change the content available for drag. Is there a control out there that does this or should I build my own? If I build my own, how should i go about doing this?? When I use the SPCalendarView control in a custom visual webpart, the navigation for expand all, collapse all, Day, Week, and Month, all show up in the calendar control itself, like SP2007 without the ribbon. Is there a way to change this behavior to make it assume these will be in the ribbon and not show up in the control. Right now I am just hiding them via css. When you look at the OOTB calendar view used in a library, it puts this stuff in the ribbon in SP2010. Here is data binding expression (dropdown list is nested in gridview) <asp:DropDownList Code Behind has function which looks like public int GetSelectedIndex(DropDownList ddl) { //loop through the item in the dropdownlist //return index based on xyz checks } The whole reason for passing the reference is to save round trip to database and not to use SESSION i am in stress how to start this what should be the first step i want to create custom application page with a ribbon and some user control web part to show document item properties. Please help me regarding this thanks in advance Regards WasiKhan Fritz Onion demonstrates how the ListView control in ASP.NET 3.5 makes data-binding tasks easier with support for styling with CSS, flexible pagination, and a full complement of sorting, inserting, deleting, and updating features. Fritz Onion MSDN Magazine March 2008 If you want to create your own professional looking tabs and controls in Office, check out the RibbonX API of the 2007 Microsoft Office system. Eric Faller Dino Esposito MSDN Magazine April 2001
http://www.dotnetspark.com/links/14221-wpf-ribbon-control-binding-to-vm-ribbon.aspx
CC-MAIN-2017-13
refinedweb
485
61.87
Introduction to Joins in Pandas “I have two different tables in Python but I’m not sure how to join them. What criteria should I consider? What are the different ways I can join these tables?” Sound familiar? I have come across this question plenty of times on online discussion forums. Working with one table is fairly straightforward but things become challenging when we have data spread across two or more tables. This is where the concept of Joins comes in. I cannot emphasize the number of times I have used these Joins in Pandas! They’ve come in especially handy during data science hackathons when I needed to quickly join multiple tables. We will learn about different types of Joins in Pandas here: - Inner Join in Pandas - Full Join in Pandas - Left Join in Pandas - Right Join in Pandas We will also discuss how to handle redundancy or duplicate values using joins in Pandas. Let’s begin! Note: If you’re new to the world of Pandas and Python, I recommend taking the below free courses: Looking to learn SQL joins? We have you covered! Head over here to learn all about SQL joins. Understanding the Problem Statement I’m sure you’re quite familiar with e-commerce sites like Amazon and Flipkart these days. We are bombarded by their advertisements when we’re visiting non-related websites – that’s the power of targeted marketing! We’ll take a simple problem from a related marketing brand here. We are given two tables – one which contains data about products and the other that has customer-level information. We will use these tables to understand how the different types of joins work using Pandas. Inner Join in Pandas Inner join is the most common type of join you’ll be working with. It returns a dataframe with only those rows that have common characteristics. An inner join requires each row in the two joined dataframes to have matching column values. This is similar to the intersection of two sets. Let’s start by importing the Pandas library: import pandas as pd For this tutorial, we have two dataframes – product and customer. The product dataframe contains product details like Product_ID, Product_name, Category, Price, and Seller_City. The customer dataframe contains details like id, name, age, Product_ID, Purchased_Product, and City. Our task is to use our joining skills and generate meaningful information from the data. I encourage you to follow along with the code we’ll cover in this tutorial. product=pd.DataFrame({ 'Product_ID':[101,102,103,104,105,106,107], 'Product_name':['Watch','Bag','Shoes','Smartphone','Books','Oil','Laptop'], 'Category':['Fashion','Fashion','Fashion','Electronics','Study','Grocery','Electronics'], 'Price':[299.0,1350.50,2999.0,14999.0,145.0,110.0,79999.0], 'Seller_City':['Delhi','Mumbai','Chennai','Kolkata','Delhi','Chennai','Bengalore'] }) customer=pd.DataFrame({ 'id':[1,2,3,4,5,6,7,8,9], 'name':['Olivia','Aditya','Cory','Isabell','Dominic','Tyler','Samuel','Daniel','Jeremy'], 'age':[20,25,15,10,30,65,35,18,23], 'Product_ID':[101,0,106,0,103,104,0,0,107], 'Purchased_Product':['Watch','NA','Oil','NA','Shoes','Smartphone','NA','NA','Laptop'], 'City':['Mumbai','Delhi','Bangalore','Chennai','Chennai','Delhi','Kolkata','Delhi','Mumbai'] }) Let’s say we want to know about all the products sold online and who purchased them. We can get this easily using an inner join. The merge() function in Pandas is our friend here. By default, the merge function performs an inner join. It takes both the dataframes as arguments and the name of the column on which the join has to be performed: pd.merge(product,customer,on='Product_ID') Here, I have performed inner join on the product and customer dataframes on the ‘Product_ID’ column. But, what if the column names are different in the two dataframes? Then, we have to explicitly mention both the column names. ‘left_on’ and ‘right_on’ are two arguments through which we can achieve this. ‘left_on’ is the name of the key in the left dataframe and ‘right_on’ in the right dataframe: pd.merge(product,customer,left_on='Product_name',right_on='Purchased_Product') Let’s try the above code in the live coding window below!! Let’s take things up a notch. The leadership team now wants more details about the products sold. They want to know about all the products sold by the seller to the same city i.e., seller and customer both belong to the same city. In this case, we have to perform an inner join on both Product_ID and Seller_City of product and Product_ID and City columns of the customer dataframe. So, how we can do this? Don’t scratch your head! Just pass an array of column names to the left_on and right_on arguments: pd.merge(product,customer,how='inner',left_on=['Product_ID','Seller_City'],right_on=['Product_ID','City']) Full Join in Pandas Here’s another interesting task for you. We have to combine both dataframes so that we can find all the products that are not sold and all the customers who didn’t purchase anything from us. We can use Full Join for this purpose. Full Join, also known as Full Outer Join, returns all those records which either have a match in the left or right dataframe. When rows in both the dataframes do not match, the resulting dataframe will have NaN for every column of the dataframe that lacks a matching row. We can perform Full join by just passing the how argument as ‘outer’ to the merge() function: pd.merge(product,customer,on='Product_ID',how='outer') Did you notice what happened here? All the non-matching rows of both the dataframes have NaN values for the columns of other dataframes. But wait – we still don’t know which row belongs to which dataframe. For this, Pandas provides us with a fantastic solution. We just have to mention the indicator argument as True in the function, and a new column of name _merge will be created in the resulting dataframe: pd.merge(product,customer,on='Product_ID',how='outer',indicator=True) As you can see, the _merge column mentions which row belongs to which dataframe. Left Join in Pandas Now, let’s say the leadership team wants information about only those customers who bought something from us. You guessed it – we can use the concept of Left Join here. Left join, also known as Left Outer Join, returns a dataframe containing all the rows of the left dataframe. All the non-matching rows of the left dataframe contain NaN for the columns in the right dataframe. It is simply an inner join plus all the non-matching rows of the left dataframe filled with NaN for columns of the right dataframe. Performing a left join is actually quite similar to a full join. Just change the how argument to ‘left’: pd.merge(product,customer,on='Product_ID',how='left') Here, you can clearly see that all the unsold products contain NaN for the columns belonging to the customer dataframe. Right Join in Pandas Similarly, if we want to create a table of customers including the information about the products they bought, we can use the right join. Right join, also known as Right Outer Join, is similar to the Left Outer Join. The only difference is that all the rows of the right dataframe are taken as it is and only those of the left dataframe that are common in both. Similar to other joins, we can perform a right join by changing the how argument to ‘right’: pd.merge(product,customer,on='Product_ID',how='right') Take a look carefully at the above dataframe – we have NaN values for columns of the product dataframe. Pretty straightforward, right? Handling Redundancy/Duplicates in Joins Duplicate values can be tricky obstacles. They can cause problems while performing joins. These values won’t give an error but will simply create redundancy in our resulting dataframe. I’m sure you can imagine how harmful that can be! Here, we have a dataframe product_dup with duplicate details about products: product_dup=pd.DataFrame({ 'Product_ID':[101,102,103,104,105,106,107,103,107], 'Product_name':['Watch','Bag','Shoes','Smartphone','Books','Oil','Laptop','Shoes','Laptop', 'Category':['Fashion','Fashion','Fashion','Electronics','Study','Grocery','Electronics','Fashion','Electronics'], 'Price':[299.0,1350.50,2999.0,14999.0,145.0,110.0,79999.0,2999.0,79999.0], 'Seller_City':['Delhi','Mumbai','Chennai','Kolkata','Delhi','Chennai','Bengalore','Chennai','Bengalore'] }) Let’s see what happens if we perform an inner join on this dataframe: pd.merge(product_dup,customer,how='inner',on='Product_ID') As you can see, we have duplicate rows in the resulting dataset as well. To solve this, there is a validate argument in the merge() function, which we can set to ‘one_to_one’, ‘one_to_many’, ‘many_to_one’, and ‘many_to_many’. This ensures that there exists only a particular mapping across both the dataframes. If the mapping condition is not satisfied, then it throws a MergeError. To solve this, we can delete duplicates before applying join: pd.merge(product_dup.drop_duplicates(),customer,how='inner',on='Product_ID') But, if you want to keep these duplicates, then you can give validate values as per your requirements and it will not throw an error: pd.merge(product_dup,customer,how='inner',on='Product_ID',validate='many_to_many') Now, you can say: What’s Next? There is also a concat() function in Pandas that we can use for joining two dataframes. I encourage you to explore that and apply it in your next project alongside what you’ve learned about joins in this tutorial. If you have any queries or feedback on this article, feel free to share it in the comments section below. I have listed some insightful and comprehensive articles and courses related to data science and Python below. Courses: - Python for Data Science - Pandas for Data Analysis in Python - Data Science Hacks, Tips and Tricks - Introduction to Data Science - A comprehensive Learning path to become a data scientist in 2020 Tutorials: 3 Comments Thanks! This was a helpful and clear explanation. I’m glad that you liked my work. Very nicely explained!
https://www.analyticsvidhya.com/blog/2020/02/joins-in-pandas-master-the-different-types-of-joins-in-python/
CC-MAIN-2020-45
refinedweb
1,666
56.55
From: Robert Ramey (ramey_at_[hidden]) Date: 2008-07-17 12:55:57 vicente.botet wrote: >>> However, >>> I would probably consider this a user error in that it violates >>> the intention of name spaces to avoid just this problem. > > Hi, > > Is there a way the user can write their code to avoid this possible > ambiguity? > Is there a way the developper can add a new interface avoiding this > possible ambiguity on the user code? > How the C++ standard library does to avoid this kind of ambiguity in > user code? This is easy, just don't put any of your own stuff into the the namespace that the library uses. > Does this banish the use of using in user code if he/she wants to > avoid incompatibilities with newer releases? If you never put any of your own stuff in to the boost:: or std:: namespaces, you shouldn't have this problem. If you use "using <namespace>" you could still have aproblem if one of your names accidently matches something this the namespace being used. For this reason, I don't particularly like using "using <namespace>" myself but rather just spell out the whole thing like boost::filesystem:: ... Robert Ramey > > Vicente > > > _______________________________________________ > Unsubscribe & other changes: > 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/2008/07/139980.php
CC-MAIN-2019-39
refinedweb
225
64.81
GORM Use size instead of length. Domain property constraints: do not use length, but size. If you use length, you won't be warned at all, but it won't work either. And a book (and a very good one!) by Graeme, the "The Definitive Guide to GRAILS", still uses the "length" in all examples. So, stay warned. Use right type parent reference when defining one-to-many relationship When defining a one-to-many relationship, in the child object you have to define a declare it by static belongsTo = Parent, but also you need to define a property that references the parent. Now, this property, has to be of the Parent type. As obvious, as it seems to be, I have spent another couple hours to figure out, why the dynamic views were not reflecting one side of the relationship. Again, there is no warning. It's up to you, so stay alert. The View GSP values declared via a tag are strings Quiz: what does this do? <g:def <% for (i in 0..loop) { println i } %> Answer: "9" is a string and the range 0..loop casts "9" to 57. Resolution: use "${9}" Controllers Getter methods are called when controller is created A controller getter method like the following: def getFoo() { ... } will be called when the controller is created. This is done, in part, to determine which of the controller's properties are Closures since those are the actions the controller can respond to. Several issues can arise. For example, if getFoo() is a resource-intensive method call, this will add to the request processing time anytime getFoo()'s controller is created. Also, exceptions might be thrown if getFoo() references dynamic properties, like servletContext, that are not yet injected into the controller. Unit testing Don't call dynamic methods from controller or unit test First, if you try to call dynamic methods (in controller you have: def scaffold = Book), from your unit tests, you'll get an ugly message, that doesn't help you understand what's the problem. The thing is, you need to switch to static scaffolding in order to be able to call controller methods from unit tests. Hidden <app_base>/target folder. Grails and the Server Auto-Reloading after changes In general, Grails tries to perform (I think, in cooperation with the web app. server) auto-reloading if you perform changes to the application while the application is running. However, if you did some domain modifications and see an error message about Hibernate exception, don't think long: you need to restart the Grails application. And in some cases, you may need to drop the DB tables, if you happen to be using persistent mode of the DB. Location of Log4j.properties File When Grails application is deployed to Tomcat, the files log4j.*properties in the grails-all/conf folder are ignored. Only the file in WEB-INF/classes (or whatever is specified in the web.xml) is actually used to configure the log4j logging. Apr 30, 2008 Pam Callaway says:Also on GORM - circular references can cause an error in Grails 1.0.2... http:/... Also on GORM - circular references can cause an error in Grails 1.0.2...
http://docs.codehaus.org/display/GRAILS/Gotchas
crawl-002
refinedweb
535
65.42
Shutdown and Draining Most SDKs use a background queue to send out events. Because the queue sends asynchronously in the background it means that some events might be lost if the application shuts down unexpectedly. To prevent this all SDKs provide mechanisms to cope with this. Typically SDKs provide two ways to shut down: a controlled shutdown where the system will wait up to about two seconds to flush out events (configurable) and an uncontrolled shutdown (also referred to as “killing” the client). The .NET SDK automatically shuts down and waits ShutdownTimeout seconds before that happens when the Init’s return value is disposed: using (SentrySdk.Init(...)) { // App code } In case of an unhandled exception that will crash the app, the SDK automatically disposes itself. The client provides a Flush method that takes the time in time.Duration for how long it waits and will return a boolean that indicates whether everything was flushed or the timeout kicked in. sentry.CaptureMessage("my message") if sentry.Flush(time.Second * 2) { fmt.Println("All queued events delivered!") } else { fmt.Println("Flush timeout reached") } The client provides a close method that optionally takes the time in milliseconds for how long it waits and will return a promise that resolves when everything was flushed or the timeout kicked in. const client = Sentry.getCurrentHub().getClient(); if (client) { client.close(2000).then(function() { process.exit(); }); } The Python SDK automatically drains on shutdown unless the AtExitIntegration is removed or the shutdown_timeout config key is set to 0. To manually drain the client provides a close method: from sentry_sdk import Hub client = Hub.current.client if client is not None: client.close(timeout=2.0) When the Rust SDK initializes a guard is returned from the init function. The destructor will automatically wait shutdown_timeout seconds. This means you just need to hold on to the guard and make sure it disposes on shutdown. Alternatively the client can be closed: use std::time::Duration; use sentry::Hub; if let Some(client) = Hub.current().client() { client.close(Some(Duration::from_secs(2))); } After shutdown the client cannot be used any more so make sure to only do that right before you shut down the application.
https://docs.sentry.io/error-reporting/configuration/draining/?platform=node
CC-MAIN-2019-39
refinedweb
364
56.35
Copyright © 1999 W3C (MIT, INRIA, Keio), All Rights Reserved. W3C liability, trademark, document use and software licensing rules apply.. This is a public W3C Working Draft on requirements for the next generation of web forms. It is intended for review by W3C members and other interested parties. The document provides an overview of the requirements currently under discussion within the Forms Subgroup of the HTML Working Group. This working draft may be updated, replaced or rendered obsolete by other W3C documents at any time. It is inappropriate to use W3C Working Drafts as reference material or to cite them as other than "work in progress". A list of current public W3C working drafts can be found at. This document is work in progress and does not imply endorsement by the W3C membership or the HTML Working Group (members only). This document has been produced as part of the W3C HTML Activity. The goals of the HTML Working Group are discussed in the HTML Working Group charter (members only).. The Web is experiencing a rapid growth in the variety of devices and applications. To meet this challenge, form fields should not be bound to a particular realisation as a control. Instead the field should state the nature of the task the user is being asked to perform. The "purpose" of a form control may be the same on various devices, whereas the rendering may vary based on different capabilities. Example: In previous versions of HTML, different markup was used for fields realised as radio buttons or as pull-down lists. Both permit the user to choose a single item from a group. On a Voice browser, there is no obvious difference between the two. Forms need to be expressed as a well-formed XML.. Note: An exception to this requirement may be a lightweight, spreadsheet-like expression syntax e.g. for simple field calculations. In today's Web forms, a substantial part of the form is often defined in ECMAScript although it would potentially be possible to define it entirely in markup. This forces user agents to understand ECMAScript in order to process rich web forms. The need for a broadly applicable way for expressing the navigation paths within a form without implying specific user interface devices such as a mouse or standard keyboard. The navigation should be made explicit for each form control by clearly marking its relative ordering with respect to other controls, devices. The next generation of Web forms should be fit for usage with non-western character sets, languages, and writing systems. The requirement that non-western characters are preserved from their initial entry in a form field until their final destination and vice versa. Note: Unicode is a key part of the solution, but is not yet widely supported by Web servers. It may be appropriate for forms to express the character repertoire accepted by a server. Character entities and ASCII transliterations may also play an interim role. This area is still under discussion. The need to enable multi-national entry of data formats for common types like dates, currency, zip codes and phone numbers. Requirement 2.3.3 "Data Formats and input validation" addresses the need for constraining the data being entered into a field. These field constraints shall not force international users to adapt to western data formats if the corresponding data format is substantially different in other regions. Postal addresses, dates, currency values and phone numbers vary in their details from one country to another. Forms designed for international access should to be able validate such fields taking the user's locale into account. The labels, sizes and input constraints for subfields need to adapt to the locale. For instance, a subfield for the postal code should ask for a "Zip code" in the US and for a "Post code" in the UK. Note: If order forms are designed for the United States, then users in other countries may be unable to enter their postal codes in the field provided. US Zip codes are restricted to digits whereas postal codes in the United Kingdom are composed from letters and digits. If the Zip code field is required, a UK customer won't be able to complete the order form. US addresses also always include a "city", but this isn't true for other countries, leading to puzzlement when filling out the form. It should be possible to access and manipulate forms via the XML Document Object Model. This is needed to allow the construction of specialized forms with behaviors going beyond the limits of the forms language itself. XHTML forms need to be accessible as part of XHTML documents. It should be possible to perform client-side calculations based on entries in form fields. A frequent need is the ability to compute a value on-the-fly according to a mathematical expression involving the previous field entries (e.g. the total sum in an order form). There needs to be a simple syntax for expressing field calculations, that can be easily parsed and processed by a wide variety of user agents. The forms language should include a set of common data types as well as a mechanism for authors to specify custom data types. There is the need for an author to be able to express the ways in which the user agent should behave when the user conflicts with the restrictions defined by a data type. A means should be provided for expressing dependencies between fields or fieldsets. It should be possible to constrain a field so that it can only receive the focus if another field has been filled out. Additionally, a similar mechanism is needed for defining when two or more form fields are bound to the same data value, so that if the value in one field is updated, then the related form fields also take that value. For fields that support multiple entries, such as an order list, it should be possible for the form control to dynamically adjust to permit the entry of further entries. It should be possible to specify the initial and maximum number of entries. Example: This is important for applications such as order lists, where each product ordered needs the user to enter the quantity, product code etc. In this scenario, it should be possible to order as many different products as desired. Once the last slot is filled out, another one is created and presented to the user. It should be possible for forms to extend across several Web pages. This requirement permits the form to be treated as a single unit or as several parts. The form's logic should apply regardless of how it is split up. A large form may be viewable as a single Web page on a desktop computer, but on a palm sized device, it may need to be presented as a sequence of smaller pages. The scheme used by form logic to address form fields should be insensitive to transformations of the XHTML document it belongs to, rather than being tied to the specific representation in XML. A forms oriented addressing scheme would be based on the logical model of forms and be designed to simplify scripting. Since the current interaction model between the browser and the server is rather limited, improvements are needed in the submit model for forms, providing for more advanced methods for exchanging data between the user agent and a remote entity such as the Web server. It should be possible for data to be inserted into a form and submitted back to a server in richer ways than flat name/value pairs. Note: The Working Group suggested allowing the use of arbitrary XML namespaces for form data, which would also make it easy to sign the forms. It should be possible to perform secure, protocol-independent form transactions as well as to be able sign a form and to work with signed forms. There should be a way to control access to a form or to sections of a form based upon user authentication. Note: The forms subgroup is exploring what is needed for a form to become a legaly binding entity, and what constraints this requirement has on the design of the new forms model. Coordination is needed with the XML-Digital Signature Working Group.. There needs to be a generalized way of preserving the changes the user has made to a form. This will make it possible for a user to save the form, and at a later time, to resume filling it out. The ability to treat forms as persistent objects encapsulating state and behavior is needed for workflow applications where forms are passed from one user to another. Note: This might lead to a new submit method "save", where the entire form together with the modifications made by the user is submitted back to the server. Apart from other benefits, this could be a simple mechanism of editing and updating XHTML documents over the web within user agents. It should be possible to layout forms using HTML tables. It should be possible to style forms using style languages such as CSS and XSL. Forms should be usable in combination with emerging standards for vector graphics and dynamic effects based upon SVG and SMIL. In general, XHTML Extended Forms should use the presentation and layout mechanisms available to XHTML, instead of defining seperate layout mechanisms designed specifically for forms. Graphical user interfaces have evolved rapidly in the last few years, but the Web has been slow to respond. The variety of forms controls should be increased to match the expectations of designers, and to provide richer functionality for data acquisition. Designers should be given greater control over the visual appearance of form controls. Example: Some possible ideas for new controls include: expandable and collapsable tree controls, list-sort controls, editable combobox controls, sliders and rotary controls. Designers would value the ability to customize controls, e.g. using images. There should be a way to define new form controls (perhaps using other markup languages such as SVG) offering a custom look and feel but integrated into the forms model so that they internally behave and react like a standard form control. This requirements document was written with the participation of the members of the Forms Subgroup of the W3C HTML Working Group (listed in alphabetical order):
http://www.w3.org/TR/1999/WD-xhtml-forms-req-19990830
CC-MAIN-2015-22
refinedweb
1,728
60.24
Your application is sent across a network to a user where it runs as JavaScript inside their web browser. Everything that happens within the user's web browser is referred to as client-side processing. When you write client-side code that is intended to run in the web browser, remember that it ultimately becomes JavaScript. Thus, it is important to use only libraries and Java language constructs that can be translated into JavaScript. To begin writing a GWT module, subclass the EntryPoint class. Tip: GWT applicationCreator creates a starter application for you with a sample EntryPoint subclass defined. package com.example.foo.client; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.core.client.GWT; /** * Entry point classes define onModuleLoad(). */ public class Foo implements EntryPoint { /** * This is the entry point method. Initialize you GWT module here. */ public void onModuleLoad() { // Writes Hello World to the module log window. GWT.log("Hello World!", null); } } The entry point method is onModuleLoad(). It contains the code that executes when you launch the application. Typically, the types of things you do in the onModuleLoad() method are: The example above logs a message to the development mode console. If you try to run this example application in production mode, you won't see anything because the GWT.log() method is compiled away when the client-side code is translated into JavaScript. Included with the GWT distribution is a sample "Hello World" program that looks like this when run in development mode: package com.google.gwt.sample.hello; import com.google.gwt.user.client.ui.Widget; /** * Hello World application. */ public class Hello implements EntryPoint { public void onModuleLoad() { Button b = new Button("Click me", new ClickHandler() { public void onClick(ClickEvent event) { Window.alert("Hello, AJAX"); } }); RootPanel.get().add(b); } } In the entry point method for the Hello World application, the following actions were taken:
http://www.gquery.org/doc/latest/DevGuideCodingBasicsClient.html
CC-MAIN-2018-09
refinedweb
309
51.04
Created on 2013-11-24 01:38 by tim.peters, last changed 2014-03-17 06:30 by python-dev. This issue is now closed. With the current default branch, test_venv fails every time for me: [1/1] test_venvjltqdgi8\pip-1.5.rc1-py2.py3-none-any.whl\pip\__init__.py", line 10 , in <module> File "C:\Users\Tim\AppData\Local\Temp\tmpjltqdgi8\pip-1.5.rc1-py2.py3-none-any.whl\pip\util.py", line 17, in <module> File "C:\Users\Tim\AppData\Local\Temp\tmpjltqdgi8\pip-1.5.rc1-py2.py3-none-any.whl\pip\_vendor\distlib\versi on.py", line 14, in <module> File "C:\Users\Tim\AppData\Local\Temp\tmpjltqdgi8\pip-1.5.rc1-py2.py3-none-any.whl\pip\_vendor\distlib\compat.py", line 66, in <module> ImportError: cannot import name 'HTTPSHandler' test test_venv failed -- Traceback (most recent call last): File "C:\Code\Python\lib\test\test_venv.py", line 288, in test_with_pip self.run_with_capture(venv.create, self.env_dir, with_pip=True) File "C:\Code\Python\lib\test\test_venv.py", line 48, in run_with_capture func(*args, **kwargs) File "C:\Code\Python\lib\venv\__init__.py", line 359, in create builder.create(env_dir) File "C:\Code\Python\lib\venv\__init__.py", line 86, in create self._setup_pip(context) File "C:\Code\Python\lib\venv\__init__.py", line 242, in _setup_pip subprocess.check_output(cmd) File "C:\Code\Python\lib\subprocess.py", line 618, in check_output raise CalledProcessError(retcode, process.args, output=output) subprocess.CalledProcessError: Command '['C:\\Users\\Tim\\AppData\\Local\\Temp\\tmpt0ca1aqn\\Scripts\\python_d .exe', '-Im', 'ensurepip', '--upgrade', '--default-pip']' returned non-zero exit status 1 1 test failed: test_venv All virtual Greek to me. Interesting - this isn't *quite* a duplicate of the buildbot failures in issue 19734 (at least, I don't think it is - the extra diagnostics I just checked in should tell us for sure). Since pip isn't useful without HTTPS, we may want to add a check for ssl support to either venv or ensurepip itself. Ah, I didn't even notice the "S" in "HTTPS"! I'm not building the SSL cruft on my box, so it's not surprising that anything requiring it would fail. It is surprising that this is the only test that _does_ fail without it ;-) FYI, here's the new output: [1/1] test_venv test test_venv failed -- Traceback (most recent call last): File "C:\Code\Python\lib\test\test_venv.py", line 289, in test_with_pip self.run_with_capture(venv.create, self.env_dir, with_pip=True) subprocess.CalledProcessError: Command '['C:\\Users\\Tim\\AppData\\Local\\Temp\\tmptw2_vda6\\Scripts\\python_d .exe', '-Im', 'ensurepip', '--upgrade', '--default-pip']' returned non-zero exit status 1 During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Code\Python\lib\test\test_venv.py", line 295, in test_with_pip self.fail(msg) AssertionError: Command '['C:\\Users\\Tim\\AppData\\Local\\Temp\\tmptw2_vda6\\Scripts\\python_d.exe', '-Im', 'ensurepip', '--upgrade', '--default-pip']' returned non-zero exit status 1 **Subprocess Output**dkfwi7it\pip-1.5.rc1-py2.py3-none-any.whl\pip\__init__.py", line 10 , in <module> File "C:\Users\Tim\AppData\Local\Temp\tmpdkfwi7it\pip-1.5.rc1-py2.py3-none-any.whl\pip\util.py", line 17, in <module> File "C:\Users\Tim\AppData\Local\Temp\tmpdkfwi7it\pip-1.5.rc1-py2.py3-none-any.whl\pip\_vendor\distlib\version.py", line 14, in <module> File "C:\Users\Tim\AppData\Local\Temp\tmpdkfwi7it\pip-1.5.rc1-py2.py3-none-any.whl\pip\_vendor\distlib\compat.py", line 66, in <module> ImportError: cannot import name 'HTTPSHandler' 1 test failed: test_venv New changeset 9891ba920f3c by Nick Coghlan in branch 'default': Issue #19744 (temp workaround): without ssl, skip pip test Temporarily skipped the test to appease the build bots for the beta release, but this should be changed so that ensurepip refuses to bootstrap pip if SSL/TLS support is not available. test_venv would then be updated to check for the appropriate behaviour (e.g. by inserting a dummy ssl.py that just raises import error into the venv) Also noting that the reason for the dummy ssl in the venv would be to provoke the "SSL/TLS not available" behaviour when running the tests in a Python that actually has those pieces (since the buildbots will have them available unless something goes wrong with the build) There's a ticket in pip to make pip work even when ssl isn't available. You wouldn't be able to install from PyPI but you would be able to install from local archives. Is that likely to be in 1.5 or 1.5.1? Not needing to special case this in ensurepip would be nice :) I've stumbled upon what appears to be a related issue, but I'm not sure it deserves its own bug report. I compiled 3.4 on my LMDE (so essentially Debian testing) system, and aside from not building tkinter, various compression modules, etc., all went well. I ran `make test` with no errors, including the success of test_venv. (There were many and various warnings about deprecated code and calling str() on bytes instances, but I'm pretty sure none of it is related). I ran `sudo make altinstall` (to not nuke my current 3.3 from the repos), and to my surprise, it failed with the following error: running install_scripts copying build/scripts-3.4/pydoc3.4 -> /usr/local/bin copying build/scripts-3.4/2to3-3.4 -> /usr/local/bin copying build/scripts-3.4/idle3.4 -> /usr/local/bin copying build/scripts-3.4/pyvenv-3.4 -> /usr/local/bin changing mode of /usr/local/bin/pydoc3.4 to 755 changing mode of /usr/local/bin/2to3-3.4 to 755 changing mode of /usr/local/bin/idle3 Traceback (most recent call last): File "/home/bill/py3.4/Python-3.4.0b1/Lib/runpy.py", line 160, in _run_module_as_main "__main__", fname, loader, pkg_name) File "/home/bill/py3.4/Python-3.4.0b1/Lib/runpy.py", line 73, in _run_code exec(code, run_globals) File "/home/bill/py3.4/Python-3.4.0b1/Lib/ensurepip/__main__.py", line 66, in <module> main() File "/home/bill/py3.4/Python-3.4.0b1/Lib/ensurepip/__main__.py", line 61, in main default_pip=args.default_pip, File "/home/bill/py3.4/Python-3.4.0b1/Lib/ensurepip/__init__.py", line 92, in bootstrap _run_pip(args + [p[0] for p in _PROJECTS], additional_paths) File "/home/bill/py3.4/Python-3.4.0b1/Lib/ensurepip/__init__.py", line 28, in _run_pip import pip File "/tmp/tmprwpsemxj/pip-1.5.rc1-py2.py3-none-any.whl/pip/__init__.py", line 10, in <module> File "/tmp/tmprwpsemxj/pip-1.5.rc1-py2.py3-none-any.whl/pip/util.py", line 17, in <module> File "/tmp/tmprwpsemxj/pip-1.5.rc1-py2.py3-none-any.whl/pip/_vendor/distlib/version.py", line 14, in <module> File "/tmp/tmprwpsemxj/pip-1.5.rc1-py2.py3-none-any.whl/pip/_vendor/distlib/compat.py", line 66, in <module> ImportError: cannot import name 'HTTPSHandler' make: *** [altinstall] Error 1 Note: I will certainly *not* be trying to `sudo make install`. In any case, the executable and modules were installed fine, so other than reporting it here, it's not causing me problems (so far). It probably can. I just need to figure out how to test it to make sure the PR that supposedly fixes it fixes it, and then figure out how to ensure it still works into the future. That I can help with. Steal the "import_fresh_module helper function from test.support (or the gist of it anyway - you can likely leave out the stuff about deprecated imports): Then do: pip_nossl = import_fresh_module("pip", blocked=["ssl"]) If the ssl import is actually in a submodule, you may need to list additional subpackages in the "fresh" parameter. If you're wondering why this isn't in the importlib API - it's because it can go wrong in an impressively large number of ways, and we don't have any hope of documenting it well enough to make it usable by anyone that either: a) couldn't write it themselves; or b) isn't getting coached by someone that could write it themselves. But when you know what you're doing and the modules involved don't break horribly when treated this way, it's a very neat trick for testing purposes. Relevant pip issue: Can this be solved in ensurepip for now? I've been banging away at this but it's going to require some refactoring in pip to make it reasonably work. The move to distlib and requests made this harder to do than the old PR against pip could handle. OK, since pip 1.5 will still have the SSL/TLS dependency, the approach I'll go with for 3.4 is to: 1. Have ensurepip refuse to bootstrap pip if the ssl module is not available (noting that we'll remove that restriction if pip 1.6 avoids the strict dependency) 2. Use import_fresh_module to check that behaviour 3. Ensure venv skips trying to bootstrap pip if the ssl module is not available (although the subprocess invocation in the venv tests could make that tricky to test when the ssl module actually *is* available) New changeset f670d8db8ef3 by Nick Coghlan in branch 'default': Issue #19744: improve ensurepip error when ssl is missing I ended up not implementing step 3 - if you don't have SSL/TLS built, and you pass with_pip to the venv module API, or use the default settings for pyvenv, you *will* get an error from ensurepip. Instead, I just kept the test skip in test_venv. ensurepip and test_ensurepip have been updated to provide a better traceback when SSL/TLS support is missing, though. Tim, could you poke around at the latest version in your local build and see if the new checks are triggering? (I've assumed the ssl module can't be imported if the necessary underlying bits aren't built) This should be fixed, so I don't think it's a release blocker any more, but I also don't want to close it until Tim confirms it also works for him. This upsets "make install" as well - currently with a traceback. Attached patch tweaks the ensurepip CLI to check immediately for ssl support, and avoid printing a traceback if it is missing. However, missing SSL support still fails the call, which fails installation. This patch is probably a better bet - it just prints a message to stderr to say that we're ignoring the ensurepip failure during installation. pip wouldn't work anyway in a Python without ssl built, but at least this way that Python can still be installed without the ensurepip invocation complaining. Ned, if this approach sounds reasonable to you, I'll commit this one. Note: I'm deliberately not worrying about ensurepip._uninstall here, since that only gets invoked implicitly in the Windows uninstaller, and that should always have a valid SSL to play with. Always, since I worked out how to disable ssl in my local build (just a small tweak to setup.py), I was able to verify the correct behaviour of test_ensurepip and test_venv with SSL unavailable. issue19744_ensurepip_install_ok_without_ssl.diff looks good to me. Note, though, that with it and with ssl support missing, test_ensurepip fails somewhat obscurely: ====================================================================== FAIL: test_bootstrap_version (test.test_ensurepip.TestBootstrappingMainFunction) ---------------------------------------------------------------------- Traceback (most recent call last): File "/py/dev/3x/root/uxd/lib/python3.4/test/test_ensurepip.py", line 293, in test_bootstrap_version ensurepip._main(["--version"]) AssertionError: SystemExit not raised ---------------------------------------------------------------------- New changeset 9f76adbac8b7 by Nick Coghlan in branch 'default': Issue #19744: Handle missing SSL/TLS in ensurepip Thanks Ned - I fixed that test to only run if SSL/TLS is available, and added a new one to test that the command "succeeds" (with a warning printed to stderr) if SSL/TLS is missing. Larry - over to you to decide whether or not to cherry pick this into the release clone. The remaining misbehaviour that was fixed in the last patch only affects custom source builds, so the beneficiaries would be people trying to build from the source tarball or release tag without SSL/TLS support. Issue 20685 created to cover inclusion in 3.4.0, already committed to default, so closing this one. New changeset cd39d4cab680 by Nick Coghlan in branch '3.4': Issue #19744: Handle missing SSL/TLS in ensurepip
http://bugs.python.org/issue19744
CC-MAIN-2016-18
refinedweb
2,066
57.16
Created by harrowdrive (contact me) Dedicated to helping people play better cricket. I am a sports graduate and ECB Coach. I play local club cricket, coach one of the youth teams at my c... (more...) Fielding drills are great. They improve skills, can be done almost anywhere and can help with your fitness. They are also hard to find online. It's about time that changed. So this lens will show you a series of drills designed to make you the best, fittest fielder in your club. To see the full size pictures of these drills, visit 4 Corner Ball Drill For speed, fitness and throwing skills Variations: Don't use a ball, instead pad up and run to the marker and back as if you were running two quickly. Don't have a keeper, simply shy at the stump. Chase and Throw Drill For endurance, throwing and pick up skills Variations The fielder/keeper begins in a lying down position. Use more balls. Have the ball fed out so it is moving. Ladder Catch and Throw Drills For running technique, speed, catching and throwing Variations: Try doing backwards running, two footed jumps or sidesteps. Make the return a shy at the stumps. Move the feeder to the middle of the ladder instead of the end and complete the catch/return in the middle of the drill. Add a 10m sprint at the end of the ladder before the catch/return Add several cones in a curved shape after the ladder to simulate running around the boundary (you can have two ladders and two boundaries to square it off if you like). Add an extra ladder in line with a feeder in the middle. After completing the first ladder the feeder rolls the ball out away from the ladder the sets off on the second ladder. The first fielder fields the ball and throws it to the feeder who has completed the ladder drill. Use a heavier ball to catch and return (but counter balance with a tennis ball and normal ball on a 3:2:1 ratio). Whole team drill For just about everything! 2. The fielder at position 1 completes a 1 handed pickup and underarm throw through the cones to the fielder at position 2. Then runs to position 2. 3. Position 2 picks up the ball 2 handed and throws the ball to the stump at position 3. Then runs to position 3. 4. The fielder at position 3 catches the ball and has a shy at the stumps. Then runs to position 4. 5. The fielder at position 4 backs up the shy and returns the ball to the coach. Then runs to position 1. 6. Repeat as many times as possible. Aiming Relay Drill For throwing, catching and teamwork Variations: Instead of placing the ball, try rolling it or throwing it. Instead of returning the ball to the fielder, try shying at the stumps As pictured, turn it onto a race with two balls and two teams. Pick Up and Underarm Drill For close fielding and throwing accuracy Variations: Try shying at the stumps instead of underarm throwing. Add extra balls.
http://www.squidoo.com/cricketfieldingdrills/
crawl-001
refinedweb
527
81.83
How do I write this C++ sentinel-controlled while loop? I need to write a sentinel-controlled while loop to see if the coefficients of a quadratic equation have real roots using a nested decision. A character q must be my sentinel. This is what I have so far, but it doesn't really work and I'm getting lost... # include <iostream> # include <iomanip> # include <cmath> using namespace std; int main () { //Declare Variables double a, b, c, r1, r2, descriminant; char q; char SENTINEL = q; cout << setiosflags (ios::fixed) << setiosflags (ios::showpoint) << setprecision (3); cout << "Input the Value for a or q to Quit: " << endl; cin >> a; // read a while (a!= SENTINEL) { if (a == 0) cout << "Zero Divide" << endl; else if (a != 0) cout << "Input the Value for b or q to Quit: " << endl; cin >> b; // read b cout << "Input the Value for c or q to Quit: " << endl; cin >> c; // read c if (descriminant < 0) cout << "No Real Roots" << endl; else if (descriminant >= 0) cout << setw(6) << "The Real Roots Are: " << endl; cin >> r1; //read r1 cin >> r2; //read r2 descriminant = pow(b,2) - (4 * a * c); r1 = (-b + (pow(b,2) - (4 * a * c))) / (2 * a); r2 = (-b - (pow(b,2) - (4 * a * c))) / (2 * a); cout <<"Root One is: " << r1 << endl; cout <<"Root Two is: " << r2 << endl; } system ("PAUSE"); return 0; }
https://www.daniweb.com/programming/software-development/threads/318792/c-help-for-a-beginner-sentinel-controlled-while-loop
CC-MAIN-2022-21
refinedweb
224
66.3
Hello guys, Ok, now I need some advice here: I have this piece of code which is not cooperating very much. You can help me to figure out what is going wrong by taking a quick look at the Xsgi source code. On the directory programs/Xserver/hw/sgi, you have to grep for shmiqInit, once you find it, quickly figure what I am doing wrong. And if you have a chance to tell me what the thing with XXX is, I will be even more happy :-) cheers, Miguel. #include <stdio.h> #include <unistd.h> #include <fcntl.h> #include <sys/types.h> #include <sys/mman.h> #include <sys/shmiq.h> #include <sys/stropts.h> #include <errno.h> int mopen (char *file, int flags, int x) { int fd; fd = open (file, flags, x); if (fd == -1){ fprintf (stderr, "can't open %s\n", file); exit (1); } } int main () { struct shmiqreq s; int shmiq, kbd, zero, qcntl; int v; void *shaddr; zero = mopen ("/dev/zero", O_RDWR,0); shaddr = mmap(0, 16384, PROT_WRITE|PROT_READ, MAP_PRIVATE, zero, 0); shmiq = mopen ("/dev/shmiq", O_RDWR|O_EXCL|O_NOCTTY, 3); qcntl = mopen("/dev/qcntl0", O_RDWR|O_EXCL|O_NOCTTY, 0); fcntl(qcntl, F_SETFD, 1); s.user_vaddr = shaddr; s.arg = 0x00000553; /* XXX, this ought to be sizeof(shmiqSOMETHING) */ /* XXX, figure what this one is */ /* 0x80085101 is QIOCATTACH */ v = ioctl (qcntl, 0x80085101, (void *) &s); if (v == -1) v = errno; printf ("map regs: %d/%d\n", v, errno); kbd = mopen ("/dev/input/keyboard", O_RDWR|O_NDELAY|O_EXCL|O_NOCTTY, 0); v = ioctl (kbd, I_PUSH, "keyboard"); printf ("I_PUSH: %d\n", v); v = ioctl (shmiq, I_LINK, kbd); printf ("I_LINK: %d\n", v); printf ("shmqevent is: %d", sizeof (struct shmqevent)); while (0){ } return 0; }
http://www.linux-mips.org/archives/linux-mips/1997-07/msg00021.html
CC-MAIN-2015-18
refinedweb
276
71.34
Hi all, Ever needed a solution for the ugly naming of your server side controls? Ever wanted to be able to control the id's ASP.NET automatically generates for you? Ever viewed the source of you aspx page and saw control with id like this: "ctl00_MB_btnExit" ? This is the post for you! The solution is very simple and all you have to do is simply wait! (For the next release of ASP.NET and VS.NET 2010) As a brief introduction lets explain what is the problem in the first place: Whenever we place a control (A server control actually) in our page and this server control implements the Interface INamingContrainer all the controls ID's within this control will have a special effect on their ID's. Their ID's will be build from the INamingContrainer control itself + the original ID of the control in side. This happens for ensuring each control on the Page will have a unique ID (For ASP.NET to work properly). If this INamingContrainer control himself is in another INamingContrainer control the ID will be the concatenation of this hierarchy. So we will get an ID in the form of: FirstContainer_SecondContainer_OurControlID. Now imagine a web application that works with master pages and GridView controls, we will get a very ugly and KB consumer in our client side HTML. (By the way , To easily understand what it does think of it as a Control namespace.) The problem gets even worse if you are not specifying an ID for this INamingContrainer control. In this case the runtime will automatically assign a container ID for you (Like ctrl100 etc). Why do we even care you ask? well for many reasons, one of them is when we have a low bandwidth we don't want a performance problem because of these ID's for example. So how will ASP.NET 4.0 solves the problem: They added to each control (actually to every control's parent, The System.Web.UI.Control) a nice property by the name : "ClientIdMode". This property will have 4 options: 1. Legacy. 2. Static. 3. Predictable. 4. Inherit. The Legacy option is very simple. It means that the same "algorithm" for creating the ID's is just like the previous framework versions, for example: <asp:TextBox will be rendered to: <input id="ctl00_someMasterPage_ctl00_txtName" name="ctl00$someMasterPage$ctl00$txtName" /> The Static option means: You want it, you got it!!!! It will render the exact ID as you wrote it. No container ID will be appended to the ID.This means that a programmer must be very careful with this option. The Inherit option is the default option for all controls. This means that when rendering the controls ID it will look it up in his parent. The Predictable option is used to be able to predict the ID when writing our code. (Since this is the problem in the first place). It will be used mostly when using DataBound control such as GridView.When using this option we will use another property by the name:"ClientIDRowSuffix" Setting up the ClientIdMode: Instead of having to specify this new property on each and every control we can specify it in several places: 1. In out Page directive such as: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" ClientIdMode="Some Option" %> 2. Do it for all our pages using the web.config file: <system.web> <pages clientIdMode="Predictable"></pages> </system.web> Nice right? Enjoy Pingback from ASP.NET 4.0 solution for the ClientID problem - Pini Dayan That is about time. Actually it is much too late. It should have been there from the start. The fact that asp.net is changing the given ids and names of formfields is a big frustration. It makes the asp controls practically useless. Except of course with using Webforms (which is another pointless exercise: it means that the values in a form are submitted twice, once as regular formfields and once in the viewstate, I have never seen such a silly approach to web applications). > This means that a programmer must be very careful with this option. What makes you think that a programmer can not think? Is there any reason to suppose that before asp.net started to create fantasy names for formfields things went massively wrong? Well i agree although if you know youe asp.net you can find solution to all therse problems... at last .... microsoft got it :) MVC is doing that perfect we are reurn back to old ASP but with OO and services help now we can start work faster :)
http://blogs.microsoft.co.il/blogs/pini_dayan/archive/2009/03/19/asp-net-4-0-solution-for-the-clientid-problem.aspx
crawl-003
refinedweb
768
66.84
Ruby is a multi-platform open-source, dynamic object-oriented interpreted language, designed to be simplistic and productive. It was created by Yukihiro Matsumoto (Matz) in 1995. According to its creator, Ruby was influenced by Perl, Smalltalk, Eiffel, Ada, and Lisp. It supports multiple programming paradigms, including functional, object-oriented, and imperative. It also has a dynamic type system and automatic memory management. This example assumes Ruby is installed. Place the following in a file named hello.rb : puts 'Hello World' From the command line, type the following command to execute the Ruby code from the source file: $ ruby hello.rb This should output: Hello World The output will be immediately displayed to the console. Ruby source files don't need to be compiled before being executed. The Ruby interpreter compiles and executes the Ruby file at runtime. You can add an interpreter directive (shebang) to your script. Create a file called hello_world.rb which contains: #!/usr/bin/env ruby puts 'Hello World!' Give the script executable permissions. Here's how to do that in Unix: $ chmod u+x hello_world.rb Now you do not need to call the Ruby interpreter explicitly to run your script. $ ./hello_world.rb Alternatively, you can use the Interactive Ruby Shell (IRB) to immediately execute the Ruby statements you previously wrote in the Ruby file. Start an IRB session by typing: $ irb Then enter the following command: puts "Hello World" This results in the following console output (including newline): Hello World If you don't want to start a new line, you can use print "Hello World" Tk is the standard graphical user interface (GUI) for Ruby. It provides a cross-platform GUI for Ruby programs. require "tk" TkRoot.new{ title "Hello World!" } Tk.mainloop The result: Step by Step explanation: require "tk" Load the tk package. TkRoot.new{ title "Hello World!" } Define a widget with the title Hello World Tk.mainloop Start the main loop and display the widget. Run the command below in a shell after installing Ruby. This shows how you can execute simple Ruby programs without creating a Ruby file: ruby -e 'puts "Hello World"' You can also feed a Ruby program to the interpreter's standard input. One way to do that is to use a here document in your shell command: ruby <<END puts "Hello World" END Create a new file named my_first_method.rb Place the following code inside the file: def hello_world puts "Hello world!" end hello_world() # or just 'hello_world' (without parenthesis) Now, from a command line, execute the following: ruby my_first_method.rb The output should be: Hello world! defis a keyword that tells us that we're def-ining a method - in this case, hello_worldis the name of our method. puts "Hello world!" puts(or pipes to the console) the string Hello world! endis a keyword that signifies we're ending our definition of the hello_worldmethod hello_worldmethod doesn't accept any arguments, you can omit the parenthesis by invoking the method
https://riptutorial.com/ruby
CC-MAIN-2021-25
refinedweb
494
58.69
Hey Programmers I could really use some help with my school assignment. We’re asked to write a program to filter a txt file. The filter should only show the three letter words. Untill now, we’ve only learned the ‘‘basic functions’’ like def main() .count len() This shouldn’t be too hard for experienced programmers. This is what I have until now: import sys def main(): string = open("verhaaltje.txt", "r") words = [word for word in string.split() if len(word)==3] file.close() print (str(words)) main() I get this error: AttributeError: ‘_io.TextIOWrapper’ object has no attribute ‘split’
https://discuss.codecademy.com/t/help-please-filtering-a-txt-file-in-python3/439601
CC-MAIN-2019-43
refinedweb
101
79.26
Hi im writing a program and one of the things i need it to do is get today's date and display it at various times. creating the date using 'datetime' i can do the problem is passing the created date strings to different classes i currently have 2 classes one displays a GUI with various buttons and the date in 3 tkinter labels (one for day month and year). the functions for the buttons and dates are within another class as they will be used with a class i've yet to write. bellow is a simplified version of what im trying to do. where ive wrote [INSERT SOMETHING HERE] is where im stuck on what to do i tried obj1.datetimetodayday but that just brings up seemingly random numbers and the name of the function in Class2 from Tkinter import * class Class1: def __init__(self): obj1= Class2() self.root = Tk() self.root.title("test window") self.can1=Canvas(self.root, width=500, height=510, bg="black") self.can1.pack(expand=False, fill=X) self.label1 = Label(self.can1, text =obj1.datetimetodayday , bg = 'black', fg= 'red',font=('Arial Black', 14)) self.can1.create_window(20,20, window=self.label1, anchor= NW) class Class2: import datetime def __init__(self): pass def datetimetodayday(self): tdate=datetime.datetime.now() tdateday = str(tdate.day) if len(tdateday)==1: tdateday= "0"+tdateday gui=Class1() gui.root.mainloop()
https://www.daniweb.com/programming/software-development/threads/260625/passing-a-string-variable-from-one-class-to-another
CC-MAIN-2018-17
refinedweb
232
58.79
Hi Ryan, On Fri, Jun 18, 2010 at 7:57 PM, Ryan Ingram <ryani.spam at gmail.com> wrote: > Related to this, I really would like to be able to use arrow notation > without "arr"; I was looking into writing a "circuit optimizer" that > modified my arrow-like circuit structure, but since it's impossible to > "look inside" arr, I ran into a brick wall. > > Has anyone done any analysis of what operations arrow notation > actually requires so that they can be made methods of some typeclass, > instead of defining everything in terms of "arr"? > > It seems to me the trickiness comes when you have patterns and complex > expressions in your arrow notation, that is, you write > > (a,b) <- some_arrow <- (c,d) > returnA -< a > The design I've been using for this has been to use data-reify, and observable sharing and to use pure let bindings to build the circuit. full_adder :: Bit -> Bit -> Bit -> (Bit, Bit) full_adder a b cin = (s2, c1 || c2) where (s1,c1) = half_adder a b (s2,c2) = half_adder s1 cin half_adder :: Bit -> Bit -> (Bit, Bit) half_adder a b = (a `xor` b, a && b) foo = do x <- exists y <- exists z <- exists assert $ full_adder x y z === (1,1) assert $ forall $ \ a b c -> (a && b) ==> c === (a ==> b ==> c) return (x,y,z) I perform a similar sharing recovery in the back end code of Numeric.RAD from the 'rad' package and Numeric.AD.Internal.Reverse in the 'ad' package. I have uses in a number of unreleased bottom-up applicative parser combinators as well, so it has a wide arrange of applicable situations. Overall, let bindings tend to be a lot lighter than the accompanying arrow sugar. You might find Andy Gill's write-up on type safe observable sharing in kansas lava to be useful. -Edward Kmett -------------- next part -------------- An HTML attachment was scrubbed... URL:
http://www.haskell.org/pipermail/haskell-cafe/2010-June/079145.html
CC-MAIN-2014-15
refinedweb
312
55.27
Opened 5 years ago Closed 2 years ago #7056 closed bug (duplicate) Relax static-PE linker object checks Description (last modified by ) cygwin 1.7 $ iconv --version iconv (GNU libiconv 1.14) E:/Develop/haskell/conv.hs : import Codec.Text.IConv as IConv import Data.ByteString.Lazy as ByteString main :: IO () main = ByteString.interact (convert "UTF-8" "GBK") then GHCi, version 7.4.1: :? for help Loading package ghc-prim ... linking ... done. Loading package integer-gmp ... linking ... done. Loading package base ... linking ... done. Prelude> :load "e:/Develop/haskell/conv.hs" [1 of 1] Compiling Main ( E:\Develop\haskell\conv.hs, interpreted ) Ok, modules loaded: Main. *Main> main Loading package bytestring-0.9.2.1 ... linking ... done. Loading package iconv-0.4.1.0 ... ghc.exe: panic! (the 'impossible' happened) (GHC version 7.4.1 for i386-unknown-mingw32): loadArchive "d:/cygwin/lib\\libiconv.a": failed Please report this as a GHC bug: *Main> Leaving GHCi. <interactive>: Unknown PEi386 section name `.drectve' (while processing: d:/cygwin/lib\libiconv.a) Attachments (1) Change History (28) Changed 5 years ago by comment:1 Changed 5 years ago by comment:2 Changed 5 years ago by Loading package nano-md5-0.1.2 ... <interactive>: Unknown PEi386 section name `.drectve' (while processing: C:\openssl\lib\libcrypto.a) ghc.exe: panic! (the 'impossible' happened) (GHC version 7.4.1 for i386-unknown-mingw32): loadArchive "C: openssl lib libcrypto.a": failed Please report this as a GHC bug: with openssl from comment:3 Changed 5 years ago by comment:4 Changed 5 years ago by comment:5 Changed 5 years ago by It also shows up (but with different unknown section) when linking with code built with gcc-4.7.0 on mingw. comment:6 Changed 5 years ago by This would be fixed by dynamic-by-default. comment:7 Changed 4 years ago by Experienced this with Mingw GCC 4.7.2 on Windows 7 when building GHC: "inplace/bin/ghc-stage2.exe" -hisuf hi -osuf o -hcsuf hc -static -H32m -O -package-name vector-0.0.0 -package ghc-prim-0.3.1.0 -package primitive-0.4.0.1 -O2 -XHaskell98 -XCPP -XDeriveDataTypeable -O2 -no-user-package-db -rtsopts -odir libraries/vector/dist-install/build -hidir libraries/vector/dist-install/build -stubdir libraries/vector/dist-install/build -dynamic-too -c libraries/vector/./Data/Vector/Fusion/Stream/Monadic.hs -o libraries/vector/dist-install/build/Data/Vector/Fusion/Stream/Monadic.o -dyno libraries/vector/dist-install/build/Data/Vector/Fusion/Stream/Monadic.dyn_o Loading package ghc-prim ... linking ... done. Loading package integer-gmp ... ghc-stage2.exe: panic! (the 'impossible' happened) (GHC version 7.7.20130413 for i386-unknown-mingw32): loadArchive "C:\\MinGW\\msys\\1.0\\home\\Max\\Programming\\ghc\\libraries\\integer-gmp\\dist-install\\build\\libHSinteger-gmp-0.5.1.0.a": failed Please report this as a GHC bug: ghc-stage2.exe: Unknown PEi386 section name `.drectve' (while processing: C:\MinGW\msys\1.0\home\Max\Programming\ghc\libraries\integer-gmp\dist-install\build\libHSinteger-gmp-0.5.1.0.a) comment:8 Changed 4 years ago by May be related. Building GHC with mingw gcc 4.8.0 and ghc 7.6.3 on Windows 8 yields: Loading package integer-gmp ... ghc-stage2.exe: Unknown PEi386 section name `.dr ectve' (while processing: C:\MinGW\msys\1.0\home\Kyle\ghc\libraries\integer-gmp\ dist-install\build\libHSinteger-gmp-0.5.1.0.a) ghc-stage2.exe: panic! (the 'impossible' happened) (GHC version 7.7.20130711 for i386-unknown-mingw32): loadArchive "C:\\MinGW\\msys\\1.0\\home\\Kyle\\ghc\\libraries\\integer-g mp\\dist-install\\build\\libHSinteger-gmp-0.5.1.0.a": failed Please report this as a GHC bug: make[1]: *** [libraries/vector/dist-install/build/Data/Vector/Fusion/Stream/Mona dic.o] Error 1 make: *** [all] Error 2 comment:9 Changed 4 years ago by I looked into this. See The .drectivesection only appears in OBJ files. It contains text representations of commands for the linker. For example, in any OBJ I compile with the Microsoft compiler, the following strings appear in the .drectvesection... This is with Microsoft compilers. Presumably, MinGW or something is doing this now too? Some searching suggests ld generally doesn't understand the directives placed in .drectve, although maybe something changed or it puts something else there. It's probably just best to ignore the section (a simple fix); I'll try to get GCC 4.8 on my Windows build machine and reproduce it. comment:10 Changed 4 years ago by Wait! The ghc-tarballs repo contains gcc for exactly this reason. The build system is supposed to use that, not any random gcc that comes with mingw. So why is it using the mingw one? Simon comment:11 Changed 4 years ago by In my case I manually modified GHC directory layout so that "mingw" points to recent mingw installation. It contained GCC 4.7. It's important if one wants to use C++ libraries built with more recent GCC. As far as I know one can't mix code built with different GCC major versions so forcing use of GCC 4.5 isn't exactly the solution. comment:12 Changed 4 years ago by Perhaps then we should simply upgrade the GCC release included in ghc-tarballs. I'm not sure if I will get to this before 7.8.1 (there's some cleanup on top of the fix for this that's needed,) although tenatively we can try. comment:13 Changed 4 years ago by comment:14 Changed 4 years ago by We should probably just ignore section names that we don't understand. I think the linker is just being extra paranoid in making sure it understands the whole contents of the object file, but this breaks with pretty much every new gcc/binutils. 3 years ago by I just got this trying to load libHSpersistent-sqlite-1.2.1.a. Any idea when it will be solved? comment:23 Changed 3 years ago by 3noch: The fix for drectve should have made it into GHC 7.8.2. This bug is still open because we ostensibly want to relax the Windows linker's object checks. comment:24 Changed 3 years ago by comment:25 Changed 2 years ago by Moving to 7.12.1 milestone; if you feel this is an error and should be addressed sooner, please move it back to the 7.10.1 milestone. SORRY FOR THE TEXT FORMAT
https://ghc.haskell.org/trac/ghc/ticket/7056
CC-MAIN-2017-22
refinedweb
1,082
53.17
Introduction Using the Eclipse IDE and Buildroot with the Ensemble Graphics Toolkit (EGT) helps simplify the compilation, remote execution and debugging of EGT applications. In this training topic you will download and install the Eclipse IDE for C/C++ Developers, configure and build a basic graphics interface for the SAM9X60-EK evaluation kit. You will run the application remotely and configure the Eclipse IDE for debugging. A typical development flow-path looks like: - Download and configure the Buildroot build system. Download the Ensemble Graphics Toolkit source code. Build an SD Memory Card image (covered in Preparing the Host PC and Target). - Once the Buildroot build has finished, the output directory will contain the SD Memory Card image to boot Linux with the Ensemble Graphics Toolkit libraries. The build output also contains the cross toolchain for graphical development on the Host PC (covered in Preparing the Host PC and Target). - Download and configure the Eclipse IDE for compilation, remote execution and debugging (this topic). At the end of this topic you will be able to develop simple graphical interfaces for the SAM9X60-EK using the Ensemble Graphics Toolkit. Steps: - Install the Eclipse IDE for C/C++ Developers - Create an Application Menu Shortcut for Eclipse - Start Eclipse and Create a Project - Adding a Source File - Configure Dependencies with the Pkg-Configure Tool - Setting Build Properties - Building the Project - Run Application on Target Remotely - Configure for Debugging Prerequisites You have prepared the Host PC with all the development software tools and Ensemble Graphics Toolkit source code as explained in the topic: Install the Eclipse IDE for C/C++ Developers In this section, you will download, install, and configure the Eclipse IDE for C/C++ Developers. You will also download and install OpenJDK, the open-source implementation of the Java Platform, Standard Edition, as either OpenJDK or Java SE is required to run the Eclipse IDE. 1 Download the Eclipse IDE for C/C++ Developers package from: Alternately, you may download the Eclipse IDE Installer from and select the Eclipse IDE for C/C++ Developers from the menu. 2 Extract the archive file in the /opt directory: $ sudo tar -zxvf eclipse-cpp-YYYY-MM-R-linux-gtk-x86_64.tar.gz -C /opt Where YYYY-MM are the year and the month of the latest stable release. 3 Optional On some Linux distributions you may need to run this command: $ sudo chown -R root:root /opt/eclipse With Eclipse installed in the /opt directory, it can be accessed by any user. 4 Install OpenJDK-8: $ sudo apt-get install openjdk-8-jdk You have completed installing the Eclipse IDE for C/C++ Developers and the OpenJDK. Create an Application Menu Shortcut for Eclipse In this section, you will create an applications menu shortcut to launch the Eclipse IDE. 1 Change directory to your home directory: $ cd ~ 2 With your favorite text editor, create a text file named eclipse.desktop: 3 Copy the following to the text file: [Desktop Entry] Name=Eclipse Type=Application Exec=/opt/eclipse/eclipse Terminal=false Icon=eclipse Comment=Integrated Development Environment NoDisplay=false Categories=Development;IDE; Name[en]=Eclipse 4 Save the text file. 5 Set the text file eclipse.desktop to be executable: $ sudo chmod +x eclipse.desktop 6 Install eclipse.desktop: $ sudo desktop-file-install eclipse.desktop 7 Create a symbolic link in /usr/local/bin: $ sudo ln -s /opt/eclipse/eclipse /usr/local/bin/eclipse 8 Add the Eclipse IDE icon to be displayed with the shortcut: $ sudo cp /opt/eclipse/icon.xpm /usr/share/pixmaps/eclipse.xpm The Eclipse IDE shortcut will now be visible in the Applications Menu. Start Eclipse and Create a Project In this section, you will start the Eclipse IDE and create an Ensemble Graphics Toolkit project. Create a Project 7 Enter the following information: Cross compiler prefix: arm-buildroot-linux-gnueabi- Cross compiler path: /home/<user>/buildroot-at91/output/host/bin This is the cross toolchain that you built in the topic: Ensemble Graphics Toolkit – Preparing the Host PC and Target You have created project EgtProject for the Ensemble Graphics Toolkit. Adding a Source File In this section, you will add a C++ source file to EgtProject. 3 Enter the following source code to the basic.cpp window pane: #include <egt/ui> #include <iostream> using namespace std; using namespace egt; int main(int argc, const char ** argv) { Application app; TopWindow window; Button button(window, "Press Me"); center(button); window.show(); return app.run(); } 4 Save your program by selecting File > Save. You have completed adding a source file to the EgtProject. Configure Dependencies with the pkg-configure Tool In this section, you will use the pkg-config tool located in the buildroot-at91 build to automate finding and configuring the correct dependencies to the Eclipse IDE to build your applications to run on the target. This tutorial assumes you are setting up your development environment to build an EGT application to run on the target. 1 On the Host PC, using your favorite text editor, add the following to your ~/.bashrc file: export PKG_CONFIG_PATH =/home/<user>/buildroot-at91/output/host/arm-buildroot-linux-gnueabi/sysroot/usr/lib/pkgconfig/ Be sure to use the path to the location of where you have buildroot-at91 installed. You have completed setting the dependencies required for the Ensemble Graphics Toolkit with the Eclipse IDE. Setting Build Properties In this section, you will set the build properties for the EgtProject in the Eclipse IDE. 2 In the left-hand pane of the Properties window select C/C++ Build > Tool Chain Editor. Observe that the Current toolchain: dropdown box has Cross GCC selected. 3 Next, select C/C++ Build > Settings. b On the Tool Settings tab, select Cross G++ Compiler > Miscellaneous. Change the Other flags text box to the following: -c -fmessage-length=0 `pkg-config libegt --cflags`. If a project contains C source files, the Cross GCC Compiler would require configuration. As the EgtProject only contains a C++ source file, this step is skipped. d On the Tool Settings tab, select Cross G++ Linker > Miscellaneous. Enter the following into the Linker flags text box: `pkg-config libegt --libs` This linker flag will pass the location of the libegt dependencies to the linker so that the pkg-config tool can fill in the libraries required to use libegt.. e Click on the Apply and Close button. This will apply all the changes you have entered. This completes setting build properties for EgtProject. Building the Project In this section, you will build the EgtProject. 1 To build the project, hover over EgtProject, right-click and select Build Project from the menu. Or you can click on the Build icon. The Console window (bottom pane) will display the build progress. At the completion of a successful build, a Debug folder in the Project Explorer window in the left pane. Note the files in the folder: makefile, sources.mk, objects.mk and subdir.mk. You have successful built EgtProject. Run Application on Target Remotely In this section, you will configure the Eclipse IDE to be able to run an application remotely on the target (SAM9X60-EK). 1 To set run properties, hover over EgtProject, right-click and select Run As > Run Configurations… from the menu. 5 Enter the following settings: Connection name: Remote Host Host: 10.0.0.20 User: root Select Password based authentication Password: <root_password> Be sure to set the Host IP address to the address you selected when you prepared your Host PC for development. 6 Click on the Finish button. 7 In the Run Configurations window, enter the following in the Remote Absolute File Path for C/C++ Application: text box: /root/basic This is the location the basic.cpp executable will be loaded and run. 8 Click on the Run button. 10 To stop the program, press the Stop button (upper left hand, just below the menu bar). This completes running an application remotely using the Eclipse IDE. The following information boxes contain information on the Application, TopWindow/Window, and Button classes used in the basic.cpp program. Application Class From ~/egt/docs/html/annotated.html, click on v1 and then Application class. All the functions, attributes and constructor associated with the Application class is documented here. The application class is a helper class that does standard setup for inputs, outputs, event loop, etc. In this example, we construct an Application and run it using the run() method to run the application. TopWindow / Window Class From ~/egt/docs/html/annotated.html, click on v1 and then click on TopWindow or Window class. TopWindow is the main Window that provides functions like pointer (cursor) that apply only for the top level window. In this example we are using the show() method of the Window class to show the main window which all widgets are drawn. Button Class From ~/egt/docs/html/annotated.html, click on v1 and then click on Button class. All the functions and constructor associated with the Button class is documented here. In this example, when we construct the button widget, we provide the text to be printed on the button. We also inherit the widget member function center() to place the button in the center of the frame. Configure for Debugging In this section, you will configure the Eclipse IDE to debug the EgtProject. 2 In the left pane, select EgtProject Debug. From the Main tab, observe the settings that you entered in the previous section: Connection: Remote Host Remote Absolute File Path for C/C++ Applications: /root/basic 4 Enter the path to the arm-based debugger: GDB debugger: /home/<user>/buildroot-at91/output/host/bin/arm-linux-gdb 5 Create a GDB initialization script by creating a text file named gdbinit in your home directory: /home/<user>. Enter the following text: handle SIGILL nostop set sysroot /home/<user>/buildroot-at91/output/host/arm-buildroot-linux-gnueabi/sysroot The purpose of the GDB initialization script is to help prevent spurious signals. 6 Save the GDB initialization script. 7 On the Debug Configurations window, under the Debugger tab, enter the path to the GDB initialization script to: GDB command file: /home/<user>/gdbinit 8 Click on the Apply button. Click on Close to close the Debug Configurations window. Before running the debug command, check if there is any application running on the target and end it. Debugging You can now click on the Debug As… icon (it looks like an insect, at the top in the ribbon) and select Local C/C++ Application. You may be shown an Authentication Message dialog box. Select Yes to accept it. Sometimes, you require a restart of the Eclipse IDE and reboot of the target. Eclipse will change to the Debug Perspective and the application will halt at main(). Press Resume (F8) to continue execution and the application should appear on the WVGA display. You can now use Eclipse to debug the application viewing variables, disassembling the code and enhance debug experience. Summary In this topic you downloaded and installed the Eclipse IDE for C/C++ Developers. You configured and built a basic graphical interface for the SAM9X60-EK. You learned how to run and debug the application remotely from the Eclipse IDE. What’s Next? There’s plenty more to learn. Here are some additional Ensemble Graphics Toolkit training topics to help you gain more knowledge and skills:
https://microchip.wikidot.com/32mpu:egt-eclipse
CC-MAIN-2021-04
refinedweb
1,892
54.73
On Tue, 2009-09-01 at 10:19 +0200, David Engster wrote: > Eric M. Ludlam <eric@...> writes: > > On Tue, 2009-09-01 at 00:29 +0200, David Engster wrote: > >> template <typename T> class test > >> { > >> public: > >> void func1() { }; > >> }; > >> > >> template <> class test <float> > >> { > >> public: > >> void func2() { }; > >> }; > >> > >> semanticdb-typecache-merge-streams doesn't know how to merge these > >> types, so the first one is kept and the second one is silently dropped. > > [...] > > > In this case, a function that accepts two tags and chooses which one to > > keep. This function doesn't need to handle the class/namespace merges, > > nor the prototype vs impl selection which is already in the merge code. > > > > The default can return the first tag. > > > > This way, C can add some fancy stuff. Anything discovered in C that > > works for other languages can be promoted back to the core typecache > > code. > > > > As for what to actually DO with these two identical tags, I don't know. > > I guess that depends on what the use cases are. The typecache is tuned > > to return only one tag during a find by name. What might that tag be > > that represents both of these things? > > Actually, I think we should not merge them at all, since they are two > different types; you can do whatever you want in those type > specializations. I'm more leaning towards renaming one of the tags, > e.g., leaving 'test' for the generic one and 'test<float>' for the > specialization. The dereferencer would then have to choose the correct > one. Maybe this should already be done in the parsing stage. > > But maybe that won't play well with the existing template code; I don't > know. I have to take a good look at it first. > > And there's another problem looming: partial template specialization. It > works something like this: > > template <typename T> class test > { > public: > void doSomething(T t) { }; > }; > > template <typename T> class test<T *> > { > public: > void doSomething(T* t) { }; > } > > That means, you can create a class that specially deals with pointers of > type T (yes, also different ones for multiple levels of pointers). > > Oh, and you can (partially) specialize nested templates and templates > with multiple type parameters. (How does one even name that? Multiple > Template Parameter Partial Template Specialization?) I would guess the first tactic is to make sure the C++ parser produces tags that are distinct for these different permutations of "test". ie, can you tell them apart based on the :template slot. Right now the second doesn't parse at all for me. ;) Then, in the typecache, when it finds two tags that differ only by template specifier, argument lists, or other, it could fabricate a new tag of class 'polymorphic, or a more descriptive 'bunch-o-tags-with-the-same-name. This tag would then have a :members list. Since lots of programming languages use polymorphism, this could be a generic tag class with a range of language overloadable features. The hard part here is that every piece of code that deals with a return value from the typecache would need to know about this new tag type, and what to do about it. Code that performs a generic search would want to know how to merge the results into one of these generic tags too. I know the analyzer has a 'choose the best tag' function somewhere. One way to simplify this problem is to have this new tag type scan the list of members, find the most generic one, and promote it's features up to the 'polymorphic tag itself. In that way, if the tag were misused by something like eldoc, it would still print out as the basic tag. Alternately, I suppose the merging of tags could clone the most generic tag, and add a :polymorphic or :bunch-o-tags-with-the-same-name attribute with the original list as a value. This might work better in the above scenario. In fact, this would be almost exactly like what it does now, except that code that cares would be able to look inside, and make smarter decisions. I like that.. It could then take over semantic-analyze-select-best-tag prototype filtering, and a few other things scattered randomly in the code. > > Every time I try to simplify some problem, C++ finds an exception. > > Yep. Sometimes I think we should just take the risk and let C++ become > self-aware, so that it can parse itself. Hmmm. Isn't that what bison does? Perhaps it has happened already. ;) Thanks for explaining this issue to me. I don't code much in C++ anymore. Eric View entire thread
http://sourceforge.net/p/cedet/mailman/message/23451322/
CC-MAIN-2015-32
refinedweb
767
72.46
On 25 May 2011 22:17, Stephen Tetley <stephen.tetley at gmail.com> wrote: > Hi Ivan > > Forks are good, no? > > The Parsec experience has suggested to me at least, that new author's > "capping" another author's work by bumping up to a major version, > causes a significant difficulties even when the original author has > gone. > > As for wl-pprint, it was a very tidy library in its original > implementation - it's a pity it now has name clashes with Applicative. > My feeling is that a new library in a new namespace with some > attention to new combinator names would be better. Such as? I'm _hopeless_ at making up names... ;-) Having a new package would require a new name and new module namespace, let alone thinking up new names for combinators... Also, by clashes with Applicative, are you referring to empty and <$> ? I'm not sure if a better name than "empty" can be found; as for <$>, maybe using pretty's notation of $$ and $+$ rather than <$> and <$$> ? -- Ivan Lazar Miljenovic Ivan.Miljenovic at gmail.com IvanMiljenovic.wordpress.com
http://www.haskell.org/pipermail/haskell-cafe/2011-May/092334.html
CC-MAIN-2013-20
refinedweb
179
65.93
Hi all, my Professor has asked us to solve this problem, which is a Midterm Practice problem for our up and coming Midterm exam, which is on Monday. I am wondering if I'm doing this the correct way or not. Here is this question the problem asks: Problem 19 Random Steps Write a function named randomSteps() that simulates a person taking a specified number of steps of varying length. The length of the steps varies at random within a specified range. (Use the function in the random module random.randint(a, b), which returns a random integer N such that a <= N <= b.) Input: Parameter 1: minStep, an integer >= 0 that is the minimum length of a single step Parameter 2: maxStep, an integer > 0 that is the maximum length of a single step Parameter 3: steps, an integer > 0 that is the total number of steps to be taken Return: An integer that is the distance walked Assume that the parameters are in the specified range. Because the steps are of random length, successive calls to randomSteps() with the same parameters may produce different output. An example of a call of randomSteps() and its output would be: >>> print(randomSteps(2, 5, 100)) >>> 355 Following the instructions, I've come up with this for my code: import random def randomSteps(minStep, maxStep, distance): length = 0 while length < distance: length = random.randint(minStep, maxStep) length += minStep distance -= length return length print(randomSteps(2, 5, 100)) I normally get an output (with these variables) of 5, 6, or sometimes 7. Can anyone tell me if this is correct, or what should I change to make it correct, or at least guide me :). Thanks so much!
https://www.daniweb.com/programming/software-development/threads/418117/need-guidance-with-a-practice-problem-using-random-randit
CC-MAIN-2017-34
refinedweb
284
56.79
- Grouping data on the fly at crystal report - Keydown stops KeyPress Event? - File System Watcher & Bitmap problem - Current namespace /class - Convert C into C# (is there a way?) - Convert Dec06 to Dec 2006 - How to rename custom control? - what am I doing wrong with my Process.Start? - Need Input from Threading Guru - Question about value types - richTextBox access from a function - folderbrowse - TcpClient close() method socket leak - How to search word in a richtextbox? - Easy Friday Question - Panel control and Table - registering assembly upon deployment - User GUID - Overriding private interface property? - Crystal Reports again - Socket.Poll - SelectRead vs. SelectError - returning Datagrid selection to the caller form - Making/using icon as custom cursor - Saving to files - XML - C# - Standard XP Icons - Testing... - Setting multiple file attributes - deploying signed assembly - Bug in the framework? - setting a breakpoint in a WinForms event handler... and then getting caught in the event loop. - Writing a C++ DLL in C# - How do you get path and filename from a SaveFileDialog ? - Redim Preserve Array - Repetivie Try/Catch Blocks - Help with DirectX 9 in a picturebox - DragDrop / interop - Queue Email Message - How to: Create a tree structure w/ web controls w/out round-trips? - Creating tables during runtime - Sealed classes and constructors / deconstructors - Displaying a form as top, and modal, but without ShowDialog - How to get the Character value when using KeyPress? - generating database script - Discovering Whose Logged On To Remote System? - Help with Custom Control - Check Files - How to use a C API in C# - How can I create dinamic columns in Crystal Reports.... - Check permissions where the files are excuted - Binding a Drawing.Color value to a datagrid. Please help :-( - C# FAQ - e.Handled=true? - Locking a Windows machine using C# .NET framework - Killing the processes. - Invoke Method - C# 2.0: Showing Nullable Types in PropertyGrid - Using a C# Collection through Interop with VB6 - NumericUpDown - net send using c# - How to: Use "custom validation" control to validate Calendar Contr - Color of a single row of a data grid - Asp.Net validation - Removing Hyperlinks - Advice: XML file as database or table - Creation of XML - .Selected property for listbox does not work - Object reference not set to an instance of an object - Events and GUI question: - Doubt on Interoperability - C# Launch Pad Application - Is COM considered 'unsafe' code - How to run a console application without showing the console screen? - Owner Draw - datagrid and binding data - Objects in Treeview - List of SQL-Server Databases - Configuration - Update a DataSet - Turn off KeyPress/find on listBox? - Setup - "Run program now" - SqlAdapter not returning value - PropertyGrid question - Help with Cursor position - Trickey problem with editing enum based properties - COM Component and C# - Building a treeview from object graph (reflection) - Windows service and socket - Problem loading assemblies in seperate AppDomain - Which book? - manipulate ListView scroll bar - How to remove namespaces from XmlDocument??? - Source of a frameset at run time... - How to re-direct C# to different CE Emulator? - Modular application - C# Hexadecimal conversion - "Generate web references" has problems with accessors - solution? - Reading an xml file into Dataset - PLS HELP - Forcing Gobal Garbage Collection - How to: set the selected "drop down list" value at run time. - Declaring a const array - Why am I getting a - HttpResponse.WriteFile sends uncomplete file - Hardware - odd question: how to "read" letters from an image? - KeyDown / KeyUp / KeyPress - can't select dataSet from DataGrid - System.Web.Mail - Using regular expressions in code generation or regeneration - looking for winforms C# CRUD examples - Which IDE is better for C#, Borland C#Builder or VS.net 2003? - Object reference not set to an instance of an object.?? Please Help - asp open window - Service takes 1 min 34 sec to start - How to implement a menu with panels - float do decimal - Dataset question. - Compiling problem, or is it? - Name of main form in app - How to get memberOf groups for a user in ldap ? - OpenFileDialog - how to select files by coding??? - if else ... - How to print contents of DataGridView - copying the listbox behaviour in "Add/Remove Programs" - Put a binary image into HtmlGenericControl - Add username/password to newly created MDB - Strings - DIfferent Validation on two datagrids - Write XML file on remote machine - Reg Expression - Error while using COM component - Full Screen Mode - how to use ApplicationSettingsBase - Getting/setting height of paddle in ScrollBar control. - COM Server boject - CollectionBase Update - Disable control's paste contextmenu - Button ToolTipText - String Syntax - Best serial rs-232 class - How to capture Mouse Single click and mouse double click event - Hyper-threading - invalid cast exception - Can't step into Interop objects in VS.NET when debugging - Is C Sharp the way to go ? - Pointer for questionnaires on Microsoft technologies - How can test the pw for Sql Server 2000 - Inherited from a base form - PrintDocument class in c# - System.UnauthorizedAccessException for all .NET code accessing COMobjects - EnumMonitors in c# - How to set radio button in datagrid? - Novice C# qu: Converting VB to C# - loop througth Literials using foreach!! - How to set the background color of a MDI Parent from? - Multiple level base calls - Multiple Excel Cells to Datagrid - Dial numeric pager question can it be done? - How to change tabControl colors? - retrieving images from access database - multiColumn ComboBox - found the C++ code, need C# code - Windows Service - stoping the OnStart event in the OnStart event - Redistribution of Microsoft.mshtml.dll - Error when open a set of rows - print listview items - Writing a logon screen for a C# winform app.... - Help needed explaining very strange behaviour of KeyPressEventHand - quickest way to find the index of the first letter in a richTextBox? - Validate UNC Path - Error after upgrading XML parser - Strange indexer behaviour - Single Setup File - cast string to long - Bitmaps and threading model - Saving PrintJob to File and then Load to Printer again - Strange problem with DEBUG directive - Start main webform in modal look like - Keep track of previous and current mouse positions in MouseMove()? - databinding a textbox to a string - List of all Instatiated Objects - ListView scrollbar? - Can we add an event handler that has different delegate? - slow performance? - The ListView - Parsing using RE? - List<t> and ICollection - sscanf - Crystal Reports with c# - adding to system menu - What's the best way to retrieve ID3 tags from WMA files? - A Visual Studio plugin for sharing code? - Can we pass a method to another class? - How to clear comboBoxes - error executing code - several projects - list box ower drawn variable item height... - scrollbar movement - suggested videos or cbts for self instruction? - EnterpriseService Component: problem enlisting in a distributed transaction - check for File In Use - C# and dot Framework version - How do I get the list of overrides for a ASP.NET WebForm in C# - abstract class - Storing reference to reference - code fails - perform poorly - HELP / ADVICE: Would this be suitable to perform a basic collision? - 2 objects with same name - Does HybridDictionay key has to be string type? - Tooltips in 2003 - Version Number - Difference between "build" and "rebuild" - connection problem (using SQLCE) - Calling a method from a Web Service - Inheritance and events - How to safely stop a service, from within OnStart...? - Custom Cursors on Custom Controls - Inheritance question - Modifying clip region - 8.3 file/dir names in C# - Scalability of a singleton remote object - Duplicates in comboBox - How to stop my beep? - Passing string array to unmanaged code - How Do u Lock a Particular Column in a datagrid? - How do I find retrieve the "My Documents" qualified path? - Check for valid file names - Unable to get events from a form - Equivalent of Array keyword ? - protection from .NET Decompiler? - OpenFileDialog in VB.Net - Search, Replace with Regular Expression - Prepared statement for Adomdcommand - Date formatting - How to get Paragraph leading? - How to extract the version from Assembly.FullName ? - conversion to c# from excel function help - Has anyone used these MS services? - GAC entries don't show up in References/.NET - Saving PrintJob to File and then Load to Printer again - Pushing data from the server to the client - CS0006: Metadata file...could not be found - Windows Form containing a Windows Form - Processing a Textfile - Time Out Event? - TRANSLATE from VB - Tray icon etc. not showing when started by Service - TRANSLATE from VB - Reports and SQL Server - c# express beta problem - TransmitFile() API - Respond to security alert - How can I get my Product Key? - Tape Device - RegEx how do I do unique? - TextBox not reflecting changes made to it - creating an umanaged object in a managed wrapper - SQL connection to Access database - Can't change cursor within a control - Namespace guidelines - passing 2-dim float array from COM to .Net - Charts and Graphs - Checking background procces - Help with SendKeys - interface vs. inheritance - NDoc and <pre> tag - 1 COM interop event OK, more than 1 event NOT OK in C# - Writing to "this", or a general OOP question I guess... - Can Setup automatically run Uninstall? - Urgent: help deploying an ASP.NET app!! - Bug: Controls rendering in "Spanish"?? - Just like NetLimiter - Bandwidth limiting per Process with C# - MDI Forms... Some unusual request... - Closing database connections in a class destructor - Copying a project - Adding a Property to a Properties getter and setter - Backup in another computer - Grabbing parameter from URL - DateTimePicker formatting - Stream into System.Drawing.Image - pc's current user - Activator.CreateInstanceFrom - Accessing Outlook Express Thru' C# - Problem with range in DataAdapter.Fill - Error with C# Compiler - Unable to access a variable from another class - please help! - Date Format problem in crystal's ParameterFieldDefinition - Scrollbars maxvalue is too high - query - Query abt Combo box - Using DllImport - files required in web page folder - devPartner C# project performance analysis - how to send mail in C# - GPRS in Compact Framework - Uploading a file thru FTP - RSACryptoServiceProvider public/private key - Regular expression - misbehaviour - Remote Debugging in VS.NET 2003 - It's Crazy (!) - V Studio 2003 Doesn't Load Supporting DLL Debug Symbols for Windows Service Remote Debug - DataGrid & ScrollBars - rundll32 - student - Interaction With Windows Services - KeyDown event question - Inheriting From FileDialog - Advice/Info/Help with Retrieving Windows Media Player playlists programmaticallyin C# - DateTime.DayOfWeek is not localized, why? - are there UML diagrams for C# API? - Checking the State of a URL before XML Read - Why can't the as operator perform user-defined conversions? - System.Net.Socket.Socket - direcx x - Determine current namespace - Setting focus to multi-line textbox? - Determining CLR .NET Installation Directories - Emergency - FileSystemWatcher limits problem - Exception handling in IDisposable.Dispose - TypeBuilder.DefinePInvokeMethod - C# Very Odd Behavior - "failed to load resources from resource file" - Inspect type for operators and use them? - emergency - ListView question,,,, - turning sockets off - ArrayList and Indexer - Help - EventLog always writes to Application log - ArrayList and Indexer - Help! - A newby question. Please help - Breakpoint on Field Change - emergency about SQL Server connection - ListView scrollbar ?! - Delegates vs. Events vs. AsyncCallback - the memory could not be read - HTML Report - Swapping Control Containers - DataGrid - Pass a lot of parameters? - System.Collections is Empty - Where to place app.config file - Unable to detect a click on a pushbutton - Deploymnet MSI Update question - Web Services & Custom Classes - OnMouseHover Issue (Bug?) - EventLog Source still created after deleting all references to it - Identifying input from keyboard devices - dateTime - Align Datagrid Headers and Detail - .NET Object as Property of another object? - C#,COM & Strong name file - Exception handling Application Block - Simple question of syntax - config file with a service - Easy DataSet question - Will C# work with Windows CE? - An Unexpected error occurred on a send - HELP : regarding Textbox Enter and Focus Question many TIA - i need some template for - mobile application & MS SQL - Reference Counting - using C# code in C++ or Java - C# inteop - C# connect to Server through SSH - How to: protect emails from "spam" bots? - How can I increment an integer one-at-a-time? - Access .Net through Javascript - Bitmap masking the .NET way - directx - How do u get the week number for a given date? - OLE control? - detached rows in DataTable - Problem passing enum to a remote object - Reading Assembly's Manifest - defining the datasource property - WebRequest.Timeout has no effect - Directx question - How to check an assembly's version? - Line to Line height? - Autocad?? - How to ... - Automation? - parameters in click or mouse down events - parameters in click or mouse down events - How to access Microsoft Outlook Address Book thru C#? - problem with circular references in OO - Using VS2005 to create an application compatible with framework 1.1 - Catching ConstraintExceptions on dialogs and allowing the user to keep trying... - Assembly: custom attributes - Passing Parameters between form classes - C# - Accessing properties of Controls in another Form - Region visible in another Region? - Get area of a circle enclosed in an image? - sockets question... - Why does .NET delete my pdb files when changing to release mode. - Determining write access - Saving from richTextBox to File - databindings - Help adding a component - Application run parameters. How to read them? - ListView srcollbar ? - Real time - FileSystemWatcher - How to find out file / directory - Most significant bit in WM_COMMAND wparam - Basic: How to represent Tab in a string, it is char 9. What is the sintaxys? - FileSystemWatcher - How find out type (directory / file) - Basic: How to get a specific character from a string? - net unit - Bug in ImageList? - DataSet question - Zoom in Report doesn`t work - control1.SetBounds(x,y,... needs to have the positions of the scrollbars thumbs subtracted from x and y - Keep a point inside a region? - Slow build?! please help - Strange code execution - MCSD certification - is it still necessary to land a job? - OLE Automation Question - Client-Server problem: sending udp packets to server causes "an existing connection was focibly closed by the remote host" - New Promotion, need advice - ListView Question - Repeater, PagedDataSource and Typed Datasets - Calling form knowledge of closing modeless form - can't invoke an internal method - ignoring events when loading form - Binding DataGrid To IList - Graphics and Treeviews - WebService "not all code paths return a value" error - can't invoke an internal method - Where is Application.aspx? - Threading with UI elements - dynamically created controls? - Threading with UI elements - dynamically created controls? - StreamReader and Peek() - SQLDMO away return NULL - Download with c# - access Microsoft Outlook Address Book thru' C# - question about pinning pointers - .net assembly question... - Delete / replace a dll that is in use - how to detect double click on the tabel cell of DataTable - basic: Is it possible to define optional parameters in a method declaration? how? - Upcoming Windows Mobile and Embedded chats and Webcasts - Upcoming Windows Mobile and Embedded chats and Webcasts - Directory.GetFiles search param - Dockable Windows in Whidbey - c# (or .NET) focus event sequence is wrong - UDP and File Transfer - Exclude app from displaying in the Alt-Tab window - Cisco CDP - DAX Error? - marshalling socket buffer - cna't compile - Change base class at runtime? - Checking if the Fn key was pressed on a laptop - Soap call not protected with a try..catch? - Decimal separator simbol - Preview in Crystal Reports - TCP Socket class send() never blocks... - Packaging MSDE in with Winforms C# app, using Windows packages - making sure <Enter> key always works??? - Please, need help with reading CSV from Excel. Please help. - Cost of Visual C# 2005 - illegal characters - Web Service & Custom Return Types - Open default e-mail client with attachments. - Discover user name given IP address or NetBIOS name - Simple Question.. - WSE 2.0 security problem - class or struct? - Object null reference - Windows service with client interaction - Using 2 mouses as input in C# game? - Can anyone help with ReadPrinter using winspool.drv? - How to check display settings - a to z buttons at runtime - Dialog inside dialog.... - How to check if a variable is an Enum - change password of AD or workgroup in c#.net? - Win32 vs. .Net/CLR - Checking for wireless adapters - vb event in c#? - Second ItemDataBound command does not fire - Timer in asp.net app. - CollectionBase Class and DataSet - how to write a callback function to be invoked by C++ DLL? - Passing parameters... - passing xml to servlet file - ASP.NET, C#, AccessDenied problem... - Accessing RepeaterItem.DataItem in nested repeaters - Get Xmlnode by an attribute - Strange Exception behavior - SmtpMail - how to auto-update a text file before closing it - Scroll in UserControl - RichTextBox line heights - Input Box in C# - FTP Server - A first chance exception of type 'System.InvalidCastException' occurred in scs.sr.dal.dll - Bug? Dialog Box and Single Click - Error after installation - backup - backup - registry backup - registry backup - How to override a method in usercontrol? - Weakreference Multicast Delegates - HASH (SHA1) of a big file - NMock problem?? - Strongly named assembly can reference only other Strongly named assembly - IpEndPoint is null error - Remoting problems with Exception - Having problems with C# unsafe. - Problems with C# unsafe code... - Setting an existing object's members through reflection - log errors - Cross process singleton - Why not "new SqlDataReader()" ? - Change NTFS Permissions - Call webPage in separate DLL - Clicking a button on a executable file - Add UserContol to Toolbox without creating Windows Control Library - Built In Printer Fonts - hiding key columns in datagrid. - Jet Rep Object. ( change password) - jet code fails with password, why ? - ASP datagrid style question while using paging - Data Area Too Small Error - dynamic tooltips - ReleaseComObject or =null - Memory Managment/Objects lifecycle managment - c# and vb 6 dll - Open file in exclusive mode - Duplicating "delete this" - where is the JRO Jet and Replication Object ?? - ostream << operator doesnt print first stream - Deployment project, can you have it generate a single .exe? - Moving a control on the page during runtime. - Application.Run - After execution - Drawing Graphics and undo this - MSDN - Outlook Open Folder Calendar - Combobox fun - "Specified argument was out of the range..." - c#, ASP.NET, Process ID for Excel - Visual Studio - Projects now contain "bin" and "obj" - Thread A calls a delegate on Thread B but Thread A executes it!?!? - Worker Thread - Convert UInt16 to Byte Array - how to have the IP of a TcpClient - Object reference error when loading control - dot net vs. powerbuilder? - Socket Handle Question
https://bytes.com/sitemap/f-326-p-111.html
CC-MAIN-2020-16
refinedweb
2,944
55.24
On Tue, 23 Sep 2003 12:56:51 -0500 Christian Grothoff <address@hidden> wrote: > > An optional alias could be attached somehow to the namespace, the > > obvious concern is collisions, i.e. two seperate namesapces want to > > use the same alias. > > Right. The key question is who is allowed to put forward that > association. If I can insert a global handle for my own namespace, I > could (maliciously) pick the alias of someone else who is popular and > try to impersonate that pseudonym. For users that use the aliases (and > that don't see the underlying public keys), this attack would succeed. > GNUnet could not tell which was the > "original" alias / handle and prevent it. > > > Alias wouldnt be the primary identifier, so collisions wouldnt be a > > problem. > > If they are to be useful for the end-users, they'd likely become the > primary identifiers... > > > Handle it the same way instant messangers do it. > > Eh, don't they just assume that the "first" person to take an alias > gets to keep it? In a distributed P2P setting (IMs are centralized!), > we can't do that. I think your talking about screen name, AIM uses screen names (words) as the primary identifier, ICQ uses UIN (a number), i think they have merged the primary identifier now, not sure exactly on the details. Alias's arent meant to be unique, multiple people could have the same alias if they wanted to, as long as the primary identifier is unique its ok. If you have someones alias you can try and use it to find there primary identifier. The alias might only narrow it down but not go all the way, in that case the user needs more information to find right namesapce, maybe the user might recognise the first couple ofdigits in the namespace identifier, or recognise the content within the namespace. Its like having the same filename for two different files, as long the files have a different hash GNUnet can handle it. Think of filename as alias, and hash as namespace. There isnt any point having two unique identifiers. I guess alias should be able to be set by the person who controls the namesapce, but should be able to overriden locally by other users. Glenn
https://lists.gnu.org/archive/html/gnunet-developers/2003-09/msg00023.html
CC-MAIN-2021-17
refinedweb
374
69.92
view raw How can one store & access attributes in the following way in Java? InnerTest it = new InnerTest(); it.id = "123"; it.user.userID = "456"; public class InnerTest { public String id; static class user { static String userName; static String userID; } } [...] "in_reply_to_user_id" : null, "in_reply_to_user_id_str" : null, "in_reply_to_screen_name" : null, "user" : { "id" : 19792676, "id_str" : "19792676", "name" : "(((Payne¯\\_(ツ)_/¯)))", [...] foo.user.id_str ... Nested class is a good choice in this situation. However, you misunderstood the purpose of static in a static class - this is a syntax for creating classes that can be created independently of the instance of their outer class. It is not a class that must have only static fields and methods. Therefore, your declaration should be fixed to make userName and userId fields non-static: public class InnerTest { public String id; public UserType user = new UserType(); static class UserType { String userName; String userID; } }
https://codedump.io/share/MCvVwAk7Iewx/1/how-to-cleanly-interact-with-nested-class-in-java
CC-MAIN-2017-22
refinedweb
143
64.81
0 Hello all, Before anything else, this issue is also posted at: I have a structure similar to the one below.I miss a lot of information about the specific template parameters, so I would need something like what is in the code. This code does not compile because we cannot have templatized virtual member functions. Does anyone have a clever idea how to solve this? The result I want is to get through the specialized operator() of B<O,true>. #include <iostream> using namespace std; class SomeClass; /* In the real code I have SomeClass< T, P, Q> * and this is not known when the compiler reaches A,B and C*/ struct OtherClass{ int i; double d; OtherClass(int ii, double dd):i(ii),d(dd){}; }; /* My idea of A is this, although it is not * possible to have a virtual template function */ class A{ public: template<class K> virtual void operator()(K input )=0; }; template<int L, bool M, class S> struct B : public A{ template<class K> void operator()(K input ){ cout << "Inside B" << endl; }; }; template<class S> struct B<0, true, S> : public A{ template<class K> void operator()(K input ){ cout << "Inside B<0,true>"<< endl; }; }; /* This class creates and stores an object of type B (or one of the specializations). * But L and M are unknown so I created A to store the B object here * K is also unknown here. */ class C{ A* object; public: C(){ /* * Get some data from files and according * to this data construct a B specialized object. */ object = new B< 0, true, SomeClass>(); }; void go(){ /* * Later, I want to call B, that was stored through the interface A */ (*object)(new OtherClass(0,2)); } }; int main(void){ C* c = new C(); c->go(); return 0; };
https://www.daniweb.com/programming/software-development/threads/173787/meta-programming-templates-virtual-member-functions
CC-MAIN-2017-09
refinedweb
294
58.05
Projects Vincent Bernat All my projects are hosted on GitHub. Here are a few of them: lldpd is a 802.1AB daemon. It sends and receives LLDP frames which enables remote L2 equipments to determine which equipment is remotely present. These frames contain information like the equipment name, the port name, VLAN, etc. Snimpy is a Python tool targeted at writing simple tools using SNMP queries. It features a very pythonic interface and any Python developer should feel at home with it. Have a look at “Snimpy: SNMP & Python” for details. hellogopher is a Makefilefor Go projects. See “A Makefile for your Go project” for details. Dashkiosk is a solution to manage dashboards on multiple screens. It provides an administration interface and a set of receivers, including a web application, an Android application, and a Chromecast application. See “Dashkiosk: manage dashboards on multiple displays” for details. eudyptula-boot boots a Linux kernel in a VM without a dedicated root filesystem. It’s useful for quick tests or to develop and debug around the Linux kernel. See “Eudyptula Challenge: superfast Linux kernel booting” for details. network-lab is a disparate set of networking labs I maintain to test various stuff. Many articles on my blog are backed by such a lab. See “Network lab with QEMU” for details. Wiremaps is a network discovery application. It will browse your network and gather information from LLDP, EDP, CDP, FDB and ARP tables using SNMP. It also includes a wayback machine to know where an equipment was plugged before it disappeared. It’s unfortunately currently unmaintained. jchroot is an enhanced chroot using Linux namespaces to provide more isolation. See “jchroot: chroot with more isolation” for details.
https://vincent.bernat.ch/en/projects
CC-MAIN-2021-25
refinedweb
282
59.8
Don't Lie to the Entity Manager JPA is the new object-relational mapping standard that you can use in EJB3 or in standalone applications. For the most part, it is phenomenally easy to use. But ever so often, you get a query from a developer such asthis one. The programmer set up a bidirectional relationship and didn't populate both sides. acc.setAddress(addr); // addr.setAccount(acc) missing I tried to set up a simple example that shows very clearly what goes wrong and why. Here goes: Every Student has aDiploma (may be null), and every Diploma has a Student. Now we set up the relationship, "forgetting" to set up the inverse: EntityManager em1 = emf.createEntityManager(); int id; try { em1.getTransaction().begin(); Student s = new Student("John Q. Public"); Diploma d1 = new Diploma(); d1.setDegree("BS"); s.setDiploma(d1); // d1.setStudent(s); // "forgot" to do this em1.persist(d1); em1.persist(s); em1.getTransaction().commit(); id = d1.getId(); } finally { em1.close(); } Of course, the student reference in the d1 object is null. But so what...in the database, this is not a problem because the inverse side doesn't actually have a foreign key. When one retrieves the diploma from the database, the Student entity is obtained by a query SELECT Student x WHERE x.diploma = diplomaId. Let's try it out by making a new entity manager and querying for the diploma. EntityManager em2 = emf.createEntityManager(); try { Diploma d2 = em2.find(Diploma.class, id); System.out.println("d2=" + d2); } finally { em2.close(); } Unfortunately, the result is a diploma object whose student reference is null. Why? In the spirit of the “Head First” books, let me BE the entity manager.I am an entity manager. I am asked to find a Diploma entity. I am a brand new entity manager. I don't know any entities. I construct a new Diploma object. I make a query to the database and retrieve the name. The DIPLOMA table has no STUDENT column, so I make another query to set the student ID.But wait, I don't do that. I get out my ouija board and communicate with the spirits of the past. I find that the client has been bad to the deceased em1 and lied about the bidirectional relationship. Therefore, I set the student property to null . . . Clearly, that can't be right. Reading the JPA spec does not help. It talks about persistence contexts, but em1 and em2 have their own independent persistence contexts. Instead, the culprit is the object cache (which is given short shrift in the spec). I did my experiment with GlassFish, which uses Toplink as its JPA provider. Apparently, the TopLink cache has located a Diploma instance (namely the one that I persisted in em1), and it now returns it, without ever accessing the database. That's what a cache is for. My lie about the null student came right back to me. Here is another example. I tried out the @OrderBy construct: @Entity public class Course { . . . @ManyToMany(mappedBy="courses") @OrderBy("name ASC") private List<Student> students = new ArrayList<Student>(); . . . } I added a bunch of students, but I didn't bother to sort them by name. I figured that the @OrderBy annotation will produce an ORDER BY in the query, so they'll come out in order anyway. That's true, except in the program run in which I persisted the Course object. That time, the cache found the original object in which the students had the wrong order, and it threw it right back into my face. Stephen Connolly pointed me to this footnote in section 2.1.1 of the spec. (The empasis is his.) [4] Portable applications should not expect the order of lists to be maintained across persistence contexts unless the OrderBy construct is used and the modifications to the list observe the specified ordering. The order is not otherwise persistent. In other words, don't lie to the entity manager. - Login or register to post comments - Printer-friendly version - cayhorstmann's blog - 3981 reads
https://weblogs.java.net/node/235839/atom/feed
CC-MAIN-2015-40
refinedweb
675
60.41
03 July 2009 21:50 [Source: ICIS news] TORONTO (ICIS news)--?xml:namespace> This was the final regulatory approval needed after authorities in the The company’s shareholders had approved in April. NOVA expected to close the transaction on or about 6 July, it said. The deal was first announced in February. NOVA is headquartered in the US, but it is originally a Canadian company and the bulk of its manufacturing is located in Canada. In related news, the Financial Times reported on Friday that IPIC planned to raise $5bn in syndicated loan facilities to help finance the acquisition of NOVA, as well as its purchase of a stake in Spanish oil refiner Cepsa and other deals. ($1 = €0.71)
http://www.icis.com/Articles/2009/07/03/9230143/canada-approves-ipics-takeover-of-nova-chemicals.html
CC-MAIN-2015-14
refinedweb
120
51.99
Go Tell It On the Mountainby Kendall Grant Clark May 15, 2002 primer 1. A name for prayer-books or devotional manuals for the use of the laity, used in England before, and for some time after, the Reformation 2.b.By extension, a small introductory book on any subject. 2.c. fig. That which serves as a first means of instruction. -- The Oxford English Dictionary, 2nd ed., Volume XII Marketing and Technology Evangelism There are only two kinds of marketing: bad and terrible. Programmers, and other people who actually create things, generally disdain marketing for good reason: it typically overpromises, inadequately explains, and dwells on the ephemeral, to the detriment of the real. But there are exceptions to most sentences which begin with "there are only two kinds of ..." Technology doesn't necessarily need to be hyped, but it often needs to be sold. So let's agree that marketing comes in two flavors -- bad and terrible -- but that technology evangelism, which is distinct from though related to marketing, can be vital to the success (and not necessarily in market terms) of a new technology. Let's also stipulate, for the sake of saving time and space, that the point of technology evangelism is to educate potential users about the utility of the technology for one of their purposes or ends, and to do so in a way that imparts a sense of reasonable and realistic enthusiasm. And if evangelism imparts a sense of fresh or novel possibility, so much the better; that's just icing on the cake. The Real Problem with RDF From at least one perspective, RDF, the Resource Description Framework, is among the most interesting of W3C specifications. But RDF is also used less often than one might expect, is not terribly well understood by its potential target audience, and generally suffers from a lack popular enthusiasm. One might even suggest that RDF is nearer to its stagnation than to its tipping point, though speculating about tipping points is notoriously tricky. In short, RDF's evangelism has not gone very well at all. For the record, I'm not interested in attaching blame to that fact; the relevant point here is that it is a fact, and it is one which can change. Which is not to say that RDF is technically perfect; it has its fair share of flaws and warts, at least one of which -- the poorly understood distinction between the RDF data model and its best-known and most-hated XML serialization -- is or is perceived to be a real impediment to its widespread adoption. But, despite its flaws, RDF can be extremely useful for a great many Web-application tasks. So my theory about why RDF is not widely used is that to date it has not been well evangelized. What can be done? The RDF Core Working Group part of the W3C's Semantic Web Activity thinks it has at least one edge piece of the RDF evangelism puzzle, namely, the RDF Primer, a draft of which was recently released. All good technology evangelism requires that potential users have an accurate, even if not very deep understanding of the technology. And one way for potential users to acquire such an understanding is for foundational developers to explain it to them, taking into account what users need to accomplish, as practically as possible, and what users know already about the technology and surrounding technologies. And the expression of this explanation needs to be one which potential users can reasonably trust to be accurate and reliable. Nothing spoils good evangelism like half-truths, distortions, and bumblings. The RDF Primer So RDF evangelists stand in strong need of something like the RDF Primer, especially a document blessed, as it were, by a trusted source. As it says, the RDF Primer is intended to "provide the reader the basic fundamentals required to effectively use RDF in their particular applications." You couldn't ask for much more. The only other thing to ask for or about is how well the RDF Primer accomplishes this important task. As the Primer is currently at the draft stage, some kinds of comment, including those about the clarity of its sentences and paragraphs, are best left to private communication with the Working Group. However, we can take an overview of the Primer as a whole, asking ourselves whether, as a whole, it constitutes a ground upon which RDF evangelism may go profitably forward. First, let's examine the Primer's structure: it offers an introduction to RDF, explains RDF's much-maligned XML serialization, introduces RDF Schema and RDF container types, describes a few real-world RDF applications, says a bit about RDF's model theory, its test cases, and about reification. My initial reaction is mixed. The first section, "Making Statements About Resources", offers a relatively accessible introduction to what RDF is all about. I found the discussion of RDF "blank nodes" to be especially helpful. But the document as a whole is too long and can be hard to wade through. The section on RDF Schema is a substantial part of the Primer, which would be stronger if the RDFS stuff were introduced very simply and quickly, with the bulk of it existing in a separate document. Of course, these judgments are very subjective, but my intuition is that the Primer should handle the most common RDF use cases, and for most of its potential users, RDF Schema is not something they need or will use first. The Primer seems to acknowledge this general point when it says that,. Which is true enough, but the implication of this claim -- that RDF provides a simple data model of its own -- for the purposes of a primer suggest that removing the RDF Schema discussion from the Primer, or at the very least slimming it down considerably, would strengthen the Primer. And while it is equally true that extensive use of RDF requires RDF Schema, the two most common public uses of it to date -- RDF Site Summary and Dublin Core -- feature user communities, the overwhelming majority of which are satisfied without extensive or any knowledge or use of RDF Schema. That some core group of schema designers needs RDF Schema (and a corresponding RDF Schema Primer, to be sure) is indisputable. But RDF is very much like XML in this respect: just because "anyone" can create an XML vocabulary or RDF schema does not itself mean that the numerical majority of XML or RDF users will ever do so. In fact, there are good reasons for believing that most users will never create vocabularies or schemas. Finally, there is the general point that, all other things being equal, short primers are better than long ones. Further, it certainly seems clear, whatever their status in the future of RDF, and despite rumors of their eventual demise, discussion of RDF containers -- <rdf:Bag>, <rdf:Seq> and <rdf:Alt> -- should precede the discussion of RDF Schema. Potential users can avoid writing RDF schemas for far longer than they can avoid dealing with container types. As for the discussion of actual RDF applications, I'm tempted to say that the important thing is that the Primer includes consideration of applications, no matter what they are. But that's not entirely true. While the most obvious use of a framework for asserting resource descriptions is metadata, the problem is that the metadata applications are the most obvious. Hence, they're the ones mostly likely to have occurred to anyone who knows anything about RDF. Three of the five RDF applications which the Primer considers are straightforwardly metadata applications. Any responsible primer about RDF must, or so it seems, include discussion of RSS and Dublin Core. Which means that the discussion of PRISM doesn't add very much. Far more interesting and non-obvious is the intelligent routing discussion. I'd like to see more discussion of RDF applications like that, and a bit less about metadata. Section 7, "Other Parts of RDF", has a very haphazard feel, as if it is serving as the dumping ground for things the Primer should discuss but which couldn't or haven't yet been worked into more obvious or conceptually elegant places. The discussion of the RDF Model Theory belongs in the introduction to RDF per se, at the beginning of the Primer. And if reification -- which surely plays the same role in the RDF drama that namespaces plays for XML -- is going to be discussed at all in the Primer, it too should be integrated into Section 2. As for the consideration of RDF Test Cases, while it is only a few shortish paragraphs, it really belongs somewhere else entirely, i.e., not in the Primer. Were these changes to be made, the Primer would have one less section entirely, which would contribute to the perception of it being as clear and simple as the truth. Lastly, Section 8, presently called "RDF as Data Model" promises to be the hidden gemstone of the Primer. If I understand correctly what it promises to become, it is precisely the sort of substantive discussion which can communicate the value of RDF in a way which fires imagination and stokes enthusiasm. A discussion of the relation of RDF to relational data storage technology is particularly crucial, since it not only reaches potential users where they live, so to speak, but also hints at one of RDF's potential uses, namely, as an application-specific data model layer, which may or may not be stored in an RDBMS. Prospects After languishing for a relatively long time, the next 12 to 18 months is a make or break time for RDF, as well as for the Semantic Web Activity, of which RDF is a crucial element. Despite the technical problems with RDF, the biggest impediment to its widespread use to date has been the failure of evangelism, not so much because it was done poorly, though there have been missteps, but, rather, because it was mostly not done at all. And so the arrival of a Primer among the work product of the RDF Core WG is a happy occasion. It offers those of us not serving on an RDF working group, but inclined to do formal or informal evangelization of RDF among our peers, a non-normative but still blessed and trusted ground upon which to base our efforts. As well, it offers curious, potential users a more easily accessible introduction to RDF, and that can only be a good thing. There is some sense in which there being an RDF primer is far more strategically valuable than the sort of primer it is. However, as with other introductory texts, often the only texts about a technology users ever read, there are certain principles it is hard to quarrel with. Among these are simplicity and concision. In what ways and to what extent these principles are met is, as always, at least partially a subjective question. I for one think that the RDF Primer gets more things right than it gets wrong, but I'm also hopeful that future drafts grow increasingly simplified and concise. What are your views on the new RDF Primer, or on this review of it? Share your opinions in our forum. (* You must be a member of XML.com to use this feature.) Comment on this Article - Telling It is not the point 2002-05-21 20:52:51 Jean-Luc Delatre [Reply] Hopefuly RDF is NOT used! Will do more harm than good and users lazyness is for once a GODD THING. See: Cheers.
http://www.xml.com/pub/a/2002/05/15/rdfprimer.html
crawl-002
refinedweb
1,939
56.49
Building Linux Audio Applications 101: A User's Guide, Part 1 Recently I've received some mail asking for a brief explanation on how to build Linux audio applications from source code packages. Ask and ye shall receive, hence the following simple guide for the perplexed, the puzzled, and the downright mystified. Compiling software is hardly rocket science, and if an old guitar-picker like myself can do it certainly you can too. This tutorial is written for users and developers who already know about Linux and who know how to use a Linux system. I'll demonstrate how to turn source code into software, using freely available tools and utilities common to almost every version of Linux. We will focus on the development of audio processing software. Linux has a powerful infrastructure for audio applications developers, and I hope that the material presented here will help new and seasoned developers alike as they venture into the world of programming Linux for music and sound. Mainstream Linux distributions tend to be somewhat conservative about program versions. The distribution maintainers want stable and proven versions for their products, understandably so. Curiously, for all the chatter about Linux being for programmers only, the mainstream distributions are aimed squarely at the desktop. As a result, many popular distributions do not include the most current version of program X or utility Z. In Linux, it often happens that the very new is also the very unsupported. Mainstream Linux distributions may not have the dependencies or the specific versions of the dependencies required by an application, which leaves the user to do one of three things: You can wait until the distribution acquires the desired program in its package repositories, you can look for something else to do the job, or you can try to build the software yourself. That last option is the focus for this article. A professional developer is not likely to need the advice offered here, but many other users want to know how they can compile and install Linux sound and music software from source code packages. The process itself is not difficult, but setting up a Linux software development system is often confusing for newbies (and even for not-so-newbies, especially if they come from a more GUI-dominated environment). This tutorial will help you decide which tools you need, how to acquire them, and how to use them to build and install a Linux audio program. But first, let's review the reasons why you might want to build your own software at all. Why Compile ? In Ye Olden Days of Linux there were few pre-built packages, so you were expected to know how to compile software you wanted to use. Books and other documentation routinely led users through the process of writing a test program and compiling it at the command prompt. By the way, "compile", "build", and "make" all mean about the same thing, and the terms are used interchangeably throughout this tutorial. Older users like myself may occasionally wax nostalgic about those yonder days, but in fact I'm a whole-hearted supporter of modern Linux distributions and their package repositories. The process of building software hasn't changed much since the old days, but some aspects of the process have been made much easier to handle. For example, I no longer need to compile the GTK and Qt graphics toolkits, a distribution upgrade usually updates those components to acceptable versions. The mainstream distributions are likely to keep up-to-date with versions of major software development tools such as the Gnu C compiler (GCC) and the graphics toolkits already mentioned. However, they are less diligent about certain components needed by certain cutting-edge Linux audio software. Due to their concerns for stability, the major distributions are also unlikely to offer packages for the very latest versions of some applications, nor will they typically offer packages of alpha or beta stage development versions. For instance, if you want to test Ardour3 you'll need current versions of the libraries and development packages for (at least) the GTK2 graphics toolkit, libsndfile, JACK, ALSA, and the Scons build manager. And that brings us to the main reason for compiling at all, i.e. to access features and capabilities not yet found in a public release. Building software from source code also ensures a "best fit" for your system's hardware. You might want a leaner version of a program, or you may need a capability available to a release version but not normally compiled into it. You might also discover that the program is currently unavailable in a packaged version, so if you want it you'll have to build it yourself. Lastly, you may be one of those strange people who just want to learn about such things and you aren't afraid to do it yourself. IDE ? What IDE ? I have purposefully avoided any discussion of GUI-based tools. There are some very nice GUI-based development tools and utilities for Linux, but for present purposes I have chosen to target the lowest common denominator of programming environments, the Linux command line (a.k.a. the terminal prompt). Regardless of flavor, size, or shape, all Linux distributions include command-line access to the system. And if you've never worked at a Linux console command-line, have no fear: If you can enter your name in a login dialog you can enter and execute commands at the terminal prompt. The power is in your hands. The One-minute Guide To Rolling Your Own The entire process of building software can be summarized by these steps : - Download and unpack the source code. - Compile the source code to create the program. - Install the program. The second step includes a few sub-stages : - Configure the source code for the resulting program's optimal performance. - Compile the source code files (*.c) into object files (*.so). - Link the objects together into an executable binary, i.e. the usable program. That's it, and it really is that easy. Of course, I've ignored the possibility of things going wrong, and some of the indicated stages may require a few additional steps before the process runs smoothly to its end. I'll address those concerns later in this tutorial, but now we'll move on into a description of the tools you'll need to make a working program from a source code package. General Environment In its original state software is a collection of files known as the program's source code. Typically, source code is made of one or more files in simple ASCII text format, written in a computer language such as C/C++, Python, Lisp, Java... the list goes on and on. Computer programming languages are all capable of doing the same things, but they are not all equally capable. Thus, some languages are better than others for certain purposes. The C language happens to be an excellent choice for system software and other performance-critical software, such as programs written to manage audio data in realtime. Most Linux audio software is written in C or C++, so the remainder of this article focuses primarily on compiling source code written in C. The following example is a variation on an old standard chunk of source code written in the C programming language : #include <stdio.h> int main() { printf("Greetings, Earthlings !\n"); exit(0); } After this code has been transformed into a working program you can run it and watch it print the message "Greetings, Earthlings !" to the screen. However, to turn that source code into a program that actually does something we need to acquire some tools and utilities specially designed for applications development. These tools make up what is called a build environment. Most mainstream distributions provide a package named build-essential (or similar) that will add the basic tools for compiling, including the GNU compiler suite, a collection of compilers and other utilities needed for building software written in C/C++ (software written in other languages will require their own compiler). You will also need a build management system such as Scons or the GNU autotools. And in case you don't know: A compiler is a specialized program that makes a working program out of source code. How it does so is beyond the scope of this article, so I'll refer readers to the controversial Wikipedia page on compilers to begin their investigations. Before we can build any source code we need to retrieve some. A package can be acquired from the Web or an ftp site through a normal download. However, software on the edge is often not packaged at all, though tarballs of the daily builds may be available. You're likely to need some tools such as cvs (the Control Version System), svn, (the SubVersion system), and the git and hg systems, all of which should be available from your distribution's software repositories. These retrieval utilities access special regulated source code repositories known as version control systems, and their use typically requires an arcane command syntax like the following request for the source code for the Ardour2 "on-going" source tree : svn co This command accesses the Subversion (svn) repository and checks out the source code from the Ardour development team's 2.0-ongoing directory. An identical directory will be created on the target machine, and the software will be delivered to it file by file, with a revision number displayed at the end of the transfer. Updates can be performed with another special command, or the normal checkout command can be re-used (only updated files will be transferred). The command for retrieval from a CVS repository is similar to the SVN example above. The following example demonstrates the 2-step procedure required for access to Csound's CVS sources : cvs -d:pserver:anonymous@csound.cvs.sourceforge.net:/cvsroot/csound login (Press the Enter key to login anonymously.) cvs -z3 -d:pserver:anonymous@csound.cvs.sourceforge.net:/cvsroot/csound co -P csound5 Again, a new csound directory will be created so be sure to put it where you want to find it. $HOME/src works well for me. Different developers prefer different version control systems. You'll need to check your selected program's Web site for the correct URL to its chosen version-controlled repository. So Many Packages If you download a package in the normal manner you'll need to unpack and install its contents. A variety of package formats exists, so let's look at some of the commonly encountered formats used for source code packages. In the beginning was the tarball, and it was good. The tar utility organizes a directory into a file that is then typically compressed with a file compression utility. The following examples demonstrate how to uncompress tarballs created with these tools : tar -xZvf foo.tar.Z tar -xzvf foo.tar.gz tar -xjvf foo.tar.bz2 where - x sets up an extraction, - v runs a verbose list of the extracted files, - f indicates that the extraction will be from a file, - Z, z, j determines which compression/decompression utility to deploy. By the way, "tar" stands for "tape archive", a reference to the days when digital data was stored on magnetic tape. The final part of the filename extension identifies the utility used to compress the file. Z refers to the UNIX compress utility, gz indicates that the GNU gzip was used, and the bz2 extension refers to a more recent compression format. The tarball is still a preferred distribution format for source code, but you also might encounter source packages in DEB (Debian), RPM (RedHat/Fedora and OpenSUSE), RAR, Windows ZIP, and other formats. Each of these formats perform the same basic package functions as the tarball, and their basic unpacking commands are as follows : dpkg -i foo.deb rpm -uVh foo.rpm unzip foo.zip rar e foo.rar 7z l foo.7z RAR and 7z have been included merely for completeness. Those formats are relatively uncommon on Linux and are typically associated with large collections of soundfonts and audio samples. Source code is also available in special RPM and DEB packages. These packages can be unpacked and compiled by their package management tools in one easy procedure, but the process lacks a configuration stage for user input. As we shall see, this pre-build configuration is an important part of the build sequence, one that should not be skipped if you want full control of the process. A word of warning: Occasionally you'll discover a badly-formed package such as one that dumps all its extracted files into the active directory, i.e. the package doesn't create its own top-level directory. It is always wise to check the package organization with a content view option (tar -t foo.package) before uncompressing the package. If no parent directory is indicated you'll need to make one to have a specified extraction target. Be sure to move the package into the new directory and then unpack it there. The Build Manager Okay, you've downloaded some source code and you're ready to compile it. Before you can do so you'll need a set of tools that assist you in the configuration process and manage the compiler's interaction with the sources. The traditional Linux toolchain includes the GNU autotools (automake, autoconf, and libtool), but other popular utilities include Scons, the cmake system, premake, and the recent waf tools. Software built with the Qt graphics libraries usually require a run of the qmake utility, followed by use of the GNU autotools' make tool. About Dependencies Dependencies are software packages that are absolutely required in order to compile the target package. System dependencies include items such as kernel headers, X11 libraries and headers, and graphics toolkits such as GTK and Qt. The libraries themselves are insufficient to build software, you will also need to install the development packages for all necessary libraries. Linux audio applications have some specific dependencies that are common to a wide variety of programs. You can expect to see requirements for the ALSA and JACK libraries and headers, the libsndfile library for soundfile I/O, and the development packages for the LADSPA and LV2 plugin systems. Other less critical packages include librdf (plugins metadata), liblo (a library for OSC functions), libfftw3 (Fast Fourier Transforms library), the Ogg/Vorbis libs (for OGG file support), and liblame (MP3 support). Outro, Part 1 In my next article we'll complete the build process. Check in again soon for the final episode. > and their basic unpacking > and their basic unpacking commands are as follows [...] > rar e foo.rar Better use: rar x foo.rar > 7z l foo.7z Perhaps you meant: 7z x foo.7z Thanks for the article. Building, and the art of Zen.... As one who has certainly mastered the gentle art of "User Error", any information that helps chaps like me to go further, with a little more confidence, and a little less angst, is a good thing. Thanks Dave. Alex. Why it not named like how to Why it not named like how to create hello world application ? Really, here is nothing about audio programming. hope part 2 will be much more interesting.. Author's reply You're correct, there's nothing here about audio programming, but you missed the point. The article is about what the title says, i.e. it's about *building* Linux audio applications from the source code. It's not about *programming* audio applications. I had some requests from Linux music people to explain how to compile applications from source code, and no, they don't want to read a book on the subject. However, as I explained in the article, they do want to acquire the basic skills needed to compile new applications that may not have reached the distro repos. Hopefully this article will assist them in acquiring these skills. Best, dp Similis sum folio de quo ludunt venti. Building Linux Applications Building Linux Applications would be a lot more honest as a title. The current title suggest that something special about building audio program is of interest, which is not.
http://www.linuxjournal.com/node/1008713
CC-MAIN-2015-48
refinedweb
2,710
53.21
Josh Bloch I was reading Effective Java again - its 99% applicable to .NET also. Now there is this whole section on making defensive copies and returning clones, all intended to prevent people from violating the invariants that your class is trying to enforce. I am 100,000% sure JB is absolutely correct in describing these vulnerabilities, but, wow, it seems like a TON of overhead both in terms of code and performance, for the remote case that someone is smart enough to try to mangle your code that way. Few of the books/examples/etc. that I come across suggest going to these lengths, so I am wondering, is JB's advice unduly coloured by his authoring ultra-widely used API's at Sun? Or do most OO programmers really do this? NetFreak Tuesday, September 28, 2004 Oh, also, I should add, this is a Fantastic book, my skepticism about this particular piece of advice notwithstanding. NetFreak Tuesday, September 28, 2004 I would agree that these types of defensive mechanisms are primarily a concern when exposing the API to the outsite world. In the .Net environment an example of an API that is "public" but not for reuse is the Context class in the Remoting namespace; the documentation for this class fully qualifies it with "this class is used internally by the .Net framework and is not intended to by used in your code". Of course people could still use this code, but at their own risk. This is in contrast to java.util.Hashtable that is a public API both technically and explicitly. BTW... Effective Java is easily the best book on API design I've come across. ~harris <a href=">Harris Reynolds</a> Wednesday, September 29, 2004 I agree completely. Its unfortunate that it appears at first glance to be Java specific. NetFreak Wednesday, September 29, 2004 Recent Topics Fog Creek Home
https://discuss.fogcreek.com/dotnetquestions/4403.html
CC-MAIN-2018-30
refinedweb
314
61.87
Wherever you are as you read this blog, I want you to take a moment and think back to how you went about your day, every small decision you consciously and unconsciously made, to get to where you are right now. Perhaps, just like every student ever, you got caught up in assignments till late last night and could barely make it to the last bus leaving for your college that’d just about get you to class in time were it not for your mother who screamed, “IT’S ALREADY 8:00 A.M YOUR CLASS STARTS IN 20 MINUTES!”, jolting you back to reality. Or maybe you’re a working professional and your boss declared, “It’s a slow day at work today fellas” so you’re just looking to brush up on your Deep Learning skills on the side. Or maybe you’re a hobbyist, just here for the fun of it. Whatever the case may be, and however you got to read this blog today, I want you to think if you would still be here reading and understanding any of this if: i. You could see everything but without the ability to interpret what you see. ii. You could hear everything around you but without the ability to understand any language at all. That seems quite harsh. But clearly, the answer is no. You wouldn’t get out of bed if your brain hadn’t interpreted whatever your mother yelled about it being 8:00 a.m and your class starting in 20, because you obviously wouldn’t know what any of that means or why that is a problem. For you, it would just be incongruous noise. You wouldn’t have made the decision to browse Deep Learning concepts if it weren’t for you understanding what, “a slow day at work” means. In, the same manner you wouldn’t be able to read or process any word of this blog because your brain wouldn’t know what a ‘word’ is in the first place. All your brain would see is white, with some black interspersed. You see, interpreting what you see, and what you hear, is something that we take for granted but cannot possibly survive without. It’s the same with a machine. In our previous two blogs, Deep Neural Networks with Keras and Convolutional Neural Networks with Keras, we explored the idea of interpreting what a machine sees. With this blog, we move on to the next idea on the list, that is, interpreting what a machine hears. In the Deep Learning world, we have a fancy term for this. We call it, Natural Language Processing. To learn more about Deep Learning, you can try out the “Practical Deep Learning with Keras and Python” online tutorial. The course comes with 3.5 hours of video that covers 8 vital sections. These include theory, installation, case studies, CNN, Graph-based models and so much more! This course is especially a helpful tool mainly if you are a beginner. Also, you can opt for a similar online tutorial “The Deep Learning Masterclass: Classify Images with Keras”. Like the above, this course requires no prior experience either. The tutorial brings you videos of 6 hours where it covers 7 impressive topics that are important in understanding the concept deeper. Natural Language Processing includes text processing (like the words in this blog), audio and speech processing. Before we discuss how we can enable a machine to interpret speech or process text, we need to understand some concepts. I recommend you go through our previous blogs in this series for a seamless read. Right. Consider a sentence from this blog itself. “In the Deep Learning world, we have a fancy term for this. We call it, Natural Language Processing. Natural Language Processing includes text processing (like the words in this blog), audio, and speech processing.” Now consider this modified sentence and note how it will still make absolutely perfect sense to you, “In the Deep Learning world, we have a fancy term for this. We call it, Natural Language Processing. It includes text processing (like the words in this blog), audio and speech processing.” The difference, of course, is just that I replaced Natural Language Processing with an ’It’. What do we learn from this? We learn that we interpret subsequent words based on our understanding of previous words. We could immediately understand that ‘It’ refers to Natural Language Processing. We don’t read one word, throw everything away, and then read another word and start thinking from scratch again. Our thoughts have persistence. For example, if you are developing an application that requires you to automatically calculate player runs in a game of cricket from the live telecast, you would first need your application to judge how many runs were scored (whether it was a 4 or 6 or a single) and then you would need to have the context from previous frames that would tell you WHICH PLAYER scored those runs so that you can add that many runs to the total for THAT PLAYER. It is difficult to imagine a conventional Deep Neural Network or even a Convolutional Neural Network could do this. This brings us to the concept of Recurrent Neural Networks. In the above diagram, a unit of Recurrent Neural Network, A, which consists of a single layer activation as shown below looks at some input Xt and outputs a value Ht. A loop allows information to be passed from one step of the network to the next. When we ‘unroll’ this loop architecture, we can see that basically, each unit passes a message to a successor, like a sequence. Past inputs, thus influences decisions made on the present outputs. This is the key that was missing. When the network begins to see things as ‘sequences’, we can immediately see that this solves our network’s initial problem of retaining or understanding ‘context’. A question then, which should crop up in your mind is, from how far back in the sequence can a Recurrent Neural Network hold a context? To reframe this, the question in focus is from how far back can past inputs, Xt, still influence the outcome of the present input activations Ht? Well, unfortunately, not so far back. But let’s understand everything with example because we believe examples are the best way to learn. Consider, we are trying to predict the last word in “when birds flap their wings they …”, we don’t need any further context, it’s pretty obvious that the next word is going to be fly. In such cases, where the gap between the relevant information and the place that it’s needed is small, Recurrent Neural Networks can learn to use past information. But if you consider a sentence as complex as the one we took as our example at the very beginning, “In the Deep Learning world, we have a fancy term for this. We call it, Natural Language Processing. It includes text processing (like the words in this blog), audio and speech processing.” Now if we were to predict the word after ‘and’ in the sentence above, we would first need to know what ‘It’ refers to. For this, we have to go even further back. It’s entirely possible for the gap between the relevant information and the point where it is needed to become very large as in our example. Unfortunately, as that gap grows, Recurrent Neural Networks become unable to learn to connect the information. This is why we need LSTMs. Because LSTM units are perfectly capable of ‘remembering’ long term dependencies in a given sequence. In fact, LSTM stands for Long Short Term Memory. Of course, to achieve this complex behavior of being able to ‘remember’ context in ‘memory’, an LSTM unit also looks quite overwhelming in comparison to our Recurrent Neural Network. The mathematical details are beyond the scope of this tutorial. A more detailed explanation of LSTMs will be covered in the coming blogs. For now, let us move on to the final and the most interesting part of this blog, the implementation. Implementation of LSTM. Step 1: Acquire the Data The data for this tutorial can be downloaded from here. Step 2: About the Data After downloading the data, which should be about 1.4 GB, you will notice 4 folders inside labeled: i. Male: Contains 3971 male audio files from different speakers (Male Training Set) ii. Female: Contains 3971 female audio files from different speakers (Female Training Set) iii. Male Test: Contains 113 male test audio from different speakers (Male Test Set) iv. Female Test: Contains 113 female test audio from different speakers (Female Test Set) The average duration of all audio files is about 5.3 seconds. Step 3: Extracting Features from Audio (Optional) Audio files are also one long sequence of numbers. But this sequence tends to be extremely long, almost 40,000 sequence numbers long, and because of our limited RAMs, we need to find more efficient ways to represent this sequence (audio). This is done by extracting the pitch of the audio along with something called the Mel Frequency Cepstral Coefficients (MFCCs) of the audio which is just a mathematical transformation to give the audio a more compact representation. Because we are dealing with audio here, we will need some extra libraries from our usual imports: import numpy as np import librosa import os import pandas as pd import scipy.io.wavfile as wav In case this throws you an import error, run the following line in your command prompt: pip install librosa pip install scipy Next, specify the paths of the Male and Female folders ON YOUR MACHINE in the variables accordingly: path_male = “C:\\Users\\Bhargav Desai\\Documents\\GitHub\\gender-classifier-using-voice\\Data Preprocessing\\Male\\”; path_female = “C:\\Users\\Bhargav Desai\\Documents\\GitHub\\gender-classifier-using-voice\\Data Preprocessing\\Female\\”; mfcc_col=[‘mfcc’+ str(i) for i in list(range(110))]; def main(path,gender): df = pd.DataFrame() print(‘Extracting features for ‘+gender) directory=os.listdir(path) for wav_file in directory: write_features=[] y, sr = librosa.load(path+wav_file) fs,x = wav.read(path+wav_file) print(wav_file) mfcc_features=get_mfcc(y,sr) write_features=[pitch]+mfcc_features.tolist()[0]+[gender] df = df.append([write_features]) df.columns = col df.to_csv(gender+’_features.csv’) def get_mfcc(y,sr): y = librosa.resample(y, sr, 8000); y = y[0:40000]; y = np.concatenate((y, [0]* (40000 - y.shape[0])), axis=0); mfcc=librosa.feature.mfcc(y=y, sr=sr, n_mfcc=10,hop_length=4000); mfcc_feature=np.reshape(mfcc, (1,110)) return mfcc_feature main(path_male,’Male’) main(path_female,’Female’) Although this part seems complicated, do not worry. It is okay if you do not understand this part of the code. It is completely okay to skip this part for now. All you need to remember is that this part of the code gives you a compact representation of the audio sequence for both the genders. The outcome of this should be two .csv files named male_features.csv and female_features.csv in the same directory containing a compact representation of our audio sequences where each sequence is of length 113! Consequently, we have successfully reduced our audio sequence length from 40,000 to 113! In case you encounter compatibility errors, please comment on your errors down below or directly download the feature extracted .csv files by clicking here. Step 4: Labelling & Preparing the Data for LSTM Model The outcome of the previous step was that we got compact representations of male and female audio sequences which might give you the impression that the data is ready. However, we are missing one critical element: Labels. Before we can train, we need to label our data so that our network can learn the difference between males and females from our data. We do this by first loading our data from the two .csv files we have obtained: os.chdir(‘/Users/bhargavdesai/Downloads’) maledf = pd.read_csv(‘male_features.csv’) femaledf = pd.read_csv(‘female_features.csv’) NOTE: Make sure that you pass the directory/folder where you have downloaded the .csv files from the above link in the argument to os.chdir() The output should look something like this: We can see that the label is ‘male’ or ‘female’ which is not in the form that we want. We need to change this to a numeric form which is either ‘1’ or ‘0’ Here’s how we do it: maledf.replace(to_replace=’male’, value=1) femaledf.replace(to_replace=’female’, value=0) You will have something like this printed out: We can see that ‘male’ has been replaced by ‘1’ and ‘female’ has been replaced by ‘0’ We will now split it into our standard X_Train and Y_Train variable format so that we are consistent with the other blogs in this Keras series: Male = maledf.replace(to_replace=’male’, value=1) Female = femaledf.replace(to_replace=’female’, value=0) X = pd.concat([Male, Female]) XTrain = X.sample(frac=1) YTrain = XTrain[‘label’] XTrain = XTrain.drop(columns="label") X_Train = XTrain.values Y_Train = YTrain.values The pd.concat() function joins two DataFrames, X.sample(frac=1) randomly shuffles the rows of the joined DataFrame and the XTrain.values function converts the DataFrame to a Numpy array X_Train. Note: Here X_Train is our training set and Y_Train are the labels that we separated using the XTrain[‘label’] function. Step 5: Building an LSTM Keras Model We have come to the conclusion of this blog where we will show you how to create an LSTM model to train on the dataset we have created. We are now familiar with the Keras imports and Keras syntax. But we’ll quickly go over those: The imports: from keras.models import Model from keras.models import Sequential, load_model from keras.layers.core import Dense, Activation, LSTM from keras.utils import np_utils Then we create a Keras Model object by: model = Sequential() Then we can assemble our Keras LSTM model by: model.add(LSTM(32, return_sequences=True, input_shape=(112, 1))) model.add(LSTM(6, return_sequences=True)) model.add(LSTM(8, return_sequences=False)) model.add(Dense(1, activation = ‘sigmoid’)) model.compile(optimizer = ‘adam’, loss = ‘binary_crossentropy’, metrics=[‘accuracy’]) model.summary() model.fit(X_Train, Y_Train, epochs = 20, batch_size = 32) As soon as you run this code, you will get an error. The error will read: ValueError: Error when checking model input: expected lstm_1_input to have 3 dimensions, but got array with shape (7942, 112) This happens because of the LSTM implementation in Keras expects sequences from you as input. A sequence has an additional dimension of ‘time’ in addition to the number of samples and features that are called ‘timesteps’ in Keras. To rectify the error, just add this line of code before you start building the model: X_Train = np.reshape(X_Train,(7942, 112, 1)) Here, our number of ‘timesteps’ which is basically how long our sequence is in time is equal to 112 with the number of samples 7942. The result of running the code after the modification will show you a screen like this: It can be seen that the accuracy is increasing consistently (~81% in just 20 epochs!) and the loss is also going down. This indicates that our LSTM network is indeed learning how to differentiate between a male voice and a female voice! On a concluding note from our side, we’d like to ask our inquisitive readers to see how much the accuracy goes up by when you train it for more epochs. At Eduonix, we push our students to go that extra mile so we’d also like to encourage all our readers here to see if they can use the code used in this tutorial to record their own audio and see if they can get our model to predict your gender correctly!
https://blog.eduonix.com/artificial-intelligence/recurrent-neural-networks-lstms-keras/
CC-MAIN-2021-17
refinedweb
2,632
64.2
Bummer! This is just a preview. You need to be signed in with a Basic account to view the entire video. Doubles2:54 with Jeremy McLain We'll learn about the *double* type: a numeric data type used to store decimal values. Clear, compile, and run: clear && mcs Program.cs && mono Program.exe Start REPL: csharp Quit REPL: quit Code: using System; namespace Treehouse.FitnessFrog { class Program { static void Main() { double runningTotal = 0; bool keepGoing = true; while(keepGoing) { // Prompt user for minutes exercised Console.Write("Enter how many minutes you exercised or type \"quit\" to exit: "); string entry = Console.ReadLine(); if(entry.ToLower() == "quit") { keepGoing = false; } else { try { // Add minutes exercised to total double minutes = double; } catch(FormatException) { Console.WriteLine("That is not valid input."); continue; } // Display total minutes exercised to the screen Console.WriteLine("You've entered " + runningTotal + " minutes."); } // Repeat until user quits } Console.WriteLine("Goodbye"); } } } - 0:00 There are a couple more things we can do to make our app more user friendly. - 0:04 To demonstrate, let me run the program again. - 0:07 What happens if I type quit with the capital Q here. - 0:10 Is that what you'd expected would happen? - 0:14 Yes, technically in our instructions to the user we said to type quit - 0:18 in all lowercase. - 0:20 Part of creating a user friendly app is being as accepting as possible - 0:24 of what the user wants to do, - 0:26 instead of forcing them to conform to the rules of the program. - 0:29 I think we can do better here. - 0:31 Let me try something else. - 0:33 What if the user wanted credit for every second of exercise that they did and - 0:37 entered, say, 20.5 minutes? - 0:40 This is probably not what the user would expect, - 0:42 and it would probably make them a little frustrated, right? - 0:46 These two problems have fairly easy fixes. - 0:49 In order to fix them, we'll learn about a new method in the string class and - 0:53 another numeric data type. - 0:55 First off, the issue of typing in Quit with a capital Q. - 0:59 The typical way to deal with this issue is to convert what the user provides - 1:03 into something that we expect. - 1:05 So for this, what if we just change all of the upper case letters in the input string - 1:10 to lower case. - 1:11 And then compare that with to our all lower case quit. - 1:15 Sounds good to me. - 1:16 There's a method for doing just this. - 1:18 It's called ToLower. - 1:20 Now even if the user capitalizes any or - 1:22 all of the letters in quit we'll still be able to detect that they typed in quit. - 1:27 Now for the issue with the decimal numbers. - 1:29 If we look at the code, we can see that we're getting this - 1:32 message because int.parse is throwing the format exception. - 1:36 Which means the parse method doesn't know how to convert the decimal number we gave - 1:40 it in to an integer. - 1:42 The issue is int.parse can only convert integers. - 1:46 Integers can't have decimals in them. - 1:49 Decimals are actually more tricky for computers to deal with. - 1:52 It prefers to work with integers, so whenever we can use integers, we should. - 1:56 And that will actually make the code run slightly faster. - 1:59 Speed is not an issue in our program, so - 2:02 we can use decimals instead of integers if we want. - 2:05 And switching our code to using decimals is actually very easy. - 2:08 There's another variable type that can store decimals called double. - 2:12 You might be wondering what double has do with decimals. - 2:16 Don't blame me for the confusing naming. - 2:18 There's a very technical reason for - 2:19 why it's called double that I don't want to get in here. - 2:22 Suffice it to say that it can store decimal numbers. - 2:25 So, now we can just swap everywhere we see int with double. - 2:30 The double class, just like int, also has a parse method but - 2:34 it knows how to deal with decimals. - 2:36 Now let's compile and run our program to see how it works. - 2:40 We can enter 20.5 or any decimal number such as 3.1415926. - 2:50 We can also enter Quit, with a capitol Q. - 2:53 Sweet.
https://teamtreehouse.com/library/doubles
CC-MAIN-2018-34
refinedweb
792
75.71
I was suggested yesterday to try PDL, here's the built of the fractal structure (diagonal 4 out of 4x4 plan +=1): #!/usr/bin/perl -w use strict; use PDL; use Algorithm::Loops qw(NestedLoops); my $element = pdl ([1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]); my $tmp = pdl ($element); my @depth = qw (2 3 4 5 6 7 8); foreach my $depth (@depth) { my $same = pdl ($tmp); my $fractal = zeroes 4**$depth,4**$depth; NestedLoops([([0..3])x2],sub{ my ($x,$y) = (@_); my ($a,$b) = ($x*(4**($depth-1)),$y*(4**($depth-1))); my ($c,$d) = ($a+((4**($depth-1))-1),$b+((4**($depth-1))-1)); my $square = slice $fractal, "$a:$c,$b:$d"; $square += $same; },); for my $coord (0..3) { my $a = $coord * (4**($depth-1)); my $b = $a + ((4**($depth-1))-1); my $square = slice $fractal, "$a:$b,$a:$b"; $square += 1; } $tmp = pdl ($fractal); $outFractal = $tmp; } [download] Frank The problem is, that although the counts at each position will be a maximum of depth, meaning that you can get away with using a single byte per position upto depth=255, the size of the matrix grows (hyper?) geometrically. That means that even using a single byte per position, with no further overhead, by the time you reach depth=8, you already require 4GB of storage. By the time you reached level 16, the storage requirement is 16e18 bytes, which according to this table is roughly 3 times the 'All words ever spoken by human beings': depth: X x Y required m +emory: 1: 4 x 4 == 16 _b 2: 16 x 16 == 256 _b 3: 64 x 64 == 4 Kb 4: 256 x 256 == 64 Kb 5: 1024 x 1024 == 1 Mb 6: 4096 x 4096 == 16 Mb 7: 16384 x 16384 == 256 Mb 8: 65536 x 65536 == 4 Gb 9: 262144 x 262144 == 64 Gb 10: 1048576 x 1048576 == 1 Tb 11: 4194304 x 4194304 == 16 Tb 12: 16777216 x 16777216 == 256 Tb 13: 67108864 x 67108864 == 4 Pb 14: 268435456 x 268435456 == 64 Pb 15: 1073741824 x 1073741824 == 1 Eb 16: 4294967296 x 4294967296 == 16 Eb 17: 17179869184 x 17179869184 == 256 Eb 18: 68719476736 x 68719476736 == 4 Zb 19: 274877906944 x 274877906944 == 64 Zb 20: 1099511627776 x 1099511627776 == 1 Yb 21: 4398046511104 x 4398046511104 == 16 Yb 22: 17592186044416 x 17592186044416 == 256 Yb 23: 70368744177664 x 70368744177664 == 4 2^90b 24: 281474976710656 x 281474976710656 == 64 2^90b 25: 1125899906842624 x 1125899906842624 == 1 2^100b 26: 4503599627370496 x 4503599627370496 == 16 2^100b 27: 18014398509481984 x 18014398509481984 == 256 2^100b 28: 72057594037927936 x 72057594037927936 == 4 2^110b 29: 288230376151711740 x 288230376151711740 == 64 2^110b 30: 1152921504606847000 x 1152921504606847000 == 1 2^120b 31: 4611686018427387900 x 4611686018427387900 == 16 2^120b 32: 18446744073709552000 x 18446744073709552000 == 256 2^120b [download] But if you think about it, even if you could calculate the data at say depth 8, then you would need a screen 70 feet square to view it. As with all fractals, as you 'zoom' in, you only want to calculate the data required to produce some small subset of the total picture: say 1280x 1024. Because you want the ordered positions in each row, you would have to calculate a 'slice' of the data, but still far less than doing the whole thing. At depth 1, the value for any given X,Y position is simply: $p = X == Y ? $depth : $depth - 1; At level 2, the value for any given X,Y position is slightly more complicated: if( X == Y ) { return depth; } elsif ( ( X,Y ) is in a 4x4 block on the major diagonal ) { return $depth - 1; } else { ## Move the 4x4 block to the origin and treat as for depth -1 X %= 4; Y %= 4; depth--; recurse; } [download] This is a recursive data structure, and calculating the value for any given (X,Y,depth) combinaton can be done recursively, quickly and without requiring a lot of memory. The following routine is close (but no cigar!): #! perl -slw use strict; $|++; our $DEPTH ||= 3; sub fract2D { use integer; my( $x, $y, $depth ) = @_; if( $x < 16 and $y < ) { ## A block on the major diagonal return $x == $y ? $depth : $depth -1; } elsif( $depth > 1 ) { return fract2D( $x % 4**$depth, $y % 4**$depth, $depth -1 ); } else { return fract2D( $x % 4**$depth, $y % 4**$depth, $depth ); } } for my $depth ( $DEPTH ) { for my $y ( 0 .. 4**$depth-1 ) { my $c = 0; for my $x ( 0 .. 4 ** $depth -1 ) { printf +( ( ++$c % 4 ) == 0 ? " %2d " : " %2d" ), fract2D( $x, $y, $depth ); } print +( $y % 4 ) == 3 ? "\n" : ''; } print ''; } [download] But I seem to have left my tuits in my other head, and its washday. Try this. It's correct at levels 1, 2, & 3, and Ithink it is correct for all levels, but it gets harder to discern. I found this really tough to get right, whether through recursion or iteration. I'd given up and moved on before the pattern dawned on me. I think a mathematician may be able to reduce this to a formula, maybe involving some kind of polynomial, but it's beyond my abilities. #! perl -slw use strict; $|++; our $DEPTH ||= 3; sub f{ use integer; my( $x, $y, $depth ) = @_; my $bsize = 4**( $depth-1 ); { if( $x == $y ) { return $depth; } elsif( $x/4 == $y/4 ) { return $depth-1; } elsif( $x/$bsize == $y/$bsize ) { $x %= 4; $y %= 4; --$depth; redo; } else { $x %= $bsize; $y %= $bsize; --$depth; redo; } } } for my $depth ( $DEPTH ) { for my $y ( 0 .. 4**$depth-1 ) { my $c = 0; for my $x ( 0 .. 4 ** $depth -1 ) { printf +( ( ++$c % 4 ) == 0 ? " %2d " : " %2d" ), f( $x, $y, $depth ); } print +( $y % 4 ) == 3 ? "\n" : ''; } print ''; } __END__ [download] I tried also to get your code working, and could'nt. I verified level 4 after your update and it does not yet match - although close ! (if you compare w/ output from PDL fractal code). I'll meet a mathematicien and if I find something better, I'll post in this thread. I'm also looking at simpler solutions using nDeep arrays. Thanks very much, Try these. fc() is just an Inline C version of f(). I'm pretty sure that they are now correct, but you should verify them yourself. #! perl -slw use strict; use Inline C => << '__C__', NAME => "_627288"; # => CLEAN_AFTER_BUILD +=> 0; #include <stdio.h> int fc( double x, double y, int d ) { double bsize = pow( 4, ( d-1 ) ); if( x == y ) return d; else if( (int)( x / 4 ) == (int)( y / 4 ) ) return d-1; else if( (int)( x / bsize ) == (int)( y / bsize ) ) return 1 + fc( fmod( x, bsize ), fmod( y, bsize ), d-1 ); else return fc( fmod( x, bsize ), fmod( y, bsize ), d-1 ); } __C__ sub f{ my( $x, $y, $d ) = @_; my $bsize = 4**($d-1); if( $x == $y ) { return $d } elsif( int( $x / 4 ) == int( $y / 4 ) ) { return $d-1; } elsif( int( $x / $bsize ) == int( $y / $bsize ) ) { return 1 + f( $x % $bsize, $y % $bsize, $d-1 ); } else{ return f( $x % $bsize, $y % $bsize, $d-1 ); } } [download] Using this I have produced plots of 1000x1000 chunks upto level 31 successfully. At that point the coordinates get so large that they blow the limits of doubles. I'm also fairly sure that you are loosing precision long before level 31. At level 16 everything appears to check out. I don't think any single set of 20 lines of code has ever (in the best part of 30 years), given me as much trouble to wrap my brain around as this! I verified level 4 after your update and it does not yet match - although close ! Gah. I See where this is headed. I add another ifelse clause to get level 4 right, and then another for level 5... This has to be possible recursively! It's amazing how something so complex evolves out of such a simple process. It's also amazing how something with so many symmetries and essentially only one dissymmetry could be so hard to generate. Part of the problem is the shear size the things grow to so rapidly. I wrote a simple png plotter that produces a png of a 1000x1000 chunk and allows you to 'move' around and zoom in--very slowly. But as the level increases, it becomes impossible to keep track of where you are, so it doesn't help much. Deep frier Frying pan on the stove Oven Microwave Halogen oven Solar cooker Campfire Air fryer Other None Results (323 votes). Check out past polls.
http://www.perlmonks.org/?node_id=627622
CC-MAIN-2016-26
refinedweb
1,407
70.57
WCF method giving 400 Bad Request in GET / POST method I recently created WCF and m faced 400 req errors when I try to hit a URL from the browser. my service contract looks like [string GetUsers();] [ ] I have already made an entry in webconfig as <serviceMetadata httpGetEnabled="true"/> the url I click in the browser is here is the webconfig part: <system.serviceModel> <services> <service name="AceWebService.AceWebService" behaviorConfiguration="AceWebService.AceWebServiceBehavior"> <!-- Service Endpoints --> <endpoint address="" binding="wsHttpBinding" contract="AceWebService.IAceWebS="AceWebService.AceWebS> </system.serviceModel> Have referenced all the questions available here on stackoverflow .. not getting any help .. please suggest changes. Thnx +3 source to share 2 answers First, use WebGet for GET requests. Second, get the service running without the service contract interface, and then when it is running, translate the contract into the interface. this works for me: [public class HelloService { [ ] [ ] public string HelloWorld() { return "Hello World!"; } }] [ ] 0 source to share
https://daily-blog.netlify.app/questions/1892516/index.html
CC-MAIN-2021-21
refinedweb
153
50.02
Introduction: Humane Multi-Mouse Trap Zapper - No Pain Instant Death Let me start out by clarifying the conflict between "Humane" and "Mouse Zapper". I have a major mouse pest problem where they eat all my dog and parrot food every night - and many of them . I tried purchasing several mouse traps which all face different drawbacks: 1. The sticky pad - the mice glue themselves and for hours struggle to get free exhausting themselves to death and die of hunger. 2. The pipe trap - locks them in and then they eventually suffocate after hours - Very bad! 3. The box trap - sometimes cuts their tails when it shuts and what do I do with them then? 4. The standard smack trap - fast death (50% of the time) but only gets one mouse . So .. I devised this multi-mouse quick death trap using an Arduino which zaps them in the head for 2 sec killing them instantly with no pain (same as done on larger animals human eat ). Step 1: How It Works.... Here is the back side (end) of the mouse path .. When it reaches the bate it is sensed by an IR sensor which the Arduino senses and activates the zapper Step 2: The Trap Door In this picture you can see the trap door activated by a standard mini servo located under the floor.. See details in picture Step 3: Video I hope the video of the zapper working with run properly .. I uploaded an MP4 from my cell phone.... Instructable does not embed stream video - you need to DL it first - sorry. Attachments Step 4: Source Code /* Humane Mouse Zapper - Moris.Zen */ #include <Servo.h> Servo servo1; // pins int ledPin = 13; // LED connected to digital pin 13 int AnalogNoseSensorPin = A0 ; // Analog Pin 0 int relayControlPin = 50; int servoPin = 15; //Declerations int NoseLocationVal = 0; // value of the led sensor // Constants const int DebugSerialSpeed = 9600; void setup() { servo1.attach(servoPin); pinMode(relayControlPin,OUTPUT); pinMode(ledPin, OUTPUT); // sets the digital pin as output pinMode(AnalogNoseSensorPin,INPUT); // throttle handle Analog in 0 Serial.begin(DebugSerialSpeed); } void loop() { digitalWrite(ledPin, HIGH); // sets the LED on delay(100); // waits for a second digitalWrite(ledPin, LOW); // sets the LED off delay(100); // waits for a second servo1.write(150);// close trap door pinMode(servoPin,INPUT);//silence Servo NoseLocationVal = analogRead(AnalogNoseSensorPin); // Optic sensor if (NoseLocationVal <50) {//Check if mouse is inside digitalWrite(relayControlPin,LOW); // Zap it delay(1000);// Zap for 1 Sec digitalWrite(relayControlPin,HIGH); // Stop Zap pinMode(servoPin,OUTPUT); // Activate Servo servo1.write(20);// Open Trap Door delay(2000);// wait for mouse to fall servo1.write(150);// close trap door delay(1000);// wait for trap door to close } else digitalWrite(relayControlPin,HIGH); // No Shock //Serial.println(NoseLocationVal); } Participated in the Epilog Challenge V Participated in the Jury Rig It! Contest 1 Person Made This Project! Recommendations 7 Comments 2 years ago Can you give me the schematics? 4 years ago What did you use for the HV source? 8 years ago on Introduction Would it be fair to say that we don't really know if the mouse will feel pain or not? Reply 5 years ago Well - I would assume not as it is very fast and direct to the head . may be 50ms or so . All the other traps are very painful . 5 years ago Short update .. I fried my Arduino due to the high voltage from the Zapper . Sorry I dont have the schematics but pritty simple to figure out . 6 years ago on Introduction The closest equivant commercial product is the Victor Multi Kill Electronic Mouse Trap, which costs $100. Their cheapest, which will only do one mouse, is $20. But, the flashing LED that shows a kill, flashes slow enough that it is a pain to have to stare one down to check if it has a mouse in it. To avoid making a custom board, and avoid the big breadboard look, does any one know if there is an Arduino shield that will control a high voltage to kill the mouse? I wonder if the power supply to those electro-luminescent wires (a.k.a. Cold Neon) would be appropriate for powering the kill circuit? 6 years ago on Introduction Could you please upload the schematics! Thanks!
https://www.instructables.com/Humane-Multi-Mouse-trap-Zapper-No-pain-instant-d/
CC-MAIN-2021-21
refinedweb
707
63.09
Another. Advertising However, Now even using PreconditionerJacobi can not remedy the issue even if it works for very few initial value and boundary conditions. On Sunday, October 16, 2016 at 10:39:49 AM UTC-5, Daniel Arndt wrote: > > In case there is an error with Trilinos, what is it? > > Am Sonntag, 16. Oktober 2016 17:27:26 UTC+2 schrieb Daniel Arndt: >> >> Hamed, >> >> >>>>> It still works with Petsc and Trilinos is not implemented at all. I >>>>> appreciate it if you could let me know what changes should be made in >>>>> step-40 to make it work with Trilinos. >>>>> >>>> What exactly, do you mean by that? So you have both PETSc and Trilinos >> installed and step-40 works. Are you saying that PETSc objects are used >> even if you use >> "using namespace ::LinearAlgebraTrilinos;" ? How did you find out? >> >> Best, >> Daniel >> > --.
https://www.mail-archive.com/dealii@googlegroups.com/msg01322.html
CC-MAIN-2017-51
refinedweb
140
73.47
i'm not going to post the entire code but i'll post the relevant part. the situation is i have a .txt file (input.txt), and the program reads that and counts the characters in it and displays the number of characters, spaces, digits, etc. but i also want it to display the actual text from the file. is there a way to have it display the file, without actually copying and pasting all of the text into the compiler? so instead of cout<<"1000000 words" cout<<input.txt something like that. so this is the first part of the code that opens the file. how do i make the program display the text when i run it? Code:#include <iomanip> #include <iostream> #include <fstream> #include <ctype.h> using namespace std; bool myIsAlpha( char ch ); bool myIsDigit( char ch ); bool myIsUpper( char ch ); int countPunct = 0, //declaring int variables to be used. countAlpha = 0, countUp = 0, countWhite=0, countLow = 0, countDig = 0, countSpace = 0, totalChar; char ch; //declaring ch as char int main() { ifstream inputFile; //opening the input file and if it fails to open, displaying and error message to the user and exiting the program inputFile.open( "input.txt" ); if( inputFile.fail() ) { cout << "input.txt failed to open"; exit( -1 ); }
http://cboard.cprogramming.com/cplusplus-programming/124446-how-display-text-file.html
CC-MAIN-2015-27
refinedweb
212
75.81
Hey, Scripting Guy! How can I get the command window to stay open when I right-click a .VBS file and choose Open With Command Prompt?? — BB Hey, BB. You know, according to BB’s email signature, he’s 9 years old. If that’s true, well, that’s absolutely amazing. A 9-year-old who knows VBScript? At age 9 the Scripting Guys could barely feed themselves or tie their own shoes. Which, in their case, simply means that the more things change the more they stay the same. Of course, we have to admit that, just because BB says he’s 9 years old doesn’t mean he really is 9 years old. After all, the Scripting Editor continues to insist that she’s 23 years old. But how, then, can she explain the photographs that clearly show her attending Franklin Delano Roosevelt’s Inauguration Ball in 1937? The truth is, she can’t. Instead, she just throws things any time the subject is broached. Anyway, we can’t be sure that BB really is 9 years old, but we’ll try to figure out a way to verify that, maybe by asking him a question that only a 9-year-old would know the answer to. You know, like this one: name all four Ninja Turtles. Good point; after all, even the Scripting Guy who writes this column knows the answer to that: Leonardo, Donatello, Michelangelo, and Raphael. And that’s without using the Internet to look up the answer. Of course, whether BB is really 9 years old or not doesn’t matter; either way he has a good question here. If you right-click a .VBS file one of the options available to you on the context menu is this: Open With Command Prompt. If you choose that option something seems to happen: typically a command window will briefly flash onscreen and then just as quickly disappear. And that’s it. Why doesn’t the script actually run, and why doesn’t the command window stay open? Let’s take the first question first. (Kind of an unusual approach for Hey, Scripting Guy!, isn’t it?) As it turns out, the script actually does run; it’s just that many VBScripts execute so quickly that you don’t realize that anything happened. (About the same time the command window appears onscreen the script has completed its tasks and it’s now time for the command window to close.) Here’s one way to verify this. Create a simple script that does nothing more than display a message box: Msgbox “Hey” Now, right-click this .VBS file and choose Open With Command Prompt. You should see the message box, indicating that the script really did run after all. So then why didn’t the command window stay open? That’s easy: by default the command window tends to do its thing and then disappear. For example, open the Run dialog box, type ipconfig, and then press ENTER. You’ll see a command window open and – if you’ve got good eyesight – you might even see that Ipconfig.exe has run. But the very instant that Ipconfig finishes, the command window automatically closes. That’s why you’re usually instructed to first open a command window and then run a script or command-line tool. If you don’t the script or tool will run, but you’ll probably never see the output. Is that a problem, having to open a command window and then run the script from within that window? Of course it is; after all, that pretty much defeats the whole idea of having an Open With Command Prompt shortcut in the first place. But we have a good news for you, BB: if you don’t like the way the Open With Command Prompt shortcut works then you can go ahead and change the behavior of this shortcut. How do you do that? Good question; might we suggest using a script like this one: Const HKEY_CLASSES_ROOT = &H80000000 strComputer = “.” Set objRegistry=GetObject(“winmgmts:\\” & strComputer & “\root\default:StdRegProv”) strKeyPath = “VBSFile\Shell\Open2\Command” strValueName = “” strValue = “cmd.exe /K cscript.exe ” & Chr(34) & “%1″ & Chr(34) & ” %*” objRegistry.SetExpandedStringValue _ HKEY_CLASSES_ROOT,strKeyPath,strValueName,strValue As it turns out, the behavior of the Open With Command Prompt shortcut is dictated by a setting in the registry (HKEY_CLASSES_ROOT\VBSFile\Shell\Open2\Command). By default, this setting simply calls the CScript or WScript script engine (depending on your preferred settings), passing along the file path as a command-line argument: %SystemRoot%\System32\CScript.exe “%1” %* If we want the command window to stay open any time we run a script using this shortcut all we have to do is modify the registry setting. How do we do that? We were just about to get to that. If you take a look at our script you’ll see that we start things off by defining a constant named HKEY_CLASSES_ROOT and setting the value to &H80000000; we’ll use this constant to tell the script which registry hive we want to work with. We then connect to the WMI service on the local computer, binding to the StdRegProv class. (Which, we should point out, resides in the root\default namespace.) After connecting to the WMI service we then assign values to three variables: Let’s talk a little bit about strValue. As we noted earlier, the command window tends to open up, do its thing, and then close. However, there is a way to keep the command window open after it completes its appointed tasks: you just have to use the /K (keep) switch when opening the window. And that’s exactly what we’re doing here. Notice that, this time, we aren’t directly starting Cscript.exe. Instead, we’re opening up a command window (Cmd.exe) and using the /K switch to ensure that the window stays open. That’s what this portion of our code is for: cmd.exe /K We then pass the name of the script host (CScript.exe) and the file path as additional command-line arguments for Cmd.exe. In other words, any time someone selects Open With Command Prompt we’re going to open a persistent version of the command window, then tell the command window that – when it opens – it needs to run CScript.exe and the selected .VBS file. Confusing? Yes, it is, at least a little. And the syntax of our command – which includes the function Chr(34), something we use to insert double quote marks into the string value – doesn’t help much. The long and short of it, however, is that strValue ends up being assigned this value: cmd.exe /K cscript.exe “%1” %* And, believe it or not, that’s the command that will “fix” the Open With Command Prompt shortcut. In fact, after assigning values to our variables all we have to do is call the SetExpandedStringValue method (because our registry value happens to have the REG_EXPAND_SZ data type) and we’re done: objRegistry.SetExpandedStringValue _ HKEY_CLASSES_ROOT,strKeyPath,strValueName,strValue Now try right-clicking a .VBS file and selecting Open With Command Prompt. This time a command window should open, the script should run, and – upon completion – the command window should stay open. Pretty sweet, huh? Again, BB, if you really are 9 years old the Scripting Guys are impressed. Or at least the Scripting Guy who writes this column is impressed. After all, was the Scripting Guy who writes this column fooling around with VBScript when he was 9? No he wasn’t, primarily because neither VBScript nor the command prompt had been invented way back then. In fact, come to think, the number 9 hadn’t even been invented yet back when the Scripting Guy who writes this column was a kid. Wow …. Hi Scripting Guy. At this moment I am struggling with my PC and my wireless arrangement, trying to make it work without leaving the ethernet cable plugged in to the Modem. My computing knowledge is that of, I imagine, a two year old and my patience is on the wane. Soon, a brush and shovel may be required to remove all the bits that could so easily litter the floor. While my wrestling was at its height, a message came up from AOL telling me that ny buddy list is kaput and I should reload the AOL disc. Well, I have no chance of finding that so I searched for info and somebody suggested to another with the same problem to type in, ipconfigure .all, so I tried it. The command box appeared so very briefly that I had no chance to see what came up. Is it possible that you may be able to explain to a totally ignorant 60 plus year old how to cure the disappearing box trick? Thanks in advance and if you can do this I shall be eternally grateful. Regards, BuiLderBoY Enter this key in Registry: Windows Registry Editor Version 5.00 [HKEY_CLASSES_ROOT*shellCMD Prompt Here] [HKEY_CLASSES_ROOT*shellCMD Prompt Herecommand] @="cmd.exe /d cd %1" and then you can open a persistent cmd window from context menu (right click) in any folder Works in Windows XP … and enter in the opened cmd window with drag-and-drop any .exe file from that folder the window will stay open after run the program
https://blogs.technet.microsoft.com/heyscriptingguy/2007/04/24/how-can-i-get-the-command-window-to-stay-open-when-i-right-click-a-script-and-choose-open-with-command-prompt/
CC-MAIN-2017-09
refinedweb
1,566
73.07
Investor returns for alternative funds. Don't expect to get pulled over or sent to detention for this offense, but, make no mistake, investors are constantly putting their financial well-beings at risk. The culprit of this little-understood crime can be traced back to performance chasing, or investing in an asset class (or fund) that has recently done well (also see Avoiding Psychological Traps). At Morningstar, our research suggests that it is not uncommon for investors to buy and sell funds at inopportune times, which results in inferior returns for investors compared with a fund’s published total returns. To better gauge the real experience of average investors, Morningstar introduced Morningstar Investor Returns in 2006. The data point has been serving as a useful tool in fund analysis ever since. Calculating Investor Returns In contrast to total return, which simply measures the change of a fund’s net asset value over a given period of time, the Morningstar Investor Return takes into account a fund’s total net assets in the calculation. For example, suppose a fund’s one-year total return is 10% but the majority of the gains (for example, 8%) come from the first three months when the fund only has a small asset base. After more assets flow in, the fund has only mediocre performance for the remainder of the year. In this case, the fund’s investor return will be much lower than 10% for the year, which suggests that the average investor poorly timed his investment. A fund’s investor returns can also be higher than its total return (although this is very rare). Higher investor return is a sign that investors manage to buy low and sell high during the measured period. Overall, investor return is representative of a typical investor’s experience. Narrow gaps between investor returns and total returns show that the majority of shareholders buy and hold and are able to capture most of the fund’s returns. Wide gaps often suggest that investors poorly time their entry and exit of the fund, chase performance, or fail to stay with the fund for a reasonable period of time. Investor Returns for Alternative Funds Morningstar often cites investor return figures as evidence that investors tend to time their purchases and sales of traditional stock and bond funds poorly. Do investors handle alternative mutual funds better? Our research shows that alternative mutual funds have much larger investor return gaps compared with long-only stock and bond funds. In other words, a typical alternative mutual fund investor has a worse investment experience than a traditional stock- or bond-fund investor. Over the past five years (as of May 31), investor returns for alternative funds have lagged total returns by an annualized 2.25%. The average annualized total return of alternative mutual funds over the past five years is 0.21%, but unfortunately, investors on average actually lost 2.04% (annualized) in their alternative investments because of their poor timing. Over the past 10 years, the gap is slightly smaller, but it still stands at 2.12%. In other words, history shows that a typical investor makes 2.12% less (annually) than the fund’s total return in the alternative space. These figures are abysmal given that investors exhibit better track records at allocating to traditional funds. The five-year gap between investor returns and total returns is 1.27% and 1.26% for the large-cap blend category and short-term bond category, respectively. Over 10 years, the numbers decrease to 0.39% and 1.02%, respectively. Using Diamond Hill Long-Short The reason is that the fund put on an astonishing show between 2003 and 2006, returning 19.5% annually, when the fund had only $302 million by the end of 2005. Massive assets flew in between 2006 and 2008 (fund’s total assets increased more than sixfold by the end of 2008 to $2 billion), but the fund’s performance has been middling since 2007. The majority of the investors did not capture the fund’s glory days between 2003 and 2006. As a result, there is a whopping 7.19% gap between investor returns and total returns for this long-short equity fund over the past 10 years.
http://www.morningstar.com/advisor/t/58991057/investors-behaving-badly.htm
CC-MAIN-2015-27
refinedweb
709
53.41
By continuing to use this site you agree to the use of cookies. Please visit this page to see exactly how we use these. I recently had trouble to run the existing editor plugin with the 3.5.0 release.The reason seems to be that all the AGS .net assemblies were changed to strong names. This is a breaking change, as the plugin compiled with an existing assembly (e.g. the plugin references AGS.Types) with a weak name is not compatible with the new one compiled with a strong name It was to get a namespace for the settings class, to differentiate between builds which are (effectively) portable and the actually releases where settings need to persist between versions. As long as the plug-in isn't mixed assembly, you can retrospectively sign it by decompiling and recompiling with a generated key. Alright, this looks like another consequence that was not thought of beforehand. There is a number of editor plugins, Speech Center is one of the most popular ones, and there is at least one other I know - Rulaman's Font Editor. Does this means we need plugin author to come by and recompile the plugin? (idk what are other editor plugins in use)From now on writing editor plugin was relatively simple, now if someone does that will have to know to do this signing too. And also, does not this mean that there should be two version of each plugin from now on - for old Editor and for the new one? May there be an alternate solution to signing, like using some third-party settings library instead of Microsoft's one?I remember you've mentioned this library, will it work without strongname? The strongname issue is mentioned in its readme, but it's not stated explicitly. For an external interface though, I would need to test it. Is there a plugin stub somewhere that I can test with? Signing. Quote from: SpeechCenter on 11 Sep 2018, 02:03Signing.Do you also see an issue referencing a specific version of irrKlang? It looks like there are some options to redirect reference loading, but with (what I think is) the newest version of the SpeechCenter plugin the first error I get is trying to load irrKlang rather than AGS.Types.Just to confirm, is this the latest version? I think the problems are generally in terms of deployment, where the program is delivered using ClickOnce and installed per user. In that case you do end up with multiple installations, so using a strongname would override where the settings are loaded from. So the main purpose of the library is to just override the settings path (manually), so that you can store settings where you like. Does the strongname signing give any other benefit for AGS rather than making settings system have consistent path? Maybe it is best to open an issue on GitHub, since future changes to the plug-in system are probably determined by the choice made here. Am I correct guessing that this will substitute the unsigned AGS.Types demanded by plugin with signed one? Could you also elaborate a little on this, what changes to plugin system will be determined by this (or how)? Just want to be sure that I understand the situation well. Page created in 0.222 seconds with 570 queries.
https://www.adventuregamestudio.co.uk/forums/index.php?topic=56457.msg636595015
CC-MAIN-2021-21
refinedweb
561
63.8
I have to create a program which generates 10000 random numbers between 0 and 1 using the Math.random(). We then have to display the largest and smallest numbers, and the average of all the numbers. We are supposed to use a loop. Here is the code I have so far. All I've figured out how to do is generate the random numbers. If somebody could help me from here it would be much appreciated! public class RandAnalysis { public static void main(String[] args) { for(int i = 0; i < 10000; i++) System.out.println("Random number ["+ (i+1) +"]:" + Math.random()); } }
http://www.dreamincode.net/forums/topic/294837-java-code-generate-10000-random-integers%3B-sum-max-min-and-average/
CC-MAIN-2016-07
refinedweb
101
68.26
I have a variable with data type string and need to convert it to unsigned char... Please help I have a variable with data type string and need to convert it to unsigned char... Please help That's nonsensical unless you want a single character from the string. A string is more or less a collection of unsigned char. What are you trying to do? My best code is written with the delete key. Code:/*============================= Manipulating strings =============================*/ #include <iostream> #include <string> using namespace std; int main() { string my_string="hello there"; for(int i = 0; i < my_string.length(); i++) { cout<<my_string[i]<<endl; //single out characters here if you want } //or if you want to convert a string to an integer //try using <sstream> cin.get(); } Code:/*============================= Or if you really wanted to... The long winded way of converting a string to a char array =============================*/ #include <iostream> #include <string> using namespace std; int main() { char array[100]; string my_string="hello there"; for(int i = 0; i < my_string.length(); i++) { array[i]=my_string[i]; } array[my_string.length()]='\0'; //get rid of the rubbish cout<<array; cin.get(); } Last edited by treenef; 10-27-2005 at 05:22 AM. I wanted to ask that I have a string of basic type and want to convert it into unicode that is unsigned char....Please help.... Okie let me be more specific... I am using SQLConnect... I am recieving the username and password through a string type variable..I need to pass it to SQLConnect which accepts only unsigned char type....I am really stuck..any help appreciated.... >I need to pass it to SQLConnect which accepts only unsigned char type Unsigned char or pointer to unsigned char? There's a huge difference if it's a pointer, and that makes more sense. The string class has a member function, c_str, that gives you what you're probably looking for. My best code is written with the delete key. No am not talking about a pointer....Please let me know any information i am missing out on SQLConnect function...As far as i know it accepts only unsigned char....I am getting a string cariable... >No am not talking about a pointer.... The reference that I'm looking at sure seems to think that SQLConnect takes a pointer to SQLCHAR for the user name and password, and SQLCHAR is defined as unsigned char. You can cast (C-style or reinterpret_cast<>) the result of c_str() to SQLCHAR * and be done with it. My best code is written with the delete key. Originally Posted by whistleOriginally Posted by whistle unicode strings are not unsigned char -- they are implementation dependent. They use wchar_t data type, which is typedefed as unsigned sort in MS-Windows os, and unsigned long in linux (maybe unix too, I don't know). And none of those are the same as SQLCHAR mentioned earlier. Can somebody please explain to me in simple terms.I got a string variable x, and need to pass it to SQLConnect as username. PLLLLLEAAAASSEEEE HEEELPPPPP These guys explained it very well...if you don't understand what they are saying you should check out some tutorials on C. Other than that, you should do some work for yourself - . SQLCHAR* is indeed a const char* therefore you CAN use string::c_str() and pass it in as your username. -"What we wish, we readily believe, and what we ourselves think, we imagine others think also."PHP Code: sadf I am sorry for the trouable but the SQLConnect is not accepting a const char*. I dunno what is wrong but it asks for unsigned char*.Hence the confusion. Thanks anyways for all the help... >I dunno what is wrong but it asks for unsigned char*.Hence the confusion. You're simply not listening to those of us who have given you a correct answer. For example, I said this not too long ago: What does that mean? It means you do this:What does that mean? It means you do this: Originally Posted by PreludeOriginally Posted by Prelude Code:unsigned char *s = reinterpret_cast<SQLCHAR *> ( server.c_str() ); unsigned char *u = reinterpret_cast<SQLCHAR *> ( user.c_str() ); unsigned char *p = reinterpret_cast<SQLCHAR *> ( pass.c_str() ); rc = SQLConnect ( h, s, server.size(), u, user.size(), p, pass.size() ); My best code is written with the delete key.
https://cboard.cprogramming.com/cplusplus-programming/71442-help-string-unsigned-char-conversion.html
CC-MAIN-2017-51
refinedweb
719
76.82
programing programing Using Java, Design a simple interface that can capture information of your choice with the following controls; Labels, Text Fields, Checkbox, Radio buttons and command buttons. You may have to use the following files Java programing Java programing need help wrting this Write a program that has an array of 5 Strings, and determines which ones are palindromes (letter-case does not matter). thanks java programing - Java Beginners java programing Write a program that reads numbers fromthe keyboard into an array of type int[]. You may assume that there will be 50 or fewer...;> I need your help about this... Hi Medinz, Here is my programing question programing question how do i use loops(for,while) to add components in java Hi Friend, The below code might help you. import java.awt.*; import javax.swing.*; class TextFieldArray extends JFrame{ JLabel l[]=new What is java program coading to convert a mp3 file to it binary equivalent java programing problem - Java Beginners java programing problem Create a class named Movie that can be used with your video rental business. The Movie class should track the Motion picture Association of America rating , ID Number, and movie title with appropriate programing - IoC and Tutorials on Java visit to : Thanks java java IO programing java IO programing how Java source file is used as input the program will echo lines guys,, need help,, in java programing,, arrays guys,, need help,, in java programing,, arrays create a program where you will input 10 numbers and arrange it in ascending way using arrays Java About Java Hi, Can anyone tell me the About Java programming language? How a c programmer can learn Java development techniques? Thanks Hi, Read about java at. Thanks About java About java how we insert our database data into the jTable in java or how we show database content into the JTable in java Hi Friend, Try the following code: import java.io.*; import basics - Java Beginners About basics Why we are typing java program in text editor? Why we are running the java program in command prompt programing about J2EE. - Java Beginners about J2EE. I know only core Java ... what chapter I will be learn to know about J2EE. Hi Friend, Please visit the following link: Thanks Ask about java Ask about java Create a java program for add and remove the details of a person, which is not using by database, a simply java program. If possible, please wil it in switch case java java what is java java is a programing langauge Java is an objected oriented programming language. It is designed to work... Multithreaded Interpreted To know more about Java, Visit Here Java About Java This article is discussing about Java, which is a programming language developed by James Gosling at Sun Microsystems. Java now part of Oracle... about Java is listed below : Around 1.1 billions desktop runs Java. Every array in java about array in java speed of a vehicle is measured using the total time and the distance by using the equation given bellow speed(km/hour)=distance... Vehicle 02 = 5 hours Write a JAVA class to represent the Vehicle. The program swing - Java Beginners about swing how implement a program of adding two numbers by entering two numbers separately by other user on the input dialog box and after that also show the result of the addition in other dialog box... your regardly java1 about java1 Sir, i want to know how we develop 3d button ,lable,textfield etc. in java . sir plz give one program as well Thank you ABOUT Jtable ABOUT Jtable My Project is Exsice Management in java swing Desktop Application. I M Use Netbeans & Mysql . How can retrive Data in Jtable from Mysql Database in Net Beans java program - Java Beginners Java programing environment From where i can download the Java programming environment about regular expression - Java Beginners about regular expression Consider the grammar G: S -> ( L ) | a L -> L, S | S a) Eliminate the left-recursion from grammar G. b) Construct a recursive descent parser for G About project code - Java Beginners about project code Respected Sir/Mam, I need to develop an SMS... in commercial areas to send alerts to their customers about the events.... This can be developed using any kind of components using JAVA. The following Threading in Java value taken in java database - JDBC about value taken in java database how to take value from Serial port communication Hyperterminal to the java database MVC in java - Java Interview Questions about MVC in java hi, In MVC Architecute can the Model and View can communicate directly or not? Hi friend, For read in details MVC Architecture visit to : About RoseIndia.net About RoseIndia.Net RoseIndia.Net is global services .... Our technical teams skills include Java (J2EE) programming, ASP, C#, PHP... Framework, Web Services, Languages Java 1.5, Jakarta Torque, Ant Wants Suggestion about an issue. - Java Magazine Wants Suggestion about an issue. Hi all, I wish to develop a website like Social Networking Websites. For the development i think i should use Java Technology. So Request u guys to do suggest me what Design Pattern, What question about applet question about applet how to run java applet on wed browser Hi Friend, Please visit the following link: Applet Tutorials Thanks About Java Programming Language About Java Programming Language Java is an Object oriented application programming language developed by Sun Microsystems. Java is a very powerful general-purpose programming about predefine classes..... about predefine classes..... how we know that the class used in your given examples are predefind and from where we get info. about other predefine classes. we need explanation about examples given by you for java beginners Database programming - Java Beginners Database programming How to do a Database programing with Balanced Multiway Tree(B+ Tree,not Binary Tree) in java desing patterns - Struts About desing patterns How many Design Patterns are there supported by Java? and what is an Application Controller? what is the difference between Front Controller & Application Contorller? Hi Friend, Please visit Questions? If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for. Ask your questions, our development team will try to give answers to your questions.
http://www.roseindia.net/tutorialhelp/comment/73107
CC-MAIN-2013-20
refinedweb
1,048
52.19
...one of the most highly regarded and expertly designed C++ library projects in the world. — Herb Sutter and Andrei Alexandrescu, C++ Coding Standards This class represents a boundary point in the text. More... #include <boost/locale/boundary/boundary_point.hpp> This class represents a boundary point in the text. It represents a pair - an iterator and a rule that defines this point. This type of object is dereference by the iterators of boundary_point_index. Using a rule() member function you can get the reason why this specific boundary point was selected. For example, When you use a sentence boundary analysis, the (rule() & sentence_term) != 0 means that this boundary point was selected because a sentence terminator (like .?!) was spotted and the (rule() & sentence_sep)!=0 means that a separator like line feed or carriage return was observed. The type of the base iterator that iterates the original text Empty default constructor Create a new boundary_point using iterator and a rule r Set an new iterator value i Fetch an iterator Automatic cast to the iterator it represents Check if the boundary point points to different location from an iterator other Check if two boundary points are different Check if the boundary point points to same location as an iterator other Check if two boundary points are the same Fetch a rule Set an new rule value r
http://www.boost.org/doc/libs/1_51_0/libs/locale/doc/html/classboost_1_1locale_1_1boundary_1_1boundary__point.html
CC-MAIN-2015-06
refinedweb
223
51.38
Here is the background: Prof Huang and her students collect samples of pond water and culture the bacteria they find under narrow-spectrum artificial light, trying to find species that photosynthesize at different wavelengths. To identity the species in each culture, they amplify the 16S ribosomal RNA gene, send it out to be sequenced, and then look up the sequence in a database like greengenes. The result is either the name of a species that has been cultured, the genus of an uncultured species, or an unknown genus. They usually start by identifying 15 samples from each culture. For example, one of their cultures yielded 9 samples of one species, three of another, and one each of three more. Looking at the results for a given culture, biologists would like to be able to answer these questions: 1) How many more species are there likely to be? 2) What is the likely prevalence of each species? 3) If we test m additional samples, how many new species are we likely to find? 4) Given a limited budget, which cultures warrant additional sampling? To answer these questions, I implemented a hierarchical Bayesian model where the top level is "How many species are there?" and the second level is "Given that there are n species, what is the prevalence of each species?" The prevalence of a species is its proportion of the population. Knowing how many species there are helps model their prevalences. In the simplest case, if we know that there is only 1 species, the prevalence of that species must be 100%. If we know there are 2 species, I assume that the distribution of prevalences for both species is uniform from 0 to 100, so the expected prevalence for both is 50%, which makes sense. If we know there are 3 species, it is less obvious what the prior distribution should be; the Beta distribution is a natural choice because 1) If we know there are k species, we can use Beta(1, k-1) as a prior, and the expected value is 1/k, which makes sense. For k=2, the result is a uniform distribution, so that makes sense, too. 2) For this scenario, the Beta distribution is a conjugate prior, which means that after an update the posterior is also a Beta distribution. We can represent a Beta distribution with an object that keeps track of the parameters: class Beta: def __init__(self, yes, no): """Initializes a Beta distribution. yes and no are the number of successful/unsuccessful trials. """ self.alpha = yes+1 self.beta = no+1 Update couldn't be easier. def Update(self, yes, no): """Updates a Beta distribution.""" self.alpha += yes self.beta += no At the top level ("How many species are there?") the prior is a uniform distribution from 1 to 20, at least for now. I could replace that with a distribution that reflects more of the domain knowledge biologists have about the experiment; for example, based on how the cultures are processed, it would be rare to find more than 10 species with any substantial prevalence. Now that the priors are in place, how do we update? Here's the top level: def Update(self, evidence): """Updates based on observing a given taxon.""" for hypo, prob in self.hypos.Items(): likelihood = hypo.Likelihood(evidence) if likelihood: self.hypos.Mult(hypo, likelihood) else: # if a hypothesis has been ruled out, remove it self.hypos.Remove(hypo) self.hypos.Normalize() The evidence is a string that indicates which taxon (species or genus) was observed. self.hypos is a Pmf that maps from a hypo to its probability (Pmf is provided by the thinkstats package, a collection of modules used in my book, Think Stats). Each hypo is a hypothesis about how many taxons there are. We ask each hypo to compute the likelihood of the evidence, then update hypos accordingly. If we see N different taxons, all hypotheses with k<N are eliminated. Having updated the top level, we pass the evidence down to the lower level and update each hypothesis. # update the hypotheses for hypo, prob in self.hypos.Items(): hypo.Update(evidence) To compute the likelihood of the evidence under a hypothesis, we ask "What is the probability of observing this taxon, given our current belief about the prevalence of each taxon?" There are two cases: 1) If the observed taxon is one we have seen before, we just look up the current Beta distribution and compute its mean: def Mean(self): """Computes the mean of a Beta distribution.""" return self.alpha / (self.alpha + self.beta) 2) If we are seeing a taxon for the first time, we get the likelihoods for all unseen taxons and add them up. To update the lower level distributions, we loop through the Beta distributions that represent the prevalences, and update them with either a hit or a miss. def Update(self, evidence): """Updates each Beta dist with new evidence. evidence is a taxon """ for taxon, dist in self.taxa.iteritems(): if taxon == evidence: dist.Update(1, 0) else: dist.Update(0, 1) And that's it. After doing a series of updates, the top level is the posterior distribution of the number of taxons, and each hypothesis at the lower level is a set of Beta distributions that represent the prevalences. Let's look at an example. Suppose we see 11 of one taxon, 4 of another, and 2 of a third. The posterior distribution of the number of taxons is: The probability is 47% that there are only 3 taxons, 28% that there are 4, and 13% that there are 5. By summing over the hypotheses, we can generate distributions for the prevalence of each taxon: The median prevalence of taxon A is 58%; the credible interval is (39%, 75%). For taxons B and C the medians are 23% and 13%. For taxons D, E, and F, there is a high probability that the prevalence is 0, because these taxons have not been observed. To predict the number of new taxons we might find by sequencing additional samples, I use Monte Carlo simulation. Here is the kernel of the algorithm: for i in range(m): taxon = self.GenerateTaxon() taxons.append(taxon) meta.Update(taxon) curve = MakeCurve(taxons) m is the number of samples to simulate. Each time through the loop, we generate a random taxon and then update the hierarchy. The result is a rarefaction curve, which is the number of taxons we observe as a function of the number of samples. To generate a random taxon, we take advantage of the recursive structure of the hierarchy; that is, we ask each hypothesis to choose a random taxon, and then choose among them in accordance with the probability for each hypothesis: def GenerateTaxon(self): """Chooses a random taxon.""" pmf = Pmf.Pmf() for hypo, prob in sorted(self.hypos.Items()): taxon = hypo.GenerateTaxon() pmf.Incr(taxon, prob) return pmf.Random() The algorithm the hypotheses use to generate taxons is ugly, so I will spare you the details, but ultimately it depends on the ability to generate Beta variates, which is provided in Python's random module. Given a sequence of taxons (real or simulated), it is easy to generate a rarefaction curve: def MakeCurve(sample): """Makes a rarefaction curve for the given sample.""" s = set() curve = [] for i, taxon in enumerate(sample): s.add(taxon) curve.append((i+1, len(s))) return curve To show what additional samples might yield, I generate 100 rarefaction curves and plot them: The first 17 points are random permutations of the observed data, so after 17 samples, we have seen 3 taxa on every curve. The last 15 points are based on simulated data. The lines are shifted slightly so they don't overlap; that way you can eyeball high-probability paths. Even after m=15 additional samples, there is a good chance that we don't see any more taxons -- but there is a reasonable chance of seeing 1-2, and a small chance of seeing 3. Finally, we estimate the probability of seeing additional taxons as a function of the number of addition samples: With 5 additional samples, the chance of seeing at least one additional taxon is 24%; with 10 samples it's 40%, and with 15 it's 53%. These estimates should help biologists allocate their budget for additional samples is order to minimize the chance of missing an important low-prevalence taxon. Next steps: I am working with Prof. Huang and her students to report the results most usefully; then we are thinking about distributing the code or deploying it as a web app.
http://allendowney.blogspot.com/2011_06_01_archive.html
CC-MAIN-2016-40
refinedweb
1,442
53.31
size of byte variable? The byte data type is represented by an 8-bit signed two's complement integer. Minimum value: -128 Maximum value: 127 No, a java file can contain only one public class. Q 3 - What is the default value of String variable? String variable has default value of null an immutable object? A - An immutable object can be changed once it is created. B - An immutable object can't be changed once it is created. C - An immutable object is an instance of an abstract class. An immutable object can't be changed once it is created. String objects are immutable. Q 6 - What kind of variables a class can consist of? A - class variables, instance variables B - class variables, local variables, instance variables D - class variables, local variables A class consist of Local variable, instance variables and class variables. Q 7 - Method Overloading is an example of Method Overloading is example of static binding. Q 8 - Which is the way in which a thread can enter the waiting state? A - Invoke its sleep() method. B - invoke object's wait method. C - Invoke its suspend() method. A thread can enter the waiting state by invoking its sleep() method, by blocking on IO, by unsuccessfully attempting to acquire an object's lock, or by invoking an object's wait() method. It can also enter the waiting state by invoking its (deprecated) suspend() method. Q 9 - Can a top level class be private or protected? No, a top level class can not be private or protected. It can have either "public" or no modifier. Q 10 - which operator is considered to be with highest precedence? Postfix operators i.e () [] . is at the highest precedence.
http://www.tutorialspoint.com/java/java_online_quiz.htm
CC-MAIN-2021-04
refinedweb
285
68.67
I am a Python newbie and I came across this exercise of checking whether or not the simple brackets "(", ")" in a given string are matched evenly. I have seen examples here using the stack command which I havent encountered yet.So I attempted a different approach. Can anyone tell me where I am going wrong? def matched(str): ope = [] clo = [] for i in range(0,len(str)): l = str[i] if l == "(": ope = ope + ["("] else: if l == ")": clo = clo + [")"] else: return(ope, clo) if len(ope)==len(clo): return True else: return False A very slightly more elegant way to do this is below. It cleans up the for loop and replaces the lists with a simple counter variable. It also returns false if the counter drops below zero so that matched(")(") will return False. def matched(str): count = 0 for i in str: if i == "(": count += 1 elif i == ")": count -= 1 if count < 0: return False return count == 0
https://codedump.io/share/h0nO0wATVqGl/1/python-program-to-check-matching-of-simple-parentheses
CC-MAIN-2017-51
refinedweb
160
77.98
!ATTLIST div activerev CDATA #IMPLIED> <!ATTLIST div nodeid CDATA #IMPLIED> <!ATTLIST a command CDATA #IMPLIED> Can someone please tell me what is wrong with this code? Depending on how I try to solve the problem, I get rotating list of errors, usually to do with a requirement for an instance of an object to reference a non static value. The troublesome lines are marked with * I don't understand why this object can't access it's own local variable. I must be missing something, so if someone could help me see how I'm getting this wrong, I'd be very greatful. using System; using System.Collections; using UnityEngine; public class BuildManager { //debug info private static int count = 0; /**** local to class *****/ *** public Material[] baseMaterials;*** public static void buildRoad(int x, int z){ Debug.Log("I have built "+BuildManager.count+" road tiles so far"); Tile tile = new Tile(); tile.Awake(x, z, _ROAD); tile.GO = GameObject.CreatePrimitive(PrimitiveType.Plane); tile.GO.name = "road_"+x+"_"+z; tile.GO.tag = "road"; tile.GO.transform.position = new Vector3(x, 0, z); ***tile.GO.transform.renderer.material = baseMaterials[0];*** } I have tried creating a Material manager class and assigning from there, I have tried deriving this class from MonoBehaviour... something just isn't clicking. Any and all help is welcome. Best Wishes, S. asked Apr 17 '10 at 02:24 AM Sean Catheroy 11 ● 2 ● 3 ● 2 The "buildRoad" function is static, but the "baseMaterials" array is not--it is an instance member. For comparison, you have referenced "BuildManager.count" within the same function as a static member. Declaring baseMaterials as static would get it compiling (but it still may not accomplish what you're trying to do, which is not entirely clear). answered Apr 17 '10 at 04:07 AM Molix 4.8k ● 15 ● 27 ● 66 On the other end of the spectrum of what Molix is saying, you could make BuildManager a singleton. So something like this // create a game object and assign this to it class BuildManager : Monobehaviour { public Material[] baseMaterials; // assign this in editor // very simple singleton pattern (doesn't prevent multiple instances, though) static BuildManager instance; void Awake() { instance = this; } // your static function public static void BuildRoads( /* whatever */ ) { // your current code // get the instance's baseMaterials array and use that tile.GO.transform.renderer.material = instance.baseMaterials[0]; // etc } } Alternatively you could make BuildRoads non static, make instance a public variable, remove the instance from the line of code above, and then do BuildManager.instance.BuildRoads instance BuildManager.instance.BuildRoads answered Jul 10 '10 at 06:40 PM Tetrad 7.2k ● 27 ● 37 ● 89 Thanks for your reply, Molix :) I tried to add this reply as a comment, but it wouldn't take... Basically, the functionality I'd like to end up with is this: 1) Have one single instance of the BuildManager running, like a daemon. Any time a road needs to be built, the BuildManager should get called to put the tile down in the location specified. While creating that Tile, it should assign an appropriate material to the tile from the array of materials I assign to it. I've created those materials in the Editor, and am assigning them through the editor as well. 2) A single instance of a game state manager, which takes care of dispatching and receiving requests and coordinating game logic, calls BuildManager any time it needs a Tile built. It sends the coordinates and type of building to be built to the buildmanager. The buildmanager might either return the instantiated building for the manager daemon to keep track of, or might add it to a master reference list (I currently do this). I had this all working in Javascript, but needed an easy way to create and manipulate 2d arrays of unspecified sizes. I understand what you're saying with respect to conflict between a static function, and the non-static array... I looked that up and discovered that issue in c#. But, if I declare baseMaterials as static then it doesn't get exposed to the editor... I could assign materials in code, but for heavens sake, what a pain to have to write that code as well. Any thoughts? answered Apr 17 '10 at 02: arrays x351 materials x272 object-reference-error x9 asked: Apr 17 '10 at 02:24 AM Seen: 1555 times Last Updated: Apr 17 '10 at 02:24 AM How do you change the tint of an entire material array for differing objects? transform array in javascript Problem comparing contents of arrays how to create multidimensional arrays in javascript Using arrays in inspector variables Add an object to Array Add a copy of a object to Array List the Index of an Array as Buttons For in loop with index value Check/compare array elements EnterpriseSocial Q&A
http://answers.unity3d.com/questions/15319/cant-assign-materials-to-objects-from-an-array.html
CC-MAIN-2013-20
refinedweb
806
54.02
QSharedMemory: IPC problem between apps which built on Qt 4.6 and Qt 5.6 Hi! I have small application (was wrote on Qt 5.6.0) which creates shared memory segment and starts external program which I got from examples of Qt 4.6.0 (/mainwindows/application). Here the main class of my app: #define QT_56 #include <QtWidgets> class SMTest : public QWidget { Q_OBJECT public: explicit SMTest(QWidget *parent = Q_NULLPTR) : QWidget(parent), _sharedMemory("hello_world", this) { _sharedMemory.create(sizeof(double)); QPushButton *goButton = new QPushButton("Go!"); connect(goButton, SIGNAL(clicked()), this, SLOT(go())); setLayout(new QHBoxLayout); layout()->addWidget(goButton); resize(200, 100); } private slots: void go() { QString pathChunk; #ifdef QT_56 pathChunk = "/SharedMemoryTesting/application_qt56/application"; #else pathChunk = "/SharedMemoryTesting/application_qt46/application"; #endif QProcess *process = new QProcess(this); process->start(QDir::homePath() + pathChunk); } private: QSharedMemory _sharedMemory; }; In Qt's example I just added a function for attaching to the shared memory segment and writing some info to a log file (this function is called in the constructor of main window). You can see the code below: void MainWindow::connectToSegment() { QFile file(QDir::homePath() + "/sharedMem_qt46.txt"); file.open(QIODevice::WriteOnly | QIODevice::Text); QTextStream out(&file); QSharedMemory *sm = new QSharedMemory("hello_world", this); if (!sm->attach()) { out << sm->errorString() << "\n"; } else { out << "Everything good!\n"; } } When I run an example from my application it doesn't attach to the shared memory segment and the log file ( "sharedMem_qt46.txt") has the following error: QSharedMemory::attach (shmget): doesn't exist. But if I take the same example from Qt 5.6.0 and run with my app, it works fine. Maybe is this Qt's bug? P.S. I use Debian 8 and don't know whether this problem will occur on other platforms. Up. On Windows 8.1 x64 works fine. - SGaist Lifetime Qt Champion Hi and welcome to devnet, Qt 4.6 being pretty old, I'd recommend moving to at least 4.8.7 and check again. Qt 4.8.6 has the same problem. On Qt 5.4.2 works fine. I think, the best solution is the moving to 5.6.0 version.
https://forum.qt.io/topic/65991/qsharedmemory-ipc-problem-between-apps-which-built-on-qt-4-6-and-qt-5-6
CC-MAIN-2018-43
refinedweb
348
51.44
Syncfusion Dashboards. Cloud-based. The only BI solution you need for your business. SfDataGrid allows you to have additional unbound header rows, known as Stacked Header Rows that span across Grid Columns. You can group two or more columns under each of the Stacked Header. A Stacked Header Row is viewed as a set of Stacked Columns, where each Stacked Column contains a number of Child Columns. By default, the Stacked Header Row’s height is constantly maintained as 24 as shown in the following screenshot. Figure 1: Default row height of the Stacked Header Row You can customize the height of Stacked Header Row by accessing the RowHeight property of the Visual Container. You can access the Visual Container by using the GetVisualContainer() extension method that exists in the Syncfusion.UI.Xaml.Grid.Helpers namespace in SfDataGrid. Calculated here is the count of the StackedHeaderRows and RowHeight is applied to each row of the Stacked Header. C# The above RowHeight value changes are set to Stacked Header Row as shown in the following screenshot. Figure 2: Customized Row Height Sample Links: WPF WRT UWP You are using an outdated version of Internet Explorer that may not display all features of this and other websites. Upgrade to Internet Explorer 8 or newer for a better experience.
https://www.syncfusion.com/kb/3119/how-to-customize-the-height-of-stacked-header-row-in-sfdatagrid
CC-MAIN-2018-47
refinedweb
216
62.17
How are colors calculated? rick2047 opened this issue · comments I have very little knowledge of C++, but I find the project fascinating. But I can't figure out how a genome is converted into colors. Looking at the code, it seems like the function to convert a genome biosim4/src/imageWriter.cpp Lines 98 to 108 in 9d9bb27 It seems like only the first and last gene is being used to convert to a color. Which seems to be unpacked and plotted here biosim4/src/imageWriter.cpp Lines 56 to 58 in 9d9bb27 I have couple questions - The first and last genes are not in any ways special, then why only use those two? This can give an illusion of two very different genomes looking very similar. - Why unpack a uint8 to three uint8s, only for visualization? Ah colors. @rick2047, you ask an interesting question. The repository code happened to capture one of many awkward ways I tried to convert a genome, which could be hundreds of bits, into a few bits of color. The draw_circle() function takes a pointer to an array of three unsigned 8-bit integers for red, green, and blue for a 24-bit color space. But I found that very light colors are hard to see against a white canvas, so I limited each color channel to six bits of the darkest colors. There's no way to map hundreds of bits of genome into an 18-bit color space in a way that shows all genomic differences. Half of the bits of a genome specify connection weights, but I intuitively felt that two genomes were more "different" if they differed in connection topology than if they differed in connection weights. That's why I preferentially used bits from neuron identifiers to map to the color space instead of using bits from connection weights. Since genomes could be very short or very long, I arbitrarily used bits from the beginning and end of the genome. It's a bit lazy but worked well enough in practice for the intended purpose. There are many other ways to do this mapping. Ok, nice to know we are not completely off :D. If I understand it correctly, the 6 bit of colors are basically mapping the sink/source type and ID for the first and last genes. I was wondering if you considered using dimensionality reduction techniques based on projection like PCA. The biggest problem I see is it would require us to learn the color space each iteration, and it would not be stable between iterations as the creatures mutate. i'm trying to write this by python(well, I like python and i dont want change my system to Linux). I use a 24bit to express a gene, 8 for sink and Red value, 8 for source and Green value, 8 for weight and Blue value, chosse the first gene to represent the genome's color, or maybe consider use the average value of all gene's RGB Hello fellow programmers. I remade this project in JavaScript but tried to reverse engineer as much of it as I could without reading the source code, so my project ended up working quite differently. The way I generated colours was as follows: I labelled the Input, Hidden and Output neurons with different categories: pheromone = 0, internal = 1, environment = 2, social = 3, hidden = 4 (space for 2 more types if needed/wanted) Then I created the colour channels as follows: Red channel Bit 1 = Source Layer (input, hidden) Bit 2-4 = Source Category (allows for 7 different types) Bit 5-8 = Source TypeID (4 bits allows for 15 different IDs per category) Green channel Bit 1 = Sink Layer (hidden, output) Bit 2-4 = Sink Category Bit 5-8 = Sink TypeID Blue channel Connection weight that is between -4 and 4 is mapped to range 0 - 255 The colour is the average of these values for each connection between neurons. The functions that I use to map the range: // returns the value between two numbers at a specified decimal midpoint lerp(x, y, a) { return (x * (1 - a) + y * a); }, // give it a number and then a minimum & maximum. If your number falls within the bounds of the min & max, it’ll return it. // If not, it’ll return either the minimum if it’s smaller, or the maximum if it’s bigger clamp(a, min = 0, max = 1) { return Math.min(max, Math.max(min, a)); }, // Inverted LERP: you pass any value, and it’ll return that decimal, wherever it falls on that spectrum invlerp(x, y, a) { return clamp((a - x) / (y - x)); }, // converts a value from one data range to another range(x1, y1, x2, y2, a) { return lerp(x2, y2, invlerp(x1, y1, a)); }, Let me know if any of this sounds dumb :)
https://giters.com/davidrmiller/biosim4/issues/16
CC-MAIN-2022-21
refinedweb
807
63.22
The banking sector has many applications for programming and IT solutions. If you’re interested in working on a project for the banking sector, then you’ve come to the right place. In this article, we’ll talk about a detailed banking project in Python so you can get started with ease. We’ve shared source code for our project so you can take inspiration from the same and create a Python-based solution for a bank. Let’s begin. Prerequisites Before you start working on the Python banking project we’ve discussed here, you should first be familiar with the following topics. This way, you wouldn’t face any difficulty while working on the project. Programming in Python To create a proper banking solution in Python, you should be familiar with the basics of this language. We also recommend that you understand how the code works before you copy it or start using it as a component in your project. Make sure that you know programming well. Experience in Working on Projects You should have some experience in working on Python projects before working on this Python banking project. It is an essential part of data science. It’s not a beginner-level task and might cause you confusion at some instances if you’re inexperienced. Database Management A large section of our project focuses on database management. You’ll have to create a database for the banking solution to facilitate its functioning. You should be familiar with the basics of database management. Read: Career Opportunities in Python Banking Project in Python The Problem Customer experience is an integral part of a bank’s operations. That’s why banks focus a lot on improving customer experience by removing hassles and enhancing the facilities they provide. Opening a new account in a bank usually requires a person to visit the bank, fill out a form, and submit the necessary papers. All of these tasks take up a lot of time and dampen the overall customer experience. Moreover, many people have to take time out of their schedules to go to a bank. The Solution You can solve this problem by creating a software solution where people can sign up and open a new account in a bank digitally. This way, the person wouldn’t have to visit the bank physically and thus, would save a lot of time and effort. The banking management system can also allow the user to make transactions, deposit and withdraw funds, and check the account balance. Your solution would need an admin section which would look after the users’ accounts and the overall wellbeing of the database. You’ll have to connect the software to a database which will store all user information in distinct storage. How to Make the Project More Challenging While this project is quite challenging, you can enhance its difficulty and take it a level further. To do so, you can add a layer of security, so the user’s data remains safe. Your software can have a login window where every user has to enter the password and username to access their accounts. You can also add a feature of opening multiple types of accounts. For example, banks offer Current accounts, Savings accounts, and others. Different accounts can have various facilities. Also Read: Python Tutorial Source Code for Python Banking Project Here’s source code for a banking project in Python. The following program has these features: - It allows users to open new accounts - Users can make transactions by entering the respective amounts - Users can check the balance of their accounts - Admin can view a list of users to see how many users there are along with their details As you can see, it is quite basic, and you can add more functionalities according to your requirements. import pickle import os import pathlib class Account : accNo = 0 name = “ deposit=0 type = “ def createAccount(self): self.accNo= int(input(“Enter the account no : “)) self.name = input(“Enter the account holder name : “) self.type = input(“Ente the type of account [C/S] : “) self.deposit = int(input(“Enter The Initial amount(>=500 for Saving and >=1000 for current”)) print(“\n\n\nAccount Created”) def showAccount(self): print(“Account Number : “,self.accNo) print(“Account Holder Name : “, self.name) print(“Type of Account”,self.type) print(“Balance : “,self.deposit) def modifyAccount(self): print(“Account Number : “,self.accNo) self.name = input(“Modify Account Holder Name :”) self.type = input(“Modify type of Account :”) self.deposit = int(input(“Modify Balance :”)) def depositAmount(self,amount): self.deposit += amount def withdrawAmount(self,amount): self.deposit -= amount def report(self): print(self.accNo, ” “,self.name ,” “,self.type,” “, self.deposit) def getAccountNo(self): return self.accNo def getAcccountHolderName(self): return self.name def getAccountType(self): return self.type def getDeposit(self): return self.deposit def intro(): print(“\t\t\t\t**********************”) print(“\t\t\t\tBANK MANAGEMENT SYSTEM”) print(“\t\t\t\t**********************”) print(“\t\t\t\tBrought To You By:”) print(“\t\t\t\tprojectworlds.in”) input() def writeAccount(): account = Account() account.createAccount() writeAccountsFile(account) def displayAll(): file = pathlib.Path(“accounts.data”) if file.exists (): infile = open(‘accounts.data’,’rb’) mylist = pickle.load(infile) for item in mylist : print(item.accNo,” “, item.name, ” “,item.type, ” “,item.deposit ) infile.close() else : print(“No records to display”) def displaySp(num): file = pathlib.Path(“accounts.data”) if file.exists (): infile = open(‘accounts.data’,’rb’) mylist = pickle.load(infile) infile.close() found = False for item in mylist : if item.accNo == num : print(“Your account Balance is = “,item.deposit) found = True else : print(“No records to Search”) if not found : print(“No existing record with this number”) def depositAndWithdraw(num1,num2): file = pathlib.Path(“accounts.data”) if file.exists (): infile = open(‘accounts.data’,’rb’) mylist = pickle.load(infile) infile.close() os.remove(‘accounts.data’) for item in mylist : if item.accNo == num1 : if num2 == 1 : amount = int(input(“Enter the amount to deposit : “)) item.deposit += amount print(“Your account is updted”) elif num2 == 2 : amount = int(input(“Enter the amount to withdraw : “)) if amount <= item.deposit : item.deposit -=amount else : print(“You cannot withdraw larger amount”) else : print(“No records to Search”) outfile = open(‘newaccounts.data’,’wb’) pickle.dump(mylist, outfile) outfile.close() os.rename(‘newaccounts.data’, ‘accounts.data’) def deleteAccount(num): file = pathlib.Path(“accounts.data”) if file.exists (): infile = open(‘accounts.data’,’rb’) oldlist = pickle.load(infile) infile.close() newlist = [] for item in oldlist : if item.accNo != num : newlist.append(item) os.remove(‘accounts.data’) outfile = open(‘newaccounts.data’,’wb’) pickle.dump(newlist, outfile) outfile.close() os.rename(‘newaccounts.data’, ‘accounts.data’) def modifyAccount(num): file = pathlib.Path(“accounts.data”) if file.exists (): infile = open(‘accounts.data’,’rb’) oldlist = pickle.load(infile) infile.close() os.remove(‘accounts.data’) for item in oldlist : if item.accNo == num : item.name = input(“Enter the account holder name : “) item.type = input(“Enter the account Type : “) item.deposit = int(input(“Enter the Amount : “)) outfile = open(‘newaccounts.data’,’wb’) pickle.dump(oldlist, outfile) outfile.close() os.rename(‘newaccounts.data’, ‘accounts.data’) def writeAccountsFile(account) : file = pathlib.Path(“accounts.data”) if file.exists (): infile = open(‘accounts.data’,’rb’) oldlist = pickle.load(infile) oldlist.append(account) infile.close() os.remove(‘accounts.data’) else : oldlist = [account] outfile = open(‘newaccounts.data’,’wb’) pickle.dump(oldlist, outfile) outfile.close() os.rename(‘newaccounts.data’, ‘accounts.data’) # start of the program ch=” num=0 intro() while ch != 8: #system(“cls”); print(“\tMAIN MENU”) print(“\t1. NEW ACCOUNT”) print(“\t2. DEPOSIT AMOUNT”) print(“\t3. WITHDRAW AMOUNT”) print(“\t4. BALANCE ENQUIRY”) print(“\t5. ALL ACCOUNT HOLDER LIST”) print(“\t6. CLOSE AN ACCOUNT”) print(“\t7. MODIFY AN ACCOUNT”) print(“\t8. EXIT”) print(“\tSelect Your Option (1-8) “) ch = input() #system(“cls”); if ch == ‘1’: writeAccount() elif ch ==’2′: num = int(input(“\tEnter The account No. : “)) depositAndWithdraw(num, 1) elif ch == ‘3’: num = int(input(“\tEnter The account No. : “)) depositAndWithdraw(num, 2) elif ch == ‘4’: num = int(input(“\tEnter The account No. : “)) displaySp(num) elif ch == ‘5’: displayAll(); elif ch == ‘6’: num =int(input(“\tEnter The account No. : “)) deleteAccount(num) elif ch == ‘7’: num = int(input(“\tEnter The account No. : “)) modifyAccount(num) elif ch == ‘8’: print(“\tThanks for using bank management system”) break else : print(“Invalid choice”) ch = input(“Enter your choice : “) Learn More About Python We hope you found this guide on doing a Python banking project useful. If you have any questions or suggestions, please let us know through the comment section. We’d love to hear from you. If you are curious about learning data science to be in the front of fast-paced technological advancements, check out upGrad & IIIT-B’s Executive PG Programme in Data Science. What is the significance of working on live projects? Working on live projects is very beneficial for a growing programming geek. There are multiple reasons why we strongly recommend you to keep working on projects: When you apply your theoretical learning in building something practical, your confidence goes on to the next level and gives you a feeling that you actually know something of value. Experimenting clears all your doubts that theory cannot. When you try to apply something and fail, it’s not a setback. It solves your confusion about the particular implementation and provides you with multiple other ways to implement it. The biggest benefit that working on projects provides is that it polishes your programming skills. Just watching video solutions does not help you get anywhere. You need practical implementation of your learning in order to master it. What is the logic behind the bank management system project? This bank management system is beginner-friendly and is based on all the beginner’s concepts. This project performs all the significant features of banking software. You can create a new login user-id, view your credit and withdrawal records and statements, send and receive money, and edit your account information. This project is specialized for beginners so you can create this project even if you are not that comfortable with Python. You can add the login system as well as where you can provide two options- “login with email id or continue with google”. You can use the Google API for adding this functionality to your banking system. Describe some project ideas similar to the bank management system. There are several project ideas that can be built using Python. Following are some of the most popular ones: A pharmacy management system should implement the functionalities such as an ordering system, inventory management, invoicing system, and additional functionality for prescribing medicines. Hotel Management System is a project that should include features such as a reservation system, room management, housekeeping management, and invoice automation. A student management system should include functionalities such as profile management, account management, student record system, and hostel management.
https://www.upgrad.com/blog/python-banking-project/
CC-MAIN-2021-43
refinedweb
1,793
51.75
Introduction AllegroGraph WebView (AGWebView) is a graphical user interface for exploring, querying, and managing AllegroGraph repositories., add, and delete Supported browsers and versions AGWebView will work with the following browsers on the noted platforms. As with many browser applications, some or all of AGWebView's features may work on other browsers or in other versions, but these have not been tested. In general, we will not fix problems with an earlier version than listed of a supported browser on the platforms noted, but will try to fix problems on later versions released after this list was prepared, if they occur. Sometimes a new version of AllegroGraph is needed so that AGWebView will work with a new version of a browser. namespaces is displayed by the Utilities | Namespaces menu choice when on a Repository page. This displays the list of all available namespaces, whether they are in use or not. The define a user namespace and define a repository namespace links below the lists let you add a new namespaces. You can also display the list of namespaces on the New Query page of a repository. Look for the "Show namespaces" link to the right. This is the list of shared and private namespaces that are available to that query. On this page the "add a namespace" link lets you create a new private namespace owned by the current user. When you show namespaces, there is a delete button to the right of each namespace allowing you to delete that namespace. To create a namespace, simply click one of the "define namespace" links and then fill out the form: Then to use the namespace, type it into an input field with the required colon (:) and the local name of the resource. AGWebView will automatically expand the full URIs behind the scenes. Modifying a namespace: If you wish to modify a namespace, so that a prefix expands to a different value, you must delete it first (using the Delete button to the right of the namespace list when Show Namespaces is chosen or the Delete button next to the namespace displayed with the Namespaces choice on the Utilities menu) and then add it back with the revised value. It is an error to try to add a namespace with a prefix already in use. Managing Users and roles AGWebView provides an interface for managing users and roles. Management takes place on the User page displayed (for superusers) by the Admin | Users menu item: Please see the Managing Users document for further information. The AGWebView interface is described in detail in that document along with the equivalent agtool user and agtool role commands. preceded repositories, with reasoning and graph filtering applied to the individual repositories of the federation. For instance, this specification federates a reasoning version of repository "A" in the root catalog with a reasoning version of the "" graph of repository "B" in the "public" catalog: <A>[rdfs++] + <public:B>{<>}[rdfs++] In a session specification, local repositories are written as <catalog:name>, or just <name> for repositories in the root catalog. Remote repositories are written by putting their URL between < and >. Multiple repositories can be federated by putting plus signs (+) between them. For example, <repository1> + <repository2>. To apply a reasoner to a repository, write [rdfs++] or [hasvalue] after it. To create a filtered repository,. Note that with the optional Sesame 2.7 transaction handling semantics, autocommit reverts to true after a "commit" or a "rollback"., and some that are shown, you may not see. You will see other banners in other illustrations. - (Backarrow) - The curly backarrow symbol lets you go back a level in the hierarchy of AGWebView pages. - Repository - This choice returns you to the current repository page. - Queries - This choice displays a menu of query choices, including: - New: Display the Query page - Saved: Display saved queries, if any - Recent: Display recent queries - Free text: Allow searches in free text indices, if any - Utilities - This dropdown menu gives access to various utilities. Some choices may be grayed out (and thus non-operational) if they do not apply. Choices include Scripts: This link displays Server Scripting page. Only users with Eval access will see this item (see the Evaluate Arbitrary Code user permission in the General permissions section of the Managing Users document for information on Eval access). This allows loading or defining User scripts and Site scripts. See the Scripting the server section in the REST/HTTP interface document for information on scripting. Namespaces: This link displays the Namespace Selection page. - Geospatial Datatype Designer: This link opens the Geospatial Datatype Designer page (see the WebView Geospatial Datatype Designer section in the N-dimensional Geospatial Usage Guide and Example document. - Settings: This link displays a settings page. See the settings page. - View Server Load: This link opens the Server Load page. - Admin - This is a drop-down menu offering various options to the AllegroGraph superuser only (non-superusers do not see this menu): - Users: This link opens the User Management page. - Jobs: This link opens the jobs page. - Requests: This link displays the Requests page. - Audit log: This link opens the Audit Log page. - View server log: This link opens the server log. - View server configuration: This link opens the configuration file (see Server Configuration and Control). - View/Edit initfile: This link opens the Initfile editing page. - Processes: This link opens the Processes page. - User - This is a menu that drops down from the name of the current user offering: - change password - logout: The current user logs out. - delete: The current user has an opportunity to delete his/her own account. -. The settings page The settings page is displayed when you select the Utilities | Settings menu choice. There are two tabs. The Server tab: This tab allows you to specify a message to be displayed when the system detects that a large operation has been requested. Large operations are backup, data export, and query download. The warning message is displayed for all those operations. Here we add a large operation warning (About to perform a large operation!!!): Then, when we execute a query and click on the Download button at the bottom, the warning dialog is displayed and the user is offered the opportunity to cancel the operation: If the large operation warning is blank (as it is initially and is if all text is deleted from the settings box), no warning is displayed and the user is not given to opportunity to cancel. Here is the Browser Session tab: This tab displays browser display options, including whether to display full URIs and whether to show graphs. User Management Page Superusers can access the User Management page by choosing Users from the Admin menu. See the Managing Users document for an explanation of user management. The User Management page lists users and roles (in the illustration, there are two users, test and anonymous, and no roles). There are links to add, edit, and delete users. Clicking on edit displays the following: Again, see the Managing Users document for more information. The Requests page This page, displayed by the Requests choice on the Admin menu, and available to superusers only, displays the recent HTTP requests received the server. The various buttons control what is displayed. Reset view restores the view to its default settings. Set page size determines how many requests to display. Set column visibity allows you to hide columns. (Besides Server, Status, Method, and URL, all visible in the illustration, there are columns for Source IP:port, Started, Finished, and Duration.) Use local timezone toggles times, usually displayed in GMT, to local time. Save to CSV saves the data to a CSV file. Refresh redisplays the table. Active requests are displayed in green, requests that completed successfully are black, and requests that failed are displayed in red. The Search box can be used to narrow the display to rows which have text which matches the search text. Clicking on a column heading sorts by that column. Additional clicks toggle between ascending and descending sorting. repository to manage. $ { } < > * + [ ] | - Start session - This field lets you create an arbitrarily complex federated repository. See Session Specification earlier in this document. Named Catalog Page From the top-level Root Catalog page, click on any non-root catalog. This opens a Named Catalog page. This page lists all the repositories that are available within that catalog. Note that this page has the name of a specific catalog at the top (tests in the illustration.). The various links include: - Repositories - These are the available repositories within this catalog. Clicking on one displays its Repository Overview page. - Create a Repository - Create a new repository in the current catalog. Note that the system catalog is reserved and users cannot create repositories in it. - Start session - This field lets you create an arbitrarily complex federated repository. See Session Specifications earlier in this document. Repository Overview Page The Repository Overview page gives you access to a specific repository within a specific catalog. The name of the repository is posted under the banner. The catalog, if it is not the root catalog, is also shown under the banner. This illustration is when the logged in user have superuser privileges and therefore everything is available. Users with fewer privileges will not see certain items on the page. (For example, a user who does not have permission to start a session will not see the Start a session choice.) If you do not see a described choice, it is likely because you do not have permission to make that choice.. There is a drop-down list of existing graphs. You may also add attributes. Attributes must be defined in the repository before being used. See Manage attribute definitions below. Attributes must be specified using JSON object syntax. The illustration shows an example. - Delete Statements - Enter any combination of URIs, wildcards, and literals into the fields of the form. Click OK to delete all matching statements from the repository. Caution: There is no way to undo this action. - Import RDF - The choices allow you either to select a file and load it into the repository. or to open a text widget and enter triple data directly. - Import RDF from an [uploaded | server-side] file - The choices from an uploaded file and from a server-side file open a file select dialog. The dialog displayed by the from an uploaded file choice is displayed below. If you click the Choose Files button, the file choice dialog initially displays the server installation directory's tutorial/ subdirectory (if it is in the expected place -- otherwise it displays the installation directory itself). Subsequent invocations display the last directory from which a file was loaded. See the tutorial directory section in AllegroGraph Quick Start for more information on the initial directory that will be displayed. The dialog displayed by the from a server-side file is similar except instead of a Choose Files button, it shows a widget showing the server-side directories and files. The dialog has many options, many associated with options to the agload utility, described in the Data Loading document. Pop-up tooltips appear when you mouse over many of the options. Note that agload will be used when you select the Using agload file loading mode and but not when you select Transactional but the meaning of the other options is the same in either case. If you select Using agload, you can then specify how many agload processes will run. This specifies a value for the --loaders option to agload. If you select Transactional, then the triples will be inserted within a single atomic transaction, which will either succeed completely or fail completely. This is suitable for small operations but not recommended for large data loads. agload loads and commits triples in batches so when it fails, some but not all triples will typically have loaded and committed. See the Data Loading document for more information on this point. The options include: format: the format of the data in the file. Choices include N-Triples, N-Quads, NQX (extended N-Quads with attributes), RDF/XML, Trix, TriG, and Turtle. See the input option to agload for more information. The default is Autodetect, which means get the format from the file extension (so an extension of ntriples or nt means an N-Triples file). Context: the default graph for the triples being loaded if it is not otherwise specified (as it is in N-Quads). Attributes: you can specify attributes which will be added to every triple which does not have attributes specified in the file (see the --attributes option to agload). Only NQX files can have attributes specified, so the attributes specified here are added to every triple in files other than NQX files. Attributes must be defined in the repository before being used. See Manage attribute definitions below. Attributes must be specified in JSON format, such as {"bar": "high"}. See the Triple Attributes document for more information. Relax syntax: see the relax-syntax option to agload. If selected, data which looks okay but is in fact improper RDF (for example, contains trailing spaces or hyphens in blank node ids) will be accepted. We recommend correcting your data files so they are proper RDF, but this option is useful during development or when demo-ing so that nearly correct data can be loaded. File loading mode: Multi-core uses agload and is possibly faster. Single-threaded means use one core only and a simpler loading program. Error handling: see the error-strategy option to agload. Cancel load means if an error is encountered, cancel the load. Note that triples already loaded will not be removed. Ignore errors will attempt to continue upon an error, so if one triple is mangled, it will be skipped but the remaining will be loaded, if possible. Use bulk load mode: see the bulk option to agtool load. Enable bulk mode while processing the loading job. Bulk mode turns off transaction log processing and can provide considerable performance gain for large jobs. Warning: transaction log processing is turned off for the entire database (not just you loading this file). Other users may be affected. The database may be irrecoverably corrupted if something goes wrong. Use this option with care! This option is invalid when loading triples into a replication instance (see the Multi-master Replication document) as replication depends on complete transaction logs. Specifying this option will cause the load to fail with an error message. - Import RDF from a text area input - This choice displays the text input dialog shown in the illustration: - Type or paste data into the input area (several lines from the N-triples file kennedy.nt are shown in that area -- the kennedy.nt file is an example file supplied with the AllegroGraph distribution). The text format must be syntactically valid for the format selected in the Format box. If the Format is Autodetect (as in the illustration) then various formats are tried until one works. As we said above, the text in the illustration is in N-triples format. The other options are similar to the file loading options described above. Click OK to load the data. Explore the Repository These choices allow you to view triples and other data in the repository. - View triples - Executes a SPARQL query that displays the first 1000 triples it finds. The purpose of this feature is to give you a quick look into the repository. (If the Limit to 1000 results checkbox on the right of the New Query Page is unchecked, all triples are displayed.) - View quads - Executes a SPARQL query that displays the first 1000 triples it finds and shows the graph of each triple. If no graph is shown, it means the triple uses the default graph. The purpose of this feature is to give you another quick look into the repository. (If the Limit to 1000 results checkbox on the right of the New Query Page is unchecked, all triples are displayed.) - View repository's classes - Executes a SPARQL query that displays the first 1000 rdf:typeclasses in the repository. (If the Limit to 1000 results checkbox on the right of the New Query Page is unchecked, all classes are displayed.) - View repository's predicates - Executes a SPARQL query that displays the first 1000 predicates found in the repository. (If the Limit to 1000 results checkbox on the right of the New Query Page is unchecked, all predicates are displayed.) - View repository's named graphs - Executes a SPARQL query that displays the first 1000 named graphs found in the repository. (If the Limit to 1000 results checkbox on the right of the New Query Page is unchecked, all named graphs are displayed.) Reports These choices display report windows providing information on storage use by the current repository. Three reports are directly linked and the fourth link goes to a page linking to all the other pages.: - Storage report - Display a Report page with a pie chart showing disk usage. The slices of the pie chart link to other Report pages. See The Reports pages for more information. - Triple indices - Display the storage Report page for triples indices. See The Reports pages for more information. - String table - Display the storage Report page for the repository's string table. See The Reports pages for more information. - Full list of reports - Display a page with links to all report pages. See The Reports pages for more information. Replication Control This link is not shown in the illustration above. It only appears when the repository being described on the page is an instance of a multi-master cluster. See Managing Clusters Using AGWebView in the Multi-master Replication document for information on using this link. Repository Control This section of the Repository Overview page lists various operations that can be performed on the repository. Many operations call functions in the Lisp API, which are linked to. Operations are generally only displayed if the current user has permission to execute them. All operations (those that are seen by a superuser) are documented. If you do not see an operation, it means you do not have permission to execute it. - Export - You can dump the repository to a file, using any of these RDF formats: - N-Triples - N-Quads - NQX - RDF/XML - TriG - Turtle - Start a Session - This link starts a dedicated session in this repository, which establishes transaction semantics. A Session menu will appear in the banner, offering Commit and Rollback links. Commit takes all changes (triple adds and deletes) since the last commit or rollback and makes them permanent in the repository. Rollback discards all uncommitted changes. The menu also offers a Close link, which ends the session. - Warmup store - This link displays the following dialog and allows you to warmup the current repository. When you warmup a repository, triple and/or string data is loaded into memory (from disk). This makes it likely that subsequent queries will execute more quickly. You can choose to warmup triples, strings, or both. - Convert store to a replication instance - AllegroGraph supports multi-master replication where there are several instances of a repository together in a replication cluster (sometimes shortened to cluster when the context is clear). Triples can be added or deleted from any instance in the cluster, with the additions and deletions propogating to the other replicas. If this choice is present, the current repository is not part of a replication cluster. If it were, this link would not appear and the Replication Control section described above (but not appearing in the main illustration) would appear instead. See Using AGWebView to create a cluster in the Multi-master Replication document for information on using this link. - Control Replication - See the document on Replication and Warm Standby. See also Replication below. Note that the replication referred to is single-master replication, not multi-master replication mentioned in the link just above. - Back-up this repository - Initiate a backup. - Export duplicate statements - Serializes a list of duplicate triples to a file in Nquads format. The duplicates can be SPO-identical (ignoring the graph) or SPOG-identical (considering the graph). Triples not visible to the current user will not be written. The triples written to the file will be the triples deleted if duplicates are deleted (prior to the next commit, which may change what are and what are not duplicates). See Deleting Duplicate Triples. - Delete duplicate statements - Performs a one-time removal of duplicates from the repository. A pop-up window allows you to chose whether two triples that share subject/predicate/object (spo) are considered duplicates or only triples that share subject/predicate/object/graph (spog). - See Deleting delete-duplicate-triples. - Optimize the repository - When clicked, the repository repositories; [running] is displayed after the link while optimization is going on and disappears when complete. (It is not an error to add or delete triples while optimization is going on, it just reduces the effect of optimization.) See optimize-indices. Clicking this option optimizes at level 2. - Recognize geospatial datatypes automatically - If checked, then when triples are being added from an external source (e.g. a N-triples file or a SPARQL INSERT), the loader will check whether the leading portion of the type URI matches an AllegroGraph geospatial type. (Both the old 2D and new nD types are checked.) If so, and if the type has not yet been encountered in this repository, the subtype is reconstructed from the type string and automatic predicate and datatype mappings are added to the repository. See The WebView Geospatial Datatype Designer in the N-dimensional Geospatial Usage Guide and Example document for details. - Control durability (bulk-load mode) - If bulk-load mode is turned on, logging of modifications to the repository. Bulk-load mode is not permitted when loading into a replication instance (see the Multi-master Replication document) as replication depends on complete transaction logs. Specifying this option will cause the load into a replication instance to fail with an error message. - Manage attribute definitions - Displays a dialog which allows you to define attributes (you must have superuser privileges). When first displayed, only the buttons (Add New, Save, and Revert) and the documentation appear. Clicking on Add New displays fields to fill in, as shown in the illustration. The documentation text describes how to input a definition. See the Defining attributes section for information on the various options. See the Attributes example below for more information. - Set static attribute filter - Displays a dialog which shows the current static attribute filter, if any, and allows adding a filter or editing the existing filter. See the Attributes example below for more information. - Manage triple indices - This link displays the Manage triple indices page, which lists all triple indices and allows addition of new indices and management of existing ones. -. - Shutdown instance - Makes the repository instance shut down and its child processes exit instantly once the repository is no longer used. This option is for administrators and is not typically needed by ordinary users. Free-Text Indices Page One reaches the Free-Text Indices page by clicking "Manage free-text indices" on the Repository Overview page. This displays the Free-text indices page for the repository. In the illustration, we have one such index, named myindex, which we created by accepting all the default values and settings. To create a new index, type its name into the field at the bottom (indicated by the red arrow). Remember that there might be many indices, so the name should be fairly specific. We have chosen the name long-word-index (because we only index words 10 characters or more long -- see the Minimum word length field indicated by the red arrow in the dialog below). Click the "Create" link and the following dialog is displayed: See the Free-Text Indices section for a discussion of the various options. Click OK at the bottom to create the index. When you create a new index or edit the parameters of an old one, AllegroGraph will reload the triples to bring the index up to date. An example of defining attributes and static filters There is a general attributes/static filter example found in java-tutorial/AttributesExample.java. Currently, all that can be done in WebView is define attributes and static filters. Currently in AGWebView there is no way to associate attributes with a user. Thus if a static filter restricts access to triples, no user can see those triples in AGWebView. They can be seen using other tools, as the Java example shows. Further, if an attribute is defined with Minimum number greater than 0, then no triple can be loaded into the repository without that attribute having a value (actually, the required number of values). These two lines from the repository view have to do with attributes and static filters: Clicking on Manage attribute definitions displays a dialog which allows attribute definitions. Here we have filled in the fields from the example referenced above: Because securityLevel has min and max 1, there must be exactly one of these attributes for every added triple. Similarly, clicking on Set static attribute filter displays a dialog allowing the filters to be defined. Here we define the filter from the example: We pasted the definition into the Edit filter area and clicked on Save, and it appeared in the Current filter area. New Query Page From the Repository Overview page, click the New link in the Queries menu. This exposes a page where you can edit a SPARQL or Prolog query to run against this repository. See the sections on SPARQL Queries and Prolog Queries for example queries to get you started. This page lets you edit a new SPARQL or Prolog query and test it against the repository. The query (as shown below) goes in the (blank in the first picture) Edit Query field. The various options and buttons work as follows. Note that Anonymous users do not have all options and may not see what a regular user sees. Results are displayed under the Edit Query field, as illustrated below. - Language - The Query page accepts SPARQL queries from all users. Users with permission to execute arbitrary code also have the option of issuing Prolog queries. - Limit to 1000 results - If checked (as it is by default), a maximum of 1000 results will be displayed. If unchecked, all results (no matter how many) will be displayed. Use care when unchecking this for large databases as there may be very many results. A LIMIT clause in the query can also limit results (as shown in the example below, where a LIMIT of 1 is specified). The number of results displayed is the minimum of the actual number of results, the LIMIT specified in the query, and 1000 if this option is checked. - Reasoning, Long parts, Graphs check boxes - When checked, enable reasoning, display full URIs when showing parts, and show graph names, respectively. - Show namespaces - Click this link to view the table of namespaces that are available to the current query. This could be a mix of shared and private namespaces. - Add a namespace - This link lets you enter a new, private namespace to use in this query. When you click this link, the following embedded dialog is displayed, allowing you to enter the namespace prefix and URI. The Bulk Input button allows you to enter multiple namespaces at once. RDF4J and Jena and also here it means processing several statements at once but is not related to transaction logging or loading.) - Modifying a namespace: If you wish to modify a namespace, so that a prefix expands to a different value, you must delete it first (there are Delete buttons next the namespaces) and then add it back with the revised value. It is an error to try to add a namespace with a prefix already in use. - Permalink. The button along the bottom are: - Execute - The Execute button runs the query. A table of results will appear in the lower half of the page. - Log Query - Clicking this button executes the query and then displays information about the operation of the query. Note the query results are not displayed nor otherwise made available. To see them, you must click Execute. - Show Plan - Displays the query plan is the results area. The plan is pseudo-code which explains the process by which the query will be answered. There is an example below. - Save As - You can save a private copy of a query for later reuse. Give it a name and then click the Save button. To find this query again, click the saved link in the Queries menu in the page banner. The *Saved* choice only appears if there are saved queries. . The Result field Results are displayed in a table. Each URI in the table is a link to a page of information about how that URI is used in the repository. - Download -. The Cancel button While a query is running, you see the word Loading and a spinning dots icon. Also, a Cancel button appears. You can click this button to stop the query. Stopping may take a few seconds. No results found will appear in the Results area when the query is stopped. . The show 1000 results indicates the value of the Limit to 1000 results checkbox when the query was run (checked in the cases shown). It will say Show all results if the box was unchecked. You can uncheck the box, if desired, before running the query. Click on an entry in the list to re-run the query. repository on the local server. Audit Log page When auditing is enabled, AllegroGraph provides a structured system audit log which tracks important changes to the server and its repositories. item, where the example below is repeated. test, added two users (fred and joe), the updated page (looking at actions by test, as test is selected, and event add user) shows when those users were added and by whom. Information is refreshed when the View Audit Log button is clicked. test (the superuser) modifies joe's user permissions several times. Here are screens after that activity, the first showing all activity and the second just the change user activity of test.. Server Load page The Server Load page, displayed by the View Server Load choice on the Utilities menu brings up a page of performance charts for the server machine. The several charts show approximately the same machine load data printed by the vmstat command, charted for the past five minutes. Here is an illustration showing several of the charts. The server in this example was not doing much so not much activity is shown. Besides CPU, Memory, Disk Bytes Transferred per Second, all shown in the image, there are graphs for Scheduling and Processes. Selecting a portion of a chart (by positioning the mouse over the chart, pressing the primary button, and dragging the mouse) causes all charts to zoom to the selected portion. While charts are zoomed, auto-refreshing is disabled (and the Auto refresh radio button is set to never), unless the selected portion goes right up to the right edge, in which case auto-refreshing continues if enabled. The Refresh button updates the charts. The Unzoom button cancels chart zooms. You can have the charts auto-refresh by choosing one of the refresh rate radio buttons under Auto refresh (with the never button meaning do not auto-refresh). The Y scale radio button choose the height of the Y-axis on the various charts. The Tiny option shows a minimal display, whith the X (time) axis displayed on the first (CPU) chart only and chart labels and legends hidden. The Time Zone button toggles (by clicking on the value) between Local (time where Webview is displayed), Server (time where the server is running), and UTC (UTC time). The Reports pages Click here to get back to the description of the repository overview page. The Reports pages are displayed by clicking on the links below the Reports heading on a Repository overview page. There are four links under that heading: Repository overview, Triple indices, String table and Full list of reports. Here is the Storage report page when the LUBM-1000 dataset (with over 138 million triples) is loaded into the LUBM-1000 repository: It shows 138+ million triples and about 17 GB of space used, mostly by triple indices (the red portion) and some by the string table (the light blue portion). Although the cursor is not visible, it is over the Triple indices (red) slice of the pie chart, which lightens the red color and when clicked, goes to the Triple indices page. There is a link to List of reports near the top which takes you to the report list page shown next (this pages is also linked from the Repository overview page). The links go to the various report pages. Here, for example, is the Triple indices page: A pie chart shows the disk usage per index. A chart below shows more information about the indices. The information in the lower chart is repeated on the Manage triple indices page. See that page for information on the various chart columns. There is a link to Manage triple indices page at the bottom of the Triple indices page (but users without write permission cannot see that page so they have no link).. Click here to get back to the description of the repository overview page. The Manage triple indices page Click here to get back to the description of the repository overview page. This page is displayed when the Manage triple indices link is clicked on the Repository overview page. . All current triple indices are listed, along with: The index style (see Index styles in the Indices document). The index status (whether or not there are jobs updating an index). The number of disk chunks the index occupies. The disk space used by the index. The Oscore (overlap or optimization score) of the index, which is the average number of chunks that must be examined to find a specific triple. The Oscore is a measure of how long it takes to find a triple in the index. The lower the number, the shorter the time. Oscores are reduced by index optimization, typically to 1.0 immediately after a level 2 optimization completes. The colored box all the way to the right it a visual indicator of the optimization quality of the index. Green indicates OK, yellow indicates optimization should be considered, and red that lack of optimization is degrading performance significantly. These are subjective measures. You may feel even a green index could benefit from optimization. The various buttons below the chart initiate actions on selected indices (more than one index can be selected). The buttons are: - Refresh - Always active. Update the chart. - Optimize - Active only when at least one index is selected. Clicking the Optimize portion initiates optimization according to the currently chosen optimization level. Clicking the ... portion of the button displays a dialog allowing you to choose the level. - Purge deleted triples - Active only when at least one index is selected. See Purging Deleted Triples. Removes inaccessible triples from indices. This button is only active when the user has permission to purge triples. In the current release, only superusers have such permission. It is active in the illustration because user test is a superuser. - Change style - Active only when at least one index is selected. Index styles are described in the Index styles section of the Indices document. Clicking this button displays a dialog indicating the current index style and allowing it to be changed. - - Active only when at least one index is selected. Deletes the selected indices. You cannot delete all indices. There always must be at least one. - Settings - Always active. Displays a settings dialog. - Add Index - Always active. Displays a dialog for adding a new index. Click here to get back to the description of the repository overview page.
https://franz.com/agraph/support/documentation/current/agwebview.html
CC-MAIN-2018-43
refinedweb
5,992
64.3
I'm a geekette who enjoys playing with new technology for software developers. I work as a Developer Evangelist for Microsoft. My current focus is on Windows Store development for Windows 8. So now we are up to the point where we can start coding! First, let me explain my app idea. I am building a children’s game called “Reveal a Picture” where you touch the screen or move the mouse on a colored screen to reveal a hidden picture underneath. This is a very simple concept, but for children ages 2-4, this is fascinating. This application will select a picture from the user’s Pictures Library to hide, so the child will be delighted to discover a picture of herself or her family. I also like this game idea because if the child plays it with a mouse, it teaches basic mouse manipulation skills (the hand/eye coordination necessary to move the mouse and correlate that action to the mouse pointer moving on the screen). Note that I’m using Visual Studio Express 2012 RC for Windows 8 for development (so if you are coming from the future, things may look slightly different). I started with the Blank XAML template in C#. (NOTE: If you’re just getting started with Metro, using the Grid template or the Split template is a good idea. It takes care of a lot of the navigation, animations, and snap screens for you.) But this app is so simple that Blank made sense. I’m assuming that you’ve already downloaded Visual Studio Express 2012 RC for Windows 8 (if not, check out the Getting Started post). In Visual Studio, select “File” and “New Project” from the menu bar. You will see a dialog box like the below. In the left navigation pane, expand “Installed”, then “Templates”, and then “Visual C#”. Select “Windows Metro style”. Then in the center pane, select “Blank App (XAML)”. Give it a name and click “OK”. Now, I need to build the functionality that shows the picture and then hides it with lots of little rectangles, which can then be individually touched or moused over to make them disappear and reveal the image. In MainPage.xaml inside of the Grid, let’s add an image for the picture that will be hidden. In addition, let’s give the Grid a name (I’ll use the super-creative name of “LayoutRoot”) so that we can access it programmatically. Next, we need some code-behind in MainPage.xaml.cs that implements the basic functionality of the game. At a high level, we are displaying an image from the Pictures Library and then covering it with a series of small rectangles. When each rectangle is touched or moused over, it will disappear and reveal the picture underneath. To implement this, we will need to initialize the LayoutRoot grid using InitializeGrid. The method SetRandomPictureAsync will get the pictures from the Pictures Library and randomly choose one, and then call SetNewHiddenPictureAsync to read in and display that picture. Next, HidePicture will cover the picture with small rectangles of a color defined by GetBackgroundColor. The event handler Rectangle_PointerEntered will make a given rectangle disappear when it is touched or moused over. Finally, Rehide will make all of the rectangles appear again; we will use this functionality in the next post when we expand the game to allow the user to uncover additional pictures. Now we need to call these functions! First, modify the constructor to call InitializeGrid(). Then, add logic to OnNavigatedTo to set the hidden image and hide it. Plus, don’t forget to add these namespaces at the top of MainPage.xaml.cs: Now, there is one more thing that we need to do. Since we are accessing the Pictures library, we need to declare that the app has this capability in the app manifest. Capabilities create a climate of trust – you as the developer state upfront certain things that your app will try to do (like accessing the user’s file libraries or webcam). When an end user sees your app in the Windows Store, they can very clearly see all of these things that your app might do and can make an informed decision on whether they want to download it. For example, if I’m downloading an eReader app to read digital books and I see that it will try to access my webcam, I might wonder about that and not download it, because I don’t see a clear reason why an eReader should need my webcam for me to read books. Which brings up another good point – if you are a developer with a valid reason to access the webcam (or whatever capability) that is not immediately clear (maybe an eReader would use the webcam to scan ISBN numbers and find the corresponding digital book?), it would behoove you to explain what the app is doing with the webcam in your app listing page in the Windows Store, so you don’t scare off cautious/paranoid users like me. For more information on capabilities, see this MSDN article on "App capability declarations". Note that if we don’t specify the “Pictures Library” capability, we will get an error at runtime: In the Solution Explorer, double-click on the Package.appxmanifest file to bring up the Visual Studio editor for the manifest. Click the “Capabilities” tab, and check the “Pictures Library Access” box. At this point, our app will run. It will grab a random picture from the Pictures library and cover it with the color cyan (a light blue/green color). The user can then touch or mouse over the picture to remove the color and reveal the picture underneath. In the next post, we will add an application bar to the app to allow the user to get a new picture when they are done uncovering the first one. Other blog posts in this series: Part 1: Why Would You Want to Develop a Metro Application for Windows 8? Part 2: Getting Started Part 3: Metro Design Part 4: My "Reveal a Picture" Algorithm and Basic Code
http://blogs.msdn.com/b/jennifer/archive/2012/06/22/developing-a-windows-8-metro-app-part-4-my-reveal-a-picture-algorithm-and-basic-code.aspx
CC-MAIN-2014-41
refinedweb
1,022
61.26
I would like this function to take a string, indicating which data(x, y or z) it should plot, as an argument. def plotfit(axis): fig = plt.figure() ax = fig.gca(projection='3d') ax.set_xlabel('x') ax.set_ylabel('y') ax.set_zlabel('z') ax.scatter(xdata, ydata, func_z(vars,fitted_z),c='r') ax.set_title('B_z of %s' % name) ax.scatter(xdata, ydata, zfield, c='b') How do I make the bolded parts of the code below replaced by my string argument so that, e.g. plotfit(x) would replace all instances of bolded z below with "x" and plot accordingly ? Points of interest: What I imagine would be something along the lines of: ax.scatter(xdata, ydata, func(axis as a string)(vars,fitted_(axis as a string)),c='r') One solution is to use exec to execute different code depending on the string type argument I presume you want to parse to the function, for example: def plotfit(axis): fig = plt.figure() ax = fig.gca(projection='3d') ax.set_xlabel('x') ax.set_ylabel('y') ax.set_zlabel('z') exec("ax.scatter(xdata, ydata, func_" + axis + "(vars,fitted_" + axis + "),c='r')") A similar technique can be used for the other lines you want to do this on. Please bear in mind that it is not recommended to use exec (or eval) as it can often hide bugs and can be ambiguous. See: Why should exec() and eval() be avoided? You can use a dictionary that will act as a switch statement in your code as outlined below. def plotfit(a_letter): assert a_letter in ["x", "y", "z"] fitted = {"x" : fitted_x, "y" : fitted_y, "z" : fitted_z} fields = {"x" : field_x, "y" : field_y, "z" : field_z} afunc = {"x" : afunc_x, "y" : afunc_y, "z" : afunc_z} # ... ax.scatter(xdata, ydata, afunc[a_letter](vars,fitted[a_letter]),c='r') #... ax.set_title('B_%s of %s' %(a_letter, name)) However, you could also consider the alternatives: Note that using exec statement for such a case is seen as bad practice as described in Why should exec() and eval() be avoided?
http://www.devsplanet.com/question/35269936
CC-MAIN-2017-09
refinedweb
334
55.13
0 Members and 1 Guest are viewing this topic. Are the calibration procedures documented for this meter? Dave - the soft case seems to have disappeared from the store - are we going to see that return (particularly one suited to the larger BM786)? If you are wondering why your new BM786 multimeter didn't come with batteries, it's because DHL Express took it upon themselves to open every package and remove them & send them back. Alkaline batteries. Freak'n ALKALINE BATTERIES. So Dave - what are you going to do with a few kilos of alkaline batteries? At least they didn't reject the entire package i suppose. I received batteries with mine locally though The link to the manual here is broken...
https://www.eevblog.com/forum/testgear/new-eevblog-bm786-multimeter/msg3424876/?PHPSESSID=3170fqjd8g25h1afn546oekoc1
CC-MAIN-2021-31
refinedweb
122
64.91
The 2003 completion of the Human Genome Project marked a true milestone in the history of the human race--a 13-year, global enterprise to map the entirety of our genetic blueprint. But the real work of this reverse engineering of our genetic makeup has only just begun. The next step is one of meaningfully interpreting this massive volume of data--a task that amounts to deciphering a text of three billion characters, in a language that's only passably understood even by molecular biologists. Such analyses present bioinformatics developers with computational tasks on scales, and at levels of complexity, rarely seen before. Using the scalable, cross-platform, network-aware power of Java technology, researchers at Great Britain's famed Sanger Institute for genetic study have spawned BioJava--an open-source project dedicated to providing genomic researchers with a Java technology-based developer's toolkit. BioJava offers bioinformatics developers over 1200 classes and interfaces for manipulating genomic sequences, file parsing, CORBA interoperability, and more. The facility is already being used at major research and pharmaceutical centers, and in over 85 countries around the world. In this era following the completion of the Human Genome Project, bioinformatics is clearly a field whose time has come. In an earlier time, genetics was a field of research whose major discoveries were typically made at the lab bench. But many, if not a majority, of such discoveries are now being made in silicon. With the sheer volume of data and analysis, spanning multi-national pharmaceutical companies and academic collaborative networks, the work simply could not be done without computers. It's not at all uncommon for larger research labs to be generating several hundred Gbytes (or more) of new data, per day. BioJava was spawned in the mid-90s as a result of the computational needs of Matthew Pocock and Thomas Down, two Ph.D. students at the Sanger Institute in Cambridge, England. As a major sequencing center of the Human Genome Project, Sanger attracts many of the best and the brightest from around the globe. "At the time we arrived," says Pocock, "the Sanger Centre was just getting into sequencing the Human Genome, and it was a very exciting time. The whole world passed through the door. Anybody who was anybody was there at some point during the weekly lab meetings." Pocock arrived at Sanger with C++ and Perl coding experience already under his belt, but soon found the languages lacking for his tasks. "With Perl, I just couldn't get the performance I needed," says Pocock. "When you're working with Genomic data sets, you're often dealing with Gigabytes of data. And Perl didn't handle that very well. C++ could handle that amount of data, but the language really didn't help you to write portable, robust code." Pocock began meeting regularly with other developers at Sanger, exchanging bioinformatics coding techniques and design patterns. Then, a year or two into his PhD program, word got out that the Java 2 platform had been ported to the various platforms being used at the center. "At that time, we had Sun Solaris nodes, Pentium Pro boxes running Red Hat Linux, and DEC Alpha systems running OSF1," he says. As a result of the diverse systems being used at the Sanger Center, cross-platform compatibility was of the utmost importance. "Once we had a Java virtual machine 1 (JVM) for all of our various platforms, I could develop and run Java applications at my desktop, but also have them run on our large compute clusters. And not only was the code portable, the Java language kept me from making terrible coding mistakes." In the same way that genomic data tends to be shared and networked, so does genomic software development. And this made the cross-platform compatibility of Pocock's Java applications all the more valuable to colleagues. "If anyone wrote a piece of software, there were typically ten people who immediately wanted to use it," he reports. "But you have no control over what hardware they may be using." Once Pocock became office-mates with Thomas Down, the two began sharing software and development tips. "We'd regularly find that we'd both written parsers for the same types of files, or had created object models for the same types of data. After a while, it all got a bit silly." So they joined forces, sharing code, and creating a CVS repository for the code. "That's when the BioJava project was really born," says Pocock. The first set of classes was officially released in the Fall of 2000. "Just in time to catch the new wave of students arriving at University," says Pocock. "We had about 100 classes at that point." From its inception, BioJava was designed by interface, but providing working implementations so that developers could extend or replace behavior and implementations. While BioJava was originally hosted out of a hardware box in someone's bedroom, the facility is now hosted and maintained under the auspices of the Open Bionformatics Foundation, which also hosts such companion bioinformatics facilities as BioPerl, BioSQL, and BioPython. The OBF handles the member facilities' modest requirements of hardware ownership, domain name management, and funding for conferences and workshops. While the foundation does not participate directly in the development or structure of the facilities, the members of the foundation are drawn from the member projects, so there is a clear commonality of direction and purpose. "Once a year or so, we all meet up on a sort of coding/hackathon vacation," notes Pocock, "to make sure all the different projects interoperate, as best as possible." The collaborative and shared nature of genomic research all but cried out for BioJava and the OBF's open source model. BioJava is distributed under an LGPL (GNU Lesser General Public License). The LGPL allows developers to modify the code and fix bugs, and to use the facility as a library foundation upon which to build both free software and commercial packages. Every attempt has been made to keep BioJava usable in almost any environment. "A major constraint is that it has to be possible for anyone to download it and use it, and compile it from scratch if they want to," says Pocock. "So we couldn't tie it into any one IDE. I personally use InteliJ, but other people use Emacs, Eclipse, NetBeans, and more. Meanwhile, we use the standard javac compiler, Apache ANT for the build, and JUnit for testing. And we also use that for regression testing. Every night, we build the entire project and run all the tests." BioJava has grown tremendously since its beginnings. The most recent site statistics show 1,264 public classes and interfaces, with over 200,000 lines of code, and over 14 people regularly contributing to the code. "The total number of classes sounds a bit scary when you count it," explains Pocock, "but there are really only about 15 interfaces. And pretty much everything you ever write is to those 15 interfaces. So there's a frightening amount of complexity that you never see, and are happy not to see!" Both Pocock and Down keep an active hand in maintaining and enhancing the BioJava code, but it is a truly collaborative open source effort. "Someone like myself, or Thomas, or Mark Schreiber, who is now a major contributor to the site, would approve anything that touched the core object model. And we would also discuss that on the mailing list or the IRC. But the project is actually quite modular. There are two people who are involved with the sequence-searching algorithm code. And they would be in charge of making sure that anything committed to that was safe and sane. In the current era, there is no one person who knows the entire library, or who has responsibility for it." The most recent monthly site statistics (for April of 2004) show a hit rate of over 170,000, with greater than 400 downloads of the BioJava package, comprising a total of over 130,000 files. At peak times, the site receives over 10,000 hits an hour. The cross-platform compatibility of BioJava has definitely served it well, particularly in an industry where vendor hardware can change at the stroke of a politician's pen, or at the dictate of a biotech corporate merger. "We're currently running on Wintel boxes," says Pocock, "on three or four flavors of Linux, on Sun Sparc, and on Mac OS X-based Xserve arrays--pretty much anywhere that can run a Java 1.2 JVM." And while cross-platform compatibility is a key requirement for the BioJava facility, of nearly equal importance are such features of Java technology as ease of development, scalability, and compatibility with legacy applications and systems. "Scalability is a huge one for us," says Pocock. "You can have genetic sequences that are seven or eight characters long, or that are 3 Gbytes long. And ideally, you want the same API to manipulate them both." The bioinformatics realm is clearly still somewhat in "wild west" mode, prone to disparate and home-brewed formats and facilities. So BioJava has to be flexible enough to accommodate this rapidly changing industry. "In bioinformatics, I can sit in my office, write a program that turns out to be useful, give it to a friend, and before I know it, it's being used by 20,000 people. And suddenly, people around the world are writing programs that consume a data format that I made up in my room at home." In addition to more newly-created home-brewed formats, developers in the genomics realm must also contend with internationally-recognized genomic data banks, as well as formats created by other major software facilities being used in the industry. In terms of genetic databanks, there are a handful of major entities. "There are three historical ones," reports Pocock, "EMBL, which is the European databank, Genbank, which is the American version, and DDBJ, which is the Japanese version. Then, for storing protein sequences, which is important in the growing field of proteomics, there's Swiss-Prot." In addition to established data banks, there is also a plethora of genetic analysis facilities, often with their own proprietary formats. "You have Fasta, which just stores the sequences raw," says Pocock, "and then Blast, SSearch, T-Coffee--and every one can have a different file format." BioJava has to seamlessly handle all of these disparate data types and data formats. "We try to make the memory representation format-agnostic, so that it doesn't matter how you read or write the sequence while you're manipulating it. You have the same sequence in memory, but can then dump it out into multiple formats. You have to enable people to drop-in their own particular formats without having to get into the guts of BioJava." And in a realm driven by both massive data storage facilities and globally networked systems, and interfacing with disparate systems and facilities, features of the Java platform such as JDBC, JNDI, RMI, and CORBA interoperability also play a vital role. "We have huge data sets," says Pocock, "and it's not practical to load all of that into memory at any one instant. So we use JDBC a lot." For Pocock, even computational throughput can sometimes be best facilitated by using the Java language. "When you're processing entire genomes, you can never have enough computing power," he admits. "But with the Java language, because you have the flexibility of using objects by API, by interface, and to delegate and shuttle things around, you can take a generic algorithm that's optimized to the particular problem such that it often runs faster than a comparable C program. If you're doing a raw compute problem, then Java won't go faster than C. But if it's a problem of complexity, Java can often, particularly with the HotSpot compiler, perform quite well." While the BioJava facility is large and offers great flexibility and features, it also offers extensive documentation and help content. The site's "Getting Started" section details the location of the downloadable binary files, CLASSPATH setup, how to obtain the modifiable source code, and how to compile and run the provided demo programs. There is also a tutorial area, and extensive JavaDoc content. Finally, thanks to Mark Schreiber, a Principal Scientist for the Novartis Institute for Tropical Diseases in Singapore, there is the "BioJava In Anger" area on the site, an extensive, generously documented "How To" section. BioJava In Anger offers a cookbook, "How Do I...?" approach to using BioJava, which was precipitated by Schreiber's own early experiences with the facility, and by frequently asked question on the mailing list. "BioJava can be hard to understand at first," says Schreiber, "particularly for novice programmers. The API is huge, so it's a bit hard to find a starting point to begin learning, and to figure out how to instantiate some of the objects. Also, it uses many advanced concepts--like interface-based design, singleton objects, and objects with private and protected constructors." Schreiber recognized that a great majority of users might have relatively simple tasks they'd like to perform. "BioJava is enormously flexible, and you can do some pretty complex things with it," he says. "But 95% of users will, at least initially, want to do fairly standard tasks." He began putting up generously-documented solutions to common tasks using BioJava. And the content has proven so popular, it's now been translated into other languages. "The most incredible thing for me is that it's now been translated into French, Japanese, and Chinese," he enthuses. Schreiber's only regret is being unable to always find the time to add desired new content. "I'm very appreciative of any contributions that other people make," he says. "I'd also like to start developing advanced pages for the site, to demonstrate some of the more complex things you can do with the API." It doesn't require a geneticist to take BioJava out for a test drive. Both Genbank and EMBL offer publicly accessible databases of genomic data. Using these, and examples from BioJava In Anger, it's relatively straightforward to put together sample BioJava-powered applications. To review, DNA has a basic alphabet of four nucleotides: A (Adenine), G (Guanine), C (Cytosine), and T (Thymine). While the computer byte contains eight digital bits, the logical unit of DNA is the "triplet code." Each group of three nucleotide bases (say, C-T-A) codes for a particular amino acid, the building blocks of all protein. These triplet codes (or "codons") instruct the methodical, step-by-step addition of amino acids, until, finally, a completed protein chain emerges. In the cell, DNA is first "transcribed" into RNA, and this complementary RNA is then "translated" into protein (through the step-by-step addition of amino acids coded for by the RNA). In the transcription of DNA, each nucleotide (A, G, C, and T) codes for a complement in the resultant RNA: A->U(Uracil), G->C, C->G, and T->A). It's a bit like translating a number from octal to hex. The same information is contained in both, it's just a matter of different storage systems. Below is an example from BioJava In Anger to transcribe a DNA sequence to RNA, and to then translate that sequence to a protein. The exploding field of bioinformatics offers Java developers an array of exciting new career opportunities. While a majority of current developers have come to the field from the biology world, picking up coding expertise along the way, the reverse path is also a very real possibility. "I would say that the industry is currently about 2/3 biologists who got into bioinformatics, and 1/3 computer people," says Pocock. "You don't need to be an expert in biology to be a bioinformatics person, but you need to know the basic processes that go on in the cell. If you're an individual who's already an experienced developer, I'd recommend reading the first few chapters of a couple of genetics textbooks, and then writing some code." BioJava 1.3 is the current official release of the facility, built upon the Java 1.2 platform. In late 2004 or early 2005, BioJava 2 is slated for release, with new features built upon the Java 1.5 platform. Pocock see the generics support of the Java 1.5 platform as a particularly big plus for their upcoming release. "It allows us to re-use much more utility code, such as from the Collections framework, without the current type safety issues," he says. "For example, using generics when processing a sequence file, we can return an Iterator over Sequence Object, whereas in earlier Java platform releases, we would have had to return an Iterator over Object. About a quarter of the bugs in the last year were due to these types of type-safety issues. The other big feature that Java 1.5 offers us is source code annotations, which allow a developer to tag source code (such as a class or method) with extra annotations." While BioJava is an open source toolkit, there are already ample business opportunities in and around the facility. In addition to his academic duties -- teaching a Bioinformatics course at The School of Computer Science, University of Newcastle upon Tyne -- Pocock offers training sessions in the use of BioJava. And in partnership with Down and several other colleagues, he has formed Symference, a company providing customized life-science computing solutions to biotech companies. In addition to working with BioJava, Symference offers a companion Java technology based facility called Taverna, which is a web services oriented workflow management tool. Taverna unifies biological discovery on one platform, integrating disparate computing resources. Meanwhile, Chris Dagdigian (who was instrumental in forming the Open Bioinformatics Foundation and is on its board of directors), has partnered with several colleagues to form BioTeam, a consulting collective dedicated to delivering vendor-neutral informatics solutions to the life sciences industry. The team offers everything from needs assessment, to application optimization, to infrastructure design, to platform installation and tuning. And the bioinformatics field is really just getting started. Less than 2% of the Human Genome codes for protein. The rest, like the dark matter of cosmology, is a relative unknown, seemingly comprised of various regulatory and "epigenetic" regions of information. Then there's the burgeoning field of proteomics (the study of protein structure and function), which may eventually dwarf genomics in terms of data and computational analysis needs. And more recently, bioinformatics has even entered into the realm of "in-silico" computational simulations of living systems--beginning at the cellular level, then, theoretically, on up to the organ level, and eventually to the level of entire organisms. Such simulations offer the promise of predictive models, where the effects of a potential new drug can be tested computationally, prior to any actual animal or human testing. In short, the more we learn in bioinformatics, the more we discover there is to learn! The computational tasks, and developer opportunities, are virtually endless.
http://www.oracle.com/technetwork/articles/javase/biojava-140011.html
CC-MAIN-2014-52
refinedweb
3,204
51.48
On Fri, 2011-06-10 at 14:25 +0200, Svante Signell wrote: > On Tue, 2011-06-07 at 15:09 +0200, Thomas Schwinge wrote: > > Hallo! > > > > On Tue, 7 Jun 2011 12:46:59 +0200, Samuel Thibault <sthibault@debian.org> wrote: > > > Svante Signell, le Tue 07 Jun 2011 10:48:04 +0200, a écrit : > > > > Is there a possibility to make ntpdate to work, even if ntpd does not? > > > > > > I'd say yes: mach has coarse-grain time adjustment. .. > Hi, looks like ntpdate (ipv4) works for querying and setting the time. > However, ipv6 does not work, and the ntp package has to be disabled. > Looks promising though. More later. Update: Now ntdate does not hang when using -4 or -6 switches, but in gdb it hangs for all combinations of switches. Looks like the hang is at the same place, independent of if poll() or select() is used, see code snippet. Hangs after first call and a new thread created: gdb: [New Thread 22736.5] 21 Jun 15:01:28 ntpdate[22736]: setsockopt() IPV6_V6ONLY failed: Protocol not available calling select, maxfd=7, rdfdes=96 <-my printf [New Thread 22736.6] HANG HERE #ifdef HAVE_POLL_H nfound = poll(rdfdes,(unsigned int)nbsock,timeout.tv_sec*1000); <-here #else nfound=select(maxfd,&rdfdes,(fd_set *)0,(fd_set *)0,&timeout); <-here #endif if (nfound > 0) input_handler(); else if (nfound == SOCKET_ERROR) {...etc Stack corruption?? How to find out?? Complete backtraces: Using poll: Using select:
https://lists.debian.org/debian-hurd/2011/06/msg00076.html
CC-MAIN-2020-16
refinedweb
235
75.61
Opened 6 years ago Closed 4 years ago #16491 closed Uncategorized (fixed) transaction.is_dirty() is very (and surprisingly) conservative Description As near as I can tell transaction.is_dirty() returns True if any queries have been executed at all (I think this is what lead to #15317 being reported). This is sort of fair enough (it's better to have a false positive for this sort of thing) but it certainly confused me for a good few minutes (commit_manually was complaining at me on exit). If it can't be made more accurate, at least the docstring should be improved. I'll try to come up with a patch tomorrow. Change History (3) comment:1 Changed 6 years ago by comment:2 Changed 4 years ago by I find no occurrences of the string "Django will raise a TransactionManagementError exception" in the Django code base. Is the commit_manually docstring still misleading? def commit_manually(using=None): """ Decorator that activates manual transaction control. It just disables automatic transaction control and doesn't do any commit/rollback of its own -- it's up to the user to call the commit and rollback functions themselves. """ ... I suggest this bug is marked as resolved. comment:3 Changed 4 years ago by This is the fix that is already committed: We're discussing. I'm accepting this ticket as a documentation patch, to fix the following inconsistency. The docs for commit_manually()are misleading: The behavior is correctly described in the next paragraph, "Requirements for transaction handling": Also, I think this is related to #6623: that ticket discusses the wording of the error message, and your confusion certainly stemmed from there too. In terms of process, please assign the ticket to yourself if you're working on a patch.
https://code.djangoproject.com/ticket/16491
CC-MAIN-2017-13
refinedweb
291
52.9
Overview The Digital Asset Links protocol and API enable an app or website to make public, verifiable statements about other apps or websites. For example, a website can declare that it is associated with a specific Android app, or it can declare that it wants to share user credentials with another website. Here are some possible uses for Digital Asset Links: - Website A declares that links to its site should open in a designated app on mobile devices, if the app is installed. - Website A declares that it can share its Chrome user credentials with website B so that the user won't have to log in to website B if it is logged into website A. - App A declares that it can share device settings, such as location, with website B. Key terms - Principal: The principal is the app or website making the statement. In Digital Asset Links, the principal is always the app or website that hosts the statement list. - Statement list: Statements are contained in a statement list that contains one or more statements. A statement list is cleartext and publicly accessible, in a location that is controlled by the principal and difficult to spoof or tamper with. It can be a free-standing file, or a section of another, larger item. For example, on a website, it is an entire file; in an Android app, it is a section in the app manifest. Statements can be viewed and verified by anyone, using non-proprietary methods. See the statement list documentation for more information. - Statement: A statement is a tightly structured JSON construct that consists of a relation (what the statement says to do, for example: Enable sharing credentials) and a target (the website or app that the relation applies to). Therefore, each statement is like a sentence, where principal says relation about target. - Statement consumer: A statement consumer requests a statement list from a principal, checks for the presence of a statement against a given principal, and if it exists, can perform the action specified. See the statement comsuming documentation for more information. Quick usage example Here's a very simplified example of how the website could use Digital Asset Links to specify that any links to URLs in that site should open in a designated app rather than the browser: - The website publishes a statement list at. This is the official name and location for a statement list on a site; statement lists in any other location, or with any other name, are not valid for this site. In our example, the statement list consists of one statement, granting its Android app the permission to open links on its site: [{ "relation": ["delegate_permission/common.handle_all_urls"], "target" : { "namespace": "android_app", "package_name": "com.example.app", "sha256_cert_fingerprints": ["hash_of_app_certificate"] } }]A statement list supports an array of statements within the [ ] marks, but our example file contains only one statement. - The Android app listed in the statement above has an intent filter that specifies the scheme, host, and path pattern of URLs that it wants to handle: in this case,. The intent filter includes a special attribute android:autoVerify, new to Android M, which indicates that Android should verify the statement on the website described in the intent filter when the app is installed. - A user installs the app. Android sees the intent filter with the autoVerifyattribute and checks for the presence of the statement list at the specified site; if present, Android checks whether that file includes a statement granting link handling to the app, and verifies the app against the statement by certificate hash. If everything checks out, Android will then forward any intents to the example.com app. - The user clicks a link to on their device. This link could be anywhere: in a browser, in a Google Search Appliance suggestion, or anywhere else. Android forwards the intent to the example.com app. - The example.com app receives the intent and chooses to handle it, opening the puppies page in the app. If for some reason the app had declined to handle the link, or if the app were not on the device, then the link would have been sent to the next default intent handler matching that intent pattern (often the browser). Important considerations and limitations: - The protocol does not authenticate the principal making the statement, but the statement is located in a specific location strongly associated with the principal, and under control of the principal. - The protocol does not authenticate the statement target, but it provides a means for the caller to authenticate the target (for example, a statement identifies mobile app targets by certificate hash and package name). - The protocol does not natively perform any statement actions; rather, it enables the ability to expose statements, which a consuming application must validate and then decide whether and how to act upon. Android M natively performs these steps for you; for example, if a website delegates link handling to a specific app, Android checks and verifies the statement, verifies the target app, and then offers the app the option to handle the given link. - The protocol does not enable making statements about two third parties: that is, website A can make a statement about website B, but website A cannot make a statement about website B's relationship to website C. However, if website B trusts website A, it can check website A for a statement granting permission to website C, and decide to implement that.
https://developers.google.com/digital-asset-links/v1/getting-started?authuser=0
CC-MAIN-2021-04
refinedweb
907
56.08
I have to mock a method which is not associated with any class. Could someone help me? It's something like this: #device.rb require_relative 'common' class Device def connect_target(target) status = connect(target) return status end end #common.rb def connect(target) puts "connecting to target device" end I have to mock a method which is not associated with any class. There is no such thing as a method not associated with any module. There is exactly one kind of method in Ruby: instance methods of modules (or classes, which are modules). connect is defined as a private instance method of Object. You would mock it something like this: allow(some_device).to receive(:connect) Note that it doesn't even matter anyway, where the method is defined: there is no mention of either Device or Object here.
https://codedump.io/share/ZxmGnXYRkbGQ/1/how-to-mock-a-method-that-is-outside-of-a-class-in-rspec
CC-MAIN-2017-17
refinedweb
138
58.48
RecursiveBlur QML Type Blurs repeatedly, providing a strong blur effect. More... - List of all members, including inherited members - RecursiveBlur is part of qtgraphicaleffects-blur.. Note: This effect is available when running with OpenGL. Example The following example shows how to apply the effect. import QtQuick import Qt5Compat.GraphicalEffects Item { width: 300 height: 300 Image { id: bug source: "images/bug.jpg" sourceSize: Qt.size(parent.width, parent.height) smooth: true visible: false } RecursiveBlur { anchors.fill: bug source: bug radius: 7.5 loops: 50 } }). By default, the property is set to 0.0 (no blur). This property defines the source item that is going to be blurred. Note: It is not supported to let the effect include itself, for instance by setting source to the effect's parent. This property defines the blur behavior near the edges of the item, where the pixel blurring is affected by the pixels outside the source edges. If the property is set to true, the pixels outside the source are interpreted to be transparent, which is similar to OpenGL clamp-to-border extension. The blur is expanded slightly outside the effect item area. If the property is set to false, the pixels outside the source are interpreted to contain the same color as the pixels at the edge of the item, which is similar to OpenGL clamp-to-edge behavior. The blur does not expand outside the effect item area. By default, the property is set to.
https://doc-snapshots.qt.io/qt6-dev/qml-qt5compat-graphicaleffects-recursiveblur.html
CC-MAIN-2022-33
refinedweb
241
60.01
EJB 3.0 client in J2SE project By pblaha on Dec 19, 2005 Today, I would like to show how you can create client for EJB 3.0 in J2SE project. First, we will need to create a bean with remote interface. Since, we are using EJB 3.0 this is very simple. Create business interface with Remote annotation and then create bean's implementation class of your bean and specify JNDI name of this bean: . The client launcher is located in bin directory of your application server. It's cool, but some smart user can ask what's about remote clients that aren't run on same machine as Glassfish? It's trivial task, you need to run package-appclient script that packs the application client container libraries and jar files into an appclient.jar file. This jar you can copied on remote server, unpack, change some properties and run your client. More info about this command is avalaible here. Now, let's develop EJB client without ACC. This client is similar as for EJB 2.1. It means first lookup bean interface and then invoke your business methods. You don't need to call create, ... and other lifecycle methods for the bean. @Stateless(name="ejb/ProcessHello") public class ProcessHelloBean implements org.netbeans.ProcessHello { public void String getHello(){ ....Now, we have two ways how to create client. First one is using Application Client Container (ACC) and second one is without that. What is advantage of the ACC? ACC can be seen as lightweight container that is responsible for security, naming, communication with application server and especially for injection. However, the worse of this approach is that you need run your application with appclient launcher. The client that uses ACC can be written like: @EJB(name="ejb/ProcessHello") private org.netbeans.ProcessHello hello; hello.getHello();Then you need to run your client's jar with launcher appclient -client InitialContext ctx = new InitialContext(); Object obj = ctx.lookup("org.netbeans.ProcessHello"); ProcessHello hello = (TestTableRemote)PortableRemoteObject.narrow(obj, ProcessHello.class); hello.getHello();In this sample I used default JNDI name that is fully qualified classname of the remote business interface (3.0) or remote home interface (2.x). If you want to change the JNDI name use mappedName attribute for @Stateless. One very important feature of GlassFish is the ability to distribute your Java EE app client via Java Web Start. This allows developers to create an application client (using Java EE 5 features like injection) and allows an enterprise to do almost painless application provisioning. This document has some more information that might be useful. Posted by guest on December 19, 2005 at 11:50 AM CET # Is such support also in other Application Server? Posted by Christopher Atlan on December 19, 2005 at 01:17 PM CET # Posted by guest on December 20, 2005 at 12:54 AM CET # Posted by guest on December 22, 2005 at 02:25 AM CET # Posted by Sahoo on December 22, 2005 at 07:27 AM CET #
https://blogs.oracle.com/pblaha/entry/ejb_3_0_client_in
CC-MAIN-2016-36
refinedweb
502
58.18
Hi!I ran into what I see as unsolvable problems that make epoll useless as ageneric event mechanism.I recently switched to libevent as event loop, and found that my programswork fine when it is using select or poll, but work eratically or haltwhen using epoll.The reason as I found out is the peculiar behaviour of epoll over fork.It doesn't work as documented, and even if, it would make the use ofthirdfd sets. This would explain the behaviour above. Unfortunately (orfortunately?) this is not what happens: when the fds are being closed byexec or exit, the fds do not get removed from the epoll set.This behaviour strikes me as extremely illogical. On the one hand, onecannot share the epoll fd between processes normally, but on fork,you can, even though it makes no sense (the child has a different fd"namespace" than the parent) and actually works on (then( unrelated fds inthe other process.It also strikes as weird that the order of closing fds should make so muchof a difference: if the epoll fd is closed first in the child, the otherfds will survive in the parent, if its closed last, they don't. Makes nosense to me.Now, the problem I see is not that it makes no sense to me - thats clearlymy problem. The problem I see is that there is no way to avoid theassociated problems except by patching all code that would ever use fork,even if it never has heard anything about epoll yet. This is extremelynonlocal action at a distance, as this affects a lot of code not even theauthorpatterns? Shouldn't epoll do refcounting, as is commonly done underUnix? As the fd space is not shared between rpocesses, why does epolltry? Shouldn't the epoll information be copied just like the fd tableitself, memory, and other resources?As it looks now, epoll looks useless except in the most controlledenvironments, as it doesn't duplicate state on fork as is done with theother fd-related resources (as opposed to the underlying files, which areproperly shared).-- The choice of a -----==- _GNU_ Deliantra, the free in data+content MORPG ----==-- _ generation ---==---(_)__ __ ____ __ --==---/ / _ \/ // /\ \/ / -=====/_/_//_/\_,_/ /_/\_\-To unsubscribe from this list: send the line "unsubscribe linux-kernel" inthe body of a message to majordomo@vger.kernel.orgMore majordomo info at read the FAQ at
http://lkml.org/lkml/2007/10/27/25
CC-MAIN-2016-26
refinedweb
401
60.04
> In a recent note, Jeff Trawick said: > > > Date: Sun, 7 May 2000 22:25:34 -0400 > > > > It should be o.k. for non-EBCDIC platforms to include and compile them as > > long as they collapse to nothing, right? > > > Alternatively, the #include could be wrapped with #ifdef EBCDIC. Minor > compile time performance consideration. > > -- gil > -- > StorageTek > INFORMATION made POWERFUL Yes, that is how it is today. At the moment, I think it is worthwhile to consider increasing build times by a very small amount in return for avoiding #ifdefs, so at the moment I'm more interested in seeing how much negative feedback I get. Your response would seem to go in that category :) Alternatively, maybe this is more palatable to everybody if it is layered as follows: Blindly include "util_charset.h" where appropriate. inside util_charset.h: #ifdef APACHE_XLATE #ifdef CHARSET_EBCDIC #include "util_ebcdic.h" #endif (future stuff applicable to charset handling in general other than stuff that would live in a module like mod_ebcdic or mod_charset) #endif /* APACHE_XLATE */ At the current time, APACHE_XLATE isn't defined and there is no util_charset.h (or even util_ebcdic.c or util_ebcdic.h) but those are minor details which are easily corrected. -- Jeff Trawick | trawick@ibm.net | PGP public key at web site: Born in Roswell... married an alien...
http://mail-archives.apache.org/mod_mbox/httpd-dev/200005.mbox/%3C200005081356.JAA08327@k5.localdomain%3E
CC-MAIN-2017-30
refinedweb
213
67.35