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
I want to plot a graph with different errors each point, independent of the value. My code is here: import matplotlib.pyplot as plt x=[1,2,3,4,5,6] y=[10,20,30,40,50,60] errorx=[0.1,0.3,0.7,0.6,1,1.5,0.2] errory=[0.1,0.8,0.4,2.3,0.1,1.2,0.6] plt.errorbar(x,y,yerr=None,xerr=None) plt.plot(x,y) Firstly, you set yerr and xerr equal to None in your example (as seen in your comment), therefore no error bars will be shown. Secondly, your list of x and y errors are not the same length as that of your x and y coordinates. Therefore if you tried to plot this you would get a ValueError: xerr must be a scalar, the same dimensions as x, or 2xN. and the same thing would happen for your the y error too. The errorbar documentation can be found here. A working example using your data is shown below: import matplotlib.pyplot as plt x = [1,2,3,4,5,6] y = [10,20,30,40,50,60] errorx = [0.1,0.3,0.7,0.6,1,1.5] #now the same length as x and y errory = [0.1,0.8,0.4,2.3,0.1,1.2] plt.errorbar(x, y, yerr=errory, xerr=errorx, linestyle='') #change linestyle to not connect the points plt.show() This produces the following graph:
https://codedump.io/share/T9oM1PuqwtZt/1/different-errors-with-matplotlib
CC-MAIN-2017-13
refinedweb
251
75.61
Opened 4 years ago Closed 4 years ago #20912 closed Uncategorized (invalid) A little modification on the tutorial Description Im unsure why, but on the beginning of the 3rd part of the tutorial, in the configuration of polls.urls only worked after I added mysite to polls polls/urls.py from polls import views I changed to from mysite.polls import views Also added the mysite to the other urls.py urlpatterns = patterns(, url(r'polls/', include('mysite.polls.urls')), url(r'admin/', include(admin.site.urls)), ) Change History (1) comment:1 Changed 4 years ago by Note: See TracTickets for help on using tickets. Hi, The tutorial looks correct to me so something else must have gone wrong on your end. Here's a few things you could check: startappcommand from inside the top-level directory of your project. If you're still running into problems, you can get some more help on our support channels: Thanks.
https://code.djangoproject.com/ticket/20912
CC-MAIN-2017-26
refinedweb
158
65.83
Green line along the top & bottom of a burned DVD. - Currently Being ModeratedJul 8, 2013 12:37 PM (in response to Eleven23) What codec does the 4:3 video use originally - by this, I mean the source clips, not the Sequence setting on your timeline. What are the pixel dimensions? Some NTSC video has 486 horizontal lines. DV has 480. Is the line there all the time or just when particular sections of video are playing? What was the sequence setting on your Timeline? Field Dominance is not a choice - it is either right or wrong. All interlaced video is upper field (odd numbered lines) dominant, but with one exception - the DV format is lower field (even numbered lines) dominant. I think I know why you have this problem but need answers to the questions above to help further. - Currently Being ModeratedJul 8, 2013 12:52 PM (in response to Eleven23) Thanks Nick, Not sure how to find this information (Codec) on the 4:3. Do I do so by checking the original source (which was simply imported only) or do I check it from the timeline on FCP ? The 4:3 was from the multi-camera video that the college made. My 16.9 is from a Canon Vixia HF R100 which I shot personal footage of and and combining the two to make a even better video. I do not mind the 4:3 changing to 16:9 and back and forth, its not a concern for me. But the second question is more about the color quality not looking so hot. Believe it or not the 4:3 color is better...... And of course the still photo's seem of poor quality once on the DVD. Is there a fix for that as well ? Let me know how I can find out the pixel dimensions, sequence setting of the timeline and yes the small green line is there all the time (top & bottom). Just more noticeable on the 4:3 playback as you see it where there is no video over the left and right black area. - Currently Being ModeratedJul 8, 2013 1:59 PM (in response to Eleven23) First, click anywhere on your timeline. Then type Command + 0 {zero) to see your Sequence Settings. Either report those sequence settings, or take a screen shot of the Sequence Settings and post that here. Next, click on the 4:3 source clip in the FCP browser to select it. Once it is selected, type Command + 9 to see the item properties for the clip. Either report those properties, or take a screen shot of the item Properties and post that here. Next, click on a source clip for the R100 video, and once it is selected, type Command + 9 to see the item properties for the clip. Either report those properties or take a screen shot of the item Properties and post that here. To clarify, you created your timeline sequence, and the exported a QuickTime movie that was self-contained and withour conversion and took that file into iDVD? MtD - Currently Being ModeratedJul 8, 2013 3:39 PM (in response to Eleven23) That's interesting. I would of never discovered that..... Lets try this as it will not let me displace the grabbed screen captures here. (say's missing plug in when I do) As for the exporting of it, I went to FCP and clicked File, SHARE, Create DVD, Play Movie...... It made the DVD self contained for me there. Thank you both for your time with this, it is much appreciated ! This is for the R100 video, (16:9): Sequence, tracks = 4V, 4A, 29.97 fps 1920 x 1080, Apple Intermediate Codec, Square, upper (Odd), nothing under composite. This is for the 4:3 media: Clip, QuickTime Player, tracks = 1V, 2A, 29.97, 720 x 480, DV/DVCPRO - NTSC, 6.9 mb / sec. Lower (Even), Normal composite. This is for the Export Timeline. Frame Size: 1920 x 1080 HDTV 1080i (16:9) Square, Upper (Odd) 29.97, Apple Intermediate Codec, quality 100% - Currently Being ModeratedJul 9, 2013 1:37 PM (in response to Eleven23) You used the Share option then, not iDVD. Share isn't very reliable. The better way would have been to Export self contained and then use Compressor - it is far better at scaling down for DVD. In Compressor, use the DVD preset that the running time of your movie fits into. You then take the files it produces into DVD Studio Pro and make your disc there. Apple Intermediate would not be my first choice of codec when we have the ProRes options in FCP. Compressor can help you with that for the 4:3 footage. You can pull the 1080 footage straight from the camera and convert to ProRes on ingest. - Currently Being ModeratedJul 9, 2013 10:14 PM (in response to Nick Holmes) Fair enough, I did not know this about the share option.... I am not familiar with Compressor and how to use it. Or anything about DVD presets in Compressor. (Suggestions on that one would be useful for me). The video is only 26 mins. in length. Also, you are saying to use ProRes (which I know is the better quality, yet bigger file to export). Is this going to become a quicktime file by doing so? Then take that into DVD Studio Pro ? You say Compressor can help me with the 4:3 footage and I can pull the that I "SHOULD" (in the future?) import the 1080 footage straight from the camera and convert to ProRes on ingest. Can you do that or wouldn't it be two a two step process. Forgive me as I am not that current on this information. Which again, is why I am here.... Any thoughts shared would be appreciated. - Currently Being ModeratedJul 9, 2013 10:38 PM (in response to Eleven23) To make a DVD using Compressor/DVD Studio 4: In FCP, export a file of your finished sequence as a Self Contained, without Conversion QuickTime movie. Take that file into Compressor, apply the settings for a DVD < 90 minutes, and let compressor work. This will result in 2 files - an audio file and a video file. Take those two files and bring them into DVD Studio Pro as Assets. Construct a menu, if you choose. Burn the DVD in DVD Studio Pro. Eleven23 wrote: import the 1080 footage straight from the camera and convert to ProRes on ingest. Can you do that or wouldn't it be two a two step process. If your camera is recording AVCHD, you can ingest most formats of AVCHD directly to FCP by connecting the camera to your computer and using File > Log and Transfer (not Log and Capture). Because FCP was written a while ago, it does not support AVCHD when shooting at 60p or 50p. For those formats, you can purchase an app called Clipwrap which will convert the files to ProRes and then import those converted files into FCP. Or you can look at new editing software such as FCP-X or Adobe Premiere Pro, both of which allow direct editing of AVCHD and H.264 source material without prior conversion. MtD
https://discussions.apple.com/message/22440959
CC-MAIN-2014-15
refinedweb
1,204
81.83
This is what you mean right? DBMS Hashing Is that for AI search or just DBMS search? This is what you mean right? DBMS Hashing Is that for AI search or just DBMS search? Sorry for the late reply. For my chatbot works, I have keyword and response. The Chatbot get the response from the keyword. So, the search algorithm is for the keywords. Or in my program it should... Yes, I already read some books and browse any information about chatbot in internet. But, any of it didn't mention the searching algorithm they use including ELIZA. It is like they made a chatbot AI... I have an AI (Artificial Intelligence) project. And I decided to make a Chatbot. To build an AI, we need searching algorithm right? The algorithm like DFS, BFS, hill climbing, etc. So, I need... Yes, I see. Alright then I'll change the GUI with JDialog. Thanks then! I marked it into solved for now. Thanks for the help. Oh, I see... So basically the dialog must wait the user. So, How about if the time is over, the program will write down automatically the false answer, so the dialog will close and continue into... So.. This is the problem: There are 3 question in this game and every question is limited by time. If the user failed to to input the answer the first question before the time limit, the user must... I solved the timer thing (the time limit is 3 second), I add this in Matimatika class: public String getInput(String input) { TimerTask task = new TimerTask() { public... No, the compiler not shown any error like that, I swear it :confused: I paste the code above again and run it and not shown any errors. Nope, no error has shown. But, it's not what I want. This is the output: run: 1 <-- This is the timer's count answer: The time didn't increase until I repeatedly inputed the answer, what I want is the timer continually count and doesn't... I already said the problem after the code section: What I want is, if I enabled the scanner, the scanner will run along with the timer's count. When the count is at 3, the scanner will ask the... I tried the java.util.Timer: package timertest; import java.util.*; public class TimerTest { I deleted the code because it solved I don't ready to advance JFrame. I guess I have to use just JOptionPane for now plus timer of course. Hahaha Hey Greg! Now I understand the stack/queue and ArrayList too :) And if you don't mind please guide me again at this thread. Thanks!... I make math game which the question is randomed and, the player must input the correct answer. I make the game with JOptionpane and it works well. Now, I want to add timer in my game, I want to add... I like the concept of 'adjustable' array, you said. I'll try to figure it out. And I'll study about ArrayList after it. Yes, now I understand Stack, because I use it for my college project. I'll... deleted I deleted my code, for safety, hahaha Yup, in that forum already have the tutorial. So, it solved. Thanks for your responses! --- Update --- Hey greg! This is the code from my previous project, hope you can help me... This the code: I deleted my code, for safety, hahaha This is for my school project. My instructor told me to make game from java but based on GUI. And I thought about it, I want to make Tic Tac Toe (X-O) game. Any one in here can guide me to complete... Yup, I will never using parallel arrays :p My understanding is until searching. But, if I really stuck for this project, I'll skip it for now. When I figure it out and make some codes, I'll post...
http://www.javaprogrammingforums.com/search.php?s=8a203cb10184b5ba07b3ab3941c1343d&searchid=1929536
CC-MAIN-2015-48
refinedweb
657
85.69
Suppose we have a list of numbers called nums. We have to find the number of permutations of nums such that sum of every pair of adjacent values is a perfect square. Two permutations A and B are unique when there is some index i where A[i] is not same as B[i]. So, if the input is like nums = [2, 9, 7], then the output will be 2, as we have [2, 7, 9] and [9, 7, 2] To solve this, we will follow these steps − res := 0 Define a function util() . This will take i if i + 1 is same as size of nums , then res := res + 1 return visited := a new empty set for j in range i + 1 to size of nums, do s := nums[i] + nums[j] if s is not visited and (square root of s)^2 is s, then mark s as visited swap nums[i + 1] and nums[j] util(i + 1) swap nums[i + 1] and nums[j] From the main method do the following − visited := a new set for i in range 0 to size of nums, do swap nums[i] and nums[0] if nums[0] is not visited, then util(0) mark nums[0] as visited swap nums[i] and nums[0] return res Let us see the following implementation to get better understanding − from math import sqrt class Solution: def solve(self, nums): self.res = 0 def util(i): if i + 1 == len(nums): self.res += 1 return visited = set() for j in range(i + 1, len(nums)): s = nums[i] + nums[j] if s not in visited and int(sqrt(s)) ** 2 == s: visited.add(s) nums[i + 1], nums[j] = nums[j], nums[i + 1] util(i + 1) nums[i + 1], nums[j] = nums[j], nums[i + 1] visited = set() for i in range(len(nums)): nums[i], nums[0] = nums[0], nums[i] if nums[0] not in visited: util(0) visited.add(nums[0]) nums[i], nums[0] = nums[0], nums[i] return self.res ob = Solution() nums = [2, 9, 7] print(ob.solve(nums)) [2, 9, 7] 2
https://www.tutorialspoint.com/program-to-count-number-of-permutations-where-sum-of-adjacent-pairs-are-perfect-square-in-python
CC-MAIN-2022-05
refinedweb
357
60.79
Technical Support On-Line Manuals C251 User's Guide #include <string.h> int hstrcmp ( const char huge *string1, /* first string */ const char huge *string2); /* second string */ The hstrcmp function compares the contents of string1 and string2 and returns a value indicating their relationship. Note The hstrcmp function returns the following values to indicate the relationship of string1 to string2: hstrcpy, strcmp #include <string.h> #include <stdio.h> /* for printf */ void tst_strcmp (char huge *buf1, char huge *buf2) { char i; i = hstrcmp (buf1, buf2); if (i < 0) printf ("buf1 < buf2\n"); else if (i > 0) printf ("buf1 > buf2\n"); else printf ("buf1 == buf2.
http://www.keil.com/support/man/docs/c251/c251_hstrcmp.htm
CC-MAIN-2020-05
refinedweb
102
69.11
Last month we announced a technical preview of the next generation of Sentinel imports in Terraform Cloud. We are now happy to announce the API has reached a level of stability and is now generally available for use in production for Terraform Sentinel policies. These imports still need to be imported using the additional "/v2" suffix at this point in time, so make sure to use import "tfconfig/v2", import "tfplan/v2" and import "tfstate/v2" in your Sentinel policies. In the future, as we transition these imports into the default path and sunset the old v1 import API for Terraform 0.12, with an option to control this behavior in Terraform Cloud. For the most up to date documentation on the imports, check out these pages within the Terraform Cloud documentation. Sentinel is offered in Terraform Cloud as part of the Team and Governance Tier or in Terraform Enterprise. To get started with Terraform Cloud, you can sign up for a free account. Finally, if you are an existing TFC or TFE customer, and you have feedback regarding the new imports, submit a support ticket and let us know. from Hashicorp Blog:
https://awsfeed.com/uncategorized/terraform-sentinel-v2-imports-are-now-ga
CC-MAIN-2020-40
refinedweb
193
60.75
Introducing Bugsy - Client Library for interacting with Bugzilla Mon 16 Jun 2014 I have created a library for interacting with Bugzilla using the native REST API. Bugsy allows you to get bugs from Bugzilla, change what you need to and then post it back to Bugzilla. I have created documentation to get you started. For example to get a bug you would do import bugsy bugzilla = bugsy.Bugsy() bug = bugzilla.get(123456) and then to put it back, or if there is no bug ID (like if you were creating it) then you would do is not currently supported but will definitely be there for the next version. Please raise issues on GitHub
http://www.theautomatedtester.co.uk/blog/2014/introducing-bugsy-client-library-for-interacting-with-bugzilla.html
CC-MAIN-2015-40
refinedweb
113
72.46
How Web APIs work? Yusei Ito Aug 17 '18 ・1 min read Hello,I'm Yusei, a Japanese student. I have written JavaScript for 4 years. At this article,I'll tell you what web API is, and how can use them easily. Please be aware of this post is written for beginners. Expressions are rough. They may be not correct strictly. What is Web API? Actually here's no definition in a narrow sense. But in a board sense,Web API is the over application or over system interface using network on HTTP protocol. APIs make get datas or use functions over application easy even if you don't know about how the functions are served. *API:Application Programming Interface So you can Request functions or datas that you want to the API-Server and, you'll get Response. Responce is the result of your request. How to request? How to get Response? It's depends on each Web-APIs. But generally,you can get response to access Query URL. Query URL is made of "Basic URL" and "Query". Basic URL is the URL for each services. For example,. To make your request, you need decide some parameters. Query specifies your parameters. Generally,Query is like [key]=[value]&&[key2]=[value2].... Field you will specify the value is specified at the left hand with a key of the parameter field, and the parameter's value is specified at the right hand. Each query expressions are connected with && Eventually, connect*Basic URL* and Query with "?". Your request's Query URL will be created like... then. You can use the created URL as a link to the response data. Generally such functions are available at all Web APIs. Point of this section - Web APIs connect application each other. - Web APIs make get datas or use functions easy. - With Web API,You don't need to know how the functions served a lot. - To using Web API,you can Request features. And results will be returned as a Response - Format of Request or Response is depends on each web API. - Generally We can create request URL with basic URL and Query. Web APIs example. They are all available in 2018 ! Google APIs. Yahoo APIs.. How to use Web API? I'll show you how to use Open Weather Map API for example. In this section,I'll tell you how to make current weather widget to embed your website. Current weather data of each location is served by Open Weather Map API. Let's start tutorial! Step 1.Set up your project. 1.Please make a directory ,and html file for your project. Set the html code up like below. <html> <head> </head> <body> <div id="Weather_Widget"> </div> <script src="index.js"></script> <!-- ^ Please put your file name. ^ --> <body> </html> If you want to embed this widget for your website, you don't need to make.Maybe you have already made that and you have files there. But the <div>element is needed for you if you don't want to create new html. Please add only the <div>to your html's somewhere you want to add the widget. 2.Make empty .js file(It's needed for everyone even if you don't need to do step 1.) 2.Sign Up to Open Weather Map API from here. 3.Get your API key . API key is the id of applications.That looks random numbers and alphabets string. The API uses this for analytics, user recognizathion,and authentication. 4.Find location id. Just you need to visit here. And search location that you want to embed weather. When the place is found, copy the location details. The url is like. The last 7 letters string is the location id. Step2. Let's code! Weather API's response is formatted as a JSON. If you don't know about JSON,please learn what it is and how to treat JSON with JavaScript. I suggest you to see this article. You understand that, see the code below. Each lines are commented for your code reading. /* The example code for using weather api. Created by Yusei Ito 2018. Creative Commons license. In this example, we will make a weather widget which shows current weather in Muang Xai, Laos. Codes will processed on order each comment shows. Ex) Process will progress like 0.Call a function.-> 1.Creat Http Request object to access the URL-> 2.Create URL ->2a. set YOUR API KEY->2b. Basic URL */ function getWeather() { var data = new XMLHttpRequest(); //1.Creat Http Request object to access the URL data.onreadystatechange = function() { //5. On 'readystate' changed, that situation means that works on progress. if ((data.readyState == 4) && (data.status == 200)) { //6.Check the status. readyState=4 means you have already got data. ststus=200 means your application received http status code 200. It means your request is processed completely. If each status means 'succeed',Go to next process below. var json = JSON.parse(data.responseText); //7.Perse data as a json object let city = json.name;//8.Get city name from son object var txt = "Weather at " + city + ", Fetch:" + Date() + "<br>";//9.Write a response header. //10.Get each values from JSON. let temp = json.main.temp_min; let weather = json.weather[0].main; let weather_desc = json.weather[0].description; let amount_clouds = json.clouds.all; let wind_speed = json.wind.speed; let wind_deg = json.wind.deg; //11.Make a text message that will be visible. txt = txt + "Temp:" + temp + " <br> Weather:" + weather + " <br> description:" + weather_desc + "\n " + "<br>clouds:" + amount_clouds + "% <br>wind:" + wind_speed + " <br>deg:" + wind_deg + "<br>"; document.getElementById("Weather_Widget").innerHTML=txt;// 12(Finally).Display the text. } }; var URL_JSON = CreateRequestURL();//2.Create URL data.open("GET", URL_JSON, true);//3.Run HTTP "GET" method to GET the response. data.send(null);//4.You don't need to send any http parameter. You send 'null'. } function CreateRequestURL() { //This function makes your query URL. let API_KEY = "321bj4g321v1utd34f12yf21tus4du12yu" //2a. set YOUR API KEY let BASE_URL = "" //2b. Basic URL let city = "1655078" //2c. city id you want to request. (This is the id of Mango Tai,Laos) return (BASE_URL + "?id=" + city + "&APPID=" + API_KEY);//2d.Make URL by connecting base URL and query. } getWeather();//0.Call a function. Then,save your .js file and open your html. The weather details text displayed? You can ask me anything if you have any problem from dev.to's comment form, or my twitter. And you can download working code from my github repo. Thank you for reading and happy coding with APIs! I've re-built my portfolio based on a Dribbble shot I found. What do you think? I built a portfolio based on a dribbble shot I found, would love your feedback
https://dev.to/yuseiito/how-web-apis-work-490c
CC-MAIN-2019-09
refinedweb
1,119
80.28
Appointment Reminders with Python and Django Ready to implement SMS appointment reminders in your Django web application? We'll use the Twilio Python Helper Library and Twilio SMS API to push out reminders to our customers when appointments are near. Here's how it works at a high level: - An administrator (our user) creates an appointment for a future date and time, and stores a customer's phone number in the database for that appointment - When that appointment is saved a background task is scheduled to send a reminder to that customer before their appointment starts - At a configured time in advance of the appointment, the background task sends an SMS reminder to the customer to remind them of their appointment Check out how Yelp uses SMS to confirm restaurant reservations for diners. Appointment Reminder Building Blocks Here are the technologies we'll use: - Django to create a database-driven web application - The Messages Resource from Twilio's REST API to send text messages - Dramatiq to help us schedule and execute background tasks on a recurring basis How To Read This Tutorial To implement appointment reminders, we will be working through a series of user stories that describe how to fully implement appointment reminders in a web application. We'll walk through the code required to satisfy each story, and explore what we needed to add at each step. All this can be done with the help of Twilio in under half an hour. Meet our Django Appointment Reminder Stack We're building this app for Django 2.1 on Python 3.6. We're big fans of Two Scoops of Django and we will use many best practices outlined there. In addition to Dramatiq, we will use a few other Python libraries to make our task easier: - The twilio-python Python helper library - django-timezone-field to give us a model field for storing time zones - django-bootstrap3 and django-forms-bootstrap to make our form templates simpler and prettier - The fantastic arrow library to make our datetime math foolproof We will also use PostgreSQL for our database and Redis as our Dramatiq message broker. Now that we have all our depenencies defined, we can get started with our first user story: creating a new appointment. Creating an Appointment As a user, I want to create an appointment with a name, guest phone number, and a time in the future. To build an automated appointment reminder app, we probably should start with an appointment. This story requires that we create a model object and a bit of the user interface to create and save a new Appointment in our system. At a high level, here's what we will need to add: - An Appointmentmodel to store information we need to send the reminder - A view to render our form and accept POST data from it - An HTML form to enter details about the appointment Alright, so we know what we need to create a new appoinment. Now let's start by looking at the model, where we decide what information we want to store with the appointment. The Appointment Model We only need to store four pieces of data about each appointment to send a reminder: - The customer's name - Their phone number - The date and time of their appointment - The time zone of the appointment We also included two additional fields: task_id and created. The task_id field will help us keep track of the corresponding reminder task for this appointment. The created field is just a timestamp populated when an appointment is created. Finally, we defined a __str__ method to tell Django how to represent instances of our model as text. This method uses the primary key and the customer's name to create a readable representation of an appointment. Our appointment model is now setup, the next step is writting a view for it. New Appointment View Django lets developers write views as functions or classes. Class-based views are great when your views need to support simple, CRUD-like features - perfect for our appointments project. To make a view for creating new Appointment objects, we'll use Django's generic CreateView class. All we need to specify is the model it should use and what fields it should include. We don't even need to declare a form - Django will use a ModelForm for us behind the scenes. Success messages Our view is ready to go with just those first three lines of code, but we'll make it a little better by adding the SuccessMessageMixin. This mixin tells our view to pass the success_message property of our class to the Django messages framework after a successful creation. We will display those messages to the user in our templates. Now that we have a view to create new appointments, we need to add a new URL to our URL dispatcher so users can get to it. Wiring up the URLs To satisfy the appointment creation user story, we'll create a new URL at /new and point it to our AppointmentCreateView. Because we're using a class-based view, we pass our view to our URL with the .as_view() method instead of just using the view's name. With a view and a model in place, the last big piece we need to let our users create new appointments is the HTML form. New Appointment Form Our form template inherits from our base template, which you can check out at templates/base.html. We're using Bootstrap for the front end of our app, and we use the django-forms-bootstrap library to help us render our form with the |as_bootstrap_horizontal template filter. By naming this file appointment_form.html, our AppointmentCreateView will automatically use this template when rendering its response. If you want to name your template something else, you can specify its name by adding a template_name property on our view class. We are not leaving this form yet. Instead, let's take a closer look at one of its widgets: the datepicker. Appointment Form Datepicker To make it easier for our users to enter the date and time of an appointment, we'll use a JavaScript datepicker widget. In this case, bootstrap-datetimepicker is a good fit. We include the necessary CSS and JS files from content delivery networks and then add a little custom JavaScript to initialize the widget on the form input for our time field. Now let's go back to our Appointment model to see what happens after we successfully post this form. Add a get_absolute_url() Method When a user clicks "Submit" on our new appointment form, their input will be received by our AppointmentCreateView and then validated against the fields we specified in our Appointment model. If everything looks good, Django will save the new appointment to the database. We need to tell our AppointmentCreateView where to send our user next. We could specify a success_url property on our AppointmentCreateView, but by default Django's CreateView class will use the newly created object's get_absolute_url method to figure out where to go next. So we'll define a get_absolute_url method on our Appointment model, which uses Django's reverse utility function to build a URL for this appointment's detail page. You can see that template at templates/reminders/appointment_detail.html. And now our users are all set to create new appointments. We are now able to create new appointments. Nex, let's quickly implement a few other basic features: listing, updating, and deleting appointments. Interacting with Appointments As a user, I want to view a list of all future appointments, and be able to edit and delete those appointments. If you're an organization that handles a lot of appointments, you probably want to be able to view and manage them in a single interface. That's what we'll tackle in this user story. We'll create a UI to: - Show all appointments - Edit individual appointments - Delete individual appointments Because these are basic CRUD-like operations, we'll keep using Django's generic class-based views to save us a lot of work. We have the high level view of the task, so let's start with listing all the upcoming appointments. Showing a List of Appointments Django's ListView class was born for this. All we need to do it's to point it at our Appointment model and it will handle building a QuerySet of all appointments for us. And wiring up this view in our reminders/urls.py module is just as easy as our AppointmentCreateView: from .views import AppointmentListView re_path(r'^$', AppointmentListView.as_view(), name='list_appointments'), Our view is ready, now let's check out the template to display this list of appointments. Appointment List Template Our AppointmentListView passes its list of appointment objects to our template in the object_list variable. If that variable is empty, we include a <p> tag saying there are no upcoming appointments. Otherwise we populate a table with a row for each appointment in our list. We can use our handy get_absolute_url method again to include a link to each appointment's detail page. We also use the {% url %} template tag to include links to our edit and delete views. And now that our appointment listing requirement is complete, let's see how we can use the new Appointment form to update exisiting appointments. Tweaking our Form Template Django's UpdateView makes it easy to add a view for updating appointments. Our form template needs a few tweaks, though, to handle prepopulated data from an existing appointment. Django will store our datetimes precisely, down to the second, but we don't want to bother our users by forcing them to pick the precise second an appointment starts. To fix this problem we use the extraFormats configuration option of bootstrap-datetimepicker. By configuring our datetimepicker with a format value that doesn't ask users for seconds, and an extraFormat value that does accept datetimes with seconds, our form will populate correctly when Django provides a full datetime to our template. We now have everything to List, Create and Update an Appointment. All that is left is handle the Delete. Delete View DeleteView is an especially handy view class. It shows users a confirmation page before deleting the specified object. Like UpdateView, DeleteView finds the object to delete by using the pk parameter in its URL, declared in reminders/urls.py: from .views import AppointmentDeleteView re_path(r'^/(?P[0-9]+)/delete$', AppointmentDeleteView.as_view(), name='delete_appointment'), We also need to specify a success_url property on our view class. This property tells Django where to send users after a successful deletion. In our case, we'll send them back to the list of appointments at the URL named list_appointments. When a Django project starts running, it evaluates views before URLs, so we need to use the reverse_lazy utility function to get our appointment list URL instead of reverse. By default, our AppointmentDeleteView will look for a template named appointment_confirm_delete.html. You can check out ours in the templates/reminders directory. And that closes out this user story. Our users now have everything they need to manage appointments - all that's left to implement is sending the reminders. Sending the Reminder As an appointment system, I want to notify a customer via SMS an arbitrary interval before a future appointment. To satisfy this user story, we need to make our application work asynchronously - on its own independent of any individual user interaction. One of the most popular Python library for asynchronous tasks is Dramatiq. To integrate Dramatiq with our application, we need to make a few changes: - Create a new function that sends an SMS message using information from an Appointmentobject - Register that function as a task with Dramatiq so it can be executed asynchronously - Run a separate Dramatiq worker process alongside our Django application to call our SMS reminder function at the right time for each appointment If you're brand new to Dramatiq, you might want to skim its Introduction to Dramatiq page before proceeding. Next we will configure Dramatiq to work with our project. Setting up Dramatiq Dramatiq and Django are both big Python projects, but they can work together easily. By following the instructions in the Dramatiq docs, we can include our Dramatiq settings in our Django settings modules. We can also write our Dramatiq tasks in tasks.py modules that live inside our Django apps, which keeps our project layout consistent and simple. To use Dramatiq, you also need a separate service to be your message broker. We used Redis for this project. The Dramatiq-specific settings in our common.py settings module is DRAMATIQ_BROKER. If you want to see all the steps to get Django, Dramatiq, Redis, and Postgres working on your machine check out the README for this project on GitHub. Now that Dramatiq is working with our project, it's time to write a new task for sending a customer an SMS message about their appointment. Creating a Dramatiq task Our task takes an appointment's ID - it's primary key - as its only argument. We could pass the Appointment object itself as the argument, but this best practice ensures our SMS will use the most up-to-date version of our appointment's data. It also gives us an opportunity to check if the appointment has been deleted before the reminder was sent, which we do at the top of our function. This way we won't send SMS reminders for appointments that don't exist anymore. Let's stay in our task a bit longer, because the next step is to compose the text of our SMS message. Sending an SMS Message We use the handy arrow library to format our appointment's time. After that, we use the twilio-python library to send our message. We instantiate a Twilio REST client at the top of the module, which looks for TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN environment variables to authenticate itself. You can find the correct values for you in your account dashboard. Sending the SMS message itself is as easy as calling client.messages.create(), passing arguments for the body of the SMS message, the recipient's phone number, and the Twilio phone number you want to send this message from. Twilio will deliver the SMS message immediately. With our send_sms_reminder task complete, let's look at how to call it when our appointments are created or updated. Calling our Reminder Task We added a new method on our Appointment model to help schedule a reminder for an individual appointment. Our method starts by using arrow again to build a new datetime with the appointment's time and time_zone. Moving backward in time can be tricky in normal Python, but arrow's .replace() method lets us easily subtract minutes from our appointment_time. The REMINDER_TIME setting defaults to 30 minutes. We finish by invoking our Dramatiq task, using the delay parameter to tell Dramatiq when this task should execute. We can't import the send_sms_reminder task at the top of our models.py module because the tasks.py module imports the Appointment model. Importing it in our schedule_reminder method avoids a circular dependency. The last thing we need to do is ensure Django calls our schedule_reminder method every time an Appointment object is created or updated. Overriding the Appointment Save Method The best way to do that is to override our model's save method, including an extra call to schedule_reminder after the object's primary key has been assigned. Avoiding duplicate or mistimed reminders Scheduling a Dramatiq task every time an appointment is saved has an unfortunate side effect - our customers will receive duplicate reminders if an appointment was saved more than once. And those reminders could be sent at the wrong time if an appointment's time field was changed after its creation. To fix this, we keep track of each appointment's reminder task through the task_id field, which stores Dramatiq's unique identifier for each task. We then look for a previously scheduled task at the top of our custom save method and cancel it if present. This guarantees that one and exactly one reminder will be sent for each appointment in our database, and that it will be sent at the most recent time provided for that appointment. Fun tutorial, right? Where can we take it from here? Finishing the Django Appointment Reminder Implementation We used Django's class-based views to help us quickly build out the features to support simple CRUD operations on our Appointment model. We then integrated Dramatiq into our project and used the twilio-python helper library to send SMS reminders about our appointments asynchronously. You'll find instructions to run this project locally in its GitHub README. Where to Next? And with a little code and a dash of configuration, we're ready to get automated appointment reminders firing in our application. Good work! If you are a Python developer working with Twilio, you might want to check out other tutorials in Python: Put a button on your web page that connects visitors to live support or sales people via telephone. Two-Factor Authentication Improve the security of your Python app's login functionality by adding two-factor authentication via text message..
https://www.twilio.com/docs/sms/tutorials/appointment-reminders-python-django
CC-MAIN-2020-16
refinedweb
2,887
60.55
What is COMInteroperability (Interop)? Why is it important? These are some of the basic questions that might come to mind when Interop is mentioned. And if you are developing a data access layer, another question pops into mind. How does this affect our components when we have ADO.NET to take care of all the needs as far as data access is concerned? In this chapter, we will arrive at some answers to these questions, and gain an understanding of how to use Interop in our applications. Interop enables the interoperation of managed code with unmanaged code, and vice versa. The code that runs under the Common Language Runtime (CLR) is managed code, and the code that runs outside CLR is unmanaged code. For example, all the components (assemblies) that are created using the .NET framework are managed code, and all the components that are developed with Win32 API are unmanaged code. The.NET framework introduces a completely new model for application development and deployment. We no longer have to think about the choice of programming language because every language generates the same metadata in Microsoft Intermediate Language (MSIL) format. At the end of the day it does not matter how the metadata was generated, it will all be Just In Time (JIT) compiled to same native (for example x86) code. If we closely study all the evolutionary changes that every developer will have to take into consideration, it may not be very incorrect to say that we will have to unlearn all the old concepts and start from square one. Does this mean that all the old applications and components that you have been using for quite some time on the server side or middle tier will stop working in .NET framework, or cannot be used in the .NET enabled applications? Absolutely not. Our efforts and investment in the old and tested components will not be wasted at all. This is where Interop comes into play. COM Interop allows us to utilize existing COM (Component Object Model) components in our .NET applications without needing to modify the COM components in any way. As .NET gains acceptance we will hear a lot about Interop in the .NET framework. This chapter will first give a brief overview of Interop and then demonstrate the ways in which it can be used to access classic ADO components, and exploit facilities not yet developed for ADO.NET to leverage your .NET data access components. Interop enables managed code to call unmanaged code transparently, and for unmanaged code to call managed code. In practice, this means that we do not need to rewrite unmanaged components to operate with .NET applications, and that we can develop managed components to work with unmanaged components. All we need to do, is make use of some utilities and tools provided with the .NET SDK to integrate existing applications with managed applications. We will look at these tools and utilities later in the chapter. In an ideal world, we would probably want to covert all existing unmanaged code to managed code. In many cases this would be impractical, given certain design constraints, however, and � more importantly � the time framework in which to roll out the new application. Sometimes it is not possible to convert the unmanaged code to managed code at all: for example, if the source code is not available. Also, there may be a particular type of operation that we wish to implement: for instance, utilizing a recordset with a server side cursor, which cannot be achieved with ADO.NET. In both these types of situations, Interop comes to the rescue by enabling the use of classic ADO technology. Also, there are some other technologies, complementing ADO, such as Microsoft ActiveX Data Objects Extensions for Data Definition Language and Security ( ADOX), Jet Engine and Replication Objects (JRO) and ADO for Multi-Dimensional Data (ADOMD) that are not supported by ADO.NET. Interop is the only way to integrate these technologies into a managed application. Therefore, Interop is going to play a very important role when migrating existing applications to .NET. This chapter will not discuss how to use ADO, ADOX, JRO, and ADOMD data access technologies. If you wish to learn more about them, please consult Professional ADO 2.5 Programming (Wrox Press, ISBN 1-861002-75-0) and ADO 2.6 Programmer's Reference (Wrox Press, ISBN 1-861004-63-X). All the managed objects are garbage collected, meaning that when a particular object is not required anymore, and there is no one holding any reference to it, the garbage collector (GC) releases memory associated with it from the managed memory heap. We are however, talking about Interop with unmanaged code. We know that there is no GC for code running outside the CLR. So what happens to the managed components that are used by the unmanaged components? What releases the references for unmanaged COM components when they are used inside the managed code? The .NET framework performs the following operations for the interoperation of managed and unmanaged code: These wrapper objects act as the conduits between managed and unmanaged execution engines. These objects act as the proxies that marshal the calls between the managed and unmanaged objects. When a COM client calls into a managed object, the runtime creates a new managed object and a CCW for that object. The object's lifetime is managed by this CCW. When the COM client calls AddRef on this managed object, the CCW holds the reference count for it. Therefore, to the COM client, this managed object appears exactly like a regular COM component. When the Release method is called on the object, CCW decrements the reference count on it. When there are no outstanding references to this managed object (in other words the reference count drops down to zero), the CCW releases the managed object in the CLR. In the next cycle of garbage collection, this released managed object gets removed from the managed heap. The COM clients using the managed objects should follow the classic COM rules for reference counting, and should make a Release call for every AddRef call. If the unmanaged code forgets to release the managed code, the CCW will keep on holding to the object, and the garbage collector will never collect it. When the managed code creates an instance of unmanaged COM components, the CLR creates the RCW for this component and maintains the reference count for it. Every time a new object of this component is created, the reference count is incremented on this RCW. When all of the referenced object are no longer needed, the RCW releases the reference to the COM object and during next garbage collection cycle this wrapper (RCW) gets collected. Before we dig deep into the use of Interop for data access components, there is one important aspect that we should look at. It is the way error handling mechanism works in Interop. In the existing COM components, the error conditions are communicated to the caller via HRESULT codes. If the call succeeds, the components return S_OK, otherwise an error code (E_FAIL, or some custom code) is returned to the caller. The managed code takes a different approach. The errors are reported by means of exceptions. If a component wants to report a failure condition to the caller, it throws an exception. This exception can be one of the .NET framework provided exception classes (for example, InvalidCastException, InvalidOperationException, and so on) or it can be a user-defined exception (a class derived from System.Exception class). When a COM component returns an error, the Interop layer converts it to one of the framework-defined classes and stores the HRESULT code into HResult property of the System.Exception class object. When a managed code throws an exception, the Interop layer converts it to an HRESULT value. Therefore, if our managed code is calling method of unmanaged code, then we should guard our implementation by providing exception handlers for the errors that will be returned. On the other side of spectrum, if we are implementing a managed code that will be used by unmanaged code, we should store the HRESULT code in the HResult property of the exception class before throwing the exception to the caller. Managed code, running in CLR, is not capable, by itself, of crossing the CLR boundary to make calls into unmanaged components. The managed code has no knowledge of the data types defined by the unmanaged code. The .NET framework is all about data types, so it needs some mechanism to refer to the data types defined in unmanaged code. The COM components define their types in the type library, which could be present in a separate file (.TLB file) or embedded as a resource in the DLL or EXE file. The .NET component's meta-data is contained in the assembly file. The .NET framework provides the tools to convert between CLR and COM data type information. This is a command line tool that can be used to convert the co classes and interfaces information, contained in a COM component's type library, into the .NET metadata information. The following example shows the simplest use of this tool to convert the ADO type library, embedded in msado15.dll, to the .NET metadata, defining the corresponding CRL types: C:\>tlbimp msado15.dll /out:ClassicADO.dll The first argument is the name of the file that contains the COM type library. This file can be a DLL, EXE, OLB, OCX or TLB file. The second argument is optional parameter that can be used to fine-tune the output from the tool. In this case, I have used the /out parameter, which specifies the name of the output file (ClassicADO.dll in this case). The detailed explanation of each optional parameter is out of scope of this book. We can call this tool with a /? option to see all the options supported, and a brief explanation of each one of them. The following screen short shows the list of options generated by the /? Parameter: For detailed explanation of these optional parameters, refer to the .NET Framework Tools section in the .NET Framework SDK Documentation. The tool converts the entire type library into the .NET metadata assembly. It cannot be used for partial conversion of the type library. Once we have created the assembly describing the metadata, we can discard the source type library file. The Interop operation does not depend on the source file anymore. The MANIFEST created in the assembly saves the GUID of the co class as GuidAttribute. The CLR creates the instance of COM object using this information from the registry. We can create the unmanaged objects in your managed applications simply by calling new operator. There is no CoCreateInstance and no QueryInterface call. The RCW takes care of all these steps behind the scene. It calls the CoCreateInstance method by using the GUID stored in the manifest of the metadata assembly generated for the COM object. This command line tool is the counterpart of the TLBIMP tool. It converts the metadata contained in a managed assembly into a type library. The following example shows the use of this tool: C:\>tlbexp myassembly.dll /out:unmancode.dll Like TLBIMP, this tool also supports a few optional parameters. The above example uses the /out parameter to specify the name of the output file. The detailed explanation of each optional parameter is out of scope of this book. We can call this tool with the /? option to see all the options supported and a brief explanation of each one of them. The following screen short shows the list of options generated by the /? Parameter: For detailed explanations of these optional parameters, refer to the .NET Framework Tools section in the .NET Framework SDK Documentation. We can directly add references to an already registered COM component's type library using Visual Studio 7.0. It will generate the assembly containing the metadata information corresponding to the types contained in the type library. It is like using TLBIMP tool where the IDE defines the optional parameter. We can add reference to the type library by selecting COM tab on the Add Reference dialog box. This will bring up the list of all type libraries registered on the system. Select the one that you want to add the reference to. These two steps will create the assembly and add the reference to the project. The following screen shots show the addition of reference for ADO 2.7 type library in a project: The type library has been added with the namespace ADODB. This class, defined in System.Runtime.InteropServices namespace, provides a programmatic way of creating the metadata information from a COM type library. This class has two methods, ConvertTypeLibToAssembly and ConvertAssemblyToTypeLib that do the conversion of types. We will not be discussing these methods in this book. For more details, refer to this class in .NET Framework Documentation. After the assembly has been created using one of the above tools, we need to refer to this assembly when compiling the source code. Depending on the programming language used, we can refer to the namespace of this assembly as shown below: VB.NET: Imports ClassicADO C#: using ClassicADO; If you are using Visual Studio 7.0, then you don't have to do any manual steps to add reference to the assembly containing the metadata information. For command line compilation of the code, use the /r option to add the reference to the DLL. VB.NET: vbc /r:ClassicADO.dll Foo.vb C#: csc /r:ClassicADO.dll Foo.cs In the last few years, ADO technology has come a long way. A lot of hard work and investment has been poured into developing robust, scalable, and reliable components that use this data access technology. The .NET data access class, OleDbDataAdapter, takes this into account and provides the Fill method, which takes an ADO Recordset object as its input parameter and populates the DataSet object with the supplied data. For more details, refer to the Fill method of the OleDbDataAdapter class in the DataAdapter chapter. This is one approach that we can use to employ ADO Recordset objects in our managed application. We can use the TlbImp tool to import the type library from existing COM objects, that have methods and properties returning the Recordset objects. Consider a case of a typical COM component, for example, Shop.dll, which has a method returning a Recordset of inventory records. First, we would use TlbImp to import the type library into a .NET assembly: C:\>tlbimp /out:ShopObjects.dll Shop.dll This imports the type library to ShopObjects.dll. Next, add reference to this managed assembly into a managed application: vbc /r:ShopObjects.dll /r:ClassicADO.dll ShopApplication.vb csc /r:ShopObjects.dll /r:ClassicADO.dll ShopApplication.cs Then in our managed assembly, create this unmanaged component as a regular CLR object using the new operator. The first step for using classic ADO objects in our managed application is to establish a reference to the metadata file, describing all the interfaces exposed by it. By default, the ADO library file, msado15.dll, is present in the following folder: <System Drive>\Program Files\Common Files\System\Ado We would use the TLBIMP tool to generate the .NET compatible assembly that we will refer to from managed code: In the above example, we have called TLBIMP from root directory, while the msado15.dll file is located in that folder. The reason we are able to do is, because we have specified the folder location of ADO files in the path variable of the system environment. Otherwise, it would be necessary that the TLBIMP tool be invoked from the same folder as the source file. Although the source file is not in the root folder, the output will be created in the root folder (C:/) and then copied to any folder from where we want to refer this metadata assembly. All the examples in the subsequent sections in this chapter invoke the TLBIMP tool from the root folder using the same approach of setting system environment's path variable. This operation will generate a .NET assembly ClassicADO.dll containing the metadata for the ADO library with the namespaceClassicADO. We can provide a fully qualified name for all the ADO objects scoped within this namespace such as ClassicADO.Connection, ClassicADO.Command, and ClassicADO.Recordset: To compile the ADO assembly generated by the TLBIMP tool into the managed code, we would add a reference as follows: VB.NET: vbc /t:library /r:ClassicADO.dll /out:EmployeeDB.dll EmployeeDB.vb C#: csc /t:library /r:ClassicADO.dll /out:EmployeeDB.dll EmployeeDB.cs The following example shows the use of ADO objects in a managed assembly. This example requires use of server side cursor support, which is not provided by ADO.NET. It opens an ADO Connection by providing a connection string and then calls the Execute method to get the Recordset object. It then uses this Recordset object to populate the DataSet using the Fill method of the OleDbDataAdapter class. This approach can also be used to get a Recordset with a server side cursor and pass it to the unmanaged code. VB.NET: Dim strQuery As String = "SELECT * FROM Employees WHERE EmployeeID = 1" Dim strConn As String = "Provider=SQLOLEDB; Data Source = SYNCMONK" & _ "; Initial Catalog = Northwind; User ID = sa; Pwd =" ' Create a new instance ADO Connection object Dim dbConn As New Connection () dbConn.CursorLocation = CursorLocationEnum.adUseClient ' Open the connection with specified connection string. dbConn.Open (strConn, "", "", (int)ConnectModeEnum.adModeUnknown) ' Execute SQL query to get the emploee record. Object recsAffected = Null Dim rs Recordset = dbConn.Execute (strQuery, recsAffected, CType (CommandTypeEnum.adCmdText, Integer)) Dim dtSet As New DataSet () Dim dtAdapter As New OleDbDataAdapter () dtAdapter.Fill (dtSet, rs, "Employee") rs.Close () C#: string strQuery = "SELECT * FROM Employees WHERE EmployeeID = 1"; string strConn = "Provider=SQLOLEDB; Data Source = Northwind"; strConn += "; Initial Catalog = Northwind"; strConn += "; User ID = sa; Pwd = ;"; // Create a new instance ADO Connection object Connection dbConn = new Connection (); dbConn.CursorLocation = CursorLocationEnum.adUseServer; // Open the connection with specified connection string. dbConn.Open (strConn, "", "", (int)ConnectModeEnum.adModeUnknown); // Execute SQL query to get the employee record. object recsAffected = null; _Recordset rs = dbConn.Execute (strQuery, out recsAffected, (int)CommandTypeEnum.adCmdText); DataSet dtSet = new DataSet (); OleDbDataAdapter dtAdapter = new OleDbDataAdapter (); dtAdapter.Fill (dtSet, rs, "Employee"); rs.Close (); Note that the second parameter to the Execute method call on the ADO Connection has been passed as a System.Object and not as a VARIANT. The reason is that VARIANT is an unmanaged data type and Interop marshals this as a System.Object. Whenever we are not clear about what data types to use for the unmanaged method parameters, it is a good idea to use the ILDASM tool and take a look at the IL Code generated for the method. IL Code generated by the TLBIMP can provide complete information about the type of parameters that need to be passed into a method call, and what kind of output it will return. The IL code acts like documentation for the imported unmanaged objects. ADO.NET provides a framework for manipulating existing data sources. Like classic ADO, it does not provide direct support for creating new data source objects, such as physical data files, maintaining users, and groups and working with the permission objects. ADO provides the Microsoft ActiveX Data Objects Extension for Data Definition Language and Security (ADOX) model, an extension library, to accomplish these tasks. But in ADO.NET, there is no direct or indirect support for these tasks. This means that we must rely on Interopto make calls into the ADOX library and perform these operations. Although ADO.NET provides managed providers for SQL Server (version 7.0 and higher), OLE DB providers, and native ODBC drivers, the use of ADOX through Interop is still limited by the ADOX features supported by the particular OLE DB provider. Of the OLE DB providers currently available, Microsoft Jet has complete support for ADOX. The OLE DB providers for SQL Server, Oracle, DB2, and others, provide a very limited implementation of ADOX. The first step for using ADOX in a managed app is to establish a reference to the metadata file describing all the interfaces exposed by it. The ADOX library file name is msadox.dll, which is present in the following folder on your machine. <System Drive>\Program Files\Common Files\System\Ado Use the TlbImp tool to generate the .NET compatible assembly that we will refer to from managed code: This operation will generate a .NET assembly ADOX.dll containing the metadata for the ADOX library with the ADOX namespace. We can provide fully qualified names for all the ADOX model objects scoped within this namespace, such as ADOX.Catlog and ADOX.Table: We will need to add reference to the ADOX assembly, generated by the TLBIMP tool, to compile it with our managed code. The following example adds a reference to ADOX.dll to generate a managed component EmployeeDB.dll. VB.NET: vbc /t:library /r:ADOX.dll /out:EmployeeDB.dll EmployeeDB.vb C#: csc /t:library /r:ADOX.dll /out:EmployeeDB.dll EmployeeDB.cs The Catalog object in ADOX can be used to create a new Access database by calling the Create method. The following code shows the use of the ADOX metadata assembly in a managed assembly to create a new database. First, it creates a new instance of the Catalog object simply by calling New operator. It instantiates a Catalog object, and then the Create method is called on it with a connection string. The connection string specifies that Jet4.0 OLE DB provider will be used to create the new Microsoft Access Database file: VB.NET: Option Explicit On Option Strict On Imports System Imports ADOX Namespace ADOX_Interop Public Class ADOX_EmployeeDB Public Function CreateEmployeeDB () As Boolean Try Dim strConn As String = "Provider=Microsoft.JET.OLEDB.4.0;" & _ "Data Source = C:\\EmployeeDB.mdb" ' Create instance of Catalog object. Dim dbCatalog As New Catalog () ' Call Create method to create mdb file. dbCatalog.Create (strConn) Catch ex As System.Exception Console.WriteLine (ex.Message) Return False End Try Return True End Function End Class End Namespace C#: using System; using ADOX; namespace ADOX_Interop { public class ADOX_EmployeeDB { public ADOX_EmployeeDB (){} public void CreateEmployeeDB () { try { string strConn="Provider=Microsoft.JET.OLEDB.4.0;"; strConn += "Data Source = C:\\EmployeeDB.mdb"; // Create instance of Catalog object. Catalog dbCatalog = new Catalog (); //Call Create method to create mdb file. dbCatalog.Create (strConn); } catch (System.Exception ex) { Console.WriteLine (ex.Message); Return false; } return true; } } } The Catalog object in ADOX exposes Tablesobject. The Tables object exposes the Columns, Index, Keys, and Properties collections. We can use these objects to append a new table to the database. The following code sample shows how we can use a Catalog object to create a Microsoft Access 2000 database .mdb file. First, the Catalog object is created to which the table will be added. Then a new instance of the Table object is created. This is the object to which all the data columns will be added. Then new data columns are appended to the Columns collection of the Table. The Column object exposes properties like Name, Attributes, DefinedSize, NumericScale, Precision, and Type. For the sake of brevity, in this example only three properties have been specified for each column, name, data type and the size. After adding the columns to the collection, the table is appended to Tables collection of the catalog by calling Append method. Finally, a primary key index is added to the Indexes collection of the table. The Index object exposes properties like Name, Unique, PrimaryKey, and so on, that can be used to control its action. VB.NET: Dim strConn As String = "Provider=Microsoft.JET.OLEDB.4.0;" & _ "Data Source = C:\\EmployeeDB.mdb" ' Create instance of Catalog object Dim dbCatalog As New Catalog () dbCatalog.Create (strConn) ' Create instance of Table object Dim dtTable As New Table () With dtTable .Name = "Address" .Columns.Append ("AddressID", ADOX.DataTypeEnum.adInteger, 4) .Columns.Append ("Street", ADOX.DataTypeEnum.adVarWChar, 128) .Columns.Append ("City", ADOX.DataTypeEnum.adVarWChar, 128) .Columns.Append ("State", ADOX.DataTypeEnum.adVarWChar, 128) .Columns.Append ("Zip", ADOX.DataTypeEnum.adVarWChar, 128) .Columns.Append ("Country", ADOX.DataTypeEnum.adVarWChar, 128) End With ' Append the table to catalog. dbCatalog.Tables.Append (CType(dtTable, Object)) ' Create the primary key column with unique values. Dim primKeyIdx As New Index () With primKeyIdx .Name = "UniqueAddrID" .Unique = True .PrimaryKey = True .Columns.Append ("AddressID", ADOX.DataTypeEnum.adInteger, 4) End With ' Append the primary index to table. dtTable.Indexes.Append (CType (primKeyIdx, Object), Nothing) C#: string strConn = "Provider=Microsoft.JET.OLEDB.4.0;" + "Data Source = J:\\NetProjects\\EmployeeDB.mdb"; // Create instance of Catalog object. Catalog dbCatalog = new Catalog (); dbCatalog.Create (strConn); // Create instance of Table object. Table dtTable = new Table (); dtTable.Name = "Address"; dtTable.Columns.Append ("AddressID", ADOX.DataTypeEnum.adInteger, 4); dtTable.Columns.Append ("Street", ADOX.DataTypeEnum.adVarWChar, 128); dtTable.Columns.Append ("City", ADOX.DataTypeEnum.adVarWChar, 128); dtTable.Columns.Append ("State", ADOX.DataTypeEnum.adVarWChar, 128); dtTable.Columns.Append ("Zip", ADOX.DataTypeEnum.adVarWChar, 128); dtTable.Columns.Append ("Country", ADOX.DataTypeEnum.adVarWChar, 128); // Append the table to catalog. dbCatalog.Tables.Append ((object)dtTable); // Create the primary key column with unique values. Index primKeyIdx = new Index (); primKeyIdx.Name = "UniqueAddrID"; primKeyIdx.Unique = true; primKeyIdx.PrimaryKey = true; primKeyIdx.Columns.Append ("AddressID", ADOX.DataTypeEnum.adInteger, 4); // Append the index to table. dtTable.Indexes.Append ((object)primKeyIdx, null); We can use ADOX objects through Interop to improve the functionality of the managed applications. Before using any of the ADOX features it is important to read the documentation for that particular OLE DB managed provider to check what support is available and what is not. For example, using the OLE DB managed provider for SQL Server, we cannot create a new table in the database as we would have using the Create method of the Catalog object in classic ADO. The following example shows how to use ADO and ADOX objects to create a new data table in a SQL Server database. VB.NET: Dim strConn As String = "Provider=SQLOLEDB;" & _ "Data Source = DOTNET; Database = FashionHouse;" & _ "User ID = foo; Pwd = ;" ' Create instance of Catalog object. Dim dbCatalog As New Catalog () ' Create ADO Connection object Dim dbConn As New Connection () dbConn.Open (strConn) dbCatalog.ActiveConnection = CType (dbConn, Object) ' Create instance of Table object. Dim dtTable As New Table () With dtTable .Name = "Categories" .Columns.Append ("CategoryID", ADOX.DataTypeEnum.adInteger, 4) .Columns.Append ("Name", ADOX.DataTypeEnum.adVarWChar, 64) .Columns.Append ("Descr", ADOX.DataTypeEnum.adVarWChar, 128) End With ' Append the table to catalog. dbCatalog.Tables.Append (CType(dtTable, Object)). To establish a reference to the metadata file, describing all the interfaces exposed by the JRO library, we would use the TlbImp tool on msjro.dll to create a .NET enabled assembly. This library file resides, by default, in the following folder on your machine: <System Drive>\Program Files\Common Files\System\Ado This operation will generate a .NET assembly JRO.dll containing the metadata for the JRO library with JRO namespace. We can provide a fully qualified name for all the JRO model objects scoped within this namespace, such as JRO.Replica and JRO.Filter: To compile the JRO assembly generated by the TLBIMP tool into the managed code, we would add a reference, as follows: VB.NET: vbc /t:library /r:JRO.dll /out:EmployeeDB.dll EmployeeDB.vb C#: csc /t:library /r:JRO.dll /out:EmployeeDB.dll EmployeeDB.cs The following example shows how a JRO Replica object can be used to create a full replication of a Microsoft Access database. VB.NET: Dim strConn As String = "Provider=Microsoft.JET.OLEDB.4.0;" & _ "Data Source = C:\\EmployeeDB.mdb" Dim strRep As String = "J:\\ EmployeeDB_Rep.mdb" 'Create an instance of Replica object Dim dbRep As New Replica () dbRep.MakeReplicable ("J:\\NetProjects\\EmployeeDB.mdb", True) ' Call CreateReplica method to create replica of Employee database dbRep.CreateReplica (strRep, "Replica of Employee Database", _ ReplicaTypeEnum.jrRepTypeFull) C#: string strRep = "C:\\EmployeeDB_Rep.mdb"; // Create an instance of Replica object Replica dbRep = new Replica (); dbRep.MakeReplicable ("C:\\EmployeeDB.mdb", true); // Call CreateReplica method to create replica of Employee database dbRep.CreateReplica (strRep, "Replica of Employee Database", ReplicaTypeEnum.jrRepTypeFull, VisibilityEnum.jrRepVisibilityGlobal, -1, UpdatabilityEnum.jrRepUpdFull); Please note that all parameters for the CreateReplica method (ReplicaType, Visibility, Priority and Updatability) must be specified in C#, whereas in VB they are optional. Does this mean that the managed code generated for VB is different than that generated for C#? Before I answer this question, lets look at the method signature generated by TLBIMP tool: .method public hidebysig newslot virtual instance void CreateReplica( [in] string marshal( bstr) replicaName, [in] string marshal( bstr) description, [in][opt] valuetype JRO.ReplicaTypeEnum ReplicaType, [in][opt] valuetype JRO.VisibilityEnum Visibility, [in][opt] int32 Priority, [in][opt] valuetype JRO.UpdatabilityEnum updatability ) runtime managed internalcall { .custom instance void [mscorlib]System.Runtime.InteropServices.DispIdAttribute::.ctor(int32) = ( 01 00 0E 00 02 60 00 00 ) // .....`.. .param [3] = int32(0x00000002) .param [4] = int32(0x00000001) .param [5] = int32(0xFFFFFFFF) .param [6] = int32(0x00000000) .override JRO.IReplica::CreateReplica } Pay attention to the last four parameters of the CreateReplica method. There are two attributes associated with each one of these. The first is [in] indicating that it is an INPUT parameter, and the second is [opt] indicating that it is an OPTIONAL parameter. Visual Basic allows the missing parameters in the methods. In case of VB, the framework replaces the missing parameters with Type.Missing object that indicates that if there are any default values specified for these parameters, use those values. The C# language specifications do not allow the use of missing parameters. You will have to specify the values for these optional parameters either explicitly or provide the Type.Missing objects for these values. The Type.Missing class is defined in the System.Reflection namespace. .NET provides no support for manipulating On Line Analytical Processing (OLAP) server data. Classic ADO provided this support through the companion ADOMD library. Once again, through Interop, we can incorporate ADOMD features into our managed applications. To establish a reference to the metadata file, describing all the interfaces exposed by ADO library, use TlbImp tool on msado.dll to create a .NET enabled assembly. This file resides, by default, in the following folder on your machine: <System Drive>\Program Files\Common Files\System\Ado This operation will generate a .NET assembly � ADOMD.dll � containing the metadata for the ADOMD library with ADOMD namespace. We can provide fully qualified names for all the ADOMD objects scoped within this namespace, such as ADOMD.Catalog and ADOMD.CubeDef. These fully qualified names will be essential if you are using ADOX objects along with ADOMD objects, because there is name collision in two namespaces: for example, both the namespaces contain the Catalog object: To compile the ADOMD assembly generated by the TlbImp tool into the managed code, add a reference as follows: VB.NET: vbc /t:library /r:ADOMD.dll /out:EmployeeDB.dll EmployeeDB.vb C#: csc /t:library /r:ADOMD.dll /out:EmployeeDB.dll EmployeeDB.cs The following example shows how ADOMD objects Catalog, CubeDefs, and CubeDef can be used along with an ADO Connection object to find all the cubes defined in the FoodMart data source provided with SQL Analytical Server 2000. The code follows the following steps: VB.NET: Dim strConn As String = _ "Provider=msolap; Data Source = localhost; " & _ "Initial Catalog = FoodMart 2000; User ID=sa; Pwd=" Dim dbConn As New ClassicADO.Connection () dbConn.Open (strConn) Dim dtCatalog As New ADOMD.Catalog () dtCatalog.ActiveConnection = CType (dbConn, Object) Dim cubes As ADOMD.CubeDefs = dtCatalog.CubeDefs Dim cube As ADOMD.CubeDef For Each cube in cubes Console.WriteLine (cube.Name) Next C#: string strConn = "Provider=msolap; Data Source = SULTAN;" + "Initial Catalog = FoodMart 2000; User ID =; Pwd="; ClassicADO.Connection dbConn = new ClassicADO.Connection (); dbConn.Open (strConn, "", "", (int)ConnectModeEnum.adModeUnknown); ADOMD.Catalog dtCatalog = new ADOMD.Catalog (); dtCatalog.ActiveConnection = (object)dbConn; CubeDefs cubes = dtCatalog.CubeDefs; Console.WriteLine ("Number of Cubes = {0}", cubes.Count.ToString ()); foreach (ADOMD.CubeDef cube in cubes) { Console.WriteLine (cube.Name); } The output of the above example is as follows: Number Of Cubes = 3 Sales Warehouse Warehouse and Sales The above example can be extended to access the Dimension, Hierarchy, Level, and Member objects contained in the various CubeDef objects. The following C# code can be added to the above example to print out the information from Time dimension of WarehouseCubeDef: ADOMD.CubeDef warehouse = cubes["Warehouse"]; ADOMD.Dimension timeDim = warehouse.Dimensions["Time"]; foreach (ADOMD.Level lvl in timeDim.Hierarchies[0].Levels) { Console.WriteLine (lvl.Caption); foreach (ADOMD.Member mem in lvl.Members) { Console.WriteLine ("\t" + mem.Caption + "\t" + mem.UniqueName); } } The following screen shot shows the output of the above code. In this chapter, we have seen how to use Interop to incorporate the features from our existing unmanaged components and other classic ADO objects. This is a very powerful mechanism provided by the .NET framework to ease the migration path from unmanaged components to managed assemblies. There are some features that mandate the use of Interop on the existing platform. The most important of these are the transaction services. The MTS and COM+ infrastructure is COM based. Therefore, if we want to create a managed component that should be able to participate in the transactions, we will have to implement it in such a way that it can be registered as a COM component. The .NET components can be registered as native COM objects using the REGASM tool. Then the component can be installed in the COM+ explorer. Now the .NET component can participate in the transactions by using Interop capabilities. Calls have to cross the CLR boundary, therefore, performance will suffer. Therefore, Interop should only be used where there is no other .NET option available. This chapter is taken from ".NET Programmer's Reference" by Dushan Bilbija, Paul Dickinson, Fabio Claudio Ferracchiati, Jeffrey Hasan, Naveen Kohli, John McTanish, Matt Milner, Jan D Narkiewicz, Adil Rehan, Jon D Reid, published by Wrox Press Limited in September 2001; ISBN 186100558X; copyright �. General News Question Answer Joke Rant Admin
http://www.codeproject.com/KB/books/186100558x_16.aspx
crawl-002
refinedweb
5,677
50.12
What is more vs optimized? Using a c# dll or just sticking everything in unity without a namespace? Answer by jashan · Dec 09, 2009 at 06:10 PM Regarding performance, there is simply no difference at all. Regarding workflow: It very much depends on your project size and how much code you want to reuse. It may be helpful to have several Visual Studio projects that go into several DLLs, using namespaces etc.; if you have very large projects and a lot of code you want to reuse. For smaller projects, this kind of overhead won't make sense. If you're on the iPhone, you can only have a limited amount of DLLs, so for that plattform, you should definitely keep as much as possible in the Unity project and avoid using your own DLLs. Answer by Ashkan_gc · Nov 18, 2009 at 08:01 AM scripting is a powerful tool for many tasks and it has many advantages: it is platform independent and you don't need to write different codes for different platforms. it's easier than coding in unmanaged languages like C++ but it's slower. .NET/MONO code is too fast and you don't need to use other languages in most cases but if you have algorithms that they are complex and they need to run many times it's a good idea to write them in C++ and then call them from unity. AI and path finding are good examples. there are also other situations that you need special features of a specific platform or you need to communicate with a special hardware and in those situations you need to write C++ or C code too. Answer by Ricardo · Nov 19, 2009 at 05:24 PM I'm unclear on what you mean by "vs optimized". Do you mean code performance, or Visual Studio ease of use? On performance, the very short version is that even if you add your C# code as scripts, Unity will end up building it to a DLL. At the end of the day, it'll be the same. Regarding Visual Studio usability, there will be no difference other than you obviously can't edit the precompiled DLL, but as long as there's a reference to it, you'll still get autocomplete and compilation working without Distributing Precompiled Scripts 1 Answer Read Files from a folder -> Load their icons as Textures 1 Answer XInputDotNetPure plugin: Namespace could not be found. 1 Answer Unity started rejecting my scripts? 1 Answer
https://answers.unity.com/questions/7860/dynamic-linking-library-more-optimized.html
CC-MAIN-2019-04
refinedweb
421
66.78
A Short Background Almost 4 months ago I switched companies and dove head first into a pool full of new technologies. After working 7 years with Java and Java technologies, all of the sudden, I used everything… except for Java. After spending the first-month doing shadow work on a hybrid mobile project, I joined the project I am currently working on. The project was for an Intellectual Property (IP) protection company. Everything revolves around Microsoft technologies so, naturally, the automation framework that was already in place was developed in Visual Studio 2017 using C# technologies. The switch from Java to C# (as programming languages) is not as difficult as Java to Python, Ruby, JavaScript. Or so I thought… The Problem It is always challenging when joining a project that has the skeleton for an automation solution in place and the team you are joining appears to already be having some success with that solution. After all, it is the QA dream to be part of the ‘birth’ of the automation solution: when all the important decisions are made, all the technologies are picked, when the architecture is decided, and so on. Energized by the change, I set up the project and got to work. I started running the first C# tests of my QA career. I spent time understanding the automation solution, read tons of documentation on Visual Studio, C#, .Net, and related technologies. After I got more familiarized with the structure and the conventions, I started putting together my first tests. As one can imagine, a lot of copy and pasting from one place to another was involved at first. Going over the tests and working on the ones I was assigned to do, I noticed something weird. The test method implementations were not doing anything to verify the steps they were performing. They were not asserting for anything: not for an element present, not for a text present, not for a visible button, not for an expected image, NOTHING. Instead of that, every method was part of a try-catch block. public void AddStudent() { try { addButton.Click(); Browser.Wait(3); firstName.SendKeys("FirstName"); Browser.Wait(3); secondName.SendKeys("SecondName"); age.SendKeys("19"); majoringIn.SendKeys("Computer Science"); Browser.Wait(1); } catch(Exception E) { Console.WriteLine("Cannot add student " + E.Message); throw E; } } The same thing was happening when actually calling for the test methods in the framework: public void CreateGradeCard() { try { LoginPage.Goto(); LoginPage.UserLogin(UserName: "user", Password: "password"); Student.AddStudent(); Student.EditStudent("StudenName"); Student.SaveTemplate(); Student.RemoveStudent("StudentName"); Header.SignOff(); } catch(Exception E) { Console.WriteLine("Test Fail " + E.Message); } } At first, I tried following the same pattern because I was a C# newbie. I put together the first batch of tests and ran them. I followed the browser and noticed that not all steps from the test method got executed, but when I switched back to Visual Studio, the test run was marked in Green. Opening the Output looked like below: So, the test passed, but we know for sure one step was not performed because of the Could not find element error. Basically, there were times when big chunks of steps were not even executed, but the test outcome would still be Passed. This would make the automation solution unreliable. The Solution A “good practice” in automation testing and especially UI functional testing, which is the case here, is making sure that what we EXPECT to happen, DID happen. Enter: TESTING ASSERTIONS. A test assertion is defined as an expression which encapsulates some testable logic specified about a target under test. As an example: - Imagine we have to test a login page for the happy flow, so the successful login. How do we know that the login was successful if we just perform steps and not assert anything? To have a reliable test we need to test that after login, we land, for example, on the expected page. So assert on the page title. I’ve been doing this my whole QA life and I expected it to be straightforward in C# as well. After removing the try-catch blocks from the tests I was designing, I started to type Assert. and expected Visual Studio to suggest the library that needed to be imported (you know, Java-style), but nothing happened. So I started Google-ing. After a couple of hours (yeah, don’t laugh, I was a newbie in C#) this stackoverflow post from 2012 appeared on the search result page with the solution. Basically, the C# framework works with references: Note the Microsoft.VisualStudio.QualityTools.UnitTestFramework reference above. It is the reference that allows users to work with Assert class. It is also one of the references that are not added to a test project by default in Visual Studio. Comparing with my previous experience, when setting up a project in Java, there were no other references/classes/modules to add individually. You would just type something like: Assert. and you would get all the suggestions that you need. But for this particular framework, in order to have it available in the automation solution, you need to add it explicitly, like below: - Microsoft.VisualStudio.QualityTools.UnitTestFramework.dll.dll can be found in “C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\PublicAssemblies\” and can be added to the project by right-clicking Referencesand Add Reference: Once added, it should be visible in the Reference Manager window: Note: the path where the .dll can be found may vary, depending on the VS installation path. Once the setup is in place, all that is left to do is importing the actual library in the class you want (this also needs to be done, as there are no suggestions to auto-import it): using Microsoft.VisualStudio.TestTools.UnitTesting; Type Assert. in the class now. The entire assert package is available. Now, if the tests will fail, the error will look like this: Now we can start creating more reliable automation solutions for our UI functionality testing. Conclusion The problem may seem trivial to an expert C# user, but it took a little time for the untrained eye to find the solution. This is meant to help whoever finds themselves working with a C# automation solution and needs to use assertions to build a more reliable test framework. It also targets the users that make the switch to C# related technologies and may find this problem in the setup process or later on. Ciprian Simon Related Posts - How to Use Test Data for Increased Software Quality Test data is a major influencer of test reliability and should be the main concern… - Pytest-bdd, TestRail, and Test Artifacts This is part of the Python Automation Testing blog series. You can review the code…
https://moduscreate.com/blog/integrating-test-assertions-in-c/
CC-MAIN-2022-21
refinedweb
1,125
54.83
10:55 AM Hello, I have a TestCase where I need to generate x number of unique strings. Let's say 10 email addresses. The way I am doing things now is I have 10 groovy script test steps that randomly create the email string and 10 Transfers. Is there a way to condense this? If I have one groovy script that generates the random string can I just evaluate it each time I do a property transfer? I have 6 other strings I need to generate as well (FirstName, LastName, etc...) so the way I am currently doing things I would have 70 test steps just for generating data. Thanks! Solved! Go to Solution. 06-19-2017 11:16 AM I typically create a properties step and use a groovy script to write my properties to that with a groovy test step. If I need multiple of the same value per request, I name them differently. Example: CustomerEmail ManagerEmail etc. If I need multiple data-sets for multiple requests, I'd have: CustomerEmail1 ManagerEmail1 CustomerEmail2 ManagerEmail2 Then in my groovy script I have a for-loop that iterates through how many data-sets I need, and generates how many elements I need per dataset. Here's a very quick groovy script example. def propertiesStep = testCase.testSteps["Properties"]; def generateEmail() { // insert email generation script here } for(int i = 1; i < 100; i++) { propertiesStep.setPropertyValue("CustomerEmail" + i, generateEmail()); propertiesStep.setPropertyValue("ManagerEmail" + i, generateEmail()); i++; } 06-19-2017 11:56 AM 06-19-2017 12:13 PM This seems like a good idea. I will try it, thanks! 06-19-2017 12:45 PM
https://community.smartbear.com/t5/SoapUI-Pro/Property-Transfer-Question/m-p/144431
CC-MAIN-2017-34
refinedweb
272
66.84
The following test asserts on mozilla-central revision c83282305cb9 (options -m -n -a): var callStack = new Array(); function exitFunc (funcName) { var lastFunc = callStack.pop(); } gczeal(4); var sb = evalcx(''); sb.parent = this; this.f = function name(outer) { return (exitFunc ('test')); } evalcx('this.f = parent.f; var s = ""; for (i = 0; i < 10; ++i) s += f(true); s', sb); S-s due to assertion known to be dangerous. This now shows up as Assertion failure: addr % Cell::CellSize == 0, at ../../gc/Heap.h:825 Created attachment 638559 [details] [diff] [review] patch This bug is similar to bug 753283. We run for a while in the methodjit and then we return to the interpreter to finish running the method. We return with the PC set to a SETLOCAL op. We immediately call the barrier verifier, which scans the VM stack. It expects the slot referenced by the SETLOCAL to be valid, but the SETLOCAL hasn't run yet, so it's uninitialized. The patch just avoids running the verifier at the start of the Interpret when a rejoin is taking place. This is a debug-only bug, so no reason to keep it closed. A testcase for this bug was automatically identified at js/src/jit-test/tests/basic/bug767074.js.
https://bugzilla.mozilla.org/show_bug.cgi?id=767074
CC-MAIN-2017-13
refinedweb
209
66.64
Java Left Shift "<<" Operator Java Left Shift "<<" Operator  ... Shift "<<" operator in Java. The Java programming language has... the usage of Left Shift "<<" operator. Description of code Shift Array Elements in Java Java Shift Array Elements This section illustrates you how to shift the array... to enter the array elements, the direction of shifting (Right or Left... accordingly and displayed the array with shifted elements. Method that shift left shift and rigth shift operators left shift and rigth shift operators hi some programs for left shift and right shift operators Master Java In A Week Master Java In A Week Master Java Programming Language in a week. This tutorial is good for beginners in Java and it will teach you the basics... in Java. Using for, while and do-while loops is not always the right idea to use Change Background of Master Slide Using Java Change Background of Master Slide Using Java  ... are using SlideShow constructor and to create master slide we are using SlideMaster... to create a slide then change background of the master slide. In this example we Master java in a week ; Class Declaration: Class is the building block in Java...; The main method is the entry point in the Java program and java program can't run... is always first thing that is executed in a java program. Here is the main method Left and Right panel in JSP - Java Beginners Java application using ajax functionality. Regards RKB...Left and Right panel in JSP Hello Friends, Please help me to showing right and left frame on my JSP page. I want to showing fix left frame which how to print from right to left in java???? how to print from right to left in java???? can anyone pls tell how to print from right to left in java Natural Left Join a connection between the java class and the database. In our program we are using... Natural Left Join In this program we are going to join the two table by using Internet and Web related questions for Web Master. Internet and Web related questions for Web Master. Explain the difference between the Internet and Web. What are Web browsers? Explain the two main... is Java? What are the applications of Java that you can use for Web designing Shifting Row Using JSP Shifting row using JSP In this program we are going to shift the row using java...; In this example, we first create 50 cells and then insert 50 values, then we shift rows Join tables with the NATURAL LEFT JOIN operation \jdbc\jdbc\jdbc-mysql>java NatLeftJoinTable Natural Left Join Tables... Join tables with the NATURAL LEFT JOIN operation This section describes the NATURAL LEFT JOIN Java EJB 3.0 Tutorials Orientating Components Right to Left,java newsletter,java,tutorial Arranging Components We often arrange the components either from left to write or right to left. For the components orientation we uses Layout Manager..., right, left and center. The BoxLayout arranges the components either in single java , visit the following links: How to shift and unshift using JavaScript? How to shift and unshift using JavaScript? How to shift and unshift using JavaScript JAVA I M building a media player using jframes using libraries of jmf and done with all things but left with some problems.. 1) not able show the timing of song.. 2) not able to volume functionality hi im new to java plz suggest me how to master java....saifjunaid@gmail.com Java Courses RoseIndia Java Courses provided online for free can be utilized by beginners in Java anywhere in the world. They can use this course to master Java language.... Using the implicit objects available to scripting elements. Using Java java java what are abstract methods Please visit the following link: Java AWT Package Example to handle different key events on the Java Awt component by using the event... This is a simple program of java awt package which constructs a look like a form by using... it. This is done by using java gui programming using Classes or APIs of java awt package highlight words in an image using java want to highlight name in the image using java/jsp/javascript.please help me...highlight words in an image using java Hai all,In my application left side image is there and right side an application contains textboxes like java :// Java Web Services Online Training Java Web Services Online Training Java Web Services online training enables students and learners to make interactive web based services using Java and its... of Java Web services. syllabus and what it takes to master java web services EJB 3.0 Tutorials using the java language. EJB is a complex topic and requires a lot of effort...; This tutorial gradually takes a new comer to master EJB along with learning the updated JEE specifications using glass-fish server java using Stack - Java Beginners java using Stack How convert decimal to binary using stack in java using eval in Java using eval in Java using eval in Java java java code of image movement left and right query String - Java Beginners query String Hi friends, I have some page and given link left side like master,utilities,reports,if i am clicking master then open master file... how i implemmented and write code and send send me, I using query string or any Java array - Java Beginners Java array Q 1- write a program that counts the frequency of a character in a string with out using in built functions? Q2-Write a program to convert a binary no to integer with out using in built functions? Q 3- Write ??all the database must be in master computer only and all other computer must retrieve that data from the master computer only.please help write a programm using java write a programm using java print the following using java programming Using throw in java method Using throw in java method using throw with method implies what New To JAVA - Java Beginners :// Thanks...New To JAVA hi iam new to java..,can you please guide me how to learn the java and also tell me how many days it takes to learn java Hi java java sample code for RARP using java java java RARP implementation using java socket java java write a java program using filenotfoundexception Creating Trapezoid Using Java on PowerPoint slide using java. In this example, we are creating a slide master... Creating Trapezoid Using Java  ... master slide we use SlideMaster constructor. Then we create an object of Slide java java how to edit text document by using java then how to edit starting and ending of text document by using java Project - Java Beginners these modules. All these modules are using more than two common master files i.e. employee master. Now, can you tell in Java programming with Mysql How can...Java Project Dear Sir, I have to do Project in "IT in HR i.e. using Stack - Java Beginners java using Stack How convert decimal to binary using stack in java? whats the java program or code to that. Thank you rose india and java experts Hi Friend, Try the following code: import java.util. java java online telephone directory i need coding for online telephone directory..by using java....pls help me java java dear, i want a field for date picker using java/java script java java How to set java Policy for applet using jdk 6 java java code to search the nodes how to write the java code to search the nodes using routers java java create java program for delete and update the details,without using database, just a normal java program Masters of Java Assignment Plugin it significantly easier to develop Master of Java Assignments by making use of the Eclipse Java IDE. The plugin has the following features... Masters of Java Assignment Plugin   div align left css div align left css Hi, How to align the div to left using the css in HTML page. Thanks RARP program using java RARP program using java hai, how to implement the RARP concept using java Mysql Left to view data of Table named employee1 using Left: The Query is used... Mysql Left Mysql Left is used to return the Left String character from a String java java how to determine the bandwidth utilization for nodes(system) using java java java how to write the java code to search the nodes using routers java java java script using add values in spring with hipernet progrme java java hello sir,how to run a particular directory using java java java tribonacci series program in java by using a return statements java java how to get values using datainputstream in java java java how to post a text on web page using java and xml java java how to print special series using java literals java java How to create progress bar in neatbean software(using java)? Can i have shooting code in neatbean software(using java Image using Java coding Image using Java coding Hai, Display image in pdf file using Java coding through Xsl file.. Please help me.. xsl file generate the pdf file java code using swings java code using swings code that should be able to enter data of student details using all swings into the access database using jdbc connectivity OOP using Java - Java Beginners OOP using Java Can you write a Java statement that creates the object mysteryClock of the Clock type, and initialize the instance variables hr,min...); } } For more information on Java visit to : java - Java Beginners information : Thanks...java Why java does not support multiple inhertance? Hi... multiple inheritance but the multiple inheritance can be achieved by using covert the following using java covert the following using java how to convert (for eg : 2.89) . this decimal to binary in java java java Write a java code to speak the characters, words, sentences, paragraphs using voice base.(Is it possible to hear or listen voice through java code OOP Using JAVA - Java Beginners OOP Using JAVA OBJECT ORIENTED PROGRAMMING USING JAVA (hope guys u will help me please i need your help,thank you so much) Create a Java program...(); oops.OopType(); } } For more information on Java visit to : http java why are we using MVC modle in our java project.. 1.what is the use of transient,native and volatile (access modifier)...? 2.why are we using MVC modle in our java project java java how we can create the purches order by using the java awt java java how we can create purches order format by using the java awt java java how to run java program with using comand prompt in windows os java java how to run java program without using comand prompt in windows os JAva JAva how to make a class final without using final keyword java java create an interactive java program for displaying student details by using multiple constructors java java sir i need a java simple program to reverse a string using array java java write a java program to find sum of two numbers using reading data from keyboard java java I have a file ,I want this file is given to the power builder application using java program or jsp. if anybody help in this.... in advance thanks java java 01)write a java program to add two integer variables and display the sum of them .using java swing 02)write a java program to find the surface of the sphere.Radius of the sphere may be any number that user gives leftshift operator add 1 instead of 0 to do. If I have some some int variable and If I apply left shift operator... this, 5 as binary : 0101 1st time left shift: 01010 2nd time left shift: 010100..., it should have something like this..: 5 as binary : 0101 1st time left shift Java Java Can any one tell me How can we convert a String into Character array without using and String class method in java java java using java how to show password in stars (**). but not in JSP. plz im waiting for ur reply eagerly. thanks in advance Java - Java Beginners Java Java Master get ready.... Can we make plugin for Browser in java ? Any reply is appriciated Java Training and Tutorials, Core Java Training ; Bitwise and Bit Shift Operators: Java... bitwise OR " |" operator: Java Left Shift "<<" Operator: Java java beginners - Java Beginners java beginners is there any other way to do this ? i want to do by using charAt() function and by decreasing the ascii code by 2 . Write a program to encode a message. The idea is to shift each letter of a alphabet uSING JAVA API uSING JAVA API How to extract Quickbooks online data using Quickbooks api( Rest ApI) write in java code ? 1.register company account 2..register application 3.get apptoken,consumer key,consumer screte 4.how can i Advertisements If you enjoyed this post then why not add us on Google+? Add us to your Circles
http://www.roseindia.net/tutorialhelp/comment/92479
CC-MAIN-2016-07
refinedweb
2,189
59.74
26 May 2005 16:58 [Source: ICIS news] HOUSTON (CNI)--Rohm and Haas said Thursday that 70 persons could lose their jobs in the closing of its ?xml:namespace> The Philadelphia-based company said the plant would be shut in the first quarter of 2006. Its ?xml:namespace> It said the closing of the plant at Wytheville, 200 miles southwest of A spokesman said the company will offer to reassign Wytheville employees to the other two power coatings plants or other Rohm and Haas facilities. Rohm and Haas said the As a result of the plant closing, Rohm and Haas said it expects to take restructuring charges of $8-10m related to asset impairments and $4m in cash charges related to termination benefits and plant closing costs. Rohm and Hass is a specialty materials company with operations in 27 nations and sales of more than $8bn
http://www.icis.com/Articles/2005/05/26/680713/rh-to-merge-powder-coatings-ops-close-virginia-plant.html
CC-MAIN-2014-42
refinedweb
146
59.98
I need help with the source code that I am going to attach. I have all of the pieces but I cannot figure out to put the pieces together. I am to ( 1) have a display showing denominations of money accepted, total amount deposited, price of a soda, and a coin return that shows coins rejected (like pennies), and change returned by denomination (two dimes and one nickel, for example). (2) the program should dispense a soda when an adequate deposit has been made. (3) the program should repeat until told to quit. (4) as with real soda machines, it should randomly take a customers money without dispensing a soda. I can improve/improvise on the basics for extra credit. This program is due no later than Oct 25, 2004. Please I need help. This is the code that I have been trying to get to work for days now and I can't get it to work. Please send me any help and source code so that I can finish this project. My lab teacher does not give us a lot of instruction on different programs, he only gives us a few examples and expects us to do the rest. Thanks for any help and source code, Jeannette #include <iostream> #include <iomanip> #include <conio.h> #include <cstdlib> // #include <cmath> using std::setprecision; using std::setw; using std::cin; using std::cout; using std::endl; using std::fixed; char flag = 'N'; void display(); int coke(); int reject(); void takemoney ( void ); int buy(); int deposit = 0; double coinreturn; int money; int main() { int sum; cout << "Enter coin: \t"; cin >> deposit; deposit++; sum = coke(); // display(); // takemoney(); // buy(); // cout <<"Do you want to continue to buy another drink?" << endl; // cin >> flag; return 0; } // display function // displays the screen for buying a drink void display() { double slot = 0; double rejected = 0; double money = 0; double deposit = 0; // int sum; cout << "\t\t **********************" << endl; cout << "\t\t\tSODA MACHINE" << endl; cout << "\t\t **********************" << endl << endl; cout << "Soda $1.00" << endl << endl; cout << "Money accepted: Dollar, Quarters, Dimes, Nickels" << endl; cout << "\t\t($1.00)\t (.25)\t (.10)\t (.05)" << endl << endl; cout << "Enter coin: \t"; cin >> deposit; coke(); // money += deposit; // slot += deposit; // rejected -= deposit; // int coke(); cout << "Total Amount Deposited: \t\t" << fixed << setprecision ( 2 ) << money << endl; cout << "Slot: \t" << fixed << setprecision ( 2 ) << slot << endl; cout << "Coin return: \t" << endl; // // reject(); } // function for entering money and status of money int coke() { double deposit = 0; double money = 0; if ( deposit == 1.00 ) { ++money; cout << "You have deposited the correct amount!" << endl; cout << "Here is your soda!" << endl; } if ( deposit == .05 ) { ++money; cout << "Deposit more money!" << endl; } if ( deposit == .10 ) { ++money; cout << "Deposit more money!" << endl; } if ( deposit == .25 ) { ++money; cout << "Deposit more money!" << endl; } // if ( deposit == .50 ) // { // ++money; // cout << "Deposit more money!" << endl; // } // if ( deposit == .75 ) // { // ++money; // cout << "Deposit more money!" << endl; // } return deposit; } // function to reject money int reject() { double rejected = 0; double slot; if ( deposit > .01 || deposit < .05 ) { money = 0; deposit = 0; slot = rejected; // rejected -= deposit; cout << "WRONG AMOUNT, ENTER CORRECT COINS!" << endl << endl; } return slot; } // function for taking money and giving no drink void takemoney( void ) { money = rand() % 5; if ( money == .50 ) money = 0; cout << "Lost money" << endl; cout << "No drink" << endl; } // function to continue buying a drink int buy() { // int sum; char flag = 'N'; int N = 0; if ( flag == 'Y' || flag == 'y' ) // cout << "Enter deposit to continue: "; // cin >> flag; coke(); return flag; }
https://www.daniweb.com/programming/software-development/threads/12836/help-with-getting-soda-machine-program-running
CC-MAIN-2017-09
refinedweb
571
71.55
Difference between revisions of "ReleaseNotes/Liberty" Revision as of 16:52, 10 November 2015) - 1.13 OpenStack Trove (DBaaS) - 1.14 OpenStack Bare metal (Ironic) - 1.15 OpenStack Key Manager (Barbican) - 1.16 OpenStack Image Service (Glance) - 1.17 OpenStack Shared File System (Manila) OpenStack Object Storage (Swift) Please see full release notes at New Features - Allow 1+ object-servers-per-disk deployment enabled by a new > 0 integer config value, "servers_per_port" in the [DEFAULT] config section for object-server and/or replication server configurations. The setting's integer value determines how many different object-server workers handle requests for any single unique local port in the ring. In this mode, the parent swift-object-server process continues to run as the original user (i.e. root if low-port binding is required). It binds to all ports as defined in the ring. It then forks off the specified number of workers per listen socket. The child, per-port servers, drops privileges and behaves pretty much how object-server workers always have with one exception: the ring has unique ports per disk, the object-servers will only handle requests for a single disk. The parent process detects dead servers and restarts them (with the correct listen socket). It starts missing servers when an updated ring file is found with a device on the server with a new port, and kills extraneous servers when their port is no longer found in the ring. The ring files are started at most on the schedule configured in the object-server configuration by every the "ring_check_interval" parameter . - The object server includes configurations (RBAC). - The 'external_network_bridge' option for the L3 agent has been deprecated in favor of a bridge_mapping with a physnet. For more information, see the "Network Node" section of this scenario in the networking guide: Performance Considerations - The stock Trusty Tahr kernel (3.13) shows linear performance degradation when running "ip netns exec" as the number of namespaces increases. In cases where scale is important, a later version kernel (e.g. 3.19) should be used. [WHICH VERSION OF 3.13 EXHIBITED THIS. MOST VERSIONS WILL HAVE THIS FIX ALREADY.] Note: This regression should be fixed in Trusty Thar since 3.13.0-36.63 and later kernel versions. For further references see: - () - A new config option "handle_virt_lifecycle_events" in the DEFAULT group was added to allow disabling the event callback handling for instance lifecycle events from the virt driver (which is only implemented by the libvirt and hyper-v drivers in Liberty). This mostly serves as a workaround in case the callbacks are racing under heavy load and causing problems like shutting down running instances. See for: - The default DB driver we test against is now pymysql rather than Python-MySQL - The "powervm" hv_type shim has been removed. This only affects users of the PowerVC driver on stackforge which are using older images with hv_type=powervm in the image metadata. - The minimum required version of libvirt in the Mitaka release will be 0.10.2. Support for libvirt < 0.10.2 is deprecated in Liberty: - The libvirt.remove_unused_kernels config option is deprecated for removal and now defaults to True: - Setting force_config_drive=always in nova.conf is deprecated, use True/False boolean values instead: Deprecated Features -. - Support for data publishing from Ceilometer to Gnocchi. - Mandatory limit - limit restricted querying is enforced. The limit must be explicitly provided on queries, otherwise the result set is restricted to a default limit. - Distributed, coordinated notification agents - support for workload partitioning across multiple notification agents. - Events RBAC support. - PowerVM hypervisor support. - Improved MongoDB query support - performance improvement to statistic calculations. - Additional meter support: - Magnum meters - DBaaS meters - DNSaaS meters Gnocchi Features - Initial influxdb driver implemented. Aodh Features - Event alarms - ability to trigger an action when an event is received. - Trust support in alarms link. Upgrade Notes - The name of some middleware used by ceilometer changed in a backward incompatible way. Before upgrading, edit the paste.inifile for ceilometer to change oslo.middlewareto. Deprecated Features - Ceilometer Alarms is deprecated in favour or Aodh. - RPC publisher and collector is deprecated in favour of a topic based notifier publisher. - Non-metric meters are still deprecated, and are to be removed in a future release. OpenStack Identity (Keystone) Key New Features - Experimental: Domain specific configuration options can be stored in SQL instead of configuration files, using. - The credentials list call can now have its results filtered by credential type. - Support was improved for out-of-tree drivers by defining stable Driver Interfaces. - Several features were hardened, including Fernet tokens, Federation, domain specific configurations from database and role assignments. - Certain variables in keystone.conf now have options, which determine if the user's setting is valid. Upgrade Notes - The EC2 token middleware, deprecated in Juno, is no longer available in keystone. It has been moved to the keystonemiddleware package. - The compute_port configurationoption, no longer available. keystone.confnow references entrypoint names for drivers. For example, the drivers are now specified as "sql", "ldap", "uuid", rather than the full module path. See the sample configuration file for other examples. -. - A new secure_proxy_ssl_headerconfiguration option is available when running keystone behind a proxy. - Several configuration options have been deprecated, renamed, or moved to new sections in the keystone.conffile. - Domain name information can now be used in policy rules with the attribute domain_name. Deprecated Features -. - Default LVM backends to be thin provisioned if available. - Corrected cinder service-list to show as Down when a driver fails to initialize. - Improved volume migration management: - Able to see if previous migration attempt was successful - Admins able to monitor migrations via cinder list - New volume status of 'maintenance' to prevent operations being attempted while migration is occurring - Improve backend volume name/id consistency after migration completes Upgrade Notes - A change in parameters to RPC APIs and work on object conversion prevent running Liberty c-vol or c-api services with Kilo or earlier versions of either service. Deprecated Features - Removed Simple and Chance Schedulers. - Removed deprecated HDS HUS iSCSI driver. - Removed Coraid driver. - Remove Solaris iSCSI driver. - Removed --force option for allowing upload of image to attached volume. - Marked the v1 API as deprecated. modifying) Key New Features - New plugins and versions: - Ambari plugin with supports HDP 2.2 / 2.3 - Apache Hadoop 2.7.1 was added, Apache Hadoop 2.6.0 was deprecated - CDH 5.4.0 was added with HA support for NameNode and ResourceManager - MapR 5.0.0 was added - Spark 1.3.1 was added, Spark 1.0.0 was deprecated - HDP 1.3.2 and Apache Hadoop 1.2.1 was removed - Added support for using Swift with Spark EDP jobs - Added support for Spark EDP jobs in CDH and Ambari plugins - Added support for public and protected resources - Started integration with OpenStack client - Added support for editing all Sahara resources - Added automatic Hadoop configuration for clusters - Direct engine is deprecated and will be removed in Mitaka release - Added OpenStack manila NFS shares as a storage backend option for job binaries and data sources - Added support for definition and use of configuration interfaces for EDP job templates Deprecated Features - Direct provisioning engine - Apache Hadoop 2.6.0 - Spark 1.0.0 - All Hadoop 1.X removed Deprecated Features Additional DNS Server Backends - InfoBlox - Designate Upgrade Notes - New service designate-zone-manager - It is recommended to use a supported tooz backend. - ZooKeeper is recommended, or anything supported by tooz. - If a tooz backend is not used, all zone-managers will assume ownership of all zones, and there will be 'n' "exists" messages per hour, where 'n' is the number of zone-manager processes. designate-pool-managercan do active/passive failover for periodic tasks. - It is recommended to use a supported tooz backend. - If a tooz backend is not used, all pool-managers will assume ownership of the pool, and multiple periodic tasks will run. This can result in unforeseen consequences. Deprecated Features - V1 API - An initial notice of intent, as there are operations that still a Zaqar subscriber's email address. When there is a new message posted to the queue, the subscriber will receive the message by email. - Policy Support - Support fine-grained permission control with the policy.jsonfile like most of the other OpenStack components. - Persistent Transport - Added support for websocket as a persistent transport alternative for Zaqar. Now users will be able to establish long-lived connections between their applications and Zaqar to interchange large amounts of data without the connection setup adding overhead. OpenStack Dashboard (Horizon) Key New Features - A new network topology – The network topology diagram has been replaced with an interactive graph containing collapsible networks, and scales far better in large deployments (). - Plugin improvements – Horizon auto discovers JavaScript files for inclusion, and now has mechanisms for pluggable SCSS and Django template overrides. - Compute (Nova) - Support for shelving and unshelving of instances (). - Support for v2 block device mapping, falling back to v1 when unavailable (). - Networking (Neutron) - Added support for subnet allocation via subnet pools (). - Added actions to easily associate LBaaS VIP with a floating IP (). - Images (Glance) - The metadata editor has been updated with AngularJS (). - Compute images metadata can now be edited from the Project dashboard, using the new metadata editor (). - Block Storage (Cinder) - Enabled support for migrating volumes (). - Volume types can be now edited, and include description fields (). - Orchestration (Heat) - Improvements to the heat topology, making more resources identifiable where previously they had no icons and were displayed as unknown resources (). - Data Processing (Sahara) - Unified job interface map. This is a human readable method for passing in configuration data that a job may require or accept (). - Added editing capabilities for job binaries (). - Added editing capabilities for data sources (). - Added editing capabilities for job templates (). - Exposed event log for clusters (). - Added support for shell job types (). - Databases (Trove) - Added initial support for database cluster creation and management. Vertica and MongoDB are currently supported (). - Identity (Keystone) - Added mapping for Identity Provider and Protocol specific WebSSO (). - Configurable token hashing ( and). - Horizon (internal improvements) - Full support for translation in AngularJS, along with simpler tooling (). - Added Karma for JavaScript testing (). - Added ESLint for JavaScript linting, using the eslint-config-openstack rules (). - Horizon now supports overriding of existing Django templates (). - JavaScript files are now automatically included (). Upgrade Notes - Django 1.8 is now supported, and Django 1.7 is our minimum supported version (). - Database-backed sessions will likely not persist across upgrades due to a change in their structure ( and). - Horizon no longer uses QUnit in testing, and it has been removed from our requirements (). - Horizon now has multiple configuration options for the default web URL ( WEBROOT), static file location ( STATIC_ROOT) and static file URL ( STATIC_URL) in its settings files. - Themes have moved location from openstack_dashboard/static/themes, to openstack_dashboard/themes. Paths may need to be updated accordingly. Furthermore, Horizon is aligning closer with Bootstrap markup, and themes should be built around this ideology; see the top bar and side navigation for details. - The deprecated OPENSTACK_QUANTUM_NETWORKconfiguration option has been removed. If you still use it, replace it with OPENSTACK_NEUTRON_NETWORK - There is now an OPENSTACK_NOVA_EXTENSIONS_BLACKLISToption in the settings, to disable selected extensions for performance reasons (). - Trove and Sahara panels now reside in openstack_dashboard/contrib. This is to provide separation for reviews provided mostly by the service teams. In the future, these panels may become plugins rather than being kept in Horizon (). - Horizon requires both a volumeand volumev2endpoint for Cinder, even if only using v2. - Many JavaScript files and most notably the base page template ( horizon/templates/base.html) have moved from the framework portion of the repo ( horizon) to the application side ( openstack_dashboard) to better separate the framework from the application. OpenStack Trove (DBaaS) Key New Features - Redis - Configuration Groups for Redis - Cluster support - MongoDB - Backup and restore for a single instance - User and database management - Configuration Groups - Percona XtraDB Cluster Server - Cluster support - Allow deployer to associate instance flavors with specific datastores - Horizon support for database clusters - Management API for datastore and versions - Ability to deploy Trove instances in a single admin tenant, so that the nova instances are hidden from the user OpenStack Bare metal (Ironic) Ironic has switched to an intermediate release model and released version 4.0 during Liberty, followed by two minor updates. Version 4.2 forms the basis for the OpenStack Integrated Liberty release and will receive stable updates. Please see full release notes here: New Features - Added "ENROLL" hardware state, which is the default state for newly created nodes. - Added "abort" verb, which allows a user to interrupt certain operations while they are in progress. - Improved query and filtering support in the REST API. - Added support for CORS middleware. Hardware Drivers - Added a new BootInterface for hardware drivers, which splits functionality out of the DeployInterface. - iLO virtual media drivers can work without Swift. - Added Cisco IMC driver. - Added OCS Driver. - Added UCS Driver. - Added Wake-On-Lan Power Driver. - ipmitool driver supports IPMI v1.5. - Added support to SNMP driver for “APC MasterSwitchPlus” series PDU’s. - pxe_ilo driver now supports UEFI Secure Boot (previous releases of theiLO driver only supported this for agent_ilo and iscsi_ilo). - Added Virtual Media support to iRMC Driver. - Added BIOS configuration to DRAC Driver. - PXE drivers now support GRUB2. Deprecated Features - The "vendor_passthru" and "driver_vendor_passthru" methods of the DriverInterface have been removed. These were deprecated in Kilo and replaced with the @passthru decorator. - The migration tools to import data from a Nova "baremetal" deployment have been removed. - Deprecated the "parallel" option to periodic task decorator. - Removed deprecated ‘admin_api’ policy rule. - Support for the original "bash" deploy ramdisk is deprecated and will be removed in two cycles. The ironic-python-agent project should be used for all deploy drivers. Upgrade Notes - Newly created nodes default to the new ENROLL state. Previously, nodes defaulted to AVAILABLE, which could lead to hardware being exposed prematurely to Nova. - The addition of API version headers in Kilo means that any client wishing to interact with the Liberty API must pass the appropriate version string in each HTTP request. Current API version is 1.14. OpenStack Key Manager (Barbican) New Features - Added the ability for project administrators to create certificate authorities per project. Also, project administrators are able to define and manage a set of preferred certificate authorities (CAs) per project. This allows projects to achieve project specific security domains. - Barbican now has per project quota support for limiting number of Barbican resources that can be created under a project. By default the quota is set to unlimited and can be overridden in Barbican configuration. - Support for a rotating master key which is used for wrapping project level keys. In this lightweight approach, only the project level key (KEK) is re-wrapped with new master key (MKEK). This is currently applicable only for the PKCS11 plug-in. () - Updated Barbican's root resource to return version information matching Keystone, Nova and Manila format. This is used by keystoneclient's versioned endpoint discovery feature. - Removed administrator endpoint as all operations are available on a regular endpoint. No separate endpoint is needed as access restrictions are enforced via Oslo policy. - Added configuration for enabling sqlalchemy pool for the management of SQL connections. - Added ability to list secrets which are accessible via ACL using GET /v1/secrets?acl-only=true request. - Improved functional test coverage around Barbican APIs related to ACL operations, RBAC policy and secrets. - Fixed issues around creation of SnakeOil CA plug-in instance. - Barbican client CLI can now take a Keystone token for authentication. Earlier only username and password based authentication was supported. - Barbican client now has ability to create and list certificate orders. Upgrade Notes - Removed project secret association table. Secret project relationship is maintained by foreign key. For more detail, see . - Renamed barbican configuration file to barbican.conf. OpenStack Image Service (Glance) Updated project guide that includes some details on operating, installing, configuring, developing to and using the service: Key New Features - Added support for uploading signed images. For more information, see . - Scrubbing of images in parallel is now possible. For more information, see . - The health of a Glance node can be monitored using the healthcheck middleware. For more information, see . - The EXPERIMENTAL Artifacts API is now available for use. Please note, it is subject to change in the future until it becomes a standard API. - S3 store now has proxy support. For more information, see . - Swift store now has v3 authentication support. - python-glanceclient now support some advanced aspects of keystone sessions. - python-glanceclient now supports tags for Metadata Definition Catalog. Upgrade Notes - python-glanceclient now defaults to using Glance API v2 and if v2 is unavailable, it will fallback to v1. - Dependencies for backend stores are now optionally installed corresponding to each store specified. - Some stores like swift, s3, vmware now have python 3 support. - Some new as well as updated default metadata definitions ship with the source code. - More python 3 support added to Glance API, and now continuous support is extended by the means of tests to ensure compatibility. - utf-8 is now the default charset for the backend MySQL DB. - Migration scripts have been updated to perform a sanity check for the table charset. - 'ram_disk' and 'kernel' properties can now be null in the schema and 'id' is now read only attribute for v2 API. - A configuration option client_socket_timeouthas been added to take advantage of the recent eventlet socket timeout behaviour. - A configuration option scrub_pool_sizehas been added to set the number of parallel threads that a scrubber should run and defaults to 1. - An important bug that allowed to change the image status using the Glance v1 API has now been fixed. Deprecated Features - The experimental Catalog Index Service has been removed and now is a separate project called Searchlight. - The configuration options scrubber_datadir, cleanup_scrubberand cleanup_scrubber_timehave been removed following the removal of the file backed queuing for scrubber. New Features - Enabled support for availability zones. - Added administrator API components to share instances. - Added pool weigher which allows Manila scheduler to place new shares on pools with existing share servers. - Support for share migration from one hostpool to another hostpool (experimental). - Added shared extend capability in the generic driver. - Support for adding consistency groups, which allow snapshots for multiple filesystem shares to created at the same point in time (experimental). - Support for consistency groups in the NetApp cDOT driver and generic driver. - Support for oversubscription in thin provisioning. - New Windows SMB driver: - Support for handling Windows service instances and exporting SMB shares. - Added new osapi_share_workersconfiguration option to improve the total throughput of the Manila API service. - Added share hooks feature, which allows actions to be performed before and after share drive methods calls, call additional periodic hook for each 'N' tick, and update the results of a driver's action. - Improvements to the NetApp cDOT driver: - Added variables netapp:dedup, and netapp:compression when creating the flexvol that backs up a new manila share. - Added manage/unmanage support and shrink_share support. - Support for extended_shareAPI component. - Support for netapp-lib PyPI project to communicate with storage arrays. - Improvements to the HP 3PAR driver: - Added reporting of dedupe, thin provisioning and hp3par_flash_cache capabilities. This allows share types and the CapabilitiesFilter to place shares on hosts with the requested capabilities. - Added share server support. - Improvements to the Huawei Manila driver: - Added support for storage pools, extend_share, manage_existing, shrink_share, read-only share, smartcache and smartpartition. - Added reporting of dedupe, thin provisioning and compression capabilities. - Added access-level support to the VNX Manila driver. - Added support for the Manila HDS HNAS driver. - Added GlusterFS native driver. - GlusterFS drivers can now specify the list of compatible share layouts. - Added microversion support (v2 API). Deprecated Features - The share_reset_statusAPI component is deprecated and replaced by share_instance_reset_status.
https://wiki.openstack.org/w/index.php?title=ReleaseNotes/Liberty&diff=prev&oldid=96251
CC-MAIN-2019-39
refinedweb
3,271
50.23
What are the must know features of python programming language List comprehensions One of the major features of python is list comprehension. It is a natural way of creating a new list where each element is the result of some operations applied to each member of another sequence of an iterable. The construct of a list comprehension is such that it consists of brackets containing an expression followed by a for clause then by zero or more for or if clause. List comprehensions always returns a list. Simple example squares = [x**2 for x in range(10)] In a rather real usage scenarios, the expression after the bracket ‘[‘ is a call to a method/function. some_list = [function_name(x) for x in some_iterable] Generators Before learning about generators, it is important and essential to understand what an iterable is. Putting it simple, an iterable is an object that can be looped over. Therefore, a list, string, dictionary, file, etc are iterable objects. A generator is something that simplifies creating iterators. More specifically, a generator is a function that produces a sequence of results instead of a single value. When a generator function is called, it returns a generator object without even beginning execution of the called function. Now when the next method is called for the first time, the function starts executing until it reaches yeild statement. Hence yeilded value is returned by the next call. Sample Example def gen_example(): print “Begining of the function” for i in range(5): print “before yeild” yield I print “after yeild” print “End of the function” Generators Expressions It is the generator version of list comprehension. Everything is same as the list comprehension except that it returns a generator. Sample Example squares = (x**2 for x in range(5)) Docstrings A docstring is a string literal that occurs as the first statement in a module, function, class, or method definition. Such a docstring becomes the __doc__ special attribute of that object. In fact, every module should have a docstring. Additionally all the functions and classes exported by a module should have a docstrings. Also, the public methods including constructor should also have docstrings. Sample Example def sum_elements(elements): “““Returns the sum of elements of the passed list””” return sum(elements) *args and **kwargs *args and *kwargs allow you to pass a variable number of arguments to a function. It is not know before hand about how many arguments can be passed to your function. *args is used to send a non-keyworded variable length argument list to the function. def func_with_args(*argv): for arg in argv: print arg func_with_args('gopal', 'ramesh', 'paresh') The above code produces the result as follows: gopal ramesh paresh On the other hand, **kwargs allows you to pass keyworded variable length of arguments to a function. Below is a basic example def func_with_kwargs(**kwargs): if kwargs is not None: for key, value in kwargs.iteritems(): print “%s == %s” %(key, value) func_with_kwargs(customer= “Gopal”, salesman = “Ramesh”) Following is the output of the above code: customer == Gopal salesman == Ramesh This is an open-ended article. Please comment below about the features you think should not be missed. Thanks for reading.
http://www.thetaranights.com/must-know-features-python-programming-language/
CC-MAIN-2018-26
refinedweb
528
52.9
Quill A lightweight game engine, that keeps your game simple by only using feathers and quills! Why Quill? The idea of Quill is to give you full control over your game or application. Using Quill is simple, everything is a node based Feather, but your Feathers can turn into a Quill, which contains many of the Component class. Quills can be preset to contain specific components. You can use preset Quills, or you can create your own! Quick Start lib/main.dart import 'package:quill/quill.dart'; import 'dart:ui' void main() async { /// Start the application with 60.0 frames per second new QuillEngine(new Application(), fps: 60.0) ..start(); } class Application extends Feather { /// `Sprite` is a `Quill` preset Sprite user; @override void init() { super.init(); /// Create a Sprite user = new Sprite() ..initWithColor(const Color(0xFFFF0000) ..setPosition(0.0, 0.0) ..setSize(100.0, 100.0); addFeather('user', user); addFeather<Sprite>('block', new Sprite()) ..initWithColor(const Color(0xFF0000FF)) ..setPosition(200.0, 200.0 ..setSize(50.0, 50.0) ..origin = Origin.top_left; } @override void update(Time time) { super.update(time); /// Move the user 10 pixels per second user.position.x += 10.0 * time.elapsedSeconds; } } The Feather Loop Each feather, and all associated components follow a main way of looping. Primarily through the input, update, and render methods. init: Initializes the feather/component. destroy: Disposes of the feather/component, and all internal properties. load: Loads any data neccessary for the feather/component. unload: Unloads any data, to make room for loading new data. input: Handles input events as neccessary for the feather/component. update: Updates our feather/component. render: Draws our feather/component to the screen. Custom Components & Quills Creating custom components & quills is simple, you just need to extend the Quill or Component class. Use the Feather Loop above to override any methods you need, or create your own unique methods. Try to be consistent, and avoid using constructors, as there are plans to remove the use of them as soon as possible. So, rather than passing parameters in the constructor, use a custom setter such as setSize(double width, double height); like the SizeComponent. For Quills, using custom initializers works great, like the Sprite quill: initWithColor(Color color, Point position, Size size)... then you can initialize each of these as components! Upcoming Please note that Quill is still in it's early stages, so there are a lot of missing features. I have finally gotten the foundation finalized, so now it's just a matter of adding each of these features. Here is a list of upcoming features: Version 0.2.0 - Audio - Image Caching - LifeCycle Management Version 0.x.0 - Local/Push Notifications - Admob support (?) - May be in a separate package such as quill-admob - Native Game Center support Suggestions & Feedback I hope this library helps others build their games rapidly an easily. Any feedback that could help make Quill even better, are more than welcome! Please use github as an open way to communicate those ideas. Contributing I hope that one day there will be a community of components and quills to help new users streamline their app development. More Coming. [...]
https://pub.dartlang.org/documentation/quill/latest/
CC-MAIN-2019-04
refinedweb
523
58.89
Test::Kit::Features - Features available for Test::Kit. Version 0.100 explain use Test::Kit '+explain'; This exports an &explain function into your namespace. It's like &diag, but only runs if your tests are being run in verbose mode prove -v. If any references are passed, it uses Data::Dumper to display the references. on_fail use Test::Kit '+on_fail'; This exports an &on_fail function into your namespace. When called, if any subsequent tests fail, it will execute the 'on_fail' subroutine passed in. The function receives one argument, an object with the following methods: name The 'name', if any, passed to the test function. For example: ok $value, 'The value should be true'; The 'name' is "The value should be true". package The package the test function was called in. filename The name of the file the test function was called in. line The line number of the file the test function was called in.
http://search.cpan.org/~ovid/Test-Kit/lib/Test/Kit/Features.pm
CC-MAIN-2016-26
refinedweb
155
74.79
The thought process is that we don't care about saving the 0 in the array, when we are scanning the array, as soon as we see a 0, just keep i incrementing without assigning. We only assign value when the element is not 0. In the end, the index save the spot that should have all the zeroes and we can simply fill it with zeroes using Arrays.fill(); public class Solution { public void moveZeroes(int[] nums) { int index = 0; for(int i = 0; i < nums.length; i++) { if(nums[i] != 0) { nums[index++] = nums[i]; } } Arrays.fill(nums, index, nums.length, 0); } }
https://discuss.leetcode.com/topic/32750/simple-o-n-java-solution-6-lines-take-care-of-it
CC-MAIN-2017-39
refinedweb
104
75.1
Find a specific item instance owned by a specific parent, resolving all synonym names #include <drvr/hwinfo.h> unsigned hwi_find( const char *device_name, int unit, unsigned hwi_off); The hwi_find() function lets you find a specific item instance owned by a specific parent, resolving (all) synonym names (aliases) to a real device or bus. If the unit instance of device_name has been added to the hwinfo section of the system page and belongs to parent hwi_off, the function returns its hwi offset. If hwi_off is HWI_NULL_OFF, indicating no parent specified, then hwi_find() does a system-wide search and returns the results regardless of the owning parent. If unit is -1, indicating that you aren't looking for a specific instance, hwi_find() returns the offset of the first occurrence of device_name. Setting unit to -1 is most useful when you're searching for a device on a specific bus (i.e., hwi_off != HWI_NULL_OFF). Note that the search can be directed from a specific item hwi_off. Therefore, if a certain device is expected to be found attached to a certain bus, you can set hwi_off to the results of hwi_find_bus(). For example, if you have multiple instances of the same device attached to two different buses, the hwi_off parameter allows you to find the instance connected to one of the buses only. The offset of the device found, or HWI_NULL_OFF if no device was found.
http://www.qnx.com/developers/docs/7.0.0/com.qnx.doc.neutrino.lib_ref/topic/h/hwi_find.html
CC-MAIN-2018-43
refinedweb
232
57
ProLang Introducing ProLang... ...the best lang for beginners. It's also the best lang for non-beginners. Source: - Just click run, it will run a sample program. You will get a package installation screen before it runs, though. If you get program is already running, please run it again, or something like that, do what it says. Run it again. Features - Data Types: - Numbers - Strings - Booleans ( true, false) null - Lists - Instances - Basic Operations + - * / ^(powers) - Parentheses - print() - input() - Variables - Syntax: var name = value - Conditionals* - Loops* - Functions* - Anonymous Functions - Classes* - Imports - Syntax: import name * Syntax shown in examples Examples Hello world is quite simple: print("Hello, world!") Arithmetic is quite easy too: print(2 + 2) You can also do variables: var a = 100 print(a) if statements work as well. Elifs / elses don't though, so here's how you would make a simple size classifier: var a = ___ if a < 10 { print("Small") } if a < 20 and a >= 10 { print("Regular") } if a < 50 and a >= 20 { print("Large") } if a >= 50 { print("HUGE") } for loops have a slightly odd style: for i = 1 to 10 { print(i) } You can also do functions quite easily: function greet(name) { print("Hello " + name) } var name = "Simon" greet(name) Lists are quite simple too: var list = ["a", "hello", "b", "goodbye"] print(list) You can even have a rudimentary version of classes! class Dog(name){ var trained = false var name = "hello" function bark(name) { print(name + " is barking!") } function train(name) { print(name + " is training...") trained = true } } var tim = new Dog("Tim").train("Tim"); var tom = new Dog("Tom").bark("Tim"); Credits Team - @simontiger (high-level features, CLI, ...trying to understand what AndyPython was doing) - @AndyPython (idea, the implementation, lots of stuff) - @arnavsirigere (just support :) ) Thanks to them, I could not have done this without them (though AndyPython was a bit pressuring and thought the deadline was before I'm posting this 😅) Source - Just click run, it will run a sample program. You will get a package installation screen before it runs, though. If you get program is already running, please run it again, or something like that, do what it says. Run it again. love it so far! excited to try it out. love the focus on simplicity and especially having only one way to write functions Check out the examples directory about all of the examples including object oriented ones! why is this the genius 9 year old from this really old dev spotlight? now 11 (or 12)? wow you're really smart... are you doing college math by now?
https://replit.com/talk/challenge/ProLang/51767?order=new
CC-MAIN-2021-17
refinedweb
427
72.87
Wrapper DLL The topic of Wrapper DLLs comes up often on the mailing list. Usually it is in the context of a Windows DLL because folks try to use the FIPS DLL as a general purpose DLL. On occasion it comes up in the context of Linux, like on Android or iOS. Trying to use the Visual Studio DLL is almost always a bad idea. The Visual Studio DLL is a FIPS DLL, it is hard to use and it is missing all non-FIPS classes. Also see the Visual Studio and FIPS DLL wiki pages, which provide a lot of the gory details. If your heart is set on creating a Windows DLL with a selection of classes you provide, then see Converting static link library to dynamic dll on Stack Overflow. You can use the static library and a module-definition file (DEF file) to do it. An additional problem on Linux and Unix is, the makefile can produce a shared object that exports nearly every symbol the library has. The shared object with symbols is over 41 MB on x86_64, and you won't use most of the code. It is also slow to load because the export table is so large. Once you investigate things you probably don't want to use the library's shared object. Wrapper DLLs and shared objects can use symbol visibility to help control some of the problems with DLLs and shared objects. It is easier to control visibility and improve load times using a wrapper because you know exactly what must be exported. In fact GCC reports one C++ library went from a 6 minute load time to an 8 second load time when symbol visibility was used. Also see Visibility on the GCC wiki. Wrapper DLLs and shared objects have one tricky area due to C++ exceptions. As a general rule of thumb, you should not let exceptions cross a module boundary. The DLL or shared object should always catch Crypto++ exceptions and return a success/failure code. If an exception is intended to cross a module boundary then Runtime Type Information (RTTI) must be available so the caller can catch the exception. This page will show you how to create a wrapper DLL or shared object that is considerably smaller in size that you can use in you Android, iOS, Linux and Windows projects. If you use a C-interface then you can use them in managed languages like Java and .Net, too. Related wiki articles are Nmake (Command Line), MSBuild (Command Line), Visual Studio and FIPS DLL. Contents Runtime Linking Runtime linking is Windows specific, and Linux and Unix users can skip this section. By default the Visual Studio project uses static runtime linking. That usually causes problems in projects that use the C++ runtime in a dynamic configuration, like ATL, MFC and Qt. The problems include duplicate runtime library symbols. Before you begin to wrap the static library in a DLL you should probably change runtime linking from static to dynamic in the Visual Studio project files. You can find the instructions at Visual Studio | Runtime Linking. Once you change the runtime linker settings you should clean and rebuild the library. After changing the setting you should not have problems with duplicate symbols when using libraries like ATL, MFC and Qt. External API The first thing you should do is design the basic interface for your wrapper DLL or shared object. For demonstration purposes this article creates a shared object to generate and verify SHA256 digests. The wrapper DLL needs two functions to accomplish its goals. It will use a C interface to make calling its functions easy. It will also use visibility controls to avoid symbol pollution and make link-loading faster. - sha256_hash_message - sha256_verify_message Both functions need to take pointers to a message buffer and a digest buffer. sha256_hash_message reads the message and writes the digest. sha256_verify_message reads both the message and digest. Both functions will follow most C API conventions and return 0 for success and non-0 for failure. The final API should look something like the following. int sha256_hash_message(uint8_t* digest, size_t dsize, const uint8_t* message, size_t msize) int sha256_verify_digest(const uint8_t* digest, size_t dsize, const uint8_t* message, size_t msize) Wrapper DLL The wrapper DLL is shown below. There is not much to it because the wrapper defers to the library for the heavy lifting. When compiling the wrapper on Windows you should define BUILDING_DLL so dllexport is exposed. #include "cryptlib.h" #include "sha.h" #include <stdint.h> #if defined _WIN32 || defined __CYGWIN__ #ifdef BUILDING_DLL #ifdef __GNUC__ #define DLL_PUBLIC __attribute__ ((dllexport)) #else #define DLL_PUBLIC __declspec(dllexport) #endif #else #ifdef __GNUC__ #define DLL_PUBLIC __attribute__ ((dllimport)) #else #define DLL_PUBLIC __declspec(dllimport) #endif #endif #define DLL_LOCAL #else #if __GNUC__ >= 4 #define DLL_PUBLIC __attribute__ ((visibility ("default"))) #define DLL_LOCAL __attribute__ ((visibility ("hidden"))) #else #define DLL_PUBLIC #define DLL_LOCAL #endif #endif extern "C" DLL_PUBLIC int sha256_hash_message } } extern "C" DLL_PUBLIC int sha256_verify_digest(const uint8_t* digest, size_t dsize, const uint8_t* message, size_t msize) { using CryptoPP::Exception; using CryptoPP::SHA256; try { bool verified = SHA256().VerifyTruncatedDigest(digest, dsize, message, msize); return verified ? 0 : 1; } catch(const Exception&) { return 1; // failure } } Symbol Visibility There are some sharp edges when working with GCC symbol visibility and LD linker behavior. Namely, you have to do more than just compile with -fvisibility=hidden and -fvisibility-inlines-hidden. Unfortunately the GCC wiki article on Visibility does not discuss it. The first thing you need to know is, when you define DLL_PUBLIC __attribute__ ((visibility ("default"))) and then use DLL_PUBLIC it only applies to your source code. In the example above that means it only applies to sha256_hash_message and sha256_verify_digest. The second thing you need to know is, you are linking against libcryptopp.a. The members of the static archive were not compiled with symbol visibility and -fvisibility=hidden and -fvisibility-inlines-hidden did not affect the object files in the archive. Everything in the archive is still public. The third thing you need to know is, you need to use LD's -Wl,--exclude-libs,ALL to avoid re-exporting the static library's symbols. In this case the LD option is needed to avoid making all of libcryptopp.a symbols public in your shared object. The three rules above mean the minimum command line to use for your wrapper shared object is: $ g++ -fPIC -fvisibility=hidden -fvisibility-inlines-hidden -c sha256_wrapper.cxx $ g++ -shared -o sha256_wrapper.so sha256_wrapper.o ./libcryptopp.a -Wl,--exclude-libs,ALL The -Wl,--exclude-libs,ALL is the important one on Linux with a GNU linker. Without the option the linker will re-export symbols from libcryptopp.a that were not stripped or removed. If you are working on Solaris then see the documentation for -xldscope. If you are working on OS X then see this question and answer. Other compilers and linkers on other platforms will need to be researched. DLL Sizes Earlier we said the library's DLL or shared object exports nearly every symbol the library has, and it makes for a bloated shared object. Below we compare the numbers on Linux using the code for the shared object shown earlier. The measurements were taken on Fedora 28 x86_64. First, we build the Crypto++ and enable dead code stripping and garbage collection on unused symbols. Notice the use of -ffunction-sections, -fdata-sections and -Wl,--gc-sections. If you are working on OS X then you would use -ffunction-sections, -fdata-sections and -Wl,-dead_code. $ make shared lean -j 4 g++ -DNDEBUG -g2 -O3 -fPIC -pthread -pipe -ffunction-sections -fdata-sections -c cryptlib.cpp g++ -DNDEBUG -g2 -O3 -fPIC -pthread -pipe -ffunction-sections -fdata-sections -c cpu.cpp ... g++ -shared -o libcryptopp.so.7.1.0 -Wl,-soname,libcryptopp.so.7 -DNDEBUG -g2 -O3 -fPIC -pthread -pipe -ffunction-sections -fdata-sections -Wl,--gc-sections cryptlib.o cpu.o integer.o ... Then inspect the size of libcrpytopp.so. The size of the library is large because debug symbols are present. Stripping the library will reduce the size by orders of magnitude, but it will still be 6 or 8 MB in size. $ ls -Al libcryptopp.so* lrwxrwxrwx. 1 cryptopp cryptopp 20 Aug 26 13:45 libcryptopp.so -> libcryptopp.so.7.1.0 lrwxrwxrwx. 1 cryptopp cryptopp 20 Aug 26 13:45 libcryptopp.so.7 -> libcryptopp.so.7.1.0 -rwxrwxr-x. 1 cryptopp cryptopp 41561968 Aug 26 13:45 libcryptopp.so.7.1.0 And finally strip libcrpytopp.so. $ objcopy --strip-debug libcryptopp.so $ ls -Al libcryptopp.so* lrwxrwxrwx. 1 cryptopp cryptopp 20 Aug 26 14:20 libcryptopp.so -> libcryptopp.so.7.1.0 lrwxrwxrwx. 1 cryptopp cryptopp 20 Aug 26 14:20 libcryptopp.so.7 -> libcryptopp.so.7.1.0 -rwxrwxr-x. 1 cryptopp cryptopp 6167384 Aug 27 10:48 libcryptopp.so.7.1.0 Now the wrapper shared object. $ g++ -DNDEBUG -g2 -O3 -fPIC -ffunction-sections -fdata-sections -c sha256_wrapper.cxx $ g++ -o sha256_wrapper.so -DNDEBUG -g2 -O3 -shared -fPIC -ffunction-sections -fdata-sections -fvisibility=hidden -fvisibility-inlines-hidden sha256_wrapper.o ./libcryptopp.a -Wl,--gc-sections -Wl,--exclude-libs,ALL After the wrapper shared object is built you can check the export table: $ nm -CD sha256_wrapper.so | grep ' T ' 00000000000184e8 T _fini 00000000000069d0 T _init 00000000000095b0 T sha256_hash_message 0000000000009710 T sha256_verify_digest The unstripped size of the wrapper shared object. $ ls -Al sha256_wrapper.so -rwxrwxr-x. 1 cryptopp cryptopp 13300848 Aug 27 10:49 sha256_wrapper.so And the stripped size of the wrapper shared object. $ objcopy --strip-debug sha256_wrapper.so $ ls -Al sha256_wrapper.so -rwxrwxr-x. 1 cryptopp cryptopp 182576 Aug 27 10:50 sha256_wrapper.so So there is a significant savings (6.2 MB vs 182 KB) when using the wrapper shared object instead of the library's shared object. Takeaways A lot of information was covered in the previous sections. Here are the takeaways. - provide a wrapper DLL or shared object for your app - provide a flat C-interface to callers - don't let exceptions cross module boundaries - use DLL_PUBLIC macro to export symbols - use the Crypto++ static archive - compile with -fvisibility=hidden -fvisibility-inlines-hidden for symbol visibility - compile with dllexport on Windows for symbol visibility - compile with -ffunction-sections -fdata-sections for symbol stripping - compile with /Gy on Windows for symbol stripping - link with -Wl,--exclude-libs,ALL for symbol visibility - link with -Wl,--gc-sections or -Wl,-dead_strip for symbol stripping - link with /OPT:REF on Windows for symbol stripping References Here is a small list of references. - GCC Visibility - How to apply -fvisibility option to symbols in static libraries? - Hiding the symbols of a static library in a dynamic library in MAC OS X? - Symbol hiding in static libraries built with Xcode - MSVC++: Optimizing C++ Code : Dead Code Elimination - MSVC++: Exporting from a DLL Using __declspec(dllexport)
https://www.cryptopp.com/wiki/Wrapper_DLL
CC-MAIN-2020-34
refinedweb
1,792
56.45
On the Confluent website, you can find this title: Stream data changes everything From the createors of Kafka, a real-time messaging system, this is not a surprising assertion. Yet, data streaming infrastructures have gained in popularity and many projects require the data to be processed as soon as it shows up. This contributed to the development of famous technologies like Spark Stremaing, Apache Storm and more broadly websockets. This latest piece of software in particular brought real-time data feeds to web applications, trying to solve low-latency connections. Coupled with the asynchronous Node.js, you can build a powerful event-based reactive system. But what about Python? Given the popularity of the language in data science, would it be possible to bring the benefits of this kind of data ingestion? As this two-part post series will show, it turns out that modern Python (Python 3.4 or later) supports asynchronous data streaming apps. Introducing asyncio Python 3.4 introduced in the standard library the module asyncio to provision the language with: Asynchronous I/O, event loop, coroutines and tasks While Python treats functions as first-class objects (meaning you can assign them to variables and pass them as arguments), most developers follow an imperative programming style. It seems on purpose: It requires super human discipline to write readable code in callbacks and if you don’t believe me look at any piece of JavaScript code. – Guido van Rossum So Asyncio is the pythonic answer to asynchronous programming. This paradigm makes a lot of sense for otherwise costly I/O operations or when we need events to trigger code. Scenario For fun and profit, let’s build such a project. We will simulate a dummy electrical circuit composed of three components: - A clock regularly ticking - A board I/O pin randomly choosing to toggle its binary state on clock events - A buzzer buzzing when the I/O pin flips to one This set us up with an interesting machine-to-machine communication problem to solve. Note that the code snippets in this post make use of features like async and await introduced in Python 3.5. While it would be possible to backport to Python 3.4, I highly recommend that you follow along with the same version or newer. Anaconda or Pyenv can ease the installation process if necessary. $ python --version Python 3.5.1 $ pip --version pip 8.1.2 Asynchronous webscoket Client/Server Our first step, the clock, will introduce both asyncio and websocket basics. We need a straightforward method that fires tick signals through a websocket and wait for acknowledgement. # filename: sketch.py async def clock(socket, port, tacks=3, delay=1) The async keyword is sugar syntaxing introduced in Python 3.5 to replace the previous @asyncio.coroutine. The official pep 492 explains it all but the tldr : API quality. To simplify websocket connection plumbing, we can take advantage of the eponymous package: pip install websockets==3.5.1. It hides the protocol’s complexity behind an elegant context manager. # filename: sketch.py # the path "datafeed" in this uri will be a parameter available in the other side but we won't use it for this example uri = 'ws://{socket}:{port}/datafeed'.format(socket=socket, port=port) # manage asynchronously the connection async with websockets.connect(uri) as ws: for payload in range(tacks): print('[ clock ] > {}'.format(payload)) # send payload and wait for acknowledgement await ws.send(str(payload)) print('[ clock ] The keyword await was introduced with async and replaces the old yield from to read values from asynchronous functions. Inside the context manager the connection stays open and we can stream data to the server we contacted. The server: IOPin At the core of our application are entities capable of speaking to each other directly. To make things fun, we will expose the same API as Arduino sketches, or a setup method that runs once at startup and a loop called when new data is available. # -*- coding: utf-8 -*- # vim_fenc=utf-8 # # filename: factory.py import abc import asyncio import websockets class FactoryLoop(object): """ Glue components to manage the evented-loop model. """ __metaclass__ = abc.ABCMeta def__init__(self, *args, **kwargs): # call user-defined initialization self.setup(*args, **kwargs) def out(self, text): print('[ {} ] {}'.format(type(self).__name__, text)) @abc.abstractmethod def setup(self, *args, **kwargs): pass @abc.abstractmethod async def loop(self, channel, data): pass def run(self, host, port): try: server = websockets.serve(self.loop, host, port) self.out('serving on {}:{}'.format(host, port)) asyncio.get_event_loop().run_until_complete(server) asyncio.get_event_loop().run_forever() exceptOSError: self.out('Cannot bind to this port! Is the server already running?') exceptKeyboardInterrupt: self.out('Keyboard interruption, aborting.') asyncio.get_event_loop().stop() finally: asyncio.get_event_loop().close() The child objects will be required to implement setup and loop, while this class will take care of: - Initializing the sketch - Registering a websocket server based on a asynchronous callback (loop) - Telling the event loop to poll for… events The websockets states the server callback is expected to have the signature on_connection(websocket, path). This is too low-level for our purpose. Instead, we can write a decorator to manage asyncio details, message passing, or error handling. We will only call self.loop with application-level-relevant information: the actual message and the websocket path. # filename: factory.py import functools import websockets def reactive(fn): @functools.wraps(fn) async def on_connection(klass, websocket, path): """Dispatch events and wrap execution.""" klass.out('** new client connected, path={}'.format(path)) # process messages as long as the connection is opened or # an error is raised whileTrue: try: message = await websocket.recv() aknowledgement = await fn(klass, path, message) await websocket.send(aknowledgement or 'n/a') except websockets.exceptions.ConnectionClosed as e: klass.out('done processing messages: {}n'.format(e)) break return on_connection Now we can develop a readable IOPin object. # filename: sketch.py import factory class IOPin(factory.FactoryLoop): """Set an IO pin to 0 or 1 randomly.""" def setup(self, chance=0.5, sequence=3): self.chance = chance self.sequence = chance def state(self): """Toggle state, sometimes.""" return0if random.random() We finally need some glue to run both the clock and IOPin and test if the latter toggles its state when the former fires new ticks. The following snippet uses a convenient library, click 6.6, to parse command-line arguments. #! /usr/bin/env python # -*- coding: utf-8 -*- # vim_fenc=utf-8 # # filename: arduino.py import sys import asyncio import click import sketchs @click.command() @click.argument('sketch') @click.option('-s', '--socket', default='localhost', help='Websocket to bind to') @click.option('-p', '--port', default=8765, help='Websocket port to bind to') @click.option('-t', '--tacks', default=5, help='Number of clock ticks') @click.option('-d', '--delay', default=1, help='Clock intervals') def main(sketch, **flags): if sketch == 'clock': # delegate the asynchronous execution to the event loop asyncio.get_event_loop().run_until_complete(sketchs.clock(**flags)) elif sketch == 'iopin': # arguments in the constructor go as is to our `setup` method sketchs.IOPin(chance=0.6).run(flags['socket'], flags['port']) else: print('unknown sketch, please choose clock, iopin or buzzer') return1 return0 if__name__ == '__main__': sys.exit(main()) Don’t forget to chmod +x the script and start the server in a first terminal ./arduino.py iopin. When it is listening for connections, start the clock with ./arduino.py clock and watch them communicate! Note that we used here common default host and port so they can find each other. We have a good start with our app, and now in Part 2 we will further explore peer-to-peer communication, service discovery, and the streaming machine-to-machine concept. About the author Xavier Bruhiere is a lead developer at AppTurbo in Paris, where he develops innovative prototypes to support company growth. He is addicted to learning, hacking on intriguing hot techs (both soft and hard), and practicing high intensity sports.
https://hub.packtpub.com/reactive-python-asynchronous-programming-rescue-part-1/
CC-MAIN-2019-18
refinedweb
1,305
50.23
/* findcmd.c -- Functions to search for commands by name. */ /* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ #include "config.h" #include <stdio.h> #include "chartypes.h" #include "bashtypes.h" #if !defined (_MINIX) && defined (HAVE_SYS_FILE_H) # include <sys/file.h> #endif #include "filecntl.h" #include "posixstat.h" #if defined (HAVE_UNISTD_H) # include <unistd.h> #endif #include "bashansi.h" #include "memalloc.h" #include "shell.h" #include "flags.h" #include "hashlib.h" #include "pathexp.h" #include "hashcmd.h" #include "findcmd.h" /* matching prototypes and declarations */ extern int posixly_correct; /* Static functions defined and used in this file. */ static char *_find_user_command_internal __P((const char *, int)); static char *find_user_command_internal __P((const char *, int)); static char *find_user_command_in_path __P((const char *, char *, int)); static char *find_in_path_element __P((const char *, char *, int, int, struct stat *)); static char *find_absolute_program __P((const char *, int)); static char *get_next_path_element __P((char *, int *)); /* The file name which we would try to execute, except that it isn't possible to execute it. This is the first file that matches the name that we are looking for while we are searching $PATH for a suitable one to execute. If we cannot find a suitable executable file, then we use this one. */ static char *file_to_lose_on; /* Non-zero if we should stat every command found in the hash table to make sure it still exists. */ int check_hashed_filenames; /* DOT_FOUND_IN_SEARCH becomes non-zero when find_user_command () encounters a `.' as the directory pathname while scanning the list of possible pathnames; i.e., if `.' comes before the directory containing the file of interest. */ int dot_found_in_search = 0; /* Return some flags based on information about this file. The EXISTS bit is non-zero if the file is found. The EXECABLE bit is non-zero the file is executble. Zero is returned if the file is not found. */ int file_status (name) const char *name; { struct stat finfo; int r; /* Determine whether this file exists or not. */ if (stat (name, &finfo) < 0) return (0); /* If the file is a directory, then it is not "executable" in the sense of the shell. */ if (S_ISDIR (finfo.st_mode)) return (FS_EXISTS|FS_DIRECTORY); r = FS_EXISTS; #if defined (AFS) /* We have to use access(2) to determine access because AFS does not support Unix file system semantics. This may produce wrong answers for non-AFS files when ruid != euid. I hate AFS. */ if (access (name, X_OK) == 0) r |= FS_EXECABLE; if (access (name, R_OK) == 0) r |= FS_READABLE; return r; #else /* !AFS */ /* Find out if the file is actually executable. By definition, the only other criteria is that the file has an execute bit set that we can use. The same with whether or not a file is readable. */ /* Root only requires execute permission for any of owner, group or others to be able to exec a file, and can read any file. */ if (current_user.euid == (uid_t)0) { r |= FS_READABLE; if (finfo.st_mode & S_IXUGO) r |= FS_EXECABLE; return r; } /* If we are the owner of the file, the owner bits apply. */ if (current_user.euid == finfo.st_uid) { if (finfo.st_mode & S_IXUSR) r |= FS_EXECABLE; if (finfo.st_mode & S_IRUSR) r |= FS_READABLE; } /* If we are in the owning group, the group permissions apply. */ else if (group_member (finfo.st_gid)) { if (finfo.st_mode & S_IXGRP) r |= FS_EXECABLE; if (finfo.st_mode & S_IRGRP) r |= FS_READABLE; } /* Else we check whether `others' have permission to execute the file */ else { if (finfo.st_mode & S_IXOTH) r |= FS_EXECABLE; if (finfo.st_mode & S_IROTH) r |= FS_READABLE; } return r; #endif /* !AFS */ } /* Return non-zero if FILE exists and is executable. Note that this function is the definition of what an executable file is; do not change this unless YOU know what an executable file is. */ int executable_file (file) const char *file; { int s; s = file_status (file); return ((s & FS_EXECABLE) && ((s & FS_DIRECTORY) == 0)); } int is_directory (file) const char *file; { return (file_status (file) & FS_DIRECTORY); } int executable_or_directory (file) const char *file; { int s; s = file_status (file); return ((s & FS_EXECABLE) || (s & FS_DIRECTORY)); } /* Locate the executable file referenced by NAME, searching along the contents of the shell PATH variable. Return a new string which is the full pathname to the file, or NULL if the file couldn't be found. If a file is found that isn't executable, and that is the only match, then return that. */ char * find_user_command (name) const char *name; { return (find_user_command_internal (name, FS_EXEC_PREFERRED|FS_NODIRS)); } /* Locate the file referenced by NAME, searching along the contents of the shell PATH variable. Return a new string which is the full pathname to the file, or NULL if the file couldn't be found. This returns the first readable file found; designed to be used to look for shell scripts or files to source. */ char * find_path_file (name) const char *name; { return (find_user_command_internal (name, FS_READABLE)); } static char * _find_user_command_internal (name, flags) const char *name; int flags; { char *path_list, *cmd; SHELL_VAR *var; /* Search for the value of PATH in both the temporary environments and in the regular list of variables. */ if (var = find_variable_internal ("PATH", 1)) /* XXX could be array? */ path_list = value_cell (var); else path_list = (char *)NULL; if (path_list == 0 || *path_list == '\0') return (savestring (name)); cmd = find_user_command_in_path (name, path_list, flags); return (cmd); } static char * find_user_command_internal (name, flags) const char *name; int flags; { #ifdef __WIN32__ char *res, *dotexe; dotexe = (char *)xmalloc (strlen (name) + 5); strcpy (dotexe, name); strcat (dotexe, ".exe"); res = _find_user_command_internal (dotexe, flags); free (dotexe); if (res == 0) res = _find_user_command_internal (name, flags); return res; #else return (_find_user_command_internal (name, flags)); #endif } /* Return the next element from PATH_LIST, a colon separated list of paths. PATH_INDEX_POINTER is the address of an index into PATH_LIST; the index is modified by this function. Return the next element of PATH_LIST or NULL if there are no more. */ static char * get_next_path_element (path_list, path_index_pointer) char *path_list; int *path_index_pointer; { char *path; path = extract_colon_unit (path_list, path_index_pointer); if (path == 0) return (path); if (*path == '\0') { free (path); path = savestring ("."); } return (path); } /* Look for PATHNAME in $PATH. Returns either the hashed command corresponding to PATHNAME or the first instance of PATHNAME found in $PATH. Returns a newly-allocated string. */ char * search_for_command (pathname) const char *pathname; { char *hashed_file, *command; int temp_path, st; SHELL_VAR *path; hashed_file = command = (char *)NULL; /* If PATH is in the temporary environment for this command, don't use the hash table to search for the full pathname. */ path = find_variable_internal ("PATH", 1); temp_path = path && tempvar_p (path); if (temp_path == 0 && path) path = (SHELL_VAR *)NULL; /* Don't waste time trying to find hashed data for a pathname that is already completely specified or if we're using a command- specific value for PATH. */ if (path == 0 && absolute_program (pathname) == 0) hashed_file = phash_search (pathname); /* If a command found in the hash table no longer exists, we need to look for it in $PATH. Thank you Posix.2. This forces us to stat every command found in the hash table. */ if (hashed_file && (posixly_correct || check_hashed_filenames)) { st = file_status (hashed_file); if ((st & (FS_EXISTS|FS_EXECABLE)) != (FS_EXISTS|FS_EXECABLE)) { phash_remove (pathname); free (hashed_file); hashed_file = (char *)NULL; } } if (hashed_file) command = hashed_file; else if (absolute_program (pathname)) /* A command containing a slash is not looked up in PATH or saved in the hash table. */ command = savestring (pathname); else { /* If $PATH is in the temporary environment, we've already retrieved it, so don't bother trying again. */ if (temp_path) { command = find_user_command_in_path (pathname, value_cell (path), FS_EXEC_PREFERRED|FS_NODIRS); } else command = find_user_command (pathname); if (command && hashing_enabled && temp_path == 0) phash_insert ((char *)pathname, command, dot_found_in_search, 1); /* XXX fix const later */ } return (command); } char * user_command_matches (name, flags, state) const char *name; int flags, state; { register int i; int path_index, name_len; char *path_list, *path_element, *match; struct stat dotinfo; static char **match_list = NULL; static int match_list_size = 0; static int match_index = 0; if (state == 0) { /* Create the list of matches. */ if (match_list == 0) { match_list_size = 5; match_list = strvec_create (match_list_size); } /* Clear out the old match list. */ for (i = 0; i < match_list_size; i++) match_list[i] = 0; /* We haven't found any files yet. */ match_index = 0; if (absolute_program (name)) { match_list[0] = find_absolute_program (name, flags); match_list[1] = (char *)NULL; path_list = (char *)NULL; } else { name_len = strlen (name); file_to_lose_on = (char *)NULL; dot_found_in_search = 0; stat (".", &dotinfo); path_list = get_string_value ("PATH"); path_index = 0; } while (path_list && path_list[path_index]) { path_element = get_next_path_element (path_list, &path_index); if (path_element == 0) break; match = find_in_path_element (name, path_element, flags, name_len, &dotinfo); free (path_element); if (match == 0) continue; if (match_index + 1 == match_list_size) { match_list_size += 10; match_list = strvec_resize (match_list, (match_list_size + 1)); } match_list[match_index++] = match; match_list[match_index] = (char *)NULL; FREE (file_to_lose_on); file_to_lose_on = (char *)NULL; } /* We haven't returned any strings yet. */ match_index = 0; } match = match_list[match_index]; if (match) match_index++; return (match); } static char * find_absolute_program (name, flags) const char *name; int flags; { int st; st = file_status (name); /* If the file doesn't exist, quit now. */ if ((st & FS_EXISTS) == 0) return ((char *)NULL); /* If we only care about whether the file exists or not, return this filename. Otherwise, maybe we care about whether this file is executable. If it is, and that is what we want, return it. */ if ((flags & FS_EXISTS) || ((flags & FS_EXEC_ONLY) && (st & FS_EXECABLE))) return (savestring (name)); return (NULL); } static char * find_in_path_element (name, path, flags, name_len, dotinfop) const char *name; char *path; int flags, name_len; struct stat *dotinfop; { int status; char *full_path, *xpath; xpath = (*path == '~') ? bash_tilde_expand (path, 0) : path; /* Remember the location of "." in the path, in all its forms (as long as they begin with a `.', e.g. `./.') */ if (dot_found_in_search == 0 && *xpath == '.') dot_found_in_search = same_file (".", xpath, dotinfop, (struct stat *)NULL); full_path = sh_makepath (xpath, name, 0); status = file_status (full_path); if (xpath != path) free (xpath); if ((status & FS_EXISTS) == 0) { free (full_path); return ((char *)NULL); } /* The file exists. If the caller simply wants the first file, here it is. */ if (flags & FS_EXISTS) return (full_path); /* If we have a readable file, and the caller wants a readable file, this is it. */ if ((flags & FS_READABLE) && (status & FS_READABLE)) return (full_path); /* If the file is executable, then it satisfies the cases of EXEC_ONLY and EXEC_PREFERRED. Return this file unconditionally. */ if ((status & FS_EXECABLE) && (flags & (FS_EXEC_ONLY|FS_EXEC_PREFERRED)) && (((flags & FS_NODIRS) == 0) || ((status & FS_DIRECTORY) == 0))) { FREE (file_to_lose_on); file_to_lose_on = (char *)NULL; return (full_path); } /* The file is not executable, but it does exist. If we prefer an executable, then remember this one if it is the first one we have found. */ if ((flags & FS_EXEC_PREFERRED) && file_to_lose_on == 0) file_to_lose_on = savestring (full_path); /* If we want only executable files, or we don't want directories and this file is a directory, or we want a readable file and this file isn't readable, fail. */ if ((flags & (FS_EXEC_ONLY|FS_EXEC_PREFERRED)) || ((flags & FS_NODIRS) && (status & FS_DIRECTORY)) || ((flags & FS_READABLE) && (status & FS_READABLE) == 0)) { free (full_path); return ((char *)NULL); } else return (full_path); } /* This does the dirty work for find_user_command_internal () and user_command_matches (). NAME is the name of the file to search for. PATH_LIST is a colon separated list of directories to search. FLAGS contains bit fields which control the files which are eligible. Some values are: FS_EXEC_ONLY: The file must be an executable to be found. FS_EXEC_PREFERRED: If we can't find an executable, then the the first file matching NAME will do. FS_EXISTS: The first file found will do. FS_NODIRS: Don't find any directories. */ static char * find_user_command_in_path (name, path_list, flags) const char *name; char *path_list; int flags; { char *full_path, *path; int path_index, name_len; struct stat dotinfo; /* We haven't started looking, so we certainly haven't seen a `.' as the directory path yet. */ dot_found_in_search = 0; if (absolute_program (name)) { full_path = find_absolute_program (name, flags); return (full_path); } if (path_list == 0 || *path_list == '\0') return (savestring (name)); /* XXX */ file_to_lose_on = (char *)NULL; name_len = strlen (name); stat (".", &dotinfo); path_index = 0; while (path_list[path_index]) { /* Allow the user to interrupt out of a lengthy path search. */ QUIT; path = get_next_path_element (path_list, &path_index); if (path == 0) break; /* Side effects: sets dot_found_in_search, possibly sets file_to_lose_on. */ full_path = find_in_path_element (name, path, flags, name_len, &dotinfo); free (path); /* This should really be in find_in_path_element, but there isn't the right combination of flags. */ if (full_path && is_directory (full_path)) { free (full_path); continue; } if (full_path) { FREE (file_to_lose_on); return (full_path); } } /* We didn't find exactly what the user was looking for. Return the contents of FILE_TO_LOSE_ON which is NULL when the search required an executable, or non-NULL if a file was found and the search would accept a non-executable as a last resort. If the caller specified FS_NODIRS, and file_to_lose_on is a directory, return NULL. */ if (file_to_lose_on && (flags & FS_NODIRS) && is_directory (file_to_lose_on)) { free (file_to_lose_on); file_to_lose_on = (char *)NULL; } return (file_to_lose_on); }
http://opensource.apple.com/source/bash/bash-80/bash/findcmd.c
CC-MAIN-2013-48
refinedweb
1,988
63.39
Immutable Servers with Puppet and Packer Puppet and Packer Immutable Server It is recommended that server upgrades or changes on servers should never be done while the servers are live. What you should is that you should create new servers having the upgrades, and then stop using the old servers. The benefit is that you will enjoy immutability as you program at the infrastructure level, and you will not be affected by the configuration drift. Nodes Our infrastructure project will be made up of nodes.yalm which will be used for definition of the node names and the AWS security groups which they belong to. This is simple, as it is used in multiple other tools such as the vagrant. The code should be as shown below: elasticsearch: group: logging zookeeper: group: zookeeper redis: group: redis size: m2.2xlarge Rakefile We will use the file “nodes.yaml” together with rake for production of packer templates for building out new AMIs. Note that most packer templates usually have similar or related features, so you can manage them as a unit, and this feature will ensure this. The code for this is given below: require ‘erb’ require ‘yaml’ namespace :packer do task :generate do current_dir = File.dirname(__FILE__) nodes = YAML.load_file( “#{current_dir}/nodes.yml”) nodes.each_key do |node_name| include ERB::Util template = File.read(“#{current_dir}/packs/template.json.erb”) erb = ERB.new(template) File.open(“#{current_dir}/packs/#{node_name}.json”, “w”) do |f| f.write(erb.result(binding)) end end end end What we have done is that we have used it together with a simple erb template which will inject the nodename into it. This is shown below: { “builders”: [{ “type”: “amazon-ebs”, “region”: “us-east-1”, “source_ami”: “ami-10314d79”, “instance_type”: “t1.micro”, “ssh_username”: “ubuntu”, “ami_name”: “<%= node_name %> {{.CreateTime}}”, “security_group_id”: “packer” }], “provisioners”: [{ “type”: “shell”, “script”: “packs/install_puppet.sh” }, { “type”: “shell”, “inline”: [ “sudo apt-get upgrade -y”, “sudo sed -i /etc/puppet/puppet.conf -e \”s/nodename/<%= node_name %>-$(hostname)/\””, “sudo puppet agent –test || true” ] }] With the above code, a packer template will be generated for each node, and this will perform the following tasks: - Install puppet. - An AMI will be created in us-east-1 - Execute Puppet once for configuration of the system. - The security group will be adjusted to EC2. The Puppet agent should not be enabled, so that we can avoid polling of updates. Once Puppet has completed, we can then remove it from the server to avoid it being baked in by AMI. The Script With packer, the user can specify the shell files and the shell commands which are to be run. When it comes to bootstrapping, this feature is the best, but it is good for the kind of configuration management needed in Puppet. Our packer templates will work by calling a shell script, and this will ensure that we do not use the old version of ruby Linux distros. The server name of the Puppet master will also be specified as part of the installation process. The code is given below: sleep 20, wget sudo dpkg -i puppetlabs-release-precise.deb sudo apt-get update sudo apt-get remove ruby1.8 -y sudo apt-get install ruby1.9.3 puppet -y sudo su -c ‘echo “””[main] logdir=/var/log/puppet vardir=/var/lib/puppet ssldir=/var/lib/puppet/ssl rundir=/var/run/puppet factpath=$vardir/lib/facter templatedir=$confdir/templates [agent] server = ip-10-xxx-xx-xx.ec2.internal report = true certname=nodename””” >> /etc/puppet/puppet.conf’ The next step in our process should be to build a new AMI for the redis by running the following command: Once you execute the above command, the server will be created, configured, imaged, and finally terminated. Note that for each AMI that you create, a cost will be incurred. The cost for a single AMI might be small, but when you have multiple of these, then this will be very costly. This is why the old images have to be cleaned up. This is a very simple task which can be done as shown below: import os import boto from fabric.api import task class Images(object): def __init__(sf, **kw): sf.con = boto.connect_ec2(**kw) def get_ami_for_name(sf, name): (keys, AMIs) = sf.get_amis_sorted_by_date(name) return AMIs[0] def get_amis_sorted_by_date(sf, name): amis = sf.conn.get_all_images(filters={‘name’: ‘{}*’.format(name)}) AMIs = {} for ami in amis: (name, creation_date) = ami.name.split(‘ ‘) AMIs[creation_date] = ami # removing the old images! keys = AMIs.keys() keys.sort() keys.reverse() return (keys, AMIs) def remove_old_images(sf, name): (keys, AMIs) = sf.get_amis_sorted_by_date(name) while len(keys) > 1: key = keys.pop() print(“deregistering {}”.format(key)) AMIs[key].deregister(delete_snapshot=True) @task def cleanup_old_amis(name): ”’ Usage: cleanup_old_amis:name={{ami-name}} ”’ images = Images( aws_access_key_id=os.environ[‘AWS_ACCESS_KEY_ID’], aws_secret_access_key=os.environ[‘AWS_SECRET_ACCESS_KEY’] ) images.remove_old_images(name) You can set up the above. It will make sure that the AMI that you have in your system is the latest one. If you need to make sure that your five last AMIs are kept for the purpose of archiving, you can tweak this. If we had data stores, then this would have been made a bit trickier, since we would have to boot each of the replicas of the primary instances, replicas promoted to primaries, and then old primaries would be retired.
http://mindmajix.com/devops/puppet-and-packer-immutable-servers
CC-MAIN-2017-13
refinedweb
877
56.45
Groovyness with Excel and XML March 27, 2007 4 Comments Today in class one of the students mentioned that they need to read data from an Excel spreadsheet supplied by one of their clients and transform the data into XML adhering to their own schema. I’ve thought about similar problems for some time and looked at the various Java APIs for accessing Excel. I spent a fair amount of time working with the POI project at Apache, which is a poor substitute but at least worked. On the XML side, the Java libraries have gotten better, but working with XML in Java is rarely fun. I know the Apache group has built a few helper projects to make it easier, but I haven’t used them that much. In class, students don’t really want to talk about other projects; they want to know what’s in the standard libraries. In short, I know I could write the necessary code to take data out of Excel and write it out to XML, but it would be long and awkward. It certainly wouldn’t be much fun. Now, though, I’m spending a lot of time with Groovy. I’m working my way through the book Groovy in Action (Manning), which has jumped to the top of my favorite technical books list. I’m still learning, but I knew there was a Groovy library for accessing Excel, and I knew Groovy had a “builder” for outputting XML. I just needed to see how to write the actual code. I set up a sample Excel spreadsheet with a few rows of data and went to work. Here’s the result. It’s about 25 lines of code all told. In other words, it’s almost trivial. I’m amazed. package com.kousenit; import org.codehaus.groovy.scriptom.ActiveXProxy def addresses = new File('addresses.xls').canonicalPath def xls = new ActiveXProxy('Excel.Application') // get the workbooks object def workbooks = xls.Workbooks def workbook = workbooks.Open(addresses) // select the active sheet def sheet = workbook.ActiveSheet // get the XML builder ready def builder = new groovy.xml.MarkupBuilder() builder.people { for (row in 2..1000) { def ID = sheet.Range("A${row}").Value.value if (!ID) break // use the builder to write out each person person (id: ID) { name { firstName sheet.Range("B${row}").Value.value lastName sheet.Range("C${row}").Value.value } address { street sheet.Range("D${row}").Value.value city sheet.Range("E${row}").Value.value state sheet.Range("F${row}").Value.value zip sheet.Range("G${row}").Value.value } } } } // close the workbook without asking for saving the file workbook.Close(false, null, false) // quits excel xls.Quit() xls.release() I’d call that a successful experiment. It certainly was a happy one. I know I’ll do more in the future. I’d bet that somebody with more experience could show me how to condense that even further. Groovy is just plain fun, and I haven’t felt that way about Java for a long, long time. Recent Comments
https://kousenit.org/2007/03/
CC-MAIN-2017-17
refinedweb
505
76.82
On point 2 I was caching the CompiledScript and using Bindings to pass in variables. I didn't realize it still required re-compiling or additional processing. The use case was for user provided expressions.. Example: x AND y My assessment was dynamically wrapping the expression in a function could potentially be error prone as the language syntax depends on line spacing. However the performance difference was so great that I ended up doing it anyway.. and sure enough there were some sample expressions I had to modify but it wasn't as bad as I anticipated. So I'm dynamically turning the expression above into.. def fx(x,y): return x AND y
http://bugs.jython.org/msg9638
CC-MAIN-2017-51
refinedweb
114
57.77
I have two graphics methods in my program. One for the menu and one for the game. I have previously written all of my code in one graphics with a bunch of nested ifs. Now I am trying to separate the two. Is there a way to call the gameGraphics method when the game is running, and then returning to the graphics method when you return to then menu? here is my code: // The "SpaceSpamEvolution" class. import java.applet.*; import java.awt.*; import javax.swing.*; import java.awt.event.*; public class SpaceSpamEvolution extends Applet implements KeyListener, ActionListener { Timer time; int screen; // 1 = menu, 2 = game int select = 1; // select from the menu 1 = play, 2 = change diffuculty, 3 = change color (maybe) int difficulty = 1; // 1 = easy, 2 = medium, 3 = difficult int gameDiff ; // gameDiff = difficulty // Place instance variables here public void init () { // Place the body of the initialization method here } // init method public void paint (Graphics g) { g.setColor(Color.red); g.fillRect (10,10,10,10); // Place the body of the drawing method here } // paint method public void keyPressed (KeyEvent e){ int key = e.getKeyCode (); if (key == KeyEvent.VK_ENTER && screen == 1){ if (select == 1){ gameDiff = difficulty; game (gameDiff); } } if (key == KeyEvent.VK_RIGHT && screen == 1){ difficulty += 1; if (difficulty == 4){ difficulty = 1; } } if (key == KeyEvent.VK_LEFT && screen == 1){ difficulty -= 1; if (difficulty == 0){ difficulty = 3; } } } public void keyReleased (KeyEvent e){} public void keyTyped (KeyEvent e){} public void game (int gameDiff){ int delaytime; time = new Timer ((2000 - (500*gameDiff)), this); } public void gameGraphics (Graphics z){ z.setColor (Color.blue); z.fillRect (50,50,50,50); } public void actionPerformed (ActionEvent e){} } // SpaceSpamEvolution class Thanks for any help.
https://www.daniweb.com/programming/software-development/threads/354633/calling-separate-graphics-methods-in-applet
CC-MAIN-2017-09
refinedweb
274
60.35
Question: Please ignore language syntax, I want to discuss only OOPS here. I will present here 2 code snippets, each of which is a sample of Composition (if I'm not wrong). Problem Statement: I have an object which keeps the stats of an entity in the system. Let those stats be: - Name - Salary *these fields can be anything, I just took these for example. so please dont think in terms of what field is necessary or not. Assume all three are necessary. I created a class which corresponds to these fields: public class Stats{ field Name; field LatsName; field Salary; } Now I came across a situation where i want to have information about a person across time period. Lets see at a point in the workflow system requires that it be presented with information about a person for all three stages - When he was child. - When he was young. - when he got retired. Point to note here is that name and lastName won't change, only salary might change. Because of this, I thought that I can perhaps create a class that can use existing object 'stats'. I'm goin to present two solutions , Please suggest which one is better and why. Code Sample 1 public class CompositeStats{ //Adding three more properties and hinding the one already existing. private objStats= new Stats(); public field FirstName{ get{return objStats.Name;} set{objStats.Name=value;} } public field LastName{ get{return objStats.LastName;} set{objStats.LastName=value;} } public field SalaryChild{get;set;} public field SalaryYoung{get;set;} public field SalaryRetired{get;set;} } In the above sample code, I did not expose the original field of salary but have created 3 new for each time span. Code Sample 2 public class CompositeStats{ private objStatsChild= new Stats(); private objStatsYoung= new Stats(); private objStatsRetired= new Stats(); public field FirstName{ get{return objStatsChild.Name;} set{objStatsChild.Name=value;} } public field LastName{ get{return objStatsChild.LastName;} set{objStatsChild.LastName=value;} } public field SalaryChild{ get{return objStatsChild.Salary;} set{objStatsChild.Salary=value;} } public field SalaryYoung{ get{return objStatsYoung.LastName;} set{objStatsYoung.LastName=value;} } public field SalaryRetired{ get{return objStatsRetired.LastName;} set{objStatsRetired.LastName=value;} } } Solution:1 I think something like this would be better all around. It allows you to create new life stages without changing your object model. Also, if a person has not reached a stage yet, there will be no information stored for it. A property called "CurrentStage" could pick the latest stage in the list. public class Stage{ object BeginStage; // Probably a DateTime or similar class. object EndStage; // Probably a DateTime or similar class. object Salary; } public class Stats{ object Name; object LastName; IEnumerable<Stage> Stages; } You could also use this variation. public enum Stage { Child, Young, Retired, } public class StageSalary { Stage Stage; object Salary; } public class Stats{ object Name; object LastName; List<StageInfo> Stages; } Solution:2 I think its obvious that first one is a better choice. Reason: 1. Performance: private objStatsChild= new Stats(); private objStatsYoung= new Stats(); private objStatsRetired= new Stats(); Why would you create three instances, when you actually need value from one of the instaces only. - Bad Design. You are creating three instances of "Stats",and while returning the name you are picking one of them (at random, atleast there is not logic to select one of them). 3.If all you want to do is to hide "Salary" in stats, then it is more of a case of inheritance, with "Salary" removed from parent class. Solution:3 Check out a design pattern called "Facade", it allows you to have a single class structure that inherits from multiple interfaces, and allowing data to only represent the structure that you categorized them as.. i.e. hide / ignore fields for "child" that are only used for "retired" etc. Solution:4 Let us consider one more usage: var dictStages = new Dictionary<Stage,double>(); Here, Stage is an enum: Child, Adult, Retired In your class add the properties CurrentStage - this will relect the latest stage from the dictStage CurrentSalary - this will reflect the salary for CurrentStage. Although, you might want to expose some methods that can return Salary for a particular stage. Solution:5 I would refactor your code to something like this: class Person { field Name; field LastName; } enum PersonAge { Child, Young, Retired } class Stage { public PersonAge Age { get; set; } field Salary; } class PersonStats { public Person Person { get; set; } public IList<Stage> Stages { get; set; } } Does it make sense? Solution:6 The 'classic' "IsA", "HasA" thinking will always help steer you in the right direction: A "Person" "HasA" "Collection of Data", which your information from his life stages. Today you say "three" stages but of course you would never design to such a limited view of the problem ... right? so you have class Person { [vector or list or your favorite collection type] Data; Name; LastName; }; The snapshot you ask about "HasA" reference(s) to the Person, and a specifier for which piece of data you want in the snapshot: class PersonInfoSnapshot { [reference to] Person; /* "reference to Person.Data" could mean anything that allows retrieval of the data that you need */ [reference to] Person.Data; }; Details of specific types, visibility and so forth left as an exercise. Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com EmoticonEmoticon
http://www.toontricks.com/2018/10/tutorial-oop-composition-samples-please.html
CC-MAIN-2018-43
refinedweb
883
52.6
Release 2 (9.0.2) for UNIX April 2002Part No. A92187-01 This document summarizes updates to Oracle9i Forms Developer and Oracle9iAS Forms Services: You can also obtain the latest edition of these Release Notes and other Oracle9i Forms production information at:. This section describes general issues and their workarounds for Oracle 9i Forms Developer and Oracle9iAS Forms Services. With Oracle9i Forms, Oracle no longer ships the Open Client Adaptor (OCA) for accessing databases through ODBC rather than SQL*Net. The stated replacement for OCA is to use the Oracle Transparent Gateways as a way to access data in databases such as Microsoft SQL Server or IBM DB2. In the initial releases of Forms 9i, however, we cannot support access via the transparent gateways due to the lack of support in the gateways for "Select For Update" to enable row level locking. This deficiency will be addressed in a future release of Oracle Forms. (2258527) The following excerpt is in Chapter 3 of the Oracle9iAS Forms Services Deployment Guide Release 9.0.2: "If you are using the test certificate supplied with Oracle9iAS for test purposes, you must edit the JInitiator certdb.txt file and append the contents of the demo root certificate, which is located in <9iAS oracle_home/Apache/Apache/conf/ssl.crt/demoCAcert.txt." The demoCAcert.txt file no longer exists. If you are running with Oracle9iAS Web Cache enabled (which is usually the case), you should use the file <9iAS oracle_home>/webcache/wallets/default/b60certificate.txt instead. If you are not running with Web Cache (that is, you are accessing the Oracle HTTP Server directly) you will need to create the demo root certificate file as follows: Once you have the required certificate file, you should follow the instructions in the Oracle9iAS Forms Services Deployment Guide to configure JInitiator to use the certificate (appending it to JInitiator's certdb.txt file). (2275360) In the Online Help, F1 links to obsolete built-ins, properties, triggers, and constants give the following error message "FRM-10063: Cannot find the help file or help file is damaged". This error occurs because obsolete information has been removed from the help system. See Oracle9i Forms Developer and Forms Services: Migrating Forms Applications from Forms6i, part number A92183-01, for migration and obsolescence information. (2205868)You can download the latest JDAPI Javadoc from:. You can download the latest XMLTOOLS Javadoc from:. You can download the latest graphical user interface (GUI) version of the Migration Tool at:. Documentation for the GUI version of the Migration Tool is available at:. This section describes configuration issues and their workarounds for Oracle 9i Forms Developer and Oracle9iAS Forms Services. (2266745) Graphics, such as a chart, may not appear when a Form runs. As a workaround, modify the g90runm.sh to set TK_PRINTER to the actual $PRINTER value. (2298868) The PATH environment variable in default.env must be set to: %ORACLE_HOME%/bin in the 9i Oracle Home. Oracle9iDS Forms Japanese documentation is not available for this release. It will be available in the Japanese Oracle9iDS Forms 9.0.2 release. ORARRP is not supported. In the Oracle9i Forms Developer and Forms Services: Migrating Forms Applications from Forms6i manual (P/N A92183-01), the following converter.properties options are not supported: You can ignore these options. (2278644, 2280598) As a workaround when you receive this error, add the following to the default.env file: REPORTS_CLASSPATH=%FORMS_ORACLE_HOME%/jlib/zrclient.jar;%FORMS_ORACLE_ HOME%/rep orts/jlib/rwrun.jar (2228305) As a workaround, modify the file f90desm.sh and uncomment the line that calls reports.sh. (2262949, 2268090) On Solaris platforms, the formsweb.cfg file contains VM parameters that are not supported for deployment in a production environment. The 1.3 Sun Java plug-in is not supported as a client platform for runtime deployment. The entry in the formsweb.cfg file for this plug-in is included only for use with Oracle9iDS Forms Developer on Unix platforms, when running or debugging a form. To deploy Oracle9i Forms applications on Oracle9iAS, you must configure the forms90.conf file. Oracle9iAS Forms Services use OC4J, via mod_OC4J, for the Forms Servlet and the Forms Listener Servlet only. All other file handling, such as downloading client Java archives and JInitiator, is performed directly by the Oracle HTTP Server. the forms90.conf file is automatically configured during product installation. See the Oracle9iAS Forms Services Deployment Guide (part number A92175-01) for information about the forms90.conf file. Because there is no Apache HTTP Listener on Oracle9iDS, however, Forms uses OC4J directly for design-time deployment and for downloading client archive files. FRM-93000: Servlet internal error. Cause: A servlet error occurred, or runtime did not start propery. Action: See the error messages in the servlet (OC4J) log file for clarification. You can find the OC4J log file at: <ORACLE_HOME>/j2ee/OC4J_BI_Forms/application-deployments/forms90app The log file is called application.log, and is usually in a subdirectory like OC4J_BI_Forms_default_island_1, depending on how iAS has been configured. (2161032) If you use OTHERPARAMS in a named configuration section in the formsweb.cfg file, you overwrite the default the OTHERPARAMS parameter, which contains the DEBUG parameter. For example, suppose you have a named configuration that looks like this: [MyApp] otherparams=usesdi=yes Then you are overriding the default OTHERPARAMS, which looks like this: otherparams=debug=%debug% host=%host% port=%port% Therefore, if you use the debugger with the MyApp configuration, the debugger will not run. This behavior also occurs if the Application Server URL is modified in the Form preferences to use the MyApp configuration. The workaround is to put DEBUG, HOST, and PORT as separate parameters. Modify the appropriate base.html file and the three separate parameters. Make sure to also add them in the default section of formsweb.cfg. Then, remove them from OTHERPARAMS. To use Run Form on UNIX platforms, do the following: Note The Web Browser should not be a symbolic link; if so Run Form will hang. (2293330) To enable HTTPS and Single Sign-On (SSO) with Oracle 9i Forms, do the following: $ORACLE_HOME/jdk/bin/java -jar $ORACLE HOME/sso/lib/ossoreg.jar -oracle_ home_path %MIDTIER_ORACLE_HOME% -host %<INFRASTRUCTRE_MACHINE_NAME>% -port 1521 -sid iasdb -site_name %<INFRASTRUCTRE_MACHINE_NAME>%:1521 -success_url success-logout_url success-cancel_url TRUE -u root -sso_server_version v1.2 Note: Port 4443 is the default port with Oracle9iAS. If you want to run a form with Jinitiator, append the b64certificate.txt file to certdb.txt. If you want to run a Form natively in Internet Explorer, import this file into Internet Explorer.If you want to run a form with Jinitiator, append the b64certificate.txt file to certdb.txt. If you want to run a Form natively in Internet Explorer, import this file into Internet Explorer. The following sections describe known issues in Oracle9i Forms components: (2190329) The Forms Server is doing necessary clean-up work, such as cleaning up memory allocations. The same effect happens when the Form process is killed from the command line. (2171120) If you modify the formsweb.cfg file using Enterprise Manager, and then submit the changes, all comments that were in the formsweb.cfg file are removed. This behavior does not occur until you submit the changes; therefore, viewing is safe. (2247822) Users can no longer specify the log name for the Forms Trace file in a URL. This behavior prevents a user from accidentally writing a file to an invalid location. If a user specifies log=<filename> in the URL, the URL will be ignored. The file will be named forms_<pid>.trc where <pid> is the process ID on the server. The file will be created in the directory specified by the environment variable FORMS90_TRACE_PATH, which is specified on the server. (2296258) If you specify record=otrace, the Form will fail to start. This issue will be resolved in the next patch set to Oracle9i Forms. (1983066) When creating a simple form and saving it to a directory such as C:\Program Files\Oracle\test.fmb, and when you click the Run Form icon, an error dialog appears: FRM-40010 : Cannot read form C:\Program. This error message appears when there is a space in the URL. The following keyboard shortcuts have changed: The following sections describe known bugs in Oracle9i Forms and suggested workaround where available: (2105230) There is a known problem with conversion of dates prior to November 18, 1883 between different time zones - e.g. US/Eastern to GMT. The wrong result can be returned in these circumstances. This problem will be addressed in a future patch of Oracle9i Forms. (2060602) Data in NCHAR or NVARCHAR2 columns may not be correct. When a Form is running against a database that has non-Unicode NLS_CHARACTERSET, data can be mangled when inserting or updating from a CHAR item in the Form into an NCHAR or NVARCHAR2 column in the database, even when the server hosting the Form specifies the UTF8 character set for NLS_LANG. Data can also be mangled when querying from NCHAR or NVARCHAR2 columns. (2175919) After querying records into a data block, and if the ONETIMEWHERE property is set for the data block, Forms crashes while retrieving the ONETIMEWHERE property. As a workaround, if you set the ONETIMEWHERE property on a block, then execute the query, do not get the ONETIMEWHERE property. (1960603) In a Web environment, icons are either.GIF or.JPG files. However, in the Layout Editor in the Forms Builder, ICO files are still used to display icons. These icons are used for design-time only. At runtime, GIF and JPG files are used. A future version of Oracle9i Forms should support GIF and JPG files in the Form Builder at design-time. (2235125) In the Import Java Classes dialog, you cannot navigate using keys to the Select Java Classes field. (2250726) DATA_PARAMETER that is used with Run_Product to call Reports cannot be passed to Reports via Run_Report_Object. The migration assistant issues a warning that if this is used in Conjunction with RUN_PRODUCT() for Reports then it will no longer work. (2116895 and 2116644) The migration of a PLL file is unsuccessful if the PLL contains either the keyword "language" or "userenv('LANG')". As a workaround, we have fixed the Migration Assistant so that if it finds the occurrence of either of these words inside the PLL, it will abort the migration process with an error message. The error message is different for each keyword, and looks something like: ERROR: <OBJECT_NAME>: Invalid PL/SQL variable name "language" found. This variable should be renamed. ERROR: <OBJECT_NAME>: Invalid PL/SQL construct "userenv('LANG')" found. ora_nls.get_lang_str(ora_nls.language_abbr) should be used instead. ERROR: Stop word(s) found. Rolling back changes and aborting migration. Unfortunately, the occurrences of these stop words inside comments also cause migration to be aborted. If you don't want to abort migration of the PLL, you can comment out the userenv and language category lines in the search_replace.properties file. (2175830) Compile After Conversion (default.generateruntime) is still valid, and is a true/false property. If it is set to "true", the module is compiled after conversion (i.e .fmx or .mmx or .plx file is generated). In the case of PLL files, the PLX file is always generated, irrespective of the default.generateruntime property. This behavior is incorrect, and bug 2175830 has been filed for it. As a workaround, look at the Edit | Inherit menu. It will be disabled if the property in question has a grey dot; otherwise, it is enabled. When it is enabled, you can look at the Subclass Information property, navigate to the property class, and see if the property is inherited or not and compare values. Alternatively, you can convert the .fmb file to XML and look at the properties there. Only overwritten properties will be displayed in the XML. (2258275) When the RUN_PRODUCT Built-in to invoke a second Web-deployed Forms application, you may receive the error: Connection from a new browser window not supported Also, the original Form session may freeze when the newly created one is exited. As a workaround, use the "open_form" PL/SQL built-in to run another (or the same) Form instance in a new session instead of using run_product. This is the recommended way of running multiple Forms sessions in one browser window. (2254547) After assigning a valid bean name in the Implementation Class Property, Forms returns the following error: FRM-13008: cannot find javabean with name 'mypackage.PJCBeanWrapper'. Make sure all the dependent class files are available to Forms builder. If you have created the bean using JDeveloper PJC Wizard, add jdev-rt.jar, f90all.jar and the jar containing the bean classes to FORMS90_BUILDER_CLASSPATH as a workaround. (2258187) On Solaris, you won't see a new object in the Layout Editor after a valid bean name is set in the Implementation Class property. Unlike the Windows version of the Layout Editor, the Solaris version does not give any user feedback. Since no feedback is given, and if you've set the classpath incorrectly, or an invalid Bean name is set in the Implementation Class property, you won't know about the error until you run the Form module. (2252171) After converting an Oracle9i Forms module to its XML equivalent and then back to a Forms module, the canvases may not display correctly because custom color palettes are not preserved in the conversion. (2061461) When doing an XML to FMB conversion on an Oracle9i Form that contains a graphics object of type IMAGE, and the image file is not found, the conversion utility provides no warning. When this Form is loaded into the Forms Builder and the canvas containing that object is opened, the Form Builder crashes. (2255174) When using the XML converter on a Oracle9i Form with an attached PLL file, and if the PLL file is not in the FORMS90_PATH, the XML Converter throws an exception. Instead of a clear message which indicates the PLL file that is causing the problem, the user gets an ambiguous error: Processing XML module vec0005_fmb.xml @ ERROR - an exception has been encountered: @ oracle.forms.jdapi.JdapiException: _jni_attach_lib failed However, the XML Converter will continue without the library. (2114805) This behavior happens even if the word "CALL" is used elsewhere, such as in comments. (2116969) The PL/SQL Converter shows warnings about obsolete Built-ins that are commented out. (2215797) Internally, Forms uses uppercase characters for Oracle9i Form objects. Since Java is case-sensitive, it is important to use uppercase when referring to Forms objects using JDAPI. This section describes known issues with national language support. (2055224) This following messages related to the upgrade of obsolete menu item types are not present in non-English versions of the message file. The following messages were added to the message file: 2500,0, "PLUS-type menu items are not supported in this version of Forms.\n" 2501,0, "FORM-type menu items are not supported in this version of Forms.\n" 2502,0, "MACRO-type menu items are not supported in this version of Forms.\n" 2503,0, "This menu item has been converted to a PL/SQL-type menu item.\nThe old command text is shown within comments below.\n" 2504,0, "Consider using the HOST built-in with the original text." 2505,0, "Consider using the CALL_FORM built-in with the original text." 2506,0, "Consider using the MACRO built-in with the original text." (1994138 and 1961840) Multibyte or bidirectional characters in query parameters in a URL used to invoke the Forms Servlet may not be handled correctly. For example, attempting to run a form whose (fmx) file name contains multibyte characters using a URL like may fail with an error saying the form module was not found (where XX represent multibyte or bidirectional characters). Also, specifying a multibyte form name in the formsweb.cfg file may fail in the same way too. The workaround is to rename the Form fmx file to a name not containing multibyte characters. These issues will be addressed in a future release. (194001) Multibyte or bidirectional characters in the environment file (usually called default.env) may not be read correctly. For example, if the FORMS90_PATH variable contains such characters the form may not be found (case where path to the form includes directories whose names contain multibyte characters). A workaround is to place the form module under directories with names which only include single byte characters. This section describes known errors in the Oracle9i Forms documentation set: In the Online Help topic "About Debugging", the sixth bullet in the list incorrectly mentions that you can browse instantiated PL/SQL package global variables. These variables cannot be seen in the debugger. (2278996) The Online Help topic for the Alert Property "Default Alert Button Property" describes the property as optional when in fact it is required. (2281042) On page FORMS90_DEFAULTFONT, the description for FORMS90_DEFAULTFONT is incorrectly written as FORMS60_DEFAULTFONT. (2249678) In the Online Help topic "Java Importer", in the C.3 Installation Requirements section, there is an incorrect path: ORACLE_HOME/TOOLS/COMMON60/JAVA/importer.jar The correct path is: ORACLE_HOME/JLIB/importer.jar. (2215338) The Online Help topic "Starting A Jdapi Session" contains the following piece of Java code: import oracle.forms.jdapi.*; // Jdapi.startup() does not need to be called because we are starting // the Jdapi in default mode. // public class JdapiSessionExample { public static void main(String[] args) { // suppress errors from missing subclassed modules Jdapi.setFailSubclassLoad(true); // suppress errors from missing PLLs Jdapi.setFailLibraryLoad(true); // This line will cause initialisation FormModule. fmb = new FormModule("myform.fmb");FormModule. fmb = new FormModule("myform.fmb");// program code goes here ... // finally, free API resources Jdapi.shutdown(); } } The bold line has a period following FormModule; therefore, Java will not compile with that period there. (2170544) In the Online Help topic "Low-level Subclassing Using Parent Properties", the following line of code: blockA.setParentModuleStorage(JdapiTypes.PAMO_FILESYSTEM_CTID); causes a compilation error: cannot resolve symbol symbol: variable PAMO_FILESYSTEM_CTID blockA.setParentModuleStorage(JdapiTypes.PAMO_FILESYSTEM_CTID); The solution is to comment out this line of code and the example will compile. (2273363) In the Online Help topic "Including a JavaBean and Custom Controls", the following source code will not compile: XPos := CurrentValue; get_parameter_attr(BeanValListHdl,'MouseY',ParamType, CurrentValue); YPos := CurrentValue; MsgBox('If you click at '||to_Char(XPos)||'/'||to_Char(YPos)||' again I may drop these beans'); In the bold line, replace "message" for "MsgBox" and the code will compile. (2257223) In the Online Help topic for the EXIT_FORM Built-in, the description for DO_COMMIT states: "Forms validates the changes, performs a commit, and exits the current Form without prompting the operator." The actual behavior is that Forms validates the changes, performs a commit, and exits the current Form without prompting the operator if they want to commit the changes. (2242622) In the Online Help topic "Modifying a Variable Value", the first step says: However, it should read: ORACLE_HOME/forms90/server/forms90.conf file. <IfModule mod_osso.c>* <Location forms90/f90servlet> require valid-user authType Basic </Location> </IfModule>*However, the above is already in forms90.conf, but it is commented out. Uncomment it to enable Single Sign On (SSO). Oracle is a registered trademark, and Oracle9i is a trademark or registered trademark of Oracle Corporation. Other names may be trademarks of their respective owners.
http://docs.oracle.com/cd/B10018_07/relnotes.902/a92187/toc.htm
CC-MAIN-2017-30
refinedweb
3,205
56.15
Doh... Had the answer in the first word of my subject line. Thanks Peter. But the idea of importing the entire file seems very messy. I was hoping there would be a way I could import the effect of the new task definition without all the targets and properties that define it. Because of the potential for naming conflicts when using import, I have to prefix all the target names. This is especially annoying in the example I show below. My project uses cpptasks. And because there is no official release, I'm using svnant to keep cpptasks updated. If I use import for this, the runtime namespace of my project build file contains all these other properties and targets that have little to do with my own project, each of which need to prefix to avoid namespace collision. So... instead of... ant -f svnant.xml update I end up with ant -f svnant.xml svnant_update which seems a little redundant. Same goes for all the clean, compile, etc. targets of the svnant.xml and cpptasks.xml build files. So let me clarify my question: Is there anyway to define a new task using a target in another build file WITHOUT importing all the targets and properties of that buildfile? Or do I just need to suck it up for the moment and accept the naming prefixes? Thanks in advance. Anm Peter Reilly wrote: > Use <import> and not <ant> > > Peter > > > > On Wed, Mar 5, 2008 at 1:46 PM, Andrew n marshall wrote: > >> Is it possible to define a task in one ant build file, but use it in >> another? For example, I want to have a single build file that contains >> the properties and tasks to download a copy of svnant and define its >> tasks. Then I want to call that ant file's define_svn_task target from >> another file (which works) and call an <svn ../> task, like this: >> >> <ant antfile="svnant.xml" target="define_svn_task"/><!-- which calls taskdef --> >> <svn> >> </svn> >> >> Thus, I can copy this svnant.xml to several projects and repositories >> without having to edit out project specific details or dig for svnant >> attributes like the download URL or install directory. >> >> When I tried this, the define_svn_task target succeeded, but it "failed >> to create task or type svn" in the next line. >> >> Can someone provide an example of how to do this properly? >> >> >> Anm >> --------------------------------------------------------------------- To unsubscribe, e-mail: user-unsubscribe@ant.apache.org For additional commands, e-mail: user-help@ant.apache.org
http://mail-archives.apache.org/mod_mbox/ant-user/200803.mbox/%3C47CEF56E.5030807@mail.com%3E
CC-MAIN-2016-18
refinedweb
414
74.19
Many times you want to warn developers that some methods or classes should not be used as they are either replaced or going to be replaced with new versions. This is possible by using the “[Obsolete]” attribute. [Obsolete] In the below class we have a method called as “Method1”. Now let’s say you have created a better improvised version of “Method1” called as “NewMethod1”. You want to send an alert to all your developers who are consuming this class to use “NewMethod1” rather than using “Method1”. Method1 NewMethod1 So you can decorate “Method1” with the “[Obsolete]” attribute as shown in the below code. public class Class1 { [Obsolete] public void Method1() { } public void NewMethod1() { } } Now if any programmer consumes the above class he will get a warning message as shown in the below figure. In case you want to show some message to the developers you can pass the message in the “Obsolete” attribute as shown in the below code snippet. Obsolete [Obsolete("Please use NewMethod1")] public void Method1() { } If you want to be bit strict and do not developers to use that method, you can pass ‘true” to the “Obsolete” attribute as shown in the below code. [Obsolete("Please use NewMethod1",true)] public void Method1() { } Now in case developers try to make a call to “Method1” they will get error and not just a simple warning. Also have a look at the following practical demonstration on C# Obsolete video: -.[^] Shivprasad koirala wrote:If someone has a feeling let him express it. General News Suggestion Question Bug Answer Joke Praise Rant Admin Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
https://www.codeproject.com/Articles/620652/How-can-we-mark-a-method-as-deprecated-in-csharp?msg=4611576
CC-MAIN-2017-22
refinedweb
282
67.28
Handles the in-race GUI (messages, mini-map, rankings, timer, etc...) More... #include <race_gui.hpp> Handles the in-race GUI (messages, mini-map, rankings, timer, etc...) Animation state: none, getting smaller (old value), getting bigger (new number). The constructor is called before anything is attached to the scene node. So rendering to a texture can be done here. But world is not yet fully created, so only the race manager can be accessed safely. This function computes a polygon used for drawing the measure for a meter (speedometer, etc.) The variable measured by the meter is compared to the thresholds, and is then used to compute a point between the two points associated with the lower and upper threshold Then, a polygon is calculated linking all the previous points and the variable point which link back to the first point. This polygon is used for drawing. Consider the following example : A E -| x | -D-| -w-| |-C--| -B–v-| If the measure is inferior to the first threshold, the function will create a triangle ABv with the position of v varying proportionally on a line between B and C ; at B with 0 and at C when it reaches the first threshold. If the measure is between the first and second thresholds, the function will create a quad ABCw, with w varying in the same way than v. If the measure exceds the higher threshold, the function will return the poly ABCDE. Energy meter that gets filled with nitro. This function is called from drawSpeedEnergyRank, which defines the correct position of the energy meter. Reimplemented from RaceGUIBase. Display items that are shown once only (for all karts). Draws the mini map and the position of all karts on it. Displays the lap of the kart. Draws the rank of a player. Draws the speedometer, the display of available nitro, and the rank of the kart (inside the speedometer). Returns the size of the texture on which to render the minimap to. Implements RaceGUIBase. This is a second initialisation call (after the constructor) for the race gui. This is called after the world has been initialised, e.g. all karts do exist (while the constructor is called before the karts are created). In the base gui this is used to initialise the referee data (which needs the start positions of the karts). Note that this function is (and must be called only once, after its constructor). Reimplemented from RaceGUIBase. Render all global parts of the race gui, i.e. things that are only displayed once even in splitscreen. Reimplemented from RaceGUIBase. Render the details for a single player, i.e. speed, energy, collectibles, ... Reimplemented from RaceGUIBase. Reset the gui before a race. It initialised all rank animation related values back to the default. Reimplemented from RaceGUIBase. Height of the digit font. Maximum lap display length (either 9/9 or 99/99). Stores the previous rank for each kart. Used for the rank animation. Distance of map from bottom of screen. Height of the map in pixels on the screen, need not be a power of 2. Distance of map from left side of screen. The height of the rendered mini map in pixels, must be a power of 2. The width of the rendered mini map in pixels, must be a power of 2. Width of the map in pixels on the screen, need not be a power of 2. The size of a single marker on the screen for AI karts, need not be a power of 2. The size of a single marker on the screen or player karts, need not be a power of 2. How long the rank animation has been shown.
https://doxygen.supertuxkart.net/classRaceGUI.html
CC-MAIN-2020-16
refinedweb
614
75.91
Problem Statement In the “Minimum Characters to be Added at Front to Make String Palindrome” problem we have given a string “s”. Write a program to find the minimum characters to be added at the front to make a string palindrome. Input Format The first and only one line containing a string “s”. Output Format The first and only one line containing an integer value n. Here n denotes the minimum characters to be added at the front to make a string palindrome. Constraints - 1<=|s|<=10^6 - s[i] must be a lower case English alphabet Example edef 1 Explanation: If we add “f” at the front of string “s” then our string satisfied the condition of the palindrome. So, here only 1 should be added in the front. Algorithm 1. Concatenate the string with a special symbol and reverse of the given string ie, c = s + $ + rs 2. Build an LPS array in which each index represents the longest proper prefix which is also a suffix. 3. As the last value in the LPS array is the largest suffix that matches the prefix of the original string. So, there are those many characters that satisfy the palindrome property 4. Now, find the difference between the length of the string and the last value in the LPS array, which is the minimum number of characters needed to make a string palindrome. Working of above example s = “edef” Example for proper prefixes and suffix(Knowledge required to form LPS) Proper prefixes of “abc” are ” “, “a”, “ab” and Suffixes of “abc” are “c”, “bc”, “abc”. s (after concatenation)= “edef$fede” LPS = {0, 0, 1, 0, 0, 0, 1, 2, 3 } //Here index is the longest length of largest prefix that matches suffix. The last value of LPS = 3, so there are 3 characters that satisfy palindrome property. Now, find the difference between the length of a given string(ie, 4) and the Last value(3) Therefore, we need 1 character to make it a palindrome. Implementation C++ program for Minimum Characters to be Added at Front to Make String Palindrome #include <bits/stdc++.h> using namespace std; vector<int> computeLPSArray(string s) { int n = s.length(); vector<int> LPS(n); int len = 0; LPS[0] = 0; int i = 1; while (i < n) { if (s[i] == s[len]) { len++; LPS[i] = len; i++; } else { if (len != 0) { len = LPS[len-1]; } else { LPS[i] = 0; i++; } } } return LPS; } int solve(string s) { string rs = s; reverse(rs.begin(), rs.end()); string c = s + "$" + rs; vector<int> LPS = computeLPSArray(c); return (s.length() - LPS.back()); } int main() { string s; cin>>s; cout<<solve(s)<<endl; return 0; } Java program for Minimum Characters to be Added at Front to Make String Palindrome import static java.lang.Math.abs; import java.util.Scanner; class sum { public static int[] computeLPSArray(String str) { int n = str.length(); int lps[] = new int[n]; int i = 1, len = 0; lps[0] = 0; while (i < n) { if (str.charAt(i) == str.charAt(len)) { len++; lps[i] = len; i++; } else { if (len != 0) { len = lps[len - 1]; } else { lps[i] = 0; i++; } } } return lps; } static int solve(String str) { StringBuilder s = new StringBuilder(); s.append(str); String rev = s.reverse().toString(); s.reverse().append("$").append(rev); int lps[] = computeLPSArray(s.toString()); return str.length() - lps[s.length() - 1]; } public static void main(String[] args) { Scanner sr = new Scanner(System.in); String s = sr.next(); System.out.println(solve(s)); } } qsjhbqd 6 Complexity Analysis Time Complexity O(n) where n is the size of the given string “s”. Here we find the “lps array of KMP algorithm” which takes linear time to compute. Space Complexity O(n) because we create an LSP array to compute our answer. And here the maximum size of the LSP array is n.
https://www.tutorialcup.com/interview/string/minimum-characters-to-be-added-at-front-to-make-string-palindrome.htm
CC-MAIN-2021-49
refinedweb
636
64.1
From: Vincent Finn (vincent.finn_at_[hidden]) Date: 2003-12-22 11:07:07 Hi, I have a been looking at the assign library in the Sandbox and thought I might as well post my comments here rather than emailing Thorsten directly. I have 2 question about it The first is is it possible for the header not to include all the STL headers? I know why it is done and that it doesn't really cost anything but I am always reluctant to include headers I don't need The second question is should the function P() be in the assign namespace. I know it is a trivial function but it is needed to make using the library on maps useful so I would imagine people will have to keep defining it if it isn't supplied Other than that it's great :-) Vin Boost list run by bdawes at acm.org, david.abrahams at rcn.com, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk
http://lists.boost.org/Archives/boost/2003/12/58032.php
CC-MAIN-2013-20
refinedweb
171
71.14
For the latest version of the code and documentation, please check the project on github. This tutorial and other interesting online tutorials and books on web development are published by web-engineering.info. Other related articles:. The total cost of this project, excluding the Android device, is less than 30 €. The design goals of our project are: One can buy devices with similar features, but the price range starts at about 75 EUR and more. Also, these devices cannot be easily modified, most of them using SMD (surface mount devices) and integrated ICs, thus a possible improvement or repair when needed is either hard or impossible. In addition, because it is easy to do and it costs nothing (except a few MCU cycles and a few minutes of programming), we can easily add a few other features: Disclaimer: working with electricity is dangerous. For this project we use 5V and 3.3V voltage levels, which is safe for the human body under any environment conditions. However, the low voltage. The hardware components required for this project are presented below. These components were mostly bought from eBay and Amazon, and the listed prices include postage costs within Germany (for some also in the EU). If you are willing to wait between two and five weeks to receive the items, you can also buy them from China online shops (Aliexpress, eBay, and so on), for less than half of the prices we show further. There are applications one can use to design electronic schematics, but most of the time, these are not easy to understand for beginners. We choose to use Fritzing, which allows to draw nice looking breadboard oriented designs, but also schematics and PCB layouts. It also provides a builtin environment which integrates with the Arduino Software and allows to write the Arduino code, compile it and deploy it on the Arduino board. The hardware prototype on a breadboard is shown in Figure 1: The hardware is divided in a few blocks: Note: many of the breadboards we are aware of, does not have a default connection between the GND lines for the two power grids, therefore you need to add a connection wire between the two GND lines, as shown in Figure 1. Also, some breadboards have every power grid splited in two halfs, so you have to use a jumper wire if this is the case. For the breadboard schematic, red wires were used for +5V, orange for 3.3V and black for GND connections. For communication lines, we use green and blue for RX/TX lines, and yellow for data pin of DHT22 sensor. In Figure 2, we show the full electronics schematic, of our weather station sensor node. Our sensor node is powered by a regulated 5V@1A power brick. The Arduino Pro Mini board and most of components can directly use the 5V rail comming from the power brick. The regulation down to 3.3V, required by the ESP8266 WiFi module, is obtained by using the LM317T IC, an adjustable step-down linear voltage regulator. It only requires a few additional components: two resistors and two capacitors. It is able to provide up to 1.5A current, with appropriate cooling. However, for our example cooling is not needed, the average current being under 250mA (going up to 500mA but only for very short amounts of time, when the ESP8266 module transmits data). Figure 3 shows the 3.3V power supply built on a breadboard, and Figure 4 shows the corresponding electronics schematic.. The values of the R1 and R2 resistors are chosen according with the following rules: Vout = 1.25 ( 1 + R2 / R1) Vout ~= 3.3 The real output voltage, for R1 = 330Ω and R2 = 560Ω is Vout ~= 3.37V, so the maximum ±5% error is within specifications. C1 is a ceramic capacitor with a value of 0.1µF ( 100nF), being used to filter high frequency spikes and to prevent internal oscillation for the LM317T IC. C2 is an electrolytic capacitor with a value of 1µF (higher values, up to about 1000µF can be used), and its purpose is to smooth the output voltage (3.3V line). The designed voltage of C2 must be higher than 3.3V, and it is very important to mount the capacitor with the correct polarity. Electrolytic capacitors are very prone to small explosions if missused, such as mounting them in reverse polarity or use them with voltages over their specification. R1 = 330Ω R2 = 560Ω Vout ~= 3.37V C1 0.1µF 100nF LM317T C2 1µF 1000µF 3.3V Note: instead of the fixed value R2 resistor, a 1KΩ potentiometer can be used. In this case, a more precise output voltage is obtained if (and when) really needed. This way you can also use a lower value for R1, and a good choice is 240Ω, as recommended in the LM317 datasheet. Arduino Pro Mini board is powered by a 5V power supply, so it allows to use 5V on the UART RX and TX communication lines. ESP8266 Wifi module on the other hand uses 3.3V power supply, and it is not 5V tolerant for the VCC, RX, TX or any of its other available I/O lines. Therefore a direct connection between the RX/TX lines of the Arduino board and the RX/TX lines of the ESP8266 module is not possible, and ignoring this warning may very likely result in damaging the ESP8266 module. A simple solution for this case is to use a readily available logic converter module. Its provides 3.3V lines (some also allows 1.8V, 2.5V and 2.8V) as well as 5V communication lines. Notice that such a module can provide very low current (in the range of a few mA) on each of the lines, therefore it must be used only for data communication and not as a voltage regulator. We use a four channel module, so it provides four low voltage (3.3V) lines with four corresponding high voltage (5V) lines. Two lines are used for UART communication and the other two are used for connecting the CH_PD and RESET lines of the ESP8266 module with the pin 2 and respectively 3 of the Arduino board. It is important to notice that the RX/TX line of the Arduino Pro Mini board have to be cross-connected with the RX/TX lines of the ESP8266 module. This means: the RX line of the Arduino board connects to the TX line of the ESP8266 module and the TX line of the Arduino board connects to the RX line of the ESP8266 module. These connection is made via the logic level converter module as already explained above and also shown in Figure 1 and Figure 2. The CH_PD (channel power down) and RESET pins of the ESP8266 module needs to be connected to VCC (+3.3V) line via 3.3KΩ resistors. Normally, a 10KΩ resistor can be used, but we observed periodical resets of our WiFi module (we tested a few of them). Using test and trial method, we found that the 3.3KΩ resistor works the best for all our ESP8266 modules. Note: the ESP8266-01 module is shown in the schematic, since this was available as Fritzing component, but actually in the real board we use an ESP8266-02 module. This should make no difference, and and in general we should be able to use any version of these modules. There are about thirteen versions of ESP8266 modules, which differes in form, size and available I/O, but all have the same WiFi functionality. The DHT22 sensor allows to obtain temperature readings in the range [-40, 80]°C with a typical accuracy of ±0.5°C and a resolutin of 0.1 units (°C). However, in real tests, the accuracy we could observe is closer to ±1°C. The sensor can also read humidity values in the range [0, 100]%, with a typical accuracy of ±2 units (%) and a resolution of 0.1 units. In our real tests, the accuracy was about ±5%. [-40, 80]°C ±0.5°C 0.1 units (°C) ±1°C [0, 100]% ±2 units (%) 0.1 units The DHT22 sensor can be connected to either 3.3V line or to 5V line, and we decided to use the 5V line. The data pin of the sensor (check the datasheet for more details) is connected to 5V rail via one 10KΩ resistor, to avoid communication errors (this line must stay HIGH when the sensor does not communicate via the data pin). The sensor data pin is connected to digital pin 9 of the Arduino board. During the tests, we found that it is good to know the actual state of the ESP8266 module, specially because the module becomes unresponsive sometimes. We have used a DUO red/green LED, which is actually composed of one green and one red LEDs in a single physical package, and which share a common cathode (GND) connection. The green LED anode was connected to pin 8 of the Arduino Pro Mini board via a 560Ω resistor, thus allowing about 5mA current passing through the LED. The red LED anode was connected to pin 7 of the Arduino Pro Mini board via a 560Ω resistor, thus allowing about 6mA current passing through the LED. A LED should never be directly connected between the VCC and GND lines (or directly to I/O pins of an MCU) with the exception of special LEDs which are designed for this, on which case they have a builtin resistor or use other current limiting design. Instead one must use a series resistor to limit the current passing through the LED. Using Ohm's Law we can compute the value of the resistor by knowing the LED forward voltage (the voltage to which the LED starts conducting and emmiting light), the used supply voltage and the current we want to allow passing through the LED (which controls the LED brightness). A standard red LED has about 1.7V forward voltage, a green or orange LED has about 2V forward voltage, a white or blue led has about 2.7V forward voltage. Since we only need the LEDs to provide visual indication, they don't have to lighting very bright. After testing our DUO LED, we decided that a value of 6mA is desired for the red LED and a value of 5mA for the green LED (green light is more visible for human eye than other colors). Applying Ohm's Law, we have V = IR, so R = V / I. For our case, V is the difference between the power supply voltage (+5V) and the LED forward voltage. Solving the equation for the red LED we have R = (5 - 1.7) / 0.006, which give us R = 550Ω. Since 550Ω is not a standard value, the next available standard resistor value can be used, that being 560Ω. As homework, you can do the computations for the green LED. V = IR R = V / I R = (5 - 1.7) / 0.006 R = 550Ω Note: if you don't have a DUO LED, just use two normal LEDs. Also, you can use other LED colors if you like, and even different resistor values to obtain different brightness levels (use Ohm's Law to find the appropriate resistor value). A standard 3mm or 5mm LED usually stands up to 20mA of current, after this point it gets too warm and it is very likely that it gets burned. However some LEDs can stand much more current, but they need special drivers. Also, notice that you should not draw more than 20mA from each of the Arduino pins, or you may damage the board. The Arduino code can be written, compiled and deployed to the Arduino board by either using Fritzing or the Arduino IDE (this may be preferred in some cases, because it usually works out of the box). For our project, the following Arduino libraries are needed: An Arduino program (also known as sketch) has the following minimal structure: // 1. constants definition (optional if no constant is needed) // 2. include headers for used libraries ( optional if no library is used) // 3. define the global variables (optional if no global variable is required) // program initialization void setup() { // write here the setup code. } // infinite loop cycle void loop() { // the code from this method loops as long as the Arduino board is powered. } In the setup method we write initialization code, which is executed only once, when the Arduino is powered or after a software or hardware reset. The loop method contains the code which loops in the Arduino MCU as long as the board receives power. setup loop First we define the constants representing the used Arduino board pins. It is highly recommended to use constants instead of using the pin numbers all over the code. This way, one can easily change the constant value instead of trying to find all the places where the pin number was used, if you decide that another pin has to be used. // Arduino pin number used for the communication with DHT22 sensor. #define DHT22_PIN 9 // pins number for WiFi disabled LED #define WIFI_DISABLED_LED_PIN 7 // pins number for WiFi enabled/active LED #define WIFI_ACTIVE_LED_PIN 8 // arduino pin used to connect to the CH_PD (Power Down) WiFi module pin #define WIFI_CH_PD_PIN 2 // arduino pin used to connect to the RESET WiFi module pin #define WIFI_RESET_PIN 3 Pin 9 is used for data communication with the DHT22 sensor, pins 7 and 8 are used for the red and green LEDs (WiFi status LEDs), pin 2 allows to put the WiFi into a sleep mode (and to wake it up) and pin 3 allows us perform a hardware reset of the WiFi module, which requires to pull it down (set pin to LOW) for at least 200ms. We need to specify the libraries used by our program. This is done in the standard C/C++ style by using the #include directive: #include #include <dht.h> #include <ESP8266.h> When using this directive, <> tells to the compiler and linker to look in the libraries subfolder of the Arduino IDE installation, while using double quotes means the library files are in the your arduino skecth folder. <> As in many (if not all) Arduino programs, we use some global variables: // DHT22 sensor controller class dht dht22; // ESP8266 WiFi module controller ESP8266 esp( Serial); // store the average temperature and humidity // values, starting with last system reset float avgTemperature = 0; float avgHumidity = 0; // utility variable used to compute the averate temperature value unsigned long avgDhtStep = 1; // data template for sensors const char SENSORS_DATA_TEMPLATE[] PROGMEM = "{\"temperature\": %s, \"avgTemperature\": %s, \"humidity\": %s, \"avgHumidity\": %s, \"voltage\": %s, \"freeRam\": %d}"; The dht22 variable represents an instance of the library which controls the communication with the DHT22 sensor. The esp variable represents an instance of the ESP8266 library used to communicate with the WiFi module. As parameter for the constructor we provide the Serial object, so the communication is made on the UART0 port of the Arduino board. When using Arduino Pro Mini (also Nano or UNO) board, this is the only serial port available. However, the library is designed to work with all the Arduino boards, and some of them have up to four UART ports, accessed via Serial, Serial1, Serial2 and Serial3 global objects. dht22 esp Serial Serial1 Serial2 Serial3 Since we like to know the average temperature and humidity values measured by our Weather Station, we define the avgTemperature, avgHumidity and avgDhtStep variables. The first two are used to store the average temperature and humidity values, while the latter is used to count how many time the temperature value was read, so the correct average value can be computed according with the formula: avg = (avg * (n - 1) + newValue) / n; avgTemperature avgHumidity avgDhtStep avg = (avg * (n - 1) + newValue) / n The SENSORS_DATA_TEMPLATE variable stores the template (JSON structure) used to communicate with the Android application. The special PROGMEM variable modifier enforces the storage of the value in the flash memory instead of RAM, thus freeing up about 120Bytes of RAM (about 6% of the total RAM of the ATmega328P MCU, used by the Arduino Pro Mini, Nano and UNO boards). SENSORS_DATA_TEMPLATE PROGMEM The ESP8266 module communicates with the Arduino MCU via the UART protocol. A hardware reset for the WiFi module is recommended to ensure a correct module state before starting the UART communication. void setupWiFi() { // STEP 1: // Set pins used for WiFi status LEDs as OUTPUT. pinMode( WIFI_ACTIVE_LED_PIN, OUTPUT); pinMode( WIFI_DISABLED_LED_PIN, OUTPUT); // STEP 2: // Arduino pin connected to ESP8266 CH_PD pin is set to OUTPUT. // To keep the module active, this pin must be kept HIGH. pinMode( WIFI_CH_PD_PIN, OUTPUT); digitalWrite( WIFI_CH_PD_PIN, HIGH); // Arduino pin connected to ESP8266 RESET pin is set to OUTPUT. // To avoid random resents, we keep this HIGH. pinMode( WIFI_RESET_PIN, OUTPUT); digitalWrite( WIFI_RESET_PIN, HIGH); // STEP 3: // perform a hardware reset (ESP8266 RESET pin goes LOW) digitalWrite( WIFI_RESET_PIN, LOW); delay( 200); // allow ESP8266 module to boot digitalWrite( WIFI_RESET_PIN, HIGH); // STEP 4: // baud 115200, communication with ESP8266 module Serial.begin( 115200); // STEP 5: // wait for the ESP8266 module to start, after the forced hardware reset. // We check the wifi state once a second, until the ESP8266 WiFi module responds. while( !checkWiFi()) { delay( 1000); }; // STEP 6: // start UDP connection - wait on all ports esp.atCipstartUdp(); } The WiFi module related initialization requires the following steps: WIFI_ACTIVE_LED_PIN WIFI_DISABLED_LED_PIN WIFI_CH_PD_PIN WIFI_RESET_PIN constants UDP communication is used for the WiFi data transmission between the Android device and our Weather Station sensor node. The checkWiFi method used to check if the WiFi module is in active state (communicates via UART lines) is shown below: checkWiFi boolean checkWiFi() { if( esp.at() == ESP8266::Error::NONE) { digitalWrite( WIFI_DISABLED_LED_PIN, LOW); digitalWrite( WIFI_ACTIVE_LED_PIN, HIGH); return true; } else { digitalWrite( WIFI_ACTIVE_LED_PIN, LOW); digitalWrite( WIFI_DISABLED_LED_PIN, HIGH); return false; } } This method returns true if the ESP8266 module responds to AT command, and false otherwise. The AT command is used to check if the module is active, and it does not represents a real command for the module. In addition, the checkWiFi method enables (or disables) the red/green LED, providing visual indication of the current WiFi state. true AT false Since the WiFi setup must run only once, when the hardware powers up, we call the setupWiFi module inside the Arduino specific setup method: setupWiFi void setup() { // setup WiFi - ESP8266 module setupWiFi(); // add other code here... } The DHT22 sensor provides temperature and humidity values for our sensor node. It has a refresh rate of 0.5Hz, meaning that we can't read data from this sensor faster than once every two seconds. Reading data is fairly easy, because of all the hard code is hidden by the DHTLib library. We write a method to obtain these values and compute the temperature and humidity averaged values. void updateDHTData() { if ( dht22.read22( DHT22_PIN) == DHTLIB_OK) { avgTemperature = ( avgTemperature * (avgDhtStep - 1) + dht22.temperature) / (float)avgDhtStep; avgHumidity = ( avgHumidity * (avgDhtStep - 1) + dht22.humidity) / (float)avgDhtStep; } } The latest temperature and humidity values are available by reading the temperature and humidity properties of the dht22 object. The read22 method is used to perform a reading when DHT22 sensor is used, but instead, one can use read11 to get the same effect when the DHT11 sensor is used. The method returns DHTLIB_OK when the reading was successful, and various error codes if problems were encountered. For simplicity reasons, we ignore the possible errors, but in a further tutorial we discuss also how to solve such possible problems. temperature humidity read22 read11 DHTLIB_OK Some ATmega MCUs, such as ATmega328/168(p) have a builtin voltage sensor, which can be accessed by the code. This sensor is not very accurate (accuracy is within ±10% range). It uses the builtin 1.1V voltage reference available for these MCUs (some other ATmega MCUs also have a 2.56V internal voltage reference). The following code allows to read the AVcc line voltage, which by default is connected to VCC line of the Arduino board: float getVcc() { long result; // read 1.1V reference against AVcc ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1); // wait for Vref to settle delay(2); // convert ADCSRA |= _BV(ADSC); while (bit_is_set(ADCSRA,ADSC)); result = ADCL; result |= ADCH<<8; // Back-calculate AVcc in mV result = 1103700L / result; // return response in volts return result / 1000.0; } While this looks complicated, it actually uses a few MCU registers and some bits operations to read the VCC value agains the builtin 1.1V voltage reference, which has a pretty good stability once calibrated. By using a good quality multimeter and a stable voltage source, it is possible to "software calibrate" the internal voltage reference for individual MCUs when needed. Note: a complete guide related to RAM usage optimization for Arduino MCUs as well as details on how to get the free amount of RAM are described on our blog article Optimize Arduino Memory Usage One last piece of data we like to collect is the amount of free RAM available on our Arduino MCU. This can be achieved by calling the getFreeMCUMemory method, available as part of the ESP8266 library. It returns an integer representing the number of RAM bytes which are not used by the MCU at the moment of calling the method. getFreeMCUMemory All the sensor data we collect needs to be sent to the Android device. The first step in this direction is to listen for data requests from the Android device (periodical data requests are initiated). For this we use the loop method and wait for incomming data: void loop() { char data[10] = {0}, *ipdData = data; // Incomming data from ESP8266 module // Lengt must be greater than 7 bytes ("+IPD,n:") if ( Serial.available() > 7 && esp.ipd( ipdData) == ESP8266::Error::NONE) { // process the request processRequest( ipdData); } // a small delay before checking againd for WiFi incomming data delay( 25); } The ipd method, part of the ESP8266 library is used to split the received data over WiFi, and retain only the important parts. The WiFi module sends data in the following format: +IPD,n,id:ipdData, where n is the length of the ipdData, id is the communication link ID (an integer between 0 and 4), and ipdData represents the relevant data bytes. The first parameter of the ipd method is a reference parameter, a pointer to the received databytes. This method has additional optional parameters, providing information about the number of databytes and the connection id. Further, a method named processRequest is used to decode the data and perform required actions. ipd +IPD,n,id:ipdData n length ipdData id processRequest Since we expect data in the +IPD,n: format, (the link id is not used), it makes sense to process data only after receiving at least 7 bytes. In addition, for this simple project, we expect only a single databyte, representing the data update request. In a further version of this project we like to support much more commands, therefore we use this generic form. Also, for the same reasons, we define an enumeration which defines the list of the available commands: +IPD,n: enum class Command { GET_ALL_SENSORS_DATA = 97 }; The data we receive via TX line of the ESP8266 module (so RX line of our Arduino board) is: +IPD,1:a. The ascii representation for 97 (the Command::GET_ALL_SENSORS_DATA enumeration literal) is the char a. +IPD,1:a Command::GET_ALL_SENSORS_DATA a The processRequest method code is shown below: void processRequest( char *data) { char progmemData[150] = {0}; char *pData = progmemData; // first char represents the command char cmd = *(data); switch ( (Command)cmd) { case Command::GET_ALL_SENSORS_DATA: createSensorsDataFromTemplate( pData); esp.atCipsend( pData); break; default: // nothing to do ... break; } } Its main purpose is to decode the received command and to respond with the required data. As discussed earlier, we only have one command, so also only one action case, but this will be extended, so we use the general structure even for this simplest case. The relevant code regards the call to createSensorsDataFromTemplate method. It uses the JSON based data template, replaces the placeholders with real data and send the response to the Android device by calling atCipsend method, part of the ESP8266 library. createSensorsDataFromTemplate atCipsend void createSensorsDataFromTemplate( char *&data) { char buffTemp[7] = {0}, buffAvgTemp[7] = {0}, buffAvgHum[7] = {0}, buffHum[7] = {0}, buffVcc[5] = {0}, tmpl[140] = {0}; char *pTmpl = tmpl; uint8_t templateLen = -1; // read template from PROGMEM getPMData( SENSORS_DATA_TEMPLATE, pTmpl, templateLen); // create data string from template by replacing // parameters with their actual values from sensors sprintf( data, pTmpl, dtostrf( dht22.temperature, 6, 1, buffTemp), dtostrf( avgTemperature, 6, 1, buffAvgTemp), dtostrf( dht22.humidity, 6, 1, buffHum), dtostrf( avgHumidity, 6, 1, buffAvgHum), dtostrf( getVcc(), 4, 2, buffVcc), getFreeMCUMemory()); } Using the getPMData utility method (also part of the ESP8266 library), the data template string is read from the flash memory. Replacing the parameters with real values is made by using the standard sprintf method. While for a fully fledged C/C++ environment one will use %x.yf syntax with sprintf for floating points numbers, this will not work with Arduino code. Instead we use dtostrf to format the temperature and humidity values (we like values with just one digit after the decimal point). getPMData sprintf %x.yf dtostrf Important: the latest version of the Android software (v1.6.6+) is required for being able to compile and build the code for this project. One reason is that it uses C++11 specific constructs, such as enum class, and the older Arduino Software versions does not support C++11. While it can be done also with older Arduino Software version, this requires to alter some configuration files, so it may create additional issues. enum class We need to chose the right Arduino board by using the Tools > Board selection list (within the Arduino IDE). If Arduino Pro Mini board was used, as discussed in this tutorial, we have to choose Arduino Pro or Pro Mini. In addition, one needs to select the communication port (COM port) used for programming the Arduino board, available under Tools > Port menu. Last, click on the arrow button located in the top-left corner to start the compile-and-deploy process. Note: The Arduino Pro Mini board does not have a builtin auto-reset feature, as found in Arduino Nano, UNO, MEGA2560, and other boards. This means we need to manually push the reset button on the board as soon as the Arduion IDE says uploading. It may take a few trials to get used with the right moment to push the button, but it must be shortly after the IDE says uploading. In addition, you have to disconnect the ESP8266 TX line during the Arduino programming time, otherwise this operation fails. Since we have to do this on every code update, a jumper or a switch can be used to make task easier. An Android application is used to observe the Weather Station sensor node data. For the development of our Android application, IntelliJ IDEA Ultimate was used. A free community version of this IDE is also available and can be used for our project. As an alternative, one cau use Android Studion. The first thing you need to do after creating an empty Android application by using your preferred IDE, is to edit the application security settings. These can be found in the AndroidManifest.xml file Since we need to use WiFi communication, the following two parameters need to be added: AndroidManifest.xml <uses-permission android: <uses-permission android: In addition, we like to disable the auto-lock feature of the Android device, as long as this application is active, which requires to set the following permission: <uses-permission android: The same AndroidManifest.xml file defines the Android OS version required to run this application. We have tested this application with Android 4.3.1 (API 18) and 4.4.2 (API 19) and 5.0.1 (API 21). Therefore it is safe to set the miminum require version to API 18 by using the following parameter: <uses-sdk android: While this application may run on Android OS older than 4.3.1 (API 18), our tests with Android 2.3.3 (API 10) failed. Creating the Android application user interface can be done by using the UI editor, or, if you are already familiar with Android, directly editing the layout file. In our case this file is named main.xml and it is located under res/layout folder. main.xml res/layout We use a ScrollView container as the user interface parent, to support also small screen devices, with lower physical resolutions. As layout template, we use TableLayout, with two columns: label and value plus measurement unit. ScrollView TableLayout <ScrollView xmlns:android="" android:layout_width="fill_parent" android:layout_height="fill_parent" android: <TableLayout xmlns:android="" android:layout_width="fill_parent" android:layout_height="fill_parent" android: <TableRow android:layout_width="fill_parent" android: <!-- table row content --> </TableRow> <!-- more table rows... --> </TableLayout> </ScrollView> For example, the row used to show the current temperature value is shown below: <TableRow android:layout_width="fill_parent" android: <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceMedium" android:text=" Temperature: " android: <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceMedium" android:text="N/A°C" android: </TableRow> Each UI element has an android:id attribute, with an unique value, used to access the UI element from the Android Java code. The result user interface is shown in Figure 5. android:id We use an Android activity to implement our class. This is the simplest way to create an Android application, specially this is your first Android application. public class MainActivity extends Activity { // ...here come all the properties and methods... } For the UDP communication with the Weather Station sensor node we use Java DatagramSocket, and initialize it for port 1024 (other ports, starting with 1025, can be used as well). This code should execute before trying to send any UDP packet over the network. In this scenario, we request sensor data from the Weather Station node, once every 10 seconds. Feel free to modify it to another value if you like: DatagramSocket public class MainActivity extends Activity { int udpPort = 1025; DatagramSocket socket; // other properties.... @Override public void onCreate( Bundle savedInstanceState) { // here are some other initializations (new Thread(new Runnable() { @Override public void run() { try { socket = new DatagramSocket(udpPort); while (true) { if (appInBackground) continue; try { sendUdpData( Commands.GET_ALL_SENSORS_DATA, null); Thread.sleep( 10000); } catch (Exception e) { e.printStackTrace(); } } } catch (Exception e) { e.printStackTrace(); } } })).start(); } } An anonymous Java thread is used to request periodical data updates. The 10 seconds delay is obtained by using the Thread.sleep static method, and the data update request is performed by the sendUdpData method. Thread.sleep sendUdpData void sendUdpData( Commands cmd, byte[] params) { try { final DatagramPacket packet; int paramsLength = ( params != null ? params.length : 0); byte data[] = new byte[paramsLength + 1]; byte command[] = new byte[1]; command[0] = cmd.getValue(); System.arraycopy( command, 0, data, 0, command.length); if ( params != null) System.arraycopy(params, 0, data, 1, params.length); packet = new DatagramPacket( data, data.length, getBroadcastAddress(), udpPort); socket.send( packet); } catch( IOException e){ e.printStackTrace(); } } The sendUdpData method takes two parameters: the command to send and its optional parameters. Remember, for the Arduino code, an enumeration was used to define all the available commands (well, just one command for now, but this will change later). Now, the same applies for the Android application: using a Java enumeration, we define the GET_ALL_SENSORS_DATA command with the same command code, 97 (this is what the Arduino application expects). GET_ALL_SENSORS_DATA 97 enum Commands { GET_ALL_SENSORS_DATA ( (byte)97); private final byte id; Commands( byte id) { this.id = id; } public byte getValue() { return id; } } Further, a DatagramPacket is created, and the command (and when is the case, the command parameters too) is provided as an array of bytes (as required by the DatagramPacket constructor). The UDP packet is then sent to the Weather Station sensor node. In response, the sensor node provides a JSON object containing the sensor data required to update the user interface. Since the UDP communication is asynchronous (we don't know how long it takes for the request to reach the sensor node and how long it takes until a response is received), a thread is used to continuously listen for incoming UDP packets. DatagramPacket public void onCreate( Bundle savedInstanceState) { (new Thread(new Runnable() { @Override public void run() { while (true) { DatagramPacket udpPacket = receiveUdpData( udpPort); if (udpPacket == null) continue; String udpPacketData = new String( udpPacket.getData()); try { JSONObject jsonObj = new JSONObject(udpPacketData); updateUserInterface( jsonObj); } catch ( JSONException e) { e.printStackTrace(); } } } })).start(); } DatagramPacket receiveUdpData( int port) { try { byte[] data = new byte[1024]; DatagramPacket packet = new DatagramPacket( data, data.length); if ( socket == null) return null; socket.receive(packet); return packet; } catch( IOException e){ e.printStackTrace(); return null; } } The received UDP data (stream of bytes) is converted to a JSON object and passed to updateUserInterface method which is responsible to extract the sensor values and show them in the user interface. We show only the code which deals with the temperature value, but the same applies also for humidity, voltage, and the other values (see the full source code). updateUserInterface void updateUserInterface( final JSONObject jsonObj) { try { final double temperature = jsonObj.getDouble("temperature"); temperatureValueTextView.post(new Runnable() { public void run() { temperatureValueTextView.setText(String.valueOf(temperature) + "°C"); } }); } catch (JSONException e) { e.printStackTrace(); } } Due to Android API restrictions, a UI component object can be modified only by the thread who created it. In our case, main application thread is the one which creates the GUI component objects, while the updateUserInterface is invoked by the thread which listen for UDP data. In such case, the post method can be used, thus being able to update the sensor values in the user interface components. Getting reference to the user interface components is made by using the corresponding implementation class (e.g. TextView) and invoking the findViewById method, as shown below. TextView findViewById public class MainActivity extends Activity { // some other properties... TextView sensorsDataReceivedTimeTextView; public void onCreate( Bundle savedInstanceState) { sensorsDataReceivedTimeTextView = (TextView) findViewById(R.id.sensorsDataReceivedTimeTextView); } // some other methods... } One special requirement in our application is to provide a "disable auto-sleep feature" for the Android device, as long as the application runs. This means, the device screen stays on as long as the application is active. To obtain this behavior, we use the addFlags method of the window object (inherited from the Activity super class), and provide the corresponding parameter. In our case, these parameters are defined as literalos of the WindowManager.LayoutParams enumeration. addFlags window Activity WindowManager.LayoutParams window.addFlags( WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON); window.addFlags( WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); Remember, this requires to enable the android.permission.WAKE_LOCK permission, by editing the AndroidManifest.xml file as shows earlier on this tutorial. android.permission.WAKE_LOCK We can extend our project by considering the following improvements: Stay tuned! All these improvements are discussed in our further tutorials. This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL) AT+CWSAP? +CWSAP:"WeatherStation","LetsNurture",5,3 AT+CIPSEND=127 {"temperature": 768.0, "avgTemperature": 0.0, "humidity": 768.0, "avgHumidity": 0.0, "voltage": 4.78, "freeRam": 1379} General News Suggestion Question Bug Answer Joke Praise Rant Admin Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
https://www.codeproject.com/Articles/1079298/Arduino-WiFi-Connected-Weather-Station-with-Androi?fid=1900518&df=90&mpp=25&prof=True&sort=Position&view=Normal&spc=Relaxed&fr=26
CC-MAIN-2019-09
refinedweb
5,863
53.21
We have a user control that has jQuery tabs and editable text regions. After we upgraded to 8.1 the tabs stopped working when logged in to Administration. When logged out and viewing the site as a user would everything works fine. I followed the instructions here about using a different jQuery library with Kentico but nothing I have tried seems to work. Any ideas? Ok think managed to get this resolved. I removed the link to bootstrap.min.js as an explicit link from the head section of the master template and added it through a jQuery web part to the master page and that seemed to do the trick. This post was very helpful. Hello Mark, Could you please have a look to your browser JavaScript console if there are any errors? Best regards, Hi Ladislav, In the console there is: jQuery is not a function from jquery-core.js and t is undefined from require.js Hi Mark, Did you try to switch these two lines mentioned in the article from Roman?); Also what namespace are you using for your custom jQuery? Best regards, Martin Hi Martin, I did make that change in the jquery-core.js file. As far as the namespace goes I didn't write any functions for the tabs - its referencing the Bootstrap 3 library with jQuery 1.10.2 it would be great if you can contact us directly via e-mail: support@kentico.com and send us the exact code examples you are using so we can try to reproduce this behavior. Or maybe even if you can provide us with a temporary access to your website where we can inspect this directly. Please, sign in to be able to submit a new answer.
https://devnet.kentico.com/questions/jquery-tabs-in-administration-in-8-1
CC-MAIN-2018-34
refinedweb
293
82.65
Average: 77.1 Specifying Procedures1. (8.7 average out of 10) Muddle B. Fuddle wants to add a deleteName method to the StringTable class from Problem Set 3 ():Muddle is planning to use a Vector of String, value record pairs to represent his StringTable. He suggests this specification:Muddle is planning to use a Vector of String, value record pairs to represent his StringTable. He suggests this specification:public class StringTable { // overview: StringTable is a set of <String, double> entries, // where the String values are unique keys. A typical StringTable // is {<s0: d0>, <s1: d1>, ... }. // ... }public boolean deleteName (String name) // REQUIRES: The parameter name is not null. // EFFECTS: Goes through the entries in the elements Vector, and removes // the one whose key matches name.Identify at least three important problems with Muddle's specification and explain why each problem is bad. There are dozens of problems with Muddle's specification! The most important are:2. (7.7 / 10) Write a good specification for the deleteName method. - It is written in terms of the concrete representation, not the abstract type. Specifications should not be tied to particular implementations. - It is written in an operational (how) way ("goes through"). Specifications should be declarative (explain what it does, not how). - It is missing a modifies clause. Based on its name and effects clause, it should modify the this object. - Its postcondition does not explain what happens in all situations: what if the name is not in this? what is it is in the elements Vector more than once? (Of course, if the specification were written in terms of the abstraction, this wouldn't be a problem.) - The method header has a boolean return type, but the effects clause does not explain what this type means. public boolean deleteName (String name) // REQUIRES: The parameter name is not null. // MODIFIES: this // EFFECTS: If name matches a key in this, removes the entry // associated with that key and returns false. Otherwise, // does not modify this and returns true.We could also describe its behavior using our abstraction notation:e.g., If this_pre = { <s0: d0>, <s1: d1>} and s0 equals name, result == true and this_post == { <s1: d1>}. If name does not equal s0 or s1, then result == true and this_post == this_pre. Data Abstractions3. (8 / 10 (this was listed as being 7 points on the exam, but I graded it out of 10) As specified above, is WDGraph likely to be a useful abstraction? If so, explain briefly an application that could use it. If not, explain what methods must be changed or added to make it useful. The most obvious problem is there is no method to get the weight associated with an edge. Without this, the abstraction isn't adequate — we would be better using a normal Graph without edge weights. So, we should add a method getEdgeWeight:4. (7.8 / 10 (listed as 8, but graded out of 10) As specified, WDGraph is a mutable type. Explain what changes would be necessary to make WDGraph an immutable type instead, and identify at least one good reason why we might prefer the immutable version.public int getEdgeWeight (String fnmode, String tnode) throws NoNodeException // EFFECTS: If fnode or tnode is not the name of a node in // this.nodes, throws NoNodeException. Otherwise, if // there is an edge from fnode to tnode in the graph, // returns the weight of that edge. If there is no // edge, returns 0.Note that this.nodes in our specification means the abstract nodes set used in the overview, not anything to do with our rep (which happens to use nodes also). Perhaps, our specification should throw an exception if the node does not exist instead of returning 0. To be useful, the abstraction should have some more observers: getNeighbors (returns an iterator that yields the neighbors of a node), and perhaps nodes (returns an iterator that yields all the nodes in the graph). For some purposes, it would be more useful to be able to have zero-weight edges (but there are plenty of applications that can use the abstraction with this restriction). To be immutable, the type must not provide any mutators. So, we would need to remove the addNode and addEdge methods. If we just removed them, we would have an immutable datatype, but it wouldn't be useful. All we could do is create an empty graph and call the observers on it. So, we need to either:5. (10.1 / 15) Suppose we decide to implement WDGraph using this rep: - Provide a constructor that can create a particular graph (for example, by reading it from a file). - Or, provide producer versions of the addNode and addEdge methods. Instead of modifying the this object, these methods would create and return a new graph (with the additional node or edge). Possible advantages of making WDGraph immutable are that it makes it easier to reason about code (we don't need to worry about aliasing). A disadvantage is that implementing addNode and addEdge as producers instead of mutators will make them more complicated and require extra storage (creating all those new graphs) and computation (copying).// Rep: String nodes[]; int edges[][]; // Abstraction Function: // AF (c) = < nodes, edges > where // nodes = { c.nodes[i] | 0 < i <= c.nodes.length } // edges = { < c.nodes[fi], c.nodes[ti], c.edges[fi][ti] > | // 0 < fi <= c.nodes.length, // 0 < ti <= c.nodes.length // where c.edges[fi][ti] != 0 // // For example, the representation below would represent the flight // graph described in the overview: // // c.nodes = [ "Charlottesville", "Dulles", "Richmond" ] // c.edges = [ [ 0, 119, 89], // [ 139, 0, 0 ], // [ 0, 79, 0 ] // The hasEdge method is implemented as:private int lookupNode (String node) throws NoNodeException // EFFECTS: If node is a node in this.nodes, returns the // index such that this.nodes[result].equals (node). // Otherwise, throws NoNodeException. // (Note that lookupNode is a private method. Hence, it is okay that we // have specified it using the concrete representation instead of in // terms of the abstraction.) public boolean hasEdge (String fnode, String tnode) throws NoNodeException { return (edges[lookupNode (fnode)][lookupNode (tnode)] != 0); }What rep invariant would be necessary to make this implementation correct? The best way to think about this is to look at the code for hasEdge and determine what needs to be true for it to work:return (edges[lookupNode (fnode)][lookupNode (tnode)] != 0);We are indexing the edges array, so it must not be null://@invariant edges != nullWe are calling lookupNode. It has no require clause, though, so nothing has to be true for this to be okay. We are indexing edges[lookupNode (fnode)]. For this to be in bounds, we need to know that the result of lookupNode (fnode) is between 0 and the length of edges - 1. The effects clause for lookupNode tells us that its result is a valid index of the nodes array, hence it is between 0 and nodes.length - 1. From this, we can infer that the edges array must have at least as many elements as the nodes array://@invariant edges.length >= nodes.lengthNext, we index in the second array: edges[lookupNode (fnode)][lookupNode (tnode)]. So, edges[lookupNode (fnode)] must not be null. Further, the length of each edges[i] array must be >= nodes.length:// invariant forall 0 <= i < nodes.length // edges[i] != null // edges[i].length >= nodes.lengthThat's all we can definitively say about the rep invariant from just looking at what is necessary for hasEdge. It is likely that lookupNode will require the nodes array contain no duplicates. Testing6. (8.4 / 10) What would be a reasonable set of black box test cases to the addNode method? The important thing to remember about black box test cases is that they are based on the specification, not a particular implementation. We should test all paths through the specification of addNode:// EFFECTS: If node is the name of a node in this.nodes, // throws the DuplicateNode exception. Otherwise, // adds a node named name to this: // this_post = < this_pre.nodes U { node }, this_pre.edges >There are two obvious paths: Reasonable test cases would be:Reasonable test cases would be: - The node already exists in the graph. - The node does not already exist in the graph.WDGraph g = new WDGraph (); g.addNode ("Charlottesville"); g.addNode ("Dulles"); g.addNode ("Dulles"); // should throw DuplicateNodeExceptionWe should also test boundary or special cases: the node is null, and the graph is empty. 7. (6.9 / 10) Suppose we implement addNode as below. What additional glass box test cases (if any) are necessary?public void addNode (String node) throws DuplicateNodeException { try { lookupNode (node); throw new DuplicateNodeException (node); } catch (NoNodeException e) { String [] oldnodes = nodes; nodes = new String [oldnodes.length + 1]; for (int i = 0; i < oldnodes.length; i++) { nodes[i] = oldnodes[i]; } nodes[oldnodes.length] = node; } }The glass box test cases should excercise paths through the implmentation. One path is when lookupNode does not throw a NoNodeException. Our black box test cases already cover this when we add a duplicate node. Another path is when lookupNode throws an exception and we execute the catch block. This block has essentially infinitely many paths through the loop — we can't test them all, but we should test it for 0, 1 and several iterations. The first addNode black box test cases tests it for 0, the second tests it for 1. We need some additional tests to test it for several:8. (4.7 / 10) What is the serious flaw with our addNode implementation?WDGraph g = new WDGraph (); g.addNode ("Charlottesville"); g.addNode ("Dulles"); g.addNode ("Richmond"); g.addNode ("Reagan"); The really serious flaw is that it does not preserve the rep invariant. Among other things, our rep invariant requires: edges.length >= nodes.length. The implementation of addNode increases nodes.length by 1. We need to increase edges.length by 1 also to preserve the rep invariant. This makes sense — addNode should extend each edges array by 1 so that edges involving the new node can be stored. Note that our addNode tests would not reveal this problem. It only becomes apparent when we call a method like hasEdge that depends on the edges array satisfying the rep invariant. Another possible flaw is the code does not address what happens if node is null. The lookupNode specification implies that nodes in the graph cannot be null, but does not have a requires that node is not null. As specified, it would throw the NoNodeException if node is null (but a better lookupNode spec would make this much more clear). Hence, if addNode is passed a null node, it would add it to the array, which would violate the rep invariant. The best solution to this is probably to just add requires node != null to the specification for addNode. Design9. (14.6 / 20) Due to recent budget cuts at the University, SEAS has decided to replace the student advising office with a computer program. The program will take student course selections as input and either approve or disapprove of the course selections based on whether or not the student has satisfied the necessary prerequisites. (Note: the advising office does many other useful things too, of course. The administration is still working on ways to replace those functions with programs.) All courses have a department mnemonic (e.g., "CS") and course number (e.g., 201). (As a further cost saving measure, the administration has decided to eliminate deviant courses that have extra modifiers after the number so you don't need to worry about handling courses with names like "CS201J".) Courses also have a name that purports to describes their content (e.g., "Engineering Software"). The program will use a database with information on courses and their prerequisites. A course may have no prerequisites, or may have multiple prerequisites or alternate prerequisites. For example, the prerequisites for "CS201: Engineering Software" are "either CS101: Intro to Computer Science OR CS200: Computer Science from Ada and Euclid to Quantum Computing and the World Wide Web". The prerequisites for "UBW101: Underwater Basketweaving" are "SCU101: Scuba Diving AND (either ART253: Introduction to Basketweaving OR SPD101: Weaving Webs for Poets)". You've been hired to design the prerequisites checking program. Describe your design using a modular dependency diagram, and a brief description that describes each of the modules in your design. If a module is an abstract data type, write an overview specification of the data type and identify important methods (but you do not need to specify them). Explain a brief strategy for implementing and testing your design. Your answer should clearly identify the data abstractions in your design, but you need not explain how they will be implemented. Your answer to this question should not require more than two pages (but if you really want to say more than that, its better to use more pages than to write really small). Our design uses these abstractions:: - Course — immutable abstract type for representing a course. Includes it name, mnemonic and number, as well as the prerequisites for that course. - CourseSet — a set of courses. - Prerequisites — immutable abstract type for representing prerequisites. Prerequisites can be a single course, an AND of two prerequisites, or an OR of two prerequisites (note these are defined recursively to support nested AND and OR prerequisites). Prerequisites implements a method boolean isSatisfied (CourseSet courses) that returns true iff the courses in the CourseSet satisfy the prerequisites. Our module dependencies are:Our module dependencies are: - StudentDatabase — datatype for interacting with the student database. Provides a method that returns the StudentRecord associated with a student's ID. - StudentRecord — record with information on what courses a student has taken. A good implementation strategy would be to divide the work into:A good implementation strategy would be to divide the work into: You didn't need to provide an implementation, but we could implement Prerequisites like this:You didn't need to provide an implementation, but we could implement Prerequisites like this: - Developing and testing the prerequisites checking module which will be the trickiest part to code and test, but can for the most part be tested using stub classes for everything else (for example, before Course and CourseSet are done, we could test our prerequisites modules using String and StringSet). - Developing and testing the other modules.abstract public class PrerequisitesTerm { abstract public boolean satisfies (CourseSet c); } public class SingleCourseTerm extends PrerequisitesTerm { private /*@non_null@*/ Course c; public SingleCourseTerm (Course c) { this.c = c; } public boolean isSatisfied (CourseSet c) { return c.contains (c); } } public class AndPrerequisite extends PrerequisitesTerm { private /*@non_null@*/ Prerequisites term1; private /*@non_null@*/ Prerequisites term2; public AndPrerequisite (/*@non_null@*/ Prerequisites p, /*@non_null@*/ Prerequisites q) { term1 = p; term2 = q; } public boolean isSatisfied (CourseSet c) { return p.isSatisfied (term1) && q.isSatisfied (term2); } public class OrPrerequisite extends PrerequisitesTerm { private /*@non_null@*/ Prerequisites term1; private /*@non_null@*/ Prerequisites term2; public OrPrerequisite (/*@non_null@*/ Prerequisites p, /*@non_null@*/ Prerequisites q) { term1 = p; term2 = q; } public boolean isSatisfied (CourseSet c) { return p.isSatisfied (term1) || q.isSatisfied (term2); } public class Prerequisites { private PrerequisitesTerm term; public Prerequisites (PrerequisitesTerm term) { this.term = term; } public boolean isSatisfied (CourseSet c) { return term.isSatisfied (c); } }
http://www.cs.virginia.edu/cs201j-fall2002/exams/exam1-comments.html
CC-MAIN-2018-30
refinedweb
2,500
56.86
Odoo Help Odoo is the world's easiest all-in-one management software. It includes hundreds of business apps: CRM | e-Commerce | Accounting | Inventory | PoS | Project management | MRP | etc. Soumaya, You can override the create method of member object and with the creation of each member object, create a new user.. NOTE: tag each user with the member for future references.. (like relation between res_partner and res_users, where res_users is having a many2one to res_partner, same way u can add a many2one field referencing your member object in res_users). and remember to tag the member with the new user created..as class res_users: member_id = fields.Many2one([member_object]) class [member_class] def create(self, vals): res = super([member_class], self).create(vals) # Create your user here and tag res.id(new member created) to it at member_id field. return res Hope it helps! About This Community Odoo Training Center Access to our E-learning platform and experience all Odoo Apps through learning videos, exercises and Quizz.Test it now
https://www.odoo.com/forum/help-1/question/how-to-create-a-user-for-each-member-103350
CC-MAIN-2017-34
refinedweb
166
59.7
Updated: July 2008 Visual Studio includes SQL Server Compact 3.5, a lightweight relational database engine that is often used in device applications. SQL Server Compact 3.5 is the ideal database for device applications because it provides: Lightweight operation (It runs in process and requires only a 2MB installation on the device.) A rich subset of SQL Server query programming features. A rich and consistent subset of SQL Server data types. Support for ADO.NET and OLE DB. Local data storage using an .sdf database file. Data synchronization (using a Microsoft SQL Server database through RDA, Merge Replication, and Microsoft Synchronization Services for ADO.NET). The SQL Server Compact 3.5 database engine provides password protection and encryption to help you secure local databases on devices. It also allows you to configure a variety of connectivity security options. SQL Server Compact 3.5 supports merge replication, remote data access, security planning, and security implementation at the server. When the Smart Device Programmability option is selected, Visual Studio installs SQL Server Compact 3.5 for Devices at drive:\Program Files\Microsoft SQL Server Compact Edition\v3.5\Devices. For more information, see SQL Server Compact 3.5 and Visual Studio. SQL Server Compact 3.5 must also be installed on your device or emulator. For more information, see How to: Install SQL Server Compact 3.5 on a Device. By default, SQL Server Compact 3.5 documentation is not installed locally. To download SQL Server Compact 3.5 Books Online, visit the SQL Server Compact 3.5 Books Online Download Center. You can use Server Explorer/Database Explorer and Visual Database Tools to create and manage SQL Server Compact 3.5 (.sdf) database files in Visual Studio. For information about how to perform specific database tasks, see: How to: Create a Database (Devices) How to: Manage Tables in a Database (Devices) How to: Manage Columns in a Database (Devices) How to: Preview Data in a Database (Devices) How to: Manage Passwords for a Database (Devices) How to: Manage Indexes in a Database (Devices) How to: Shrink and Repair a Database (Devices) The Upgrade to SQL Server Compact 3.5 Database dialog box appears if you connect to a database that was developed by using an earlier version of SQL Server Compact. Visual Database Tools in Visual Studio 2008 does not support databases that were developed by using earlier versions of the SQL Server Compact/Mobile Edition. For information, see Using SQL Server 2005 Compact Edition 3.1 Databases (Devices). The System.Data.SqlServerCe namespace is the .NET Compact Framework data provider for SQL Server Compact 3.5 databases. You can use the methods and classes in this namespace to access data that is stored in SQL Server Compact 3.5 databases. You can manually access data by using the SqlServerCe data provider. Alternatively, you can use the Data Source Configuration Wizard to generate data source code in your project. For documentation on the System.Data.SqlServerCe namespace, see SQL Server Compact 3.5 Books Online. The Data Source Configuration Wizard can be configured to generate data source code that is based on either DataSet or System.Data.SqlServerCe.SqlCeResultSet. You can access the data by accessing the data source objects. You can also bind the data source objects to user interface controls for display. For more information about how to use the Data Source Configuration Wizard, see How to: Add a Database to a Device Project. In general, SqlCeResultSet executes faster and uses less memory than DataSet because it accesses the database directly. However, SqlCeResultSet is not compliant with ADO.NET. For more information, see Resultsets versus Datasets (Devices) and How to: Generate SqlCeResultSet Code (Devices). The Data Source Configuration Wizard in Visual Studio 2008 does not generate code for earlier versions of SQL Server Compact/Mobile Edition. For more information, see usingUsing SQL Server 2005 Compact Edition 3.1 Databases (Devices). Using Visual Studio 2008 Service Pack 1 and Microsoft Synchronization Services for ADO.NET, you can build occasionally connected smart device applications that synchronize data between a remote database and a SQL Server Compact database. Occasionally connected applications access remote data from a local database on the client. Periodically, they synchronize the local data cache with data in the remote database. Therefore, they can function even when a connection to the remote database is unavailable. For more information, see Occasionally Connected Applications (Devices). Visual Studio provides data designer tools that enable you to perform tasks such as dragging SQL Server Compact 3.5 data sources onto the forms designer. For more information, see: Walkthrough: A Master-Detail Application How to: Create Master-Detail Applications (Devices) How to: Generate Summary and Edit Views for Data Applications (Devices) Walkthrough: A Parameterized Query Application How to: Create Parameterized Queries (Devices) How to: Add Navigation Buttons (Devices) How to: Persist Data Changes to the Database (Devices) The data designer tools in Visual Studio 2008 do not support earlier versions of SQL Server Compact/Mobile Edition. For information, see Using SQL Server 2005 Compact Edition 3.1 Databases (Devices). When you deploy or debug a managed smart device project that uses SQL Server Compact 3.5, Visual Studio 2008 automatically deploys and installs the SQL Server Compact 3.5 runtime on the device or emulator if the runtime is not already installed. For more information, see How to: Install SQL Server Compact 3.5 on a Device. Date History Reason July 2008 Added a section about how to use Microsoft Synchronization Services for ADO.NET and SQL Server Compact to create occasionally connected smart device applications. SP1 feature change.
http://msdn.microsoft.com/en-us/library/aa983313.aspx
crawl-002
refinedweb
936
50.63
Blender Blender is a professional free and open-source 3D computer graphics software. Contents - 1 Installation - 2 Additional Features - 3 Blender 2.72b Specific - 4 See also - 5 External resources Installation Installation of recent releases of Blender on Gentoo is rather complicated. This page explains how to solve the most common issues for installation of version 2.78. Blender quickly changes, so these steps may soon become obsolete. Wiki editors will attempt to stay current on build instructions.If something is broken do not hesitate to make changes to the article. USE flags USE flags for media-gfx/blender 3D Creation/Animation/Publishing System There are many additional features that can be enabled via USE flags. See the list above or the Additional Features section below for further details. /etc/portage/make.confAppropriate Global USE flags for Blender # All these global USE flags could be specified locally if desired. # While both ffmpeg and libav currently work, only ffmpeg is officially recommended. # Cycles requires tiff. Add any additional formats required eg. jpeg png... # If audio is required, choose from openal, jack or sdl. USE="ffmpeg X opengl threads tiff openal jack sdl fftw openexr expat" /etc/portage/package.useAppropriate Local USE flags for Blender # blender media-gfx/blender python_single_target_python3_5 cycles boost openexr tiff openimageio player game-engine bullet fftw openal jemalloc opensubdiv openvdb openvdb-compression # Enable cuda or opencl if possible media-libs/opencv cuda opencl media-libs/openimageio opencv media-libs/opensubdiv cuda opencl ptex tbb Unmask related packages by adding to /etc/portage/package.accept_keywords: /etc/portage/package.accept_keywordsAccept unstable Blender related packages media-gfx/blender ~amd64 sci-libs/ldl ~amd64 # Blender 2.78 requires python 3.5.2 (2.72b runs on the stable python 3.4) dev-lang/python:3.5 # For cuda support in 2.78 (See below for 2.72b patch) dev-util/nvidia-cuda-toolkit ~amd64 # For openvdb and openvdb-compression support dev-libs/c-blosc ~amd64 # Cycles and Open Shader Language require Boost dev-libs/boost ~amd64 dev-util/boost-build ~amd64 Emerge Currently, Gentoo package tree provides two versions of Blender: - Blender 2.72, requiring Python 3.4, which is no longer enabled by default. Please refer to PYTHON_TARGETS and enabled python 3.4 if you want to install Blender 2.72. Then proceed installing blender: root # emerge --ask media-gfx/blender - Blender 2.79+, requiring Python 3.5+, which is enabled by default. However this version of blender is not marked as stable. Easiest way to unmask it and all required dependencies would be using autounmask write: root # emerge --ask --autounmask-write --ask ~media-gfx/blender-2.79 Additional Features This section lists many of the optional features available in blender and gives a brief overview of their use for beginning users. Audio Device Support Support for Jack, OpenAL or SDL audio can optionally be enabled through USE flags. Inside blender, go to the File->User Preferences->System tab and set the Audio Dev to the desired setting. Cuda Support Cycles renderer can work on GPUs, for example Nvidia GTX 970 is about twice as fast as an i5 4690k on traditional BMW benchmark. Support for AMD GPUs and opencl is improving. To enable graphics card rendering, install Cuda: root # emerge --ask --verbose dev-util/nvidia-cuda-toolkit With gcc 4.9, Cuda may not work, complaining that it does not support gcc-4.9 and higher. However, gcc 4.9 happily works after a simple dirty hack: in a file /opt/cuda/include/host_config.h ... #if defined(__GNUC__) #if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ > 8) #error -- unsupported GNU version! gcc 4.9 and up are not supported! #endif /* __GNUC__> 4 || (__GNUC__ == 4 && __GNUC_MINOR__ > 8) */ ... replace "8" with "9" twice. Inside blender, go to the File->User Preferences->System tab and set Compute Device to CUDA and select the graphics card in the box below. If the graphics card is not supported these options will not be visible. Now set the renderer to Cycles Renderer and in the renderer panel under the Render options set the Device to GPU Compute. The first time a render is created with a new version of blender, the CUDA kernels will need to be compiled. This may take over 15 minutes. File Format Support Support OpenCOLLADA (.dae), jpeg2k, sndfile and tiff image file formats can optionally be enabled through USE flags. The collada USE flag adds entries to File->Import/Export for Collada (Default) (.dae) files. The others can be used with background images in the properties panel of the 3D View or as output formats in the render panel. Blender should work with either ffmpeg or libav libraries, although only ffmpeg is officially recommended by the blender developers. Headless (Server Only) For render farms it is possible to compile blender with the headless USE flag. This is not recommended for most users. This feature reduces the blender file size by around 5 MB, but it will not be possible to run blender normally as the GUI is not available. In headless mode, blender can still be used to run python scripts from the commmand line user $ user $ blender -b -P script.py [-- [--optionsforscript .. ] ] This functionality is also available with regular versions of blender, it is not necessary to enable the headless use flag to run scripts from the command line. Memory Allocator It is recommended to enable jemalloc to use a more efficient memory allocator. This reduces wasted memory during rendering and allows for larger scenes to be rendered. Memory Profiling Support for memory profiling can be enabled using the valgrind USE flag. See Debugging for instructions on setting up Valgrind. OpenColorio Open Colorio provides additional options under the Color Management section of the Scene panel. Inside blender, select the Render View and Look options, and adjust the exposure, gamma and curves to obtain the desired look. Opensubdiv Opensubdiv is a set of libraries that improve subdivision surface modifier evaluation. This can dramatically improve the frame rate of viewing animations in the viewport when using high levels of subdivision. Not all cards are suitable. The current code checks for geometry shader, GL_ARB_gpu_shader5, glProgramParameteri, glProgramParameteriEXT and glProgramParameteriARB. These are available as part of OpenGL 3.2, 4.0 and 4.1, or as extensions. Support is enabled via the opensubdiv USE flag. Inside blender, go to the File->User Preferences->System tab and set OpenSubdiv compute to the desired option. It may be possible to choose the CPU, but cards which support GLSL Compute will give better performance. This box will not appear if the card does not meet the requirements. Finally check the Use Opensubdiv box in the subdivision surface modifier OpenVDB OpenVDB provides a data structure for storing and manipulating volumetric information efficiently. It can be compiled into blender using the openvdb USE flag, and openvdb-compression is also recommended as the data can require upwards of 20MB. In blender, set the renderer to Cycles Renderer. Go to the physics panel and enable physics for Smoke. In the smoke section select Domain. Save the file to enable editing of the smoke cache. Change File Format to Openvdb and select Blosc compression if desired. Now create and bake the simulation. Blender 2.72b Specific Blender 2.72b is quite old and upgrading to 2.78 is strongly recommended. x86 Intrinsics Compilation Due to bug #523928 cycles may fail to compile. To work around it, create /etc/portage/patches/media-gfx/blender/blender.redefinition.patch patch file: diff -Nur old/intern/cycles/util/util_simd.h new/intern/cycles/util/util_simd.h --- old/intern/cycles/util/util_simd.h 2014-10-20 03:58:22.000000000 -0400 +++ new/intern/cycles/util/util_simd.h 2015-02-03 13:29:26.156893414 -0500 @@ -19,6 +19,7 @@ #define __UTIL_SIMD_TYPES_H__ #include <limits> +#include <x86intrin.h> #include "util_debug.h" #include "util_types.h" (This patch can also be obtained from pastebin if copying and pasting from formatting adds extra spaces that break the patch.) Nvidia GTX 900 series in Blender 2.72b Newer Nvidia cards are not supported in Blender 2.72 and upgrading to 2.78 is recommended. However it is possible to patch 2.72b: - Unmask and emerge dev-util/nvidia-cuda-toolkit of version 6.5.19 or higher - Create a file /etc/portage/patches/media-gfx/blender/blender.sm_52.patch with contents diff --git a/intern/cycles/kernel/kernel.cu b/intern/cycles/kernel/kernel.cu index d5b5293..9ed4592 100644 --- a/intern/cycles/kernel/kernel.cu +++ b/intern/cycles/kernel/kernel.cu @@ -52,8 +52,8 @@ #define CUDA_KERNEL_MAX_REGISTERS 63 #define CUDA_KERNEL_BRANCHED_MAX_REGISTERS 63 -/* 5.0 */ -#elif __CUDA_ARCH__ == 500 +/* 5.0 and 5.2 */ +#elif __CUDA_ARCH__ == 500 || __CUDA_ARCH__ == 520 #define CUDA_MULTIPRESSOR_MAX_REGISTERS 65536 #define CUDA_MULTIPROCESSOR_MAX_BLOCKS 32 #define CUDA_BLOCK_MAX_THREADS 1024 Re-emerge Blender: root # emerge --ask --one-shot media-gfx/blender See also - Debugging - SpaceNavigator - OpenCL — a framework for writing programs that execute across heterogeneous computing platforms (CPUs, GPUs, DSPs, FPGAs, ASICs, etc.). - Project:Artwork/Artwork: Gentoo artwork, including a .blend file used to create some of it.
https://wiki.gentoo.org/wiki/Blender
CC-MAIN-2020-16
refinedweb
1,496
51.44
Interacting with Excel From IronPython Cookbook Excel (which exposes a COM automation interface) is accessible to .NET languages like IronPython through the .NET COM interop facilities. Here is a simple example that should get you off the ground: import clr clr.AddReferenceByName('Microsoft.Office.Interop.Excel, Version=11.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c') from Microsoft.Office.Interop import Excel ex = Excel.ApplicationClass() ex.Visible = True ex.DisplayAlerts = False workbook = ex.Workbooks.Open('foo.xls') ws = workbook.Worksheets[1] print ws.Rows[1].Value2[0,0] From here you can explore the various worksheet objects that you get back. Python itself has excellent libraries available for dealing with Excel files: These can be faster than COM, but have limitations like not being (currently) able to access the formulae in spreadsheet. If you have problems or are interested in these libraries, you can discuss them on the following Google group: Installing the Interop Assemblies To use COM components from .NET, you need .NET class libraries that wrap the COM interfaces - for most COM libraries these can be automatically generated by the framework, but for Office the automatic generation doesn't work correctly, so Microsoft have provided pre-built ones called the Office Primary Interop Assemblies (or PIAs). For Office 2003 they can be found here: Office 2003 PIAs (I'm not sure, but I think Office 2007 apps will install the PIAs automatically.) Getting Started If the PIAs are installed, you should be able to add a reference to the Excel assembly: import clr clr.AddReference("Microsoft.Office.Interop.Excel") Getting Excel Started import Microsoft.Office.Interop.Excel as Excel excel = Excel.ApplicationClass() excel.Visible = True # makes the Excel application visible to the user Getting hold of an already-running instance of Excel: from System.Runtime.InteropServices import Marshal excel = Marshal.GetActiveObject("Excel.Application") Workbooks # creating a new one workbook = excel.Workbooks.Add() # opening a workbook workbook = excel.Workbooks.Open(r"C:\My Excel Files\Book1.xls") # finding a workbook that's already open filename = r"C:\My Excel Files\Book1.xls" workbooks = [wb for wb in excel.Workbooks if wb.FullName == filename] if workbooks: workbook = workbooks[0] # just grabbing the current workbook excel.ActiveWorkbook EnvironmentError: Old format or invalid type library Traceback (most recent call last): File C:\myscript.py, line 13, in Initialize File Microsoft.Office.Interop.Excel, line unknown, in Open EnvironmentError: Old format or invalid type library. (Exception from HRESULT: 0x80028018 (TYPE_E_INVDATAREAD)) This is known bug (). You probably run an English version of Excel. However, the regional settings for the computer are configured for a non-English language. To fix it, set the english locale to the Excel thread. # opening a workbook System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo("en-US") workbook = excel.Workbooks.Open(r"C:\My Excel Files\Book1.xls") Worksheets # adding a worksheet worksheet = workbook.Worksheets.Add() # getting the active one workbook.ActiveSheet Cell ranges # a range can be one cell cell = worksheet.Range["A3"] print cell.Value2 # prints None cell.Value2 = 42 # if the sheet is visible, you'll see this appear. from System.Reflection import Missing # for optional parameters, like the arguments to the Address indexer, you can use Missing.Value to use the default. print cell.Address[Missing.Value] # prints $A$3 print cell.Address[False, False] # prints A3 (the first two parameters are whether row and column should be absolute) # or a number of cells (in which case .Value2 can be got/set as a 2D array). xlrange = worksheet.Range["A3", "D4"] print xlRange.Address[False, False] # prints A3:D4 print xlrange.Value2 # prints: # System.Object[,]( # None, None # None, None) from System import Array a = Array.CreateInstance(object, 2, 2) a[0, 1] = 3 a[1, 1] = "hi there!" xlrange.Value2 = a print xlrange.Value2 # prints: # System.Object[,]( # None, 3 # None, "hi there!") Note the use of the Value2 property of Ranges - this is a convenience property that ignores some data types. To use the Value property (which handles dates and currencies correctly), we pass an enum indicating that we want the default type (there are also XML serialisation versions selected by different values of the enum). from System import DateTime default = Excel.XlRangeValueDataType.xlRangeValueDefault cell.Value[default] = DateTime.Now print cell.Value[default] # prints 01/06/2007 15:38:10 (for me) Events Excel exposes a number of events that we might be interested in - for example, we can ask to be notified when a workbook is changed. To do this we need to add an event handler to the event we're interested in. This is a little more fiddly in the case of COM objects, because they expose events on a separate interface to their main one (this is referred to as the 'source' interface - COM Interop Exposed Part 2 has more information on this). If, for example, you have a workbook for which you'd like to receive the SheetChanged event, you need to cast it to the corresponding Excel.WorkbookEvents_Event interface first. In C# this is handled for you, but in IronPython we need to use the Python idiom for calling superclass methods. Say we have a simple handler for the SheetChange event: # the SheetChange event handler should accept the sheet and the range that changed def onSheetChange(sheet, changedRange): print "%s!%s changed" % (sheet.Name, changedRange.Address[False, False]) What we want to express is this: workbook.SheetChange += onSheetChange # doesn't work But the Worksheet interface doesn't have the SheetChange event. Instead it's on the WorkbookEvents_Event interface. So we need to add the handler 'through' the interface, but with the workbook instance we have. The trick is to realise that the line: obj.Event += handler ... is actually implemented behind the scenes in .NET as: obj.add_Event(handler) ... and in Python that method call is really: <obj's class>.add_Event(obj, handler) So we can add the handler like this: Excel.WorkbookEvents_Event.add_SheetChange(workbook, onSheetChange) Now if you change the value of a cell in the workbook, you should see a line which indicates which cell was changed. We remove the handler in the same way: Excel.WorkbookEvents_Event.remove_SheetChange(workbook, onSheetChange) As another event example, you might want to prevent the user from closing a workbook. Excel.Application provides a WorkbookBeforeClose event that can be used to prevent the workbook from being closed. The reference says that the event handler will be called with the workbook being closed, and a boolean passed by reference that can be set to True to cancel closing the workbook. def onWorkbookBeforeClose(workbook, cancel): print "you can't close this workbook!" # IronPython ensures that arguments that are declared as passed by reference # arrive as Reference objects. These are updated by setting their .Value property. cancel.Value = True # Application events are exposed by the AppEvents_Event interface Excel.AppEvents_Event.add_WorkbookBeforeClose(excel, onWorkbookBeforeClose) # Any attempts to close a workbook in the Excel instance will now be thwarted... # ...which could definitely be annoying. Excel.AppEvents_Event.remove_WorkbookBeforeClose(excel, onWorkbookBeforeClose) Incidentally, if you need to pass ByRef arguments into a method, you can construct one using the clr.Reference generic type: ref = clr.Reference[int](42) Finding Stuff The VBA Language reference provides all the information you need to drive Excel, but it's in VBA, unfortunately. Once you're familiar with the differences between how things are done in VBA and how they work in IronPython, you should be able to interpret the documentation. An important extra source of information is the interactive interpreter - if in doubt, import the Excel namespace at the command line, and use dir() on things to find out what methods and properties are available. This was especially useful for me when trying to understand how events worked - finding the *Events_Event interfaces with all of the events on them was my "Aha!" moment. (Well, that and some extremely useful pointers from Dino Viehland.) Excel 2003 VBA Language Reference: - Top-level - Application - Workbook - Worksheet - Range - a collection of one or more cells. This is probably the most useful object. Useful articles about .NET COM Interop:
http://www.ironpython.info/index.php/Interacting_with_Excel
crawl-002
refinedweb
1,337
51.14
Optimizations for AS3 calculations Well, I’m not the math whiz by any means, but thought enough of what I’ve been playing around with lately to throw this out there and see how it sticks to the flash wall (yes, Tink, i’m inviting you thrash this around a bit! ) Now, you’ve probably heard the tip about “use multiplication instead of division when dividing by 2”, right? faster: var n:Number = value *.5; slower: var n:Number = value / 2; run it with a test: [as]import flash.utils.getTimer; var time:Number = getTimer(); function runDivisionTest():void { time = getTimer(); for(var i:Number=0;i<10000000;i++) { var test:Number = i/2; } trace(“DivisionTest: “, (getTimer()-time)); } function runMultTest():void { time = getTimer(); for(var i:Number=0;i<10000000;i++) { var test:Number = i*.5; } trace(“MultTest: “, (getTimer()-time)); } runDivisionTest(); runMultTest(); [/as] traces out: DivisionTest: 162 MultTest: 110 Alright, so it’s not miles faster, but in a 3D engine like Papervision3D, this becomes the difference between a fast engine and a slow engine real quickly. Well, there’s one still that’s even faster: Bitwise shift operations Divide by 2 with a right shift: trace(10 >> 1); // traces: 5 Multiply by 2 with a left shift: trace(10 << 1); // traces: 20 Now, run the test against the Division and Multiplication tests above: [as]function runBitTest():void { time = getTimer(); for(var i:int=0;i> 1; } trace(“BitTest: “, (getTimer()-time)); } runBitTest();[/as] traces out: DivisionTest: 152 MultTest: 112 BitTest: 63 HOLY CRAP Batman – that’s nearly 1/2 the speed?? or should I say, 1*.5 the speed 😉 So, I was looking at some other stuff with uint and this seems to be a real gem when it comes to Math.floor and Math.ceil operations. I was reading through Flash’s help (I have to say, I really enjoy the new help – I live in there) on uint and realized that, like int, when you pass a number, it strips everything passed the decimal (like Math.floor). So, I thought, what the hey, let’s give er’ a speed test. Sure enough, it was much faster to use uint(n) than Math.floor(n) – nearly 10x’s as fast *** UPDATE *** After Paulius Uza’s comments about using int, I went back and added tests for int with the floor/ceil tests, and sure enough, they’re even faster than using uint. floor’s test wasn’t that drastic, but ceil’s was 1/2 the time of uint’s version *** /UPDATE *** fast: var test:int = int(1.5); //test equals 1 slow: var test:Number = Math.floor(1.5); //test equals 1 Now, I know what yer thinkin’: what about Math.ceil? +1? yes 😉 fast: var test:int = int(1.5)+1; //test equals 2 slow: var test:Number = Math.ceil(1.5); //test equals 2 Time for a test: [as]function runFloorTest():void { time = getTimer(); for(var i:uint=0;i<10000000;i++) { var n:Number = 1.5; var test:Number = Math.floor(n); } trace(“FloorTest: “, (getTimer()-time)); } function runUintFloorTest():void { time = getTimer(); for(var i:uint=0;i<10000000;i++) { var n:Number = 1.5; var test:uint = uint(n); } trace(“UintFloorTest: “, (getTimer()-time)); } function runIntFloorTest():void { time = getTimer(); for(var i:uint=0;i<10000000;i++) { var n:Number = 1.5; var test:int = int(n); } trace(“IntFloorTest: “, (getTimer()-time)); } function runCeilTest():void { time = getTimer(); for(var i:uint=0;i<10000000;i++) { var n:Number = 1.5; var test:Number = Math.ceil(n); } trace(“CeilTest: “, (getTimer()-time)); } function runUintCeilTest():void { time = getTimer(); for(var i:uint=0;i<10000000;i++) { var n:Number = 1.5; var test:uint = n == uint(n) ? n : uint(n)+1; } trace(“UintCeilTest: “, (getTimer()-time)); } function runIntCeilTest():void { time = getTimer(); for(var i:uint=0;i<10000000;i++) { var n:Number = 1.5; var test:int = n == int(n) ? n : int(n)+1; } trace(“IntCeilTest: “, (getTimer()-time)); } runFloorTest(); runUintFloorTest(); runIntFloorTest(); runUintCeilTest(); runIntCeilTest(); [/as] traces out: FloorTest: 1733 UintFloorTest: 176 IntFloorTest: 157 UintCeilTest: 650 IntCeilTest: 384 **** New - Math.abs **** I was thinking about another one that I use sometimes which was using *-1 instead of Math.abs on a number faster: var nn:Number = -23 var test:Number= nn < 0 ? nn * -1 : nn; slower: var nn:Number = -23 var test:Number = Math.abs(nn); Lets test! [as]function runABSTest():void { time = getTimer(); for(var i:uint=0;i<10000000;i++) { var n:Number = -1.5; var test:Number = Math.abs(n); } trace(“ABSTest: “, (getTimer()-time)); } function runABSMultTest():void { time = getTimer(); for(var i:uint=0;i<10000000;i++) { var n:Number = -1.5; var test:Number = n < 0 ? n * -1 : n; } trace(“ABSMultTest: “, (getTimer()-time)); } runABSTest(); runABSMultTest(); [/as] traces out: ABSTest: 1615 ABSMultTest: 153 Now, I know in alot of cases, the speed differences here are not going to matter. But in a game situation, or 3D engine – these types of changes in the render loop can make a HUGE difference in performance. The Papervision3D engine has really been scrutinized for details like this, and I firmly believe that’s why it’s one of the fastest engines out there. I realize too, that not being a total math nut, some of this is probably very obvious to other people and some of you might think “well DUH”, but for the rest of us, this could be very handy 😉 Please let me know where I’ve gone horribly wrong on any of this ! Careful with this one: uint(1)+1 != Math.ceil(1) uint(n)+1 could not be compared with Math.ceil(n). uint(n)+1 is not equivalent to Math.ceil(n) because when it comes to an integer values (i.e. 3), Math.ceil(n) does not change the value (it remains 3) while uint(n)+1 increases one (the result is 4). Really interesting post. In critical cases, a little optimization can improve performance dramatically. Nice man, I didn’t know this….. I am now learned 😉 John: It’s awesome that you are starting up a body of experimental work on this topic. Keep up the great effort! – jim It would be really cool to see a cheatsheet on speed benchmarks for different operations. Maybe we could start a site where benchmarks could be posted and then printed if the user wanted a hard copy. [@ Claus] – Oops YES, you’re right! I should have thought about that last night. Ok, I’ve adjusted the Math.ceil test with an inline or statement, and it’s still much faster than Math.ceil: var n:Number = 1.5; var test:uint = n == uint(n) ? n : uint(n)+1; //traces 2 But why uint? Wouldn’t an int do the same in this case? [@Sascha] no real reason other than I was reading the help and uint has this nice table of what happens when you pass in certain types of arguments and int didn’t – uint sparked the idea, hence, why my tests were with uint I realize that int does the same thing, but just didn’t go back and use it in my tests 😉 Thanks John, these are really useful! I added it to my post about optimization: Another nice one is for the % (modules) operator. This one can be handy, just as division by 2, 4, 8 etc…, when working with textures e.g. To get the modules of a division by 4 use x = y & 3 which equals to x = y % 4 only a bit faster, or at least it should be. I haven’t done any benchmarking in AS3 but I used this kinda stuff in the early ’90s a lot in many of my low level x86 assembler libraries (gfx/sound). Ok thanks for the hint. I just keep hearing from all sides that uint is evil and should only be used for RGB color values. 😉 uint is 4 times, and Number is 3 times slower than int in comparison functions (a Oh, and when testing, you have to use ideal conditions. In the ceil test variable named “test” has different types in different test functions (Number and uint). In real world you would want to use the result from Math.ceil(n) in further calculations. For that your result will get converted to either int or Number (as uints are slow). So if you actually replace “n == uint(n) ? n : uint(n)+1;” with “Number(n == uint(n) ? n : uint(n)+1);” it becomes 15% slower than usual Math.ceil(n). I was puzzled about my last comment, and looks that I made some mistakes. So after extensive testing I found that using int instead of uint var test:int = int(n == int(n) ? n : int(n)+1); the code executed up to 12% faster and using var test:Number = Number(n == int(n) ? n : int(n)+1); code executed up to 18% faster than the usual Math.ceil(n) For Math.floor, another option is n>>0 – which is even faster than uint() (for me about 100 ms). Something else i found while messing with this is that if you declare the variables outside the loop, the time triples. //for example var n=1.5; var time = 0; for(var i=0i Thanks for a really helpful post. Don’t know what happened to my answer, but I just tried to say that if you want to switch the values of two int variables, doing it with a^=b; b^=a; a^=b; is just a tad quicker (but more fun) than c=a; a=b; b=c; I noticed that in your examples you declare variables inside your loops. It’s quite a bit of a speed increase when you declare the variables outside of your loop and reuse them within. Thanks for putting the other examples here, really nice to have them on the web somewhere. [@Andy & Erik] – ha yes, thanks! makes sense. I’ll have to make a note about that as well on the new page I’ll create with these and other speed enhancements -_-” i know now it’s not too long but tag, let’s try again with code tag thx john!, I heard that while is faster: function runWhileUintFloorTest():void { var time = getTimer(); var n:Number = 1.5; var i:uint=0; var test:uint; while (i<10000000) { test = uint(n); i++; } trace("WhileUintFloorTest: ", (getTimer()-time)); } runWhileUintFloorTest(); result is FloorTest: 1256 UintFloorTest: 124 WhileUintFloorTest: 100 Thanks Katopz, yep – I ran your test here and sure enough, it’s slightly faster than the for loop version. Although, when I put the var declarations outside the for loop like people had suggested, the intFloor test is actually slightly faster than the while loop: IntFloorTest: 131 WhileUintFloorTest: 134 Something people might also not think about when worrying about time is how much declaring the variable type can affect performance. When i remove the type decleration from the variables in this test, for example, it takes about 16x longer to compute. (Declare your variable types!) Hey John – What you’re actually doing is what you’d like your compiler to do: recognize common simple operations and provide faster code. I’ve been using these tricks for decades and am always looking for more. When writing graphics engines back in the mid-80’s (before smart video cards), I’d tweak code for any little advantage such as adding conditional loops to get a 16% gain in a line-drawing routine. Basically, when it comes to engines (like PV3D) where such operations are common, you’ve just gotta be a speed freak. The practical problems come with non-adepts trying to decipher your code and not comprehending that “n –bitshift- 2 + n” is equivalent to “n * 5” only much faster. Morf, is that YOU?! gotta be the same guy from class…GOTTA BE! Sorry to be a party breaker, but it looks like the current int vs floor optimization only works correctly for positive numbers. For negative numbers the it gives different results: var n:Number = -1.5; trace( int(n) ); // traces -1 trace( Math.floor(n) ); // traces -2 trace( int(n+1) ); // traces 0 trace( Math.ceil(n) ); // traces -1 But it looks like this does the trick and it is still fast: floor: trace (int(n) + (n >> 31)); ceil: trace (int(n+1) + (n >> 31)); I just noticed that Andy’s n>>0 method works fine also with negative numbers. John, maybe for most practical purposes int(n) + 0.999 will work just as well for that case as the conditional you throw at it. If you need more 9s, just tack them on to the end 🙂 Test it and try it out. Thanks Mario! excellent find and solution! Following up on my first post I began exploring your tests and more of my own. For one thing, successive tests gave different results. To get more reliable data, I ran them many times; I noticed was that I was not getting the same results for the bitshiftRight “division”. In the code posted, in the first test, the iterator (i) is declared as Number in the runDivisionTest() and runMultTest() loops — but it’s declared as int in the runBitTest() loop. Then I noticed you did the same thing with “test”. You dog! With the uniform declarations, there’s still a savings – and like I said before, that’s usually worthy. But it’s not as great as originally posted. Using code with i as int and test as Number gets these results: Mean over 50 loops DivisionTest: 82.86 MultTest: 61.78 BitTest: 58.02 This doesn’t shock me that much. Before graphics cards and co-processors, math coding cheats were the way to amaze your geek buddies, frustrate your nerd enemies, and glaze over the eyes of your nosy boss – I don’t expect to save massive clock cycles these days. Wtihout getting into messy innards of microprocessor math, I delved further. What if I declared test as int as well – shouldn’t that make the operations faster? The results were rather ugly: Mean over 10 loops DivisionTest: 244.8 MultTest: 207 BitTest: 45.2 This could indicate several things: the AS3 compiler is converting ints to Numbers before * and / (and possibly other) math operations; that the compiler has the CPU handle math on floats but creates its own (slower) code for those operations on ints; that my computer is a piece of crap (please test this hypothesis on your own boxes!). What’s interesting here is that the BitTest *was* much faster, so there may be some really good ways of speeding up our code. Naturally, this is compelling me to explore other nuances of AS3’s math operations. Lord help me, I’m a speed freak. see, this is why I like you – YOU ROCK \m/ Morf! So, what I got our of your second test is that by declaring “test” as an int inside the loop made things much faster: function runBitTest():void { time = getTimer(); for(var i:int=0;i<10000000;i++) { var test:int = i>> 1; } trace("BitTest: ", (getTimer()-time)); } runBitTest(); is that what you’re saying? Yep – as long as we’re *only* talking about the bitshift operator, ints are more than 20% faster than Numbers. I’m testing other operations as well and will update. You know, I suppose I could just read the AS3 technical documents, but what’s the fun in that? 🙂 (yay, I got my wings!) Whew, been working on a bunch of these… John, is there someplace you these posted? (eMail me for details) you *want these posted I just created it – this is where I had intended to put the optimization tests and information so that the community could add / maintain it Try testing -x versus -1*x. In AS1 at least, the compiler turns the former into 0-x, I would expect subtraction to be faster than multiplication. You may be able to change the sign with bit manipulation as well. Thanks Robert! Yep, as you pointed out, it IS faster: var test:Number = n < 0 ? 0-n : n; I've added to the OSFlash page Morf has done a great job in testing Robert’s suggestion with subtraction – it’s definitely faster. He went a step further and tested with an if statement as opposed to an inline If and THAT was faster Nice work Morf! You shouldn’t have n be the same value every loop. That only tests half of your conditional. Randomize it so n covers a range of positive and negative numbers. Then you can also be certain that the compiler isn’t doing any optimization tricks by detecting that n isn’t changing. I made some expierements, and i found that all these “10x speed ups” is because that function calls was stripped. Here’s a sample. runFloorTest and runIntFloorTest are the same. runFloorTestFunc uses myFloor function, which implemets “fast int flooring”. runFloorTestClasses uses the same function, but placed into class. import flash.utils.getTimer; import benchmark.MyMath; var time:Number; function myFloor(n:Number):int { return int(n) } function runFloorTest():void { time = getTimer(); for(var i:uint=0;i Here's results: FloorTest: 2239 IntFloorTest: 244 IntFloorTestFunc: 1556 IntFloorTestClass: 2912 Conclusion: the best optimization strategy is to avoid function calls. At least until perfect times when we will have inline functions or macroses in AS. Alas, code was truncated… [code]import flash.utils.getTimer; import benchmark.MyMath; var time:Number; function myFloor(n:Number):int { return int(n) } function runFloorTest():void { time = getTimer(); for(var i:uint=0;i Thanks Dan! Yeah I’d been running some tests on just simply calling a function, calling a getter or referencing a property etc and function calls are much much slower than accessing a property >> 1 is only dealing with integers. just in case anyone missed that hi, in Math.abs test. use “var test:Number = n Alas, code was truncated… [code]import flash.utils.getTimer; import benchmark.MyMath; var time:Number; function myFloor(n:Number):int { return int(n) } function runFloorTest():void { time = getTimer(); for(var i:uint=0;i *update*: It seems with the new player it’s nothing big anymore. I tested it and got division test: 841 multi: 837 Bittest: 827 Wonder if it’s because the quad core proc. or the new flash player ? Hey, I just ran the tests also. It seems that for small number division is way faster. But for larger numbers multiplication by 0.5 on Numbers are way faster. Integers are still way faster to shift. Another word of warning – I just had to discover that the x>>0 shortcut for Math.floor(x) does not work for any x > 0x7fffffff you know, there is something ironic about having a blog post about optimization on a blog with a theme that lags out the scrolling on my browser. But in all seriousness, thanks for the post, save me countless milliseconds of processing time. This was really helpful, although I did not find the same results with bit shifting. Were you testing from a local flash player or embedded in a web page? I tested math, data structures, and graphics in my optimization article Best of Luck, Stephen Instead of: var test:Number= nn < 0 ? nn * -1 : nn; you can use: var test:Number= nn < 0 ? -nn : nn; I find it better readable and it is slightly faster. Regards, Marc Hmm, after some more testing I found out that -nn is faster than nn*-1 when you’re working with numbers. When you are working with integers nn*-1 is faster. But if you are working with integers. A even faster method is: ~nn + 1;
https://rockonflash.wordpress.com/2007/08/11/optimizations-for-as3-calculations/
CC-MAIN-2020-05
refinedweb
3,286
72.56
Name | Synopsis | Description | Return Values | Attributes | See Also #include <signal.h> int raise(int sig); The raise() function sends the signal sig to the executing thread. If a signal handler is called, the raise function does not return until after the signal handler returns. The effect of the raise function is equivalent to calling: pthread_kill(pthread_self(), sig); See the pthread_kill(3C) manual page for a detailed list of failure conditions and the signal.h(3HEAD) manual page for a list of signals. Upon successful completion, 0 is returned. Otherwise, -1 is returned and errno is set to indicate the error. See attributes(5) for descriptions of the following attributes: pthread_kill(3C), pthread_self(3C), signal.h(3HEAD), attributes(5), standards(5) Name | Synopsis | Description | Return Values | Attributes | See Also
http://docs.oracle.com/cd/E19082-01/819-2243/6n4i099fj/index.html
CC-MAIN-2015-35
refinedweb
128
50.02
Using DataWeave in Studio Enterprise DataWeave is Mule’s most powerful and versatile tool for transforming data. The Transform Message component carries out a transformation of your Mule message that follows a transform script, this transform script can be explicitly written in DataWeave code or you can use the UI to build it implicitly through dragging and dropping elements. DataWeave fully supports DataSense, allowing you to leverage metadata from connectors, schemas and sample documents to more easily design your transformations. DataSense provides content assist while you are coding and scaffolds and auto generates lines of code form actions performed in the UI. The Transform Message component offers you a preview of your output that is built on sample data and is updated in real time as you make changes to your transform, so that you can be sure of what you’ll be getting out of the other end. Using the DataWeave Transformer In Anypoint Studio, place a Transform Message element in a flow to create transforms using the DataWeave language. The editor helps you do this by offering a drag and drop UI, intelligent autocomplete suggestions, and an output preview that is updated in real time as you make changes. This generates a .dwl transformation file (or several of them) that stores your code and is packaged with your Mule application. When adding a Transform Message element to a Mule Flow, it takes the elements from the incoming Mule Message as its inputs. It then performs the necessary actions to produce a Mule message as output for the next element in the flow. If you click on an instance of the Transform Message element in your flow, its properties editor will be displayed: Note that by default the properties editor of the Transform Message element displays two main regions: On the left: is the graphical UI, which exposes the input and output structures. The mappings between input and output fields are represented through lines drawn from one side to the other. You can easily click and drag one field onto another to map these. On the right: the DataWeave code editor. This allows you to leverage the full power of DataWeave syntax, which includes many tools that allow you to aggregate, normalize, group, join, partition, pivot and filter. See the DataWeave reference documentation for a complete guide on the DataWeave language syntax. Both regions represent the same transform in different ways, and any changes done to one representation are matched in real time by the other one. The DataWeave Text Editor UI In this section, you write the actual DataWeave code that carries out the transform. Sometimes, all you need to do can be automatically built by dragging elements in the GUI, other times you may want to carry out more complex operations that involve aggregation, filtering, calculations, defining custom functions, etc and there you must write this out in DataWeave code. Directives in Studio Although DataWeave as a language supports adding input directives and naming these by any name you like, when using DataWeave in Anypoint Studio, it’s not necessary to declare any input directives for any of the components of the Mule Message that arrives to the DataWeave transformer (Payload, flow variables and input/outbound properties) nor for any system variables. These are already implicitly recognized as inputs and can be referenced anywhere in the DataWeave body without a need to include them in the header, their type is known from Mule metadata. If your transform outputs XML data, a namespace directive will be automatically added to your DataWeave header section, defining a default name for it. This namespace is then referenced in the body too. %dw 1.0 %output application/xml %namespace ns0 For further reference about writing DataWeave code, see DataWeave Language Reference The Graphical UI Two tree views show the known metadata contents of the incoming and the outgoing Mule Messages, allowing you to explore them and know what data is available for using as an input and where it can fit into, and how to reference each of these parts. You can simplify or hide the graphical UI if you wish by clicking the icons on the top right to select between the different views for this properties editor: By simple interactions with the graphical UI, you can intuitively build out much of your DataWeave code, often this is all you really need to do. Drag an element on the input structure over to another on the output structure. This will cast a line that joins them and also add a line to the DataWeave code that describes this mapping. Double click on an output field to add it into the DataWeave code with a static value. This will add an Fxicon next to it, as well as a line to the DataWeave code that assigns a default null value to the field. You can then change this value in the code to whatever you want. Select an element to have its corresponding line in the DataWeave code hightlighted. This is very helpful when dealing with large transforms. If an input field is mapped to two or more output fields, you can right-click it and then select which of the multiple outputs you want to highlight in the DataWeave code. Type a name in the search boxes at the top of the input and output structures to display only fields that match your search. This is particularly useful when dealing with large data structures with many nested elements. Defining Input Structure If the other elements in your Mule flow expose metadata about their input and output, then this information will already be available to the Transform Message component. If they don’t, you can configure these elements so that they expose this information by editing their Metadata tab. For example, you can configure an HTTP connector and assign it a JSON sample file so that this sample’s structure is exposed as metadata that your Transform Message component can read. If the Mule flow doesn’t expose Metadata about the elements you need from the incoming message, you can also manually specify it directly in the input section of your Tranform Message component. If a metadata definition is missing, a notification will advise you to provide one, otherwise you can also right-click your input and select Set Metadata. You can select an existing metadata type, this may save you several steps: Or you can also build your metadata freely using an editor: This sample data is used together with your DataWeave code to produce a sample output in the output section, which gets updated in real time as you make changes. You can then define the data structure manually by writing or pasting a sample into the newly created tab. You can also click the rescafold button to have your sample data overwritten by an empty scaffolding structure based on the metadata. When the input is of JSON or XML types, the sample input contains plain XML or JSON code. When the input is of type POJO or DataWeave, the sample input is written in DataWeave for more simplicity. In these cases the sample DataWeave code is merely a way to display the sample data, not a transformation in itself. If your metadata is missing any variables, inbound properties, outbound properties, session variables or record variables that you know will exist in the incoming mule message, you can manually add these too in the editor. Just right-click on one of these categories in the input section of the properties editor and select Add Flow Variable, Add Inbound Property or whatever the element you want to add may be. Explicitly Defining a MIME Type By default, DataWeave should be able to recognize the type of an input from the metadata. If you must explicitly define an input payload type, use the mimeType attribute in an XML tag as in the example below: If you do not provide this attribute, DataWeave will try to read the payload MIME type from the metadata. If it is undeclared or not understood it will default to 'application/java', a warning will be logged. Configuring the CSV Reader Some input formats, like CSV, allow you to define a reader with specific properties that make DataWeave parse inputs differently. You can assign any special character as the indicator for separating fields, toggling quotes, or escaping quotes. Make sure you know what special characters are being used in your input, so that DataWeave can interpret it correctly. When defining an input of type CSV, there are a few optional parameters you can add to the input directive to customize how the data will be parsed. header: boolean that defines if the first line in the data contains headers separator: character that separates fields, ','by default quote: character that defines quoted text, " "by default escape: character that escapes quotes, /by default You can set these propertes by either editing the XML code or via the UI: In Anypoint Studio, there are two ways to set this up. You can either set the parameters of the CSV input through the Transform Message component itself or by setting it up on the component of your Mule flow that actually brings this information in. On the Transform Message component, left-click on the element in the input structure and select Reader Configuration. + On the component that brings the input into the flow (eg: an HTTP Connector, FTP Connector, etc), select it, pick the Metadata tab, and click Add Metadata to provide the details about the incoming data structure. In the XML editor, if you want to parse CSV inputs with custom modifiers, you must set these up as child elements of the DataWeave component, like in the example below: The Preview Section You can enable the preview section by clicking on the Preview button on the top-right of the editor. This section presents a sample output, built by taking the sample input you provide and transforming it through the DataWeave transform. As you make changes in the DataWeave code, notice how the output data structure changes. If your transformer has multiple outputs, the Preview section will display the one corresponding to the currently selected transform. Viewing Errors For your DataWeave code’s syntax to be evaluated, you must have the Preview Section enabled. With this enabled, any syntax errors are marked. Above your DataWeave code, an additional error notification can be opened to display further detail. If you click this notification, a window opens detailing each error in your code and its cause. Handling Multiple Outputs A single Transform Message element can give shape to several different components of the output Mule message. Each of these output components must be defined in a separate .dwl file, written out in a separate tab of the Transform section. For example in one tab you may be defining the payload contents, in another those of an outbound property, and these will both be parts of the same output Mule message. To add a new output, open the dropdown menu above your DataWeave code, that should say Payload by default. Then select Add New Target. Then you must specify where in the output Mule message to place the output of this new DataWeave transform. In case you’re creating a new variable or property, you must also set a name for it. In Studio’s XML editor you can do the same by adding multiple child elements inside the dw:transform-message component. Keeping your DataWeave code in a separate file By default, DataWeave code is expressed inline within your Mule XML file. If you wish to keep it in a separate file and have your XML reference this file, you can easily do this from the DataWeave UI. In order to export the DataWeave code to a .dwl file, you need to do the following: Click on the dropdown menu above the DataWeave code that defines the output, which should say 'Payload' by default Select 'Edit current target' Select the 'File' radio button Type a name for your .dwlfile Click OK A file will be created under the 'src/main/resources' folder in your project containing your DataWeave code. Using DataWeave Language Elsewhere All components in Mule that support Mule Expression Language also support expressions written in DataWeave Language. To invoke an expression written in DataWeave language, simply invoke the dw() function, the expression will return whatever the transform outputs. DataWeave expressions defined within this function work just as those defined within a Transform Message element, the only difference is that the output is returned into the expression’s result, wherever it may be. For example, you can define a custom object and populate it with elements from the payload: dw("myobject:{id:payload.accountid, user:payload.user}") That same expression could be added inside a Logger, within a MEL expression, to print out its result: #[dw("myobject:{id:payload.accountid, user:payload.user}")].
https://docs.mulesoft.com/anypoint-studio/v/5/using-dataweave-in-studio
CC-MAIN-2017-43
refinedweb
2,161
55.17
JVM concurrency Asynchronous event handling in Scala Learn blocking and nonblocking techniques, including easy nonblocking code with the async macro Content series: This content is part # of # in the series: JVM concurrency This content is part of the series:JVM concurrency Stay tuned for additional content in this series. Asynchronous event handling is crucial in concurrent applications. Whatever the events' source — separate computational tasks, I/O operations, or interactions with external systems — your code must keep track of the events and coordinate actions taken in response to them. Applications can take one of two basic approaches to asynchronous event handling: - Blocking: A coordination thread waits for the event. - Nonblocking: The event generates some form of notification to the application without a thread explicitly waiting for it. In "JVM concurrency: To block, or not to block?" you read about ways to handle asynchronous events in Java™ 8, using both blocking and nonblocking techniques based on the CompletableFuture class. This tutorial shows some of the options for asynchronous event handling in Scala, starting with a simple blocking version and then moving on to some of the nonblocking options. Finally, you'll see how the async / await constructs can convert what looks like simple blocking code to nonblocking execution. (Get the full sample code from the author's GitHub repository.) Composing events The scala.concurrent.Promise and scala.concurrent.Future classes give Scala developers a similar range of options to what Java 8 developers have with CompletableFuture. In particular, Future offers both blocking and nonblocking ways of working with event completions. Despite the similarity at this level, however, the techniques used to work with the two types of futures differ. In this section, you'll see examples of both blocking and nonblocking approaches to working with events represented by Futures. This tutorial uses the same concurrent tasks setup as the last one. I'll quickly review that setup before digging into the code. first two operations.. Modeling asynchronous events In a real system, the sources of asynchronous events are generally either parallel computations or a form of I/O operation. It's easier to model a system of this type using simple time delays, though, and that's the approach I'm taking here. Listing 1 shows the basic timed-event code used to generate events, in the form of completed Futures. Listing 1. Timed-event code import java.util.Timer import java.util.TimerTask import scala.concurrent._ object TimedEvent { val timer = new Timer /** Return a Future which completes successfully with the supplied value after secs seconds. */ def delayedSuccess[T](secs: Int, value: T): Future[T] = { val result = Promise[T] timer.schedule(new TimerTask() { def run() = { result.success(value) } }, secs * 1000) result.future } /** Return a Future which completes failing with an IllegalArgumentException after secs * seconds. */ def delayedFailure(secs: Int, msg: String): Future[Int] = { val result = Promise[Int] timer.schedule(new TimerTask() { def run() = { result.failure(new IllegalArgumentException(msg)) } }, secs * 1000) result.future } Like the Java code from the last installment, the Listing 1 Scala code uses a java.util.Timer to schedule java.util.TimerTasks for execution after a delay. Each TimerTask completes an associated future when it runs. The delayedSuccess function schedules a task to successfully complete a Scala Future[T] when it runs, and it returns the future to the caller. The delayedSuccess function returns the same type of future but uses a task that completes the future with an IllegalArgumentException failure. Listing 2 shows how to use the Listing 1 code to create events, in the form of Future[Int]s, matching the four tasks in Figure 1. (This code is from the AsyncHappy class in the sample code.) Listing 2. Events for sample tasks // task definitions def task1(input: Int) = TimedEvent.delayedSuccess(1, input + 1) def task2(input: Int) = TimedEvent.delayedSuccess(2, input + 2) def task3(input: Int) = TimedEvent.delayedSuccess(3, input + 3) def task4(input: Int) = TimedEvent; later, you'll see examples that use the failure form. to see how Scala handles event completions. As in the Java code from the last tutorial, the simplest way to coordinate the execution of the four tasks is to use blocking waits: The main thread waits for each task to complete in turn. Listing 3 (again, from the AsyncHappy class in the sample code) shows this approach. Listing 3. Blocking waits for tasks def runBlocking() = {) val result = Promise[Int] result.success(v4) result.future } Listing 3 uses the Scala scala.concurrent.Await object result() method to do the blocking waits. The code first waits for the task1 result, then creates both the task2 and task3 futures before waiting for each in turn, and finally waits for the task4 result. The last three lines (creating and setting result) enable the method to return a Future[Int]. Returning the future makes this method consistent with the nonblocking forms I'll show next, but the future will actually be complete before the method returns. Combining futures Listing 4 (again from the AsyncHappy class in the sample code) shows one way of linking futures together to execute the tasks in the correct order and with the correct dependencies, all without blocking. Listing 4. Handling completions with onSuccess() def runOnSuccess() = { val result = Promise[Int] task1(1).onSuccess(v => v match { case v1 => { val a = task2(v1) val b = task3(v1) a.onSuccess(v => v match { case v2 => b.onSuccess(v => v match { case v3 => task4(v2 + v3).onSuccess(v4 => v4 match { case x => result.success(x) }) }) }) } }) result.future } The Listing 4 code uses the onSuccess() method to set a function (technically a partial function, because it handles only the successful completion case) to be executed when each future completes. Because the onSuccess() calls are nested, they'll execute in order (even if the futures are not all completed in order). The Listing 4 code is reasonably easy to understand but verbose. Listing 5 shows a simpler way of handling this case, using the flatMap() method. Listing 5. Handling completions with flatMap() def runFlatMap() = { task1(1) flatMap {v1 => val a = task2(v1) val b = task3(v1) a flatMap { v2 => b flatMap { v3 => task4(v2 + v3) }} } } The Listing 5 code is effectively doing the same thing as the Listing 4 code, but Listing 5 uses the flatMap() method to extract the single result value from each future. Using flatMap() eliminates the match / case constructs needed in Listing 4, giving a more concise form but keeping the same step-by-step execution path. Trying out the example The sample code uses a Scala App to run each version of the events code in turn and ensure that the time to completion (about 5 seconds) and the result (13) are correct. You can run this code from the command line by using Maven, as shown in Listing 6 (with extraneous Maven output removed): Listing 6. Running the events code dennis@linux-9qea:~/devworks/scala4/code> mvn scala:run -Dlauncher=happypath ... [INFO] launcher 'happypath' selected => com.sosnoski.concur.article4.AsyncHappy Starting runBlocking runBlocking returned 13 in 5029 ms. Starting runOnSuccess runOnSuccess returned 13 in 5011 ms. Starting runFlatMap runFlatMap returned 13 in 5002 ms. � The unhappy path So far, you've seen code to coordinate events in the form of futures that always complete successfully. In real applications, you can't depend on always staying on this happy path. Problems with processing tasks will occur, and in JVM language terms, these problems are normally represented by Throwables. It's easy to change the Listing 2 task definitions to use delayedFailure() in place of the delayedSuccess() method, as shown here for task4: def task4(input: Int) = TimedEvent.delayedFailure(1, "This won't work!") If you just run the Listing 3 code with task4 modified to complete with an exception, you get the expected IllegalArgumentException thrown by the Await.result() call on task4. If the problem isn't caught in the runBlocking() method, the exception is passed up the call chain until it's finally caught (terminating the thread if it's not caught). Fortunately, it's easy to modify the code so that if any of the tasks completes exceptionally, the exception is passed on to the caller for handling through the returned future. Listing 7 shows this change. Listing 7. Blocking waits with exceptions def runBlocking() = { val result = Promise[Int] try {) result.success(v4) } catch { case t: Throwable => result.failure(t) } result.future } In Listing 7, the original code is wrapped in a try/ catch, and the catch passes the exception back as the completion of the returned future. This approach adds a little complexity but should still be easy for any Scala developer to understand. What about the nonblocking variations of the event handling code, in Listings 4 and 5? As its name implies, the onSuccess() method used in Listing 4 only works with successful completions of a future. If you want to handle both successful and failure completions, you must instead use the onComplete() method and check to see which type of completion applies. Listing 8 shows how this technique would work for the event handling code. Listing 8. onComplete() handling of both successes and failures def runOnComplete() = { val result = Promise[Int] task1(1).onComplete(v => v match { case Success(v1) => { val a = task2(v1) val b = task3(v1) a.onComplete(v => v match { case Success(v2) => b.onComplete(v => v match { case Success(v3) => task4(v2 + v3).onComplete(v4 => v4 match { case Success(x) => result.success(x) case Failure(t) => result.failure(t) }) case Failure(t) => result.failure(t) }) case Failure(t) => result.failure(t) }) } case Failure(t) => result.failure(t) }) result.future } Listing 8 looks messy, and fortunately you have a much easier alternative: Use the Listing 5 flatMap() code instead. The flatMap() approach handles both success and failure completions without the need for any changes. Using async Recent versions of Scala include the ability to transform code during compilation by using macros. One of the most useful macros implemented so far is async, which transforms apparently sequential code that uses futures into asynchronous code during compilation. Listing 9 shows how async can simplify the task code used in this tutorial. Listing 9. Combining futures with async {} def runAsync(): Future[Int] = { async { val v1 = await(task1(1)) val a = task2(v1) val b = task3(v1) await(task4(await(a) + await(b))) } } The enclosing async {...} block in Listing 9 invokes the async macro. This invocation declares the block to be asynchronous and, by default, executed asynchronously, and it returns a future for the result of the block. Within the block, the await() method (actually a keyword for the macro, rather than a true method) shows where the result of a future is needed. The async macro modifies the abstract syntax tree (AST) of the Scala program during compilation to convert the block into code that uses callbacks, roughly equivalent to the Listing 4 code. Aside from the async {...} wrapper, the Listing 9 code looks much like the original blocking code shown in Listing 3. That's quite an accomplishment for the macro — abstracting away all the complexity of asynchronous events and making it look like you're writing simple linear code. Behind the scenes, a considerable amount of complexity is involved. async uncovered If you look at the classes generated from the source code by the Scala compiler, you'll see several inner classes with names like AsyncHappy$$anonfun$1.class. As you might guess from the name, these are generated by the compiler for anonymous functions (such as the statements passed to the onSuccess() or flatMap() methods). With the Scala 2.11.1 compiler and Async 0.9.2 implementation, you'll also see a class named AsyncUnhappy$stateMachine$macro$1$1.class. This is the actual implementation code generated by the async macro, in the form of a state machine to handle the asynchronous tasks. Listing 10 shows a partial decompiled view of this class. Listing 10. Decompiled AsyncUnhappy$stateMachine$macro$1$1.class public class AsyncUnhappy$stateMachine$macro$1$1 implements Function1<Try<Object>, BoxedUnit>, Function0.mcV.sp { private int state; private final Promise<Object> result; private int await$macro$3$macro$13; private int await$macro$7$macro$14; private int await$macro$5$macro$15; private int await$macro$11$macro$16; ... public void resume() { ... } public void apply(Try<Object> tr) { int i = this.state; switch (i) { default: throw new MatchError(BoxesRunTime.boxToInteger(i)); case 3: if (tr.isFailure()) { result().complete(tr); } else { this.await$macro$11$macro$16 = BoxesRunTime.unboxToInt(tr.get()); this.state = 4; resume(); } break; case 2: if (tr.isFailure()) { result().complete(tr); } else { this.await$macro$7$macro$14 = BoxesRunTime.unboxToInt(tr.get()); this.state = 3; resume(); } break; case 1: if (tr.isFailure()) { result().complete(tr); } else { this.await$macro$5$macro$15 = BoxesRunTime.unboxToInt(tr.get()); this.state = 2; resume(); } break; case 0: if (tr.isFailure()) { result().complete(tr); } else { this.await$macro$3$macro$13 = BoxesRunTime.unboxToInt(tr.get()); this.state = 1; resume(); } break; } } ... } The Listing 10 apply() method handles the actual state changes, evaluating the result of a future and changing the output state to match. The input state tells the code which future is being evaluated; each state value corresponds to one particular future within the async block. It's hard to tell this from the partial Listing 10 code, but from looking at some of the other bytecode, you can see that the state codes match up with the tasks, so state 0 means the result of task1 is expected, state 1 means the result of task2 is expected, and so on. The resume() method is not shown in Listing 10 because the decompiler wasn't able to figure out how to convert it to Java code. I'm not going to go through this exercise either, but from looking at the bytecode I can tell you that the resume() method does the equivalent of a Java switch on the state code. For each nonterminal state, resume() executes the appropriate fragment of code to set up the next expected future, ending by setting the AsyncUnhappy$stateMachine$macro$1$1 instance as the target of the future's onComplete() method. For the terminal state, resume() sets the result value and completes the promise for the final result. You don't actually need to dig through the generated code to understand async (though it can be interesting). The full description of how async works is included in the SIP-22 - Async proposal. async limitations Use of the async macro has some limitations because of the way the macro converts code into a state-machine class. The most significant restriction is that you can't nest await() inside another object or closure (including a function definition) within the async block. You also can't nest the await() inside a try or catch. These usage limitations aside, the biggest problem with async is that when it comes to debugging, you're right back to the callback-hell experience often associated with asynchronous code — in this case, trying to make sense of call stacks that don't reflect your apparent code structure. Unfortunately, there's no way around these problems with current debugger designs. This is an area seeing new work in Scala. In the meantime, you can disable asynchronous execution of async blocks to make debugging easier (assuming the problem you're trying to fix still occurs when you execute sequentially). Finally, Scala macros are still a work in progress. The intention is that async will become an official part of the Scala language in an upcoming release, but that will only happen when the Scala language team is satisfied with the way macros work. Until then, there are no guarantees that the form of async won't change. Conclusion Some Scala approaches to handling asynchronous events diverge significantly from the Java code discussed in "JVM concurrency: To block, or not to block?" With both the flatMap() and the async macro, Scala offers techniques that are clean and easy to understand. async is especially interesting in that you can write what looks like normal sequential code, but the compiled code executes concurrently. Scala isn't the only language to offer this type of approach, but the macro-based implementation provides superior flexibility to other approaches. Downloadable resources Related topics - Scalable Scala: Series author Dennis Sosnoski shares insights and behind-the-scenes information on the content in this series and Scala development in general. - Sample code for this tutorial: Get this tutorial's full sample code from the author's repository on GitHub. - Scala: Scala is a modern, functional language on the JVM. - "SIP-22 - Async" (Philipp Haller and Jason Zaugg, Scala Improvement Process): This Scala Improvement Process (SIP) proposal describes the intent behind the asyncand awaitconstructs and gives details of the code transformation used to build the state-machine class. - "An asynchronous programming facility for Scala" (Jason Zaugg et al, Github): Get the source code and latest documentation for the asyncimplementation.
https://www.ibm.com/developerworks/java/library/j-jvmc4/index.html
CC-MAIN-2017-26
refinedweb
2,824
55.64
.NET, pragmatism and geek cachet There's been a lot of talk about the iPhone and how it exemplifies good design, yadda yadda yadda. However, what I'd like to touch on today is a piece of design which frankly left me convinced that every person on an entire product team should be fired. I have this feeling often, but in this case it's not a feeling, it's a fact. Every single person on the Microsoft Windows Mobile team should be fired immediately. No exceptions. How can I possibly say that? Well, given the numerous bugs, inconsistencies, and general usability nightmares that is Windows Mobile I'd think it'd be pretty clear. However I'm not going to address that. I'm not going to address companies like HTC whose, should we say, unique ideas about how to implement a keyboard leave me taking 4 times as long to write an SMS with my QWERTY keyboard as my girlfriend with her 1234 keyboard. I'm similarly not going to scoff about the idiocy that is the Mobile contact system, or even worse the stupid inconsistencies between how you address an MMS as compared to an SMS. And if that blasted dictionary suggests ONE more hugely long word when the far more common short word fails to appear in it's choices...*sob* ... .... Okay, I'm back. I've dried my eyes and am now prepared to recount one of the most STUPID WTF's in programming history! Imagine some friends at a table having dinner. Imagine that one of the friends, being a complete moron, has actually been so mindbogglingly stupid as to have shelled out actual cash for the POS that is a Microsoft Windows Mobile HTC POC*1000 (Piece of Crap, new model). Let us imagine that these friends have an argument, let us further imagine that the Stupid Moronic Twit decides to settle the argument by opening the relevant Wikipedia page on his POC1000. Let us now skip past the imaginary scrolling down and down and down because the POC1000 renders wikipedia as a 5-char wide web page. Let us now arrive at the delightful point when he starts reading the portion that proves him right: "...to its diameter in Euclidean space... huh! WTF!?!" as the phone brings up, for a split second a dialog reading something along the lines of "The storage system is short of space, please clear some space immediately". Being a well trained monkey, used to the insane vagiaries of the POC1000 (e.g. the random requirement to align the screen before continuing, no matter that you were trying to phone the ambulance service or police) he immediately enters Settings, opens the Clear Storage application, ... and... the phone reboots. *Sigh* ah well, that's what you get for choosing a company that can't write software to save their lives, isn't it? Not so fast. Gather round to feel the true horror... "Wait, why is it telling me that it's setting itself up for the first time?" "Why is it making me answer stupid Customer Improvement queries?" The reality of course being that we don't need better customers, we need a better f****ing supplier. "Please, please, oh dear sweet Lord, please tell me that it hasn't wiped everything on my phone because it was marginally short of space for 5 seconds?!?!?" Surely any halfway competant engineer would know to delete the temp files and temporary internet files before moving on to contacts, emails, SMS's and system settings? Ah, there you see the problem. We're assuming that the numbnuts who coded this nighmarish piece of fly strewn horse manure were in fact competant. So here's my question for the day: "When is it acceptable to wipe your user's data in order to ensure that your stupid program can keep on wasting resources?" An extra 10 points if you work on the Microsoft Windows Mobile team. This is basically just a quick response to Roger's "WTF on WTF" rant since he doesn't allow comments. Basically, my advice boils down to: get over it. Someone, somewhere will always call WTF your code. The first thing to remember is that it's your code the person is critiquing not you. The second thing to keep in mind is that you can use such criticism to become a better developer. What doesn't work (trust me on this) is becoming defensive and angry. "What makes a person so arrogant to mock somebody elses error?" Skill, experience, and yes a fair bit of arrogance. All the best developers tend to be a bit arrogant. Keep in mind the reason Pieter was writing his WTF articles: to educate developers on what to do, and what to avoid. He could have done this with a lengthy article about the pros and cons (like I would write), but instead he chose to keep them short and to the point. The easiest way to do this is to just say "A is bad, B is good", or just "A is bad". Simple, easy little "rules" to help all the other developers stay on the track. "Not everybody is at the same level in programming" Absolutely, which is why articles that point out common mistakes that people make are good. By writing helpful articles, bad habits in the readers are hopefully reduced, and such developers become better. You only improve via learning, and the only way you'll learn is if you pay attention to teachers. "Some are experts in one language but when migrating to another language you might be used to certain methodologies" Indeed, but again, how are you going to learn that these mistakes are bad except by paying attention to the guys who are good in your chosen new language? In any case, I can't find any recent posts that point out something that is bad in C# but good in another language. All of the items give pretty good advice which would apply to any relevant language. I have my own minor disagreements with one or two of Pieter's posts, but on the whole, I'd still recommend them without a moment's hesitation. "There are many reasons why bad code slips in" Absolutely, 100% agreed. Roger goes on to mention legacy code, which is a common, but by no means exhaustive source of bad code. In my experience, the number one cause of bad code is developers who refuse to listen to criticism. The moment you mistake a critique of your code with a critique of you you get defensive, shut down, and get upset. This ensures that you do not learn from your mistakes. Your code isn't you, and frankly you should be grateful that people are picking up your mistakes and letting you know about them. Conclusion Roger then goes on to say "Writing code in a programming language is like writing a document in the English language. Would you post a blog if you found a grammatical error in somebody else's written document? Or if a foreigner gets their grammer mixed up do you laught at them? No, its stupid and a waste of time." The whole "Is LINQ to SQL dead or not" thing is making me angry and irritated all at the same time. However, I've decided that instead of complaining I should rather offer a public service. So, what I'm going to try and do is try and teach Tim Mallalieu, the Program Manager for LINQ to SQL and LINQ to Entities some straightforward English. He's written some clear posts before, notably his defence of Entity Framework against the Vote of No Confidence in it, so he's certainly capable of writing without vagueness. However, his two posts about the future of LINQ to SQL are pretty vague and covered in weaselese, so I'm going to try and help him regain his clarity. Let's start with Update on LINQ to SQL and LINQ to Entities Roadmap: Okay, there's a whole lot of filler here, so let's see if we can trim it down for him:. He followed this post up with a real gem "Clarifying the message on L2S Futures.", let's translate it piece by piece:: This is not too bad I must admit, but let's look at that phrase "a variety of responses". Hmm, if I look at the comments on the previous post, I get the following: Admittedly, I gave up counting about halfway through the comments out of sheer boredom, so there could be an uncounted late surge for Entity Framework, but I'm going to call this one. Anyway, if we look only at the comments related to this issue we get: Hmm, I admit that this could be called a "variety of responses", but my money would be on "overwhelmingly negative responses". Anyway, let's continue:). Is LINQ dead? No… heck no… There is a big difference between LINQ to SQL and LINQ. LINQ is Language Integrated Query, today we ship the following sources over which one can execute a LINQ query:. Okay, I'm not sure how many people thought that LINQ itself was being killed, but I'm guessing not many, so this portion is a clear strawman that serves no useful purpose, and we could cut it.. Buzzphrase list: "carry forward", "differentiated", "evolved", "intersection", "asks", "convergence", "strategies", "triangulating", "solution" Right, let's try this again. Next part:. Hmm, what are "investments...based on customer feedback"? I also love all this talk about being open and transparent whilst using weaselese in abundance. Here's the translation: Is LINQ to SQL Dead? Yes, but we will fix bugs.Tim MallalieuProgram Manager, Entity Framework Yes, but we will fix bugs. Conclusion Personally, I'm kind of conflicted about this. On the one hand I see their point that there should only be one data access strategy, and LINQ to Entities is clearly the bigger brother in this regard. If it were any other people running this, I'd be cheering from the sidelines. However the Entity Framework team have a history of ignoring their customers, being opaque and secretive, and delivering a bloated and inefficient product that did not address the most common requirements, despite being warned that this would happen. They've promised to be more transparent and open, but these two posts are opaque and vague. Personally, I wish them luck, and hope that they can indeed deliver a system that merges the best of LINQ to SQL and LINQ to Entities. However, until such time as they actually start speaking English and being forthright, I won't believe them. Right, so in Part 1 we looked at the requirements for a Discovery Service and in Part 2 we looked at how we'd host the WCF service. Now it's time to look at the UDP itself. First off though, if you look in Part 2, at the declaration I've got for DiscoveryServer, you'll see I'm inheriting from a DiscoveryBase. This base class will handle most of the UDP stuff, since both DiscoveryClient and DiscoveryServer need a very similar set of operations. Let's look at the most important method on DiscoveryBase: private UdpClient _udpClient; private long _connected; private int _timeToLive = 2; private IPAddress _address; internal void Prepare(IPAddress address, int localPort) { // Ensure we're not already discovering if (Interlocked.CompareExchange(ref _connected, 1, 0) == 1) throw new InvalidOperationException("Already in discovery mode."); // Create the client _udpClient = new UdpClient(localPort); // If it's broadcast we set the broadcast flag if (IsBroadcast(address)) _udpClient.EnableBroadcast = true; // If it's multicast we join the multicast group if (IsMulticast(address)) _udpClient.JoinMulticastGroup(address, _timeToLive); // Store the location to connect to _address = address; } As you can see, it's not terribly complicated. There's a little bit of concurrency logic to ensure we're not already discovering, we create a UdpClient object, and then either set it to broadcast or join a multicast group depending on the IP address. Finally we cache the address so that our child classes can access it via the Address property. _timeToLive is an interesting property, it defines how many router hops any multicast broadcasts will go. For now, I've just set this to 2, but you could easily make it configurable. Now let's hop back to DiscoveryServer and have a look at how it kicks off it's discovery: public void Publish(IPAddress address, int port) { Prepare(address, port); // Set up the discovery service _host = new ServiceHost<IDiscoveryService>(this, _address); Binding binding = BindingAddressParser.CreateTransportBinding(_address); _host.AddServiceEndpoint(typeof(IDiscoveryService), binding, _address); _host.Open(); // Now asynchronously listen for any incoming requests Client.BeginReceive(Receive, null); } So, as you can see, it calls Prepare on DiscoveryBase, in order to ready itself for UDP operations. It then begins hosting the IDiscoveryService on a transport and binding determined by an address which is passed into the DiscoveryServers constructor. Finally it kicks off an asynchronous receive operation on the UDP client. Let's have a closer look at Receive: private void Receive(IAsyncResult ar) { if (Connected) // This will be false if the UDP client has been closed { IPEndPoint remoteEP = null; byte[] result = Client.EndReceive(ar, ref remoteEP); // Now asynchronously listen for any incoming requests Client.BeginReceive(Receive, null); // Is there actual information to fetch? if ((result != null) && (remoteEP != null) && (result.Length > 0)) { string message = Encoding.ASCII.GetString(result); if (message == @"get\services") { // Handle the get services request by sending the address where the service information is hosted message = BindingAddressParser.ResolveAddressHostName(_address); byte[] response = Encoding.ASCII.GetBytes(message); Client.Send(response, response.Length, remoteEP); } } } } So, what happens is we check if we're connected (the Connected property on DiscoveryBase returns whether the _connected field we saw in Prepare is equal to 1), we then kick off another asynchronous receive just in case there's more requests on the way. Then we decide whether it's a valid request. If it it, we send the address where we hosted the IDiscoveryService. In Part 4 we'll start looking at the DiscoveryClient. Right, so in Part 1 we looked at an overview of how this discovery system should work. Now let's start looking at specifics. Before we start diving into the UDP stuff, let's look at the information that the server will publish and how this will be accomplished. If you recall, the mechanism I suggested was that the server host a normal WCF service that held the information about the services, and that the UDP would be used to provide access to this service. So let's start with the WCF side. First off we're going to require our ServiceInfo class. This is a relatively simple class, which contains an Address property and a set of Name/Value pairs. Needless to say, it needs to be decorated with the DataContract attribute. To provide access to this information we will have the IDiscoveryService interface: namespace Sanity.Net{ [ServiceContract] internal interface IDiscoveryService { [OperationContract] ServiceInfoCollection GetServices(); }} You'll note that I made this interface internal, since there's no real call for outside applications to access it without going through the Discovery system we're writing. Our next step is to create a DiscoveryServer class which will take the address it needs to publish as a parameter in its constructor. In order to keep things simple, I'm only going to allow the default binding for the transport mechanism. As I discussed in Part 1, discovery is not the place to get fancy with communication methods, it's where you find out about the fancy communication methods. We'll create a Publish method on the DsicoveryServer, that will create the service host and open the service endpoint: private string _address; private ServiceHost<IDiscoveryService> _host; public void Publish(){ // Set up the discovery service _host = new ServiceHost<IDiscoveryService>(this, _address); Binding binding = BindingAddressParser.CreateTransportBinding(_address); _host.AddServiceEndpoint(typeof(IDiscoveryService), binding, _address); _host.Open();} Now, you'll notice my BindingAddressParser, that's just a little class that will infer the binding from the address, NetTcpBinding for "net.tcp" and so forth. Our next step is to add our ServiceInfoCollection to the class so that services can be given to the discovery server: private ServiceInfoCollection _localServices; public ServiceInfo AddService(string address){ address = BindingAddressParser.ResolveAddressHostName(address); return _localServices.Add(address);} Finally, we can implement the IDiscoveryService interface: [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]public class DiscoveryServer : DiscoveryBase, IDiscoveryService{ ServiceInfoCollection IDiscoveryService.GetServices(){ return _localServices;} ServiceInfoCollection IDiscoveryService.GetServices(){ return _localServices;} } Okay, we now have a server-side that will take services with arbitrary information and make them available on TCP/IP. In Part 3 we will look at making this available on UDP as well. Just in case you thought secretly installing malware on a machine wasn't bad enough, it appears that Apple aren't actually interested in resolving security flaws in Safari. So it's bug-ridden and they're happy with that.This has led Microsoft to take the unprecedented step of advising Windows users to restrict their use of Safari. So, I guess the question of whether Apples products were 'more secure' than Microsofts due to inherent security or installed base has been definitively answered. Metadata Exchange mechanisms such as WSDL are all very well and good, but they fulfil one part of the automatic discovery experience. If you look at WCF a service consists of three parts: So, Metadata Exchange helps you figure out the Contract if you're given the Address and sometimes the Binding. All very well and good for assisting us developers get running in using a service. However, how about a scenario where you already know the Contract but you need to figure out the Address and/or Binding? In other words, what about most deployment scenarios? How can you discover where to find the server? One way would be to have a fixed location which your client connects to in order to query it for server information. However, if you can hard-config this repository, why can't you just hard-config the service location too? Setting the service location in the client configuration file seems to be a fairly common approach. Another option would be to capture the service location during installation or when the application first runs. This is fairly common as well. However, this assumes a level of technical ability and knowledge on the part of the installer/user that may not be justified. Also, what happens if the service location changes? So, what we would ideally need is a mechanism to help enable the various discovery options. Happily there is a technology ideally suited for discovery, and it's called UDP. UDP is a networking technology fairly similar to TCP/IP. Unlike TCP/IP it does not support connections, each message is sent fire-and-forget. There's no guarantee of delivery, and if your message is broken into multiple packets there's no guarantee what order they'd appear in. This makes UDP a bit hit and miss for most business applications, which is why it's very rarely used by most developers. However there are two really cool features of UDP: broadcast and multicast. Broadcast allows you to do is to send a message to all the machines on the same subnet, which is fine for discovering the machines near you, but not so good to find servers, which are usually on a different subnet. Broadcast also has the downside that it sends a lot of traffic, one message to each machine on the subnet. Multicast is different. Unlike with broadcast, you have to join a multicast group, and then messages are routed to the machines in the group. Since this is only the machines interested in the message, the number of messages flowing across the network is smaller. So, if we're looking for machines on our network, UDP would seem to be an ideal mechanism. We'd want to keep the messages small so as to avoid any issues with packet ordering. Now, if we're publishing generic information about various services, we don't really know how much information we'd be sharing. So ideally, we'd want to avoid sharing this generic service information across UDP. What we can easily share is the location of a more reliable service from which this service information can be gleaned. So the next question is how the whole UDP thing should work. A common approach is to have the servers broadcast their information at a fixed interval. This has the advantage of simplicity, but it isn't terribly elegant. Even ignoring the fact that the servers are often sending out data that no-one wants, the client machine would sometimes have to wait a while until the server next send out it's data. So, whilst a bit more complex to code, it makes a lot of sense for the client to send out a request, and the server to respond. So, what we're looking at here is a three-phase discovery mechanism: So, the client UDP request would be fairly simple, some kind of "Please give me service information" message such as "get\services". The server response would also be relatively simple, an address e.g. "net.tcp://myserver:20231/Discovery". I'm going to assume that we're not going to get into complex binding scenarios such as security and transaction information. This is simply a location to get more information, so we can keep it to the default bindings. The next question to ask is what information the server should share about the services it exposes? Well, the address of each service would be an obvious starting point. However, what else? Binding information? But that's WCF specific, and who said the services being exposed are WCF? So it probably makes sense to simply allow each service to have a set of properties: name/value pairs that contain contextual information about the service. In Part Two we'll start looking at how we're going to implement all this. Marcus Ranum has an article titled The Six Dumbest Ideas in Computer Security. I strongly suggest that anyone interested in security read it, and his other articles too. It's quite an old article, but someone put it on proggit and it made me remember it. In fact, I'd say that this article was seminal in guiding my undertstanding of computer security. For those of you too lazy to click on links, a swift summary: A point he makes about #3 and #5 is that if these worked they would have worked by now. IE would be the most secure browser on the planet and users wouldn't click on attachments anymore. Do yourself a favour, go and read the original article. It's well worth it. I recently received a chain email from a friend where the original author was complaining bitterly about the massive electricity price hikes being mooted by Eskom (our state-owned electricity company) in order to pay for their build programme. The author felt that since it was Eskom and government who were asleep at the switch and allowed the power situation to reach its current dire state, that the electricity price should not be raised. Instead, the author suggested that the power stations be built using the surplus that government has accumulated over the past few years. It's in a slightly histrionic tone, but I think many people would sympathize with the author's points, certainly the 278 people who had signed it by the time it got to me did. The Eskom situation easily inflames people since we're not only being slammed with a price hike, but also rolling blackouts, and to top it all off, a large amount of the problem seems to be from fat cats keeping their eye on profitability rather than on long-term viability. To top it all off, the stories about Eskom supplying Zimbabwe with free electricity added the outrage over our government's dithering on that country to the issue. What I'd like to do is look at things from a less emotional point of view. I'm incredibly lucky in having some inside information about this, since certain colleagues have done modeling on this issue. I don't unfortunately have the raw figures, so I'm going to have to try and remember them as best I can. The first thing to remember is that complaining about Eskom or government or whoever may make us feel a lot better, but it won't actually solve anything. What has to be dealt with is the situation that exists right now. What this boils down to is reserve margin. From the Wikipedia page about Eskom I see that their overall capacity is about 39,046 MWe. So, that's the amount they could produce in a perfect world. However, the world is not perfect, and there are situations where you have to take a power station offline in order to maintain it, and of course you have unplanned outages as well. So, the idea is that the total amount you can produce exceeds what you need by a margin, the reserve margin. It is this that has been allowed to drop too low. Eskom have enough generating capacity, in theory, to supply all of South Africa's needs. However, to do that, they'd have to stop maintaining the power stations, and we can all guess where that would lead us. The ideal reserve margin seems to be at about 15%, and ours is about 6-8% right now. Now an important point is that this reserve margin is over our peak usage. The usage of electricity during the day is similar to the graph you see here. Electricity usage is low at night, climbs rapidly in the morning, dips a bit during the course of the day, and then climbs in the evening before settling down again. So our problem is that our usage is rising above the ideal reserve capacity during the day, and this is why Eskom is being forced to have these blackouts (I refuse to call it load shedding, its bloody rolling blackouts, not some saccharine platitude). So, what can we do about this situation? Well, two main approaches are fairly obvious: 1. Increase supply 2. Decrease demand Let's look at them in a bit more detail. Well, this is nice and simple it would seem: build more power stations. All well and done, but it costs money to build power stations. More importantly, the big ones take a long time to build. The following are some of the things we can do: Buy more power from neighboring countries Unfortunately we're by far the biggest producer and consumer of electricity in the region, so the amount of power we can buy is limited. Eskom recently upped the amount we get from the Cahora Bassa hydroelectric station by 250MWe if I remember correctly. It will help, but it's a drop in the ocean. Build more power stations There are a few main kinds of power stations we can build. Coal powered stations are huge and take a long time to build. On the upside they produce vast amounts of power very cheaply. Eskom are building two huge coal powered stations called Bravo and Medupi which will start coming online in about 2012. They are also de-mothballing another three, but they're not nearly as big. Another main type of station they can build is gas turbine. These take far less time to build, but they also produce far less. Unfortunately they also cost vastly more to run as well, so the electricity from them is very expensive. Normally, because they can be switched on and shut down fairly easily, they are used only to deal with demand spikes. Hydroelectric has the advantage of being fairly green and fairly cheap. Unfortunately we live in an arid country, so the amount of these we can build is limited. Finally, we have nuclear stations. These make an awful lot of sense, the electricity from them is fairly cheap, like coal, they're "base load" stations. But, like coal stations, they take a long time to build and are very very expensive. "Green" electricity production such as wind farms and solar is also a possibility, but tends to be fairly limited in the amount of power they can produce as well. Plus, they do tend to be expensive. One of the nice things about them is that they can start coming online fairly swiftly, and every little bit helps. So, it looks like a good strategy would be to build some green producers and gas turbines, and boost the amount of coal and nuclear stations in the long term. This is in fact exactly what Eskom are proposing to do. Again, I might have these figures a bit off, but they plan on spending about R1, 3 trillion over the next 10-15 years on building new capacity. This is an awful lot of money, and it has to come from somewhere. Encourage cogeneration Cogeneration is quite interesting. There are quite a few industries in South Africa that produce an enormous amount of heat from their processes. What happens with cogeneration is that this heat is channeled into turbines which then provide electricity to the national grid. Now, a company is not going to do this out of the goodness of their hearts, they're going to expect to be paid for the electricity they supply. Unfortunately, the low price it is at right now is not enough to make this feasible. However, the increases Eskom is proposing will move us into a position where cogeneration will become viable. The amount of cogeneration capacity may be as high as 5,000 MWe, basically the same as a huge coal-fired power station. Encourage independent power producers This is in fact what government was hoping for, why they didn't want Eskom to build more power stations. They were hoping that companies would come to South Africa and build power stations. Unfortunately, for some reason, companies did not flock to compete in an environment where their only customer set the price, and more importantly the price was too low for anyone to compete with. Building a power station is expensive, and you have to recoup your capital costs somehow. Eskom didn't have to, since they already had the power stations, and had pretty much paid them all off. Anyone else coming onto the market would have to compete in an environment where they would be unlikely to be able to make a profit. Interestingly enough, the price increases that Eskom is proposing will likely make potential independent power producers interested. It would now be possible to compete. This is largely because Eskom is now undergoing the same kinds of massive capital costs an independent producer would have to go through. Encourage energy-negative houses In some countries, the power utilities are required to buy back any power you produce at home. So, if you have solar panels and your house is producing more power than it consumes, then you get paid back. This is a quite nice idea for encouraging energy efficiency, but it is unlikely to be terribly effective in South Africa. Even with Eskom's price increases, electricity would still not be so expensive as to make this profitable for the individual concerned. In any case, it is feasible for only relatively well off households, which is a small percentage of the total. This one is fairly obvious, since Eskom are using rolling blackouts as a mechanism to force decreased demand. What are some other alternatives? Encourage energy efficiency in households and offices This is fairly obvious. Switching to energy efficient light bulbs can produce a marked saving in power, geyser blankets and timers similarly help. More importantly, timers can be used to drop demand during times of peak usage. If every single person who has a geyser switched it off from 6am to 7pm, they wouldn't greatly inconvenience themselves and it would make a significant reduction to peak load. Switching from electricity to gas would probably help a bit, but not as much as you'd think, largely because you don't really cook during peak times. Tumble dryers and air conditioners are proverbially profligate in their energy usage. You could look at solar water geysers, but I think you'll find that a timer is just as effective, and much cheaper. Apparently up to 15% of your house's energy usage is consumed by appliances which are plugged in, but "off" in a standby mode. Your TV, hi-fi, cell phone charger you left plugged in and so forth. We could encourage people to unplug these. However, this raises a problem. All these ideas either cost the consumer money or they are a pain in the neck. Why would people do these things? South Africa is remarkably wasteful when it comes to electricity, a hangover from decades of cheap power. I've heard numerous suggestions such as punishing people who use "too much" with punitive fines. However, who decides what's too much? What if I have 6 people in my house and you have one in yours? It becomes very, very tricky. However, capitalism has a nice and simple way of encouraging people to use less of a thing whilst at the same time punishing those who use "too much". It's called raising prices. Unfortunately, people can easily become habituated to small changes, so to force people's behavior to fundamentally shift you have to shock them, and a big increase is likely to accomplish that, whilst numerous small ones will probably not. Shut down industries This is not a good one. Shutting down mines and aluminum smelters saves power, but it harms the economy as well. Badly. In any case, as with normal consumers, the best way to get industry to use less power is to charge them more for it. A lot more. This will lead to inflation, true, but it is far better to see some inflation rather than entire sectors of our economy being brought to a standstill. Unfortunately our Reserve Bank has an itchy trigger finger when it comes to inflation and is pursuing a punitive interest rate policy to keep it in check. I think we will have to let the Bank allow the inflation caused by Eskom's increases to work their way through the economy without raising interest rates, even if it does mean some spiking in inflation. If not, the Bank may all but shut down the economy. This would help conserve power, but not in a way any of us are likely to enjoy. Punitive blackouts This is what we have right now, where rolling blackouts happens no matter what, unless you cut your usage by 10%. The only problem is that Eskom and the municipalities are not geared to blackout small areas, so it's groups of suburbs that go down together. Ideally, in my opinion, they should try and get to a point where a blackout unit is about 10-20 houses. Then it becomes feasible for communities to encourage and work towards energy efficiency in their area. If they do so, and cut their usage by 10%, they stop getting blacked out. Right now, it's not really practical to lead a community effort to cut usage by 10% across all of Johannesburg, but a street, now that's doable. When you're sitting in the dark and the guys in the next street have lights, maybe you'd consider changing your light bulbs or putting in other energy saving mechanisms. Denying access to power This is another approach that Eskom are using; they're simply refusing to provide power to new developments. The long term effects of such a strategy will be horrific though. What they're essentially doing is stopping most new fixed investment in South Africa, investment we critically need for our economy to grow. This cannot continue for very long without causing a massive problem. Changing the peak structure This is one I find personally interesting. The idea here is not so much to conserve power, but rather to shift it, to flatten out the peaks of demand by moving that demand to the troughs. An obvious way of trying this is to charge more for peak times, just as the cell phone operators do, maybe even give "free" power away in off-peak times. Again, the difference would have to be big enough to make people sit up and take notice. Another very interesting proposal has to do with time zones. The idea here is that we split South Africa into two time zones. I'd guess that Cape Town, Port Elizabeth and Bloemfontein would fall into the one time zone, and Johannesburg and Durban into the other. This morning the sun rose at 07:11 in Cape Town and at 06:17 in Durban. So, if South Africa is in two time zones, an hour apart, that usage pattern above would be flattened out a bit, and widened. I personally find this idea fascinating and well worth the attempt. Changing time zones would not cause too much inconvenience in any case. For goodness sakes, have you ever tried to get hold of a Capetonian before 9am? Not a chance. So, this would just formalize that Quite simply, the price hikes that are being proposed are important and necessary. There is the worry about how they will affect the poor, obviously, and how the inflation created would similarly add pressure to them. However, the poor would be worse affected by our economy tanking and their ranks being swollen with newly unemployed. Right now, the fundamentals of our economy are in pretty good shape. Besides our trade deficit which is a bit worrying, the only other cloud is this power problem. If we solve it, then there's no reason our economy can't carry on growing. Of course, that would increase demand for electricity even more. You win some and lose some. Anyway, I digress, the point is that there is a lot we can do to increase supply and most of it is being done or planned for. However, to increase supply enough will require a significant increase in electricity prices; effectively they are going to have to double over the next two years. The problem is that the supply increases will largely take a long time to come on stream; we simply can't build the power stations quickly enough. Therefore, for the short and medium term we have to look at constraining demand. Blackouts and stopping new developments will quite simply bring our economy to a screeching halt. We're doing these now, because we don't have any choice, but we must aim at getting rid of these measures at the earliest possible time. That means consumers, business and industry coming to the party on saving power. Eskom and government's pleas to consumers and business have not had much effect on people's behavior. Personally, I think part of the reason for that is the anger at them for letting this situation develop in the first place, there's a sense that it's "their problem". Unfortunately, it's not, it's our problem, and will remain so for some time to come. A lot of people are understandably unhappy about the proposed price increases and see it as being punished for someone else's mistakes. Certainly there is an element of that, but think about it this way. For the last decade or so, you've had electricity at a discount. Those discounts are coming to an end. Sure, it's not nice, and it would be easier to swallow if the lights stayed on the whole time, but they were at a discount, and prices are just moving to where they should have been. Eskom and governments mismanagement extended to not increasing prices as much and as fast as they should have been. So in a sense we all benefited from their mistake in the past, and are suffering for it in the present. A final thought. Whenever I have issues that afflict me, work or personal, I always try and think about two things: It very rarely helps matters to worry about who to blame, all that does is distract you from the solutions. In this case, yes, there are definitely people to blame, and I doubt there's much many of us could have done in the past, since we didn't even know about this problem. However, we can look to the future. By conserving power, especially at peak times, even if all you do is cook a little later or install a geyser timer you can actually make an important difference. More importantly, by just being a little more energy conscious you will be planning for your future. I assure you, this power issue is the tip of the iceberg. Energy costs are rising worldwide, and this trend is going to continue. We will look back on this power cost increase in a decade and laugh at how little power cost in 2010. There seems to be a serious issue with Microsoft lately, and it seems to be a strategic and executive issue. They have, for a couple of years now, been desperately running around trying to own every technology market they're not in whilst at the same time allowing Windows, their core product to "collapse". Witness their doomed attempt to take on the iPod with the Zune. The question has to be asked, why? I mean, I can understand why Creative or Sony or another portable media company might try and rush out ill-advised competitors to the iPod, it's a major part of their business after all. But why for goodness sakes would Microsoft decide to spend a fortune taking on an established incumbent? Especially after waiting years for them to cement their lead before getting involved? Forget the numerous complaints about the Zune itself; I'm just trying to understand their strategy here. Let's not forget their decision, many years ago, to take on the games consoles. Well, that seems to have worked out okay, although it sure cost them a ton of money. Now, why did they do that? Well, the worry was that consoles might supplant PC's, a reasonable concern I guess, unlikely, but possible. They sure couldn't have done it to sell software, since MS games were few and far between at the time. So now we get onto their biggest strategic blunder; their desperate attempts to unseat Google as the king of search. It seems that Ballmer and Co are so terrified of Google and the *gasp* massive advertising revenues they earn that they are literally willing to bet the entire company on a chance, not a certainty, but a chance that they can eat into this revenue stream. Financials Let's look at some figures, to be precise the 2007 Q4 earnings reports from Microsoft and Google: So, Microsoft has assets of 2.5 times Google's, it's income is 3 times, and it's market cap is 1.8 times. Now, this is by no means a complete picture. For starters it is my opinion that Google is in fact significantly overvalued, however I'm certainly no expert. Up until fairly recently I'd also have said that Microsoft is undervalued, but I no longer think that. This is not because I think that the company as a whole is valued correctly, I just feel that the utterly idiotic actions recently demand a discount to be placed onto the Microsoft valuation. Yahoo! To be precise, the idiocies to which I am referring is the Microsoft desire to buy Yahoo come hell or high water. As a matter of interest, Yahoo has a market cap of a mere $37,860,000,000, meaning that a "perfect" merger that inflated Microsoft's market cap by Yahoo's would result in Microsoft gaining a mere 14%. Needless to say, no merger goes that easily. In this case you're merging two companies with incredibly different cultures and overlapping products, so the value to be gained from the deal is at a significant discount. The question has to be asked: what will the Yahoo deal do for Microsoft as a company? The answer: not a helluva lot. I'd imagine most of the really good Yahoo developers will not be too keen on working for Microsoft, so we can expect a raft of defections. Then Microsoft will have to shut down and merge various divisions, paying massive retrenchment packages. The final result: an even more bloated and top-heavy Microsoft with a few niche internet products and one or two good ones (flikr for example). Many years ago I worked at a large South African IT company with management who'd seriously stuffed up. It seemed that, in order to hide from the shareholders the magnitude of their mistakes, they engaged in acquisition after acquisition. You see, due to all the merger activity, it was incredibly difficult to compare one year's performance with another's, since the company profile had changed so much. Needless to say, the constant, poorly thought out acquisitions were part of the problem, and eventually resulted in the company all but collapsing. What are they doing? Given Steve Ballmer's Bush-esque charge for this Yahoo deal, ignoring overwhelming opinion that it's a bad idea and seemingly paying attention only to that tiny group of people who think it's a good idea, one has to ask what his motives are? Basically, I'm concerned that Microsoft is making misstep after misstep, from Vista itself and the Vista-capable debacle, to the Zune, the hugely overpriced Facebook deal to Yahoo, and many, many others. As a .NET developer I have a vested interest in seeing Microsoft succeed. Sometimes that means chiding them for their mistakes. However, I am growing increasingly concerned about the direction Microsoft executives have been taking recently. If I was Google, and had to pay someone to destroy Microsoft, I'm not sure if I could get them to do a better job than the current rash of poor decisions. My advice to MS I wish Microsoft would stop panicking about every upstart industry or internet fad that comes along, and focus on their products. Get Windows to where it should be, and you can probably kiss Apple OS and Linux goodbye. Work with hardware manufacturers well enough and you could possibly kill off MacBook too, or at least relegate it to a niche market. Drop the Zune, let Apple keep that market, with enough care you can effectively turn them into a consumer electronics company like a Sony. In other words, make their flair for design other people's problem, not yours. Make a decent online-capable rich client Office, along with web versions, obviously not as full featured, and you can kill off any possible Google Documents challenges. Forget advertising, it's a niche and fickle market. Let Google have it, there's already some rumblings of discontent amoungst advertisers around Google's opaque pricing strategies. Let them deal with that pain. Sure they're going to control search for a while to come, which means they will effectively be everyone's landing page. So what?Oh, and the #1 strategy? Install an ad blocker in IE, and offer to switch it on when the users install IE. You know, something like "Adverts can slow down your browsing experience, and distract from the content on the page". Something like that. Make sure it blocks Google ads. Yeah, sure you're going to effectively de-monetise the web, but since your web efforts have been, ahem, well, not as successful as you'd like, who the hell cares? So half the internet companies subsisting only on advert revenue would shut down almost immediately, why the hell would this be your problem? Best of all, make the ad blocker easily replaceable and you probably wouldn't even have to worry about anti trust issues, especially if you gave up on competing on search. A friend of mine is looking fo ASP.NET developers. He's basically looking for mid-level to more senior people, who know their way around the frameworks. The person would have to be a self-starter able to work without constant supervision. If you're interested, his name is Peter Wright and you can get hold of him on (082) 610-0605. Dunno how many of you read John Lilly's rant about Apple pushing out their Safari browser via iTunes update the other day? Basically he was rightly upset that Apple were using what should be an update and patch delivery mechanism to subtly trick users into installing their Safari web browser. His main point was Apple has made it incredibly easy — the default, even — for users to install ride along software that they didn’t ask for, and maybe didn’t want. This is wrong, and borders on malware distribution practices. I couldn't agree with him more. The issue is not so much that they deliver Safari via Apple Update, but that it's checked by default every time. The amusing thing is the usual strident defenses from Mac fanboys: ... What makes these vociferous justifications all the more poignant is the recent failure (again) of Apple in the PWN 2 OWN hacking contest. Now, for two years running, Apple has finished dead last due to security glitches in Safari, the very same Safari they are so eagerly trying to force down the throats of their iTunes customers. Let me give you a brief synopsis of the hacking contest: The Mac fell 2 minutes into Day 2. As of this time neither the Windows or Linux machine have been compromised, with Day 3 still to go [Update - Vista fell 7 hours into Day 3]. The Slashdot thread on this is also illuminating, with the most coherent fanboy conspiracy theory the severely addled idea that the researchers wanted a Macbook more than the other laptops. Therefore, they decided not to attack the other machines and concentrated on the Mac, clearly ignoring the fact that $20,000 or $10,000 can buy you quite a few Macbooks. Another idea from the sheep was that the Mac is so secure that the hackers wanted the challenge of attacking it first. The mind seriously boggles, but I guess once you enter the Reality Distortion Field your mind goes blank and you start drooling like a slack-jawed idiot. One of the best responses I saw to one of the fanboys was this one: Really? Because I see the Mac having come out as the clear loser in a head to head contest on a level playing field against the two biggest competitors it has in the laptop market. Seems pretty simple to me. Now let me stop giggling and get back to my point, I'm sure I had one. Do I think that Mac is crap because of a Safari flaw? No, not at all. Besides my digression into the vagaries of fanboyism, all it says is that Safari is not very secure compared with IE7 and Firefox. In fact, it's so insecure that twice it's been the cause of Mac failure at this competition. This is the application that Apple has decided to share with us in an underhanded and sneaky way. They are surreptitiously installing an application which provides known attack vectors into the operating system. More particularly they're supplying this to people who probably have more secure browsers already, such as Firefox or IE. Does this strike anybody as strangely familiar? (Hint: Sony rootkit) Now sure, this is not at all to the same degree, and there's no guarantee that Safari on Windows is going to be as insecure as Safari on OSX, I just don't think Apple should be slipping this kind of stuff in on the sly is all. Update The Vista machine went down 7 hours into the third day due to an Adobe Flash vulnerability, leaving Ubuntu Linux running on a Sony Vaio as the last machine standing. Now what this means is that the Mac was undone by an application that Apple pre-install on their computers, whilst Vista was undone by a third party application. Given Vista and IE7's vaunted security, it should not be possible to hijack the computer, no matter how many bugs there are in Flash. Nonetheless, Microsoft are not pushing out Flash (or even Silverlight for that matter) silently, and you have to choose to install it, a choice Apple is still deceitfully trying to take away from iTunes users. Let me say it again, deviously installing software that opens your computer to attack vectors is pretty much the definition of malware. The difference between Apple’s tactics and Sony BMG’s is not a difference in principle, merely one of degree. What's something everybody wants for their application, but very few people have the time to deliver? Performance. Let's face it, in most software projects, performance requirements are relegated to the very end of the project, when every knows they won't have the time to address them. In one sense this is a good thing, as one of my biggest bugbears is premature optimisation. Premature optimization is the root of all evil. - Hoare's Dictum, Sir Tony Hoare Premature optimization is the root of all evil. - Hoare's Dictum, Sir Tony Hoare Now keep in mind that by denigrating premature optimisation I am not saying that you should never think of performance when writing an
http://dotnet.org.za/codingsanity/default.aspx
crawl-002
refinedweb
9,023
61.26
27 July 2012 11:05 [Source: ICIS news] SINGAPORE (ICIS)--?xml:namespace> The refinery and cracker operator’s net sales rose by 11% year on year to Bt72.3bn in the second quarter, the company said in a statement. In the first half of this year, the company posted a net loss of Bt3.12bn, compared with a net profit of Bt6.11bn in the same period a year earlier, the company said. The firm’s net sales for the January-June period of this year rose by 20% year on year to Bt146.3bn, it said. IRPC is a subsidiary of ($1 = Bt31
http://www.icis.com/Articles/2012/07/27/9581560/thailands-irpc-swings-to-q2-net-loss-of-128m.html
CC-MAIN-2015-18
refinedweb
104
86.3
Search: Search took 0.01 seconds. [OPEN] Wrong Theming document about location of namespace configuration Ext.Loader: requires doesn't resolve namespace Namespacing: ExtJS vs Sencha Touch: Ext vs Touch? How to fix 404 during application loading Jasmine testing, how to set it up correctly [OPEN] Need ability to add "." in namespace Question regarding namespace in app.js How to deal with stores in another namespace How to avoid using namespace in following example Using TabReorderer as a plugin Sencha Profiles w/ sub classesStarted by StevenRaines, 24 May 2012 11:58 AM - Last Post By: - Last Post: 1 Jun 2012 7:37 AM - by StevenRaines Call namespaced function inside iframe. Dependencies & MVCStarted by jonathansimmons, 23 Mar 2012 9:18 AM - Last Post By: - Last Post: 23 Mar 2012 12:11 PM - by jonathansimmons Issue with Ext component registered and with Using NamespaceStarted by SumathiVijay, 23 Feb 2012 12:48 AM - Last Post By: - Last Post: 28 Feb 2012 9:16 PM - by SumathiVijay How to structure (my) mobile website?Started by RandomString, 24 Jan 2012 8:50 AM - Last Post By: - Last Post: 26 Jan 2012 2:54 AM - by RandomString Namespace Problem, Inheritance namespace is undefined EXTJS4Started by utkarshk.leeway, 23 Nov 2011 12:25 AM - Last Post By: - Last Post: 23 Nov 2011 5:15 AM - by utkarshk.leeway How to get association to play nice with MVC namespace NetworkError although i have set the right paths for Ext.Loader gxt 3.x and 2.x compatibility JS-namespaces for folder structur in php-class-directory????Started by Matthias_WB, 9 Aug 2011 9:07 AM - Last Post By: - Last Post: 9 Aug 2011 9:07 AM - by Matthias_WB Access data store from different namespace Apply custom namespace to Ext custom build [ClassManager] Call Ext.define with same name, The ns will be incorrectly modified. namespace issue - works in IE but not in Firefox Results 1 to 25 of 29
http://www.sencha.com/forum/tags.php?tag=namespace
CC-MAIN-2014-42
refinedweb
321
61.26
Originally posted on towardsdatascience. Finding bottlenecks and optimizing performance using cProfile If you’ve ever written a line of code (or even tens of thousands of lines), you’ve surely wondered “Why does my code take so long to run?” Answering that question isn’t always simple, but it can be easier if you search for answers the right way. Perhaps you trust your knowledge of the problem at hand, using your subject matter expertise to check certain snippets first. Maybe you time a few different modules/classes/functions to see where most of the execution time is spent. Better yet, you can profile your code to get more information about the relative time spent in different functions and sub-functions. Whatever your process is, this blog might teach you some ways to get to the answer more quickly. In this post, I’ll start off by showing you a basic profiling method. I’ll add more and more features and flavor to it, ending with a good, solid profiling decorator. For those in a hurry (or who want to refer back to this material), head over to this GitHub repository where you can find the profile decorator and an example. Time It! To profile your code, you’re gonna need to know how to time it. To do so, you can use something as simple as this: from time import timestart = time() # your script here end = time() print(f'It took {end - start} seconds!') To easily time several functions/snippets (or if you just prefer to use a cleaner and more pythonic approach), you can convert the above into a timer decorator (discussed with an example here). Using a timer on any function shows us the run time of that piece in isolation. For this approach to be useful in finding the bottleneck, we need more information. At least one of the following two conditions should be true in order to profile your code effectively: - We should know the total run time of the program to have a better picture of the relative run time of our desired function/section. For example, if a piece of code takes 5 minutes to execute, is that 10%, 40%, or 90% of the total run time? - We should know enough about the problem at hand or the run time of other parts of the program to confidently label a given piece of code as the bottleneck. Even if a function takes 10 minutes to run (let’s assume 10 minutes is relatively high), we should only worry about its inefficiency if we’re confident that there’s no other part that takes longer. As Donald Knuth famously said: Premature optimization is the root of all evil. A profiler package like cProfile helps us find the bottlenecks in our code by satisfying both of these conditions. How to Use cProfile Basic Usage The most basic way of profiling with cProfile is using the run() function. All you need to do is to pass what you want to profile as a string statement to run(). This is an example of what the report looks like (truncated for brevity): >>> import cProfile >>> import pandas as pd>>> cProfile.run("pd.Series(list('ABCDEFG'))")258 function calls (256 primitive calls) in 0.001 secondsOrdered by: standard namencalls tottime percall cumtime percall filename:lineno(function) 4 0.000 0.000 0.000 0.000 <frozen importlib._bootstrap>:997(_handle_fromlist) 1 0.000 0.000 0.000 0.000 <string>:1(<module>) 1 0.000 0.000 0.000 0.000 _dtype.py:319(_name_get) .... 11/9 0.000 0.000 0.000 0.000 {built-in method builtins.len} 1 0.000 0.000 0.000 0.000 {built-in method numpy.array} 1 0.000 0.000 0.000 0.000 {built-in method numpy.empty} .... The first line indicates that 258 calls were monitored, out of which 256 were primitive (a primitive call is one that was not induced via recursion). The next line, Ordered by: standard name, indicates that the report is sorted based on the standard name, which is the text in the filename:lineno(function) column. The line after that is the column headings: ncalls: is the number of calls made. When there are two numbers (like 11/9 above), the function recurred. The first value is the total number of calls and the second value is the number of primitive or non-recursive calls. tottime: is the total time spent in the given function (excluding time made in calls to sub-functions). percall: is the quotient of tottime divided by ncalls. cumtime: is the cumulative time spent in this and all subfunctions. This figure is accurate even for recursive functions. percall: is the quotient of cumtime divided by primitive calls. filename:lineno(function): provides the respective data of each function. The run() function can accept two more arguments: a filename to write the results to a file instead of the stdout, and a sort argument that specifies how the output should be sorted. You can check the documentation to learn more about valid sort values. Some of the common ones are 'cumulative' (for cumulative time), 'time' (for total time), and 'calls' (for number of calls). If you pass a filename and save the results, you may notice that the output is not human-readable. In this case, you need to use the pstats.Stats class to format the results, which we’ll discuss next. More Control With Profile and pstats.Stats Although using cProfile.run() can be sufficient in most cases, if you need more control over profiling, you should use the Profile class of cProfile. The snippet below is taken from the Profile class document. import cProfile, pstats, io from pstats import SortKey pr = cProfile.Profile() pr.enable() # ... do something ... pr.disable() s = io.StringIO() sortby = SortKey.CUMULATIVE ps = pstats.Stats(pr, stream=s).sort_stats(sortby) ps.print_stats() print(s.getvalue()) Let’s go through this line by line: First, we create an instance of the Profile class ( pr) and collect profiling data by calling enable. When we want to stop collecting profiling data, we call disable. What comes after that formats the collected statistics. We can then use the pstats.Stats class constructor to create an instance of the statistics object ( ps). The Stats class can create a statistics object from a profile object ( pr) and print the output to the stream that’s passed to it. The Stats class also has a sort_stats method that sorts the results based on the provided criteria. In this case, the criterion is SortKey.CUMULATIVE which is for the cumulative time spent in a function. As described in sort_stats documentation, the sorting criteria can be in the form of a SortKey enum (added in Python 3.7) or a string (i.e. using 'cumulative' instead of SortKey.CUMULATIVE is also valid). Finally, the results are created and printed to the standard output. This is good boilerplate with which to build a decorator (to learn more about decorators, I recommend this great and comprehensive primer): import cProfile import io import pstatsdef profile(func): def wrapper(*args, **kwargs): pr = cProfile.Profile() pr.enable() retval = func(*args, **kwargs) pr.disable() s = io.StringIO() sortby = SortKey.CUMULATIVE # 'cumulative' ps = pstats.Stats(pr, stream=s).sort_stats(sortby) ps.print_stats() print(s.getvalue()) return retval return wrapper# Profile foo @profile def foo(): print('Profile me!') Though it’s a good start, there are several pieces in the above decorator that can be made better. In particular, a more comprehensive function could: - Allow users to specify sorting keys (whether a single key or a tuple of sorting keys) - Only show the biggest time consumers rather than all the lines - Clean up the report by removing all the leading path information from the file names, reducing the size of the printout and making the report easier to read - Save the output to a file rather than printing to the stdout All of the above conditions can be handled by using the methods in pstats.Stats. Let’s go over them in order: - Pass the desired sort keys to the sort_stats()method (though we still need to check whether it’s a single value or a tuple) - Pass the max desired number of printed lines to print_stats() - Use strip_dirs() - By default, the outputs are printed to sys.stdoutbecause pstats.Stats()uses that as its default stream argument, but to write results to a file, we can pass a file as the stream Applying the aforementioned changes to the profile decorator will result in the following function (more explanation of the arguments is provided in the docstring): import cProfile import pstats from functools import wraps def profile(output_file=None, sort_by='cumulative', lines_to_print=None, strip_dirs=False): """A time profiler decorator. Inspired by and modified the profile decorator of Giampaolo Rodola: Args: output_file: str or None. Default is None Path of the output file. If only name of the file is given, it's saved in the current directory. If it's None, the name of the decorated function is used. sort_by: str or SortKey enum or tuple/list of str/SortKey enum Sorting criteria for the Stats object. For a list of valid string and SortKey refer to: lines_to_print: int or None Number of lines to print. Default (None) is for all the lines. This is useful in reducing the size of the printout, especially that sorting by 'cumulative', the time consuming operations are printed toward the top of the file. strip_dirs: bool Whether to remove the leading path info from file names. This is also useful in reducing the size of the printout Returns: Profile of the decorated function """ def inner(func): @wraps(func) def wrapper(*args, **kwargs): _output_file = output_file or func.__name__ + '.prof' pr = cProfile.Profile() pr.enable() retval = func(*args, **kwargs) pr.disable() pr.dump_stats(_output_file) with open(_output_file, 'w') as f: ps = pstats.Stats(pr, stream=f) if strip_dirs: ps.strip_dirs() if isinstance(sort_by, (tuple, list)): ps.sort_stats(*sort_by) else: ps.sort_stats(sort_by) ps.print_stats(lines_to_print) return retval return wrapper return inner Wrap-up Example To see how the profile decorator can help us detect bottlenecks, let’s create an example with multiple functions. Assume you have a list of products sold in the past year, and you want to know each product’s popularity by counting units sold. (What we want can be easily done using collections.Counter, or if you’re a pandas user, by pandas.Series.value_counts, but let’s forget about those for the sake of this exercise.) import random random.seed(20)def create_products(num): """Create a list of random products with 3-letter alphanumeric name.""" return [''.join(random.choices('ABCDEFG123', k=3)) for _ in range(num)] # version1 @profile(sort_by='cumulative', lines_to_print=10, strip_dirs=True) def product_counter_v1(products): """Get count of products in descending order.""" counter_dict = create_counter(products) sorted_p = sort_counter(counter_dict) return sorted_p def create_counter(products): counter_dict = {} for p in products: if p not in counter_dict: counter_dict[p] = 0 counter_dict[p] += 1 return counter_dict def sort_counter(counter_dict): return {k: v for k, v in sorted(counter_dict.items(), key=lambda x: x[1], reverse=True)} # =========== # Analysis starts here # =========== num = 1_000_000 # assume we have sold 1,000,000 products products = create_products(num) # Let's add profile decorator to product_counter_v1 function counter_dict = product_counter_v1(products) The result will be saved in product_counter_v1.prof in your current directory, and it should look like this: 1007 function calls in 0.228 seconds Ordered by: cumulative time ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 0.228 0.228 scratch_6.py:69(product_counter_v1) 1 0.215 0.215 0.215 0.215 scratch_6.py:86(create_counter) 1 0.000 0.000 0.013 0.013 scratch_6.py:105(sort_counter) 1 0.013 0.013 0.013 0.01} Examining this file, we can see that the vast majority of the execution time (0.215 of the 0.228 seconds) is spent in the create_counter function. So, let’s make a new create_counter function and check its effects. # version2 @profile(sort_by='cumulative', lines_to_print=10, strip_dirs=True) def product_counter_v2(products): """Get count of products in descending order.""" counter_dict = create_counter_v2(products) sorted_p = sort_counter(counter_dict) return sorted_p def create_counter_v2(products): counter_dict = {} for p in products: try: counter_dict[p] += 1 except KeyError: counter_dict[p] = 1 return counter_dict The result of profiling product_counter_v2 is shown below: 1007 function calls in 0.169 seconds Ordered by: cumulative time ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 0.169 0.169 scratch_6.py:78(product_counter_v2) 1 0.158 0.158 0.158 0.158 scratch_6.py:95(create_counter_v2) 1 0.000 0.000 0.010 0.010 scratch_6.py:105(sort_counter) 1 0.010 0.010 0.010 0.01} The run time decreased from 0.228 to 0.169 seconds, a ~26% reduction. If this is still not satisfactory, you can try using collections.defaultdict to create the counter_dict. For the last implementation, we’ll use collections.Counter: import collections # version3 @profile(sort_by='cumulative', lines_to_print=10, strip_dirs=True) def product_counter_v3(products): """Get count of products in descending order.""" return collections.Counter(products) Profiling product_counter_v3 shows that it yields a 62% improvement over product_counter_v1. 11 function calls in 0.086 seconds Ordered by: cumulative time ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 0.086 0.086 scratch_6.py:118(product_counter_v3) 1 0.000 0.000 0.086 0.086 __init__.py:517(__init__) 1 0.000 0.000 0.086 0.086 __init__.py:586(update) 1 0.086 0.086 0.086 0.086 {built-in method _collections._count_elements} 1 0.000 0.000 0.000 0.000 {built-in method builtins.isinstance} 1 0.000 0.000 0.000 0.000 abc.py:180(__instancecheck__) 2 0.000 0.000 0.000 0.000 _weakrefset.py:70(__contains__) 2 0.000 0.000 0.000 0.000 {built-in method builtins.len} 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects} Play around with different arguments of the profile decorator and see how the output will change. You can find the complete example in this GitHub repository. Happy profiling! Source: towardsdatascience
https://learningactors.com/how-to-profile-your-code-in-python/
CC-MAIN-2021-31
refinedweb
2,375
57.47
Section (3) pcre2_code_copy_with_tables Name PCRE2 — Perl-compatible regular expressions (revised API) Synopsis #include <pcre2.h> DESCRIPTION This function makes a copy of the memory used for a compiled pattern, excluding any memory used by the JIT compiler. Without a subsequent call to pcre2_jit_compile(), the copy can be used only for non-JIT matching. Unlike pcre2_code_copy(), a separate copy of the character tables is also made, with the new code pointing to it. This memory will be automatically freed when pcre2_code_free() is called. The yield of the function is NULL if code is NULL or if sufficient memory cannot be obtained. There is a complete description of the PCRE2 native API in the pcre2api(3) page and a description of the POSIX API in the pcre2posix(3) page.
https://manpages.net/detail.php?name=pcre2_code_copy_with_tables
CC-MAIN-2022-21
refinedweb
127
53.81
I propose the following PEP for inclusion to Python 3.1. Please comment. Regards, Mart__), as an extension to the existing ``*.pkg`` mechanism. The import statement is extended so that it directly considers ``*.pkg`` files during import; a directory is considered a package if it either contains a file named __init__.py, or a file whose name ends with ".pkg". In addition, the format of the ``*.pkg`` file is extended: a line with the single character ``*`` indicates that the entire sys.path will be searched for portions of the namespace package at the time the namespace packages is imported. Importing a package will immediately compute the package's __path__; the ``*.pkg`` files are not considered anymore after the initial import. If a ``*.pkg`` package contains an asterisk, this asterisk is prepended to the package's __path__ to indicate that the package is a namespace package (and that thus further extensions to sys.path might also want to extend __path__). At most one such asterisk gets prepended to the path. extend_path will be extended to recognize namespace packages according to this PEP, and avoid adding directories twice to __path__. No other change to the importing mechanism is made; searching modules (including __init__.py) will continue to stop at the first module encountered. Discussion ========== With the addition of ``*.pkg`` files to the import mechanism, namespace packages can stop filling out the namespace package's __init__.py. As a consequence, extend_path and declare_namespace become obsolete. It is recommended that distributions put a file <distribution>.pkg into their namespace packages, with a single asterisk. This allows vendor packages to install multiple portions of namespace package into a single directory, with no risk of overlapping files.__. Copyright ========= This document has been placed in the public domain.
https://mail.python.org/pipermail/python-dev/2009-April/088073.html
CC-MAIN-2017-04
refinedweb
292
59.09
Yet another Python client for ThoughtWorks GoCD REST API. Project description Introduction This library is a high level python API wrapper upon ThoughtWorks GoCD REST API. From the official documentation: Go Continuous Delivery is continuous integration/deployment server, which helps you automate and streamline the build-test-release cycle for worry-free. Using it, you can access to internals of the Pipelines, check their statuses, download Artifacts and more. It is designed with maximum comfort and productivity from the user perspective, so it should be very easy to use it in your own project. More information is available at official documentation Installation $ pip install yagocd Quick example from yagocd import Yagocd go = Yagocd( server='', auth=('user', 'password'), options={ 'verify': False # skip verification for SSL certificates. } ) for pipeline in go.pipelines: # Iterate over all pipelines for instance in pipeline: # Iterate over each instance of some pipeline for stage in instance: # Iterate over each stages of some pipeline instance for job in stage: # Iterate over each job of some pipeline for root, folder, files in job.artifacts: # Iterate over artifacts like `os.walk` manner for artifact in files: print(artifact.data.url) # print property of each job for key, value in job.properties.items(): print("{} => {}".format(key, value)) Different implementations of GoCD API Here is list of similar projects, that implements GoCD API: - py-gocd [python]: A Python API for interacting with Go Continuous Delivery - gocdapi [python]: A Python API for accessing resources and configuring Go (thoughtworks) continuous-delivery servers - gomatic [python]: A Python API for configuring GoCD - goapi [ruby]: Go () API ruby client - gocd-api [NodeJS]: Access API via nodeJS - gocd-api [GoLang]: An implementation of the gocd API Release History 1.0.0 (2017-04-13) Improvements - Added elastic profile support. - Added package repositories API support. - Added package management API support. - Added encryption API support. - Improvements in ValueStreamMap. - Added enumerations (constants) for stage result and state. - Reworked artifact manager (breaking change!) - ETag is now part of resource object (breaking change!) Miscellaneous - Added support for 16.11.0 version. - Added support for 17.01.0 version. - Added support for 17.02.0 version. - Added support for 17.03.0 version. - Refactored managers urls and parameters. 0.4.4 (2016-12-01) Improvements - Client’s manager are now initialized just once, which makes possible to cache the results of their calls. 0.4.3 (2016-11-23) Improvements - Improvements in ValueStreamMap. - Added possibility to programmatically disable version check in Since decorator, using ENABLED flag. Miscellaneous - Added support for 16.10.1 version. 0.4.2 (2016-10-28) Improvements - ValueStreamMap: put dictionary instead of StageInstance. 0.4.1 (2016-10-09) Improvements - Added custom exception error, which outputs error in clear format. - Added support for pluggable SCM materials API. - Added support for template API. - Improvements in ValueStreamMap. Miscellaneous - Documentation updated. - Docker image updated, which used in testing. - Added support for 16.10.0 version. 0.4.0 (2016-10-01) Improvements - Added support for pipeline config API. - Added support for version API. - Added support for plugin info API. - Added support for environments API. - Added methods for getting different internal information (undocumented): support and process_list. - Added magic methods for iterating and key based access for some classes. - All classes and their methods are now decorated with @since decorator, which adds possibility to check at run-time whether given functionality already supported in the GoCD server and let’s dynamically select correct headers. Testing - Now tests are executed for GoCD version, running in Docker container, which add possibility to test for any available version of the server. Also cassettes are also saved individually for each GoCD version. - Added testing for PEP8 and other checks via flake8. 0.3.2 (2016-07-26) Improvements - Added support of value_stream_map functionality. Bugfixes - Fix return value of Artifact.fetch method from text to binary. 0.2.0 (2016-05-24) Improvements - Added support of getting server version through parsing /about page. - Added Confirm: true header to some API calls. Project details Release history Release notifications Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/yagocd/
CC-MAIN-2020-10
refinedweb
688
51.34
마이크로소프트 Korean Developer Division SDET의 개발툴/플랫폼 이야기. Democracy Dying in South Korea - After 28 years, the call for democracy still continues <?xml:namespace prefix = o South Koreans do not know what is happening in South Korea. The media, like the government, refuses to report the truth - the people’s desires for democracy and calls for a better future. South Koreans first started a silent candle-lit protest on May 2nd 2008 against the newly elected president Lee’s policies concerning the free trade agreement, privatization, and the Korean ownership of Dok-do. Mothers came with their children. High school and middle school students came with their friends. Workers came after work to hold candles and ask President Lee Myung-Bak to reconsider his policies and live for the people. While more than 20,000 people congregated in the middle of Seoul and some main cities of Korea, their numbers were reduced to a mere 5000 people by Korea’s main news stations, KBS and SBS, and newspapers Choseon, Joonang, and Dong-A. On May 24th, people congregated on-ce again for a peaceful, candle-lit protest. Frustrated by the government’s ignorance and media’s indifference, a group of people stood up and started marching towards the Blue House calling for President Lee’s impeachment. Suddenly, the unconcerned government responded with violence. The peaceful protest soon deteriorated with threats and armies of policemen. Harsh lights were forced upon the bewildered people. A watering truck carrying water to spray on-to the protesters and disperse the crowd was also thrown in. A woman with a seven-year-old son on her back asked for mercy. Her cry for help was shut out by the police, who pushed her away roughly. Throughout the night people’s peaceful protest was trampled upon by the police. 37 people were forcefully arrested, a few of them high school students. Students, children, old men, and women were all physically assaulted with shields, truncheons, and water. The police, who were on-ce the “protectors of the people” have become their oppressors. All of this is currently on-ly known by the people who participated in the protest that night. Korea’s main news stations have not reported the unjust physical assaults of the police on the peaceful protesters. Rather they have distorted the truth, lying about the physical actions of the police and the spraying of forceful water on-to the civilians, who were on-ly holding candles for protection. What on-ce was a peaceful protest of 50,000 people is being portrayed as a riot of 500 people by the main Korea media. Word is spreading through the Korean internet, and more and more people are assembling in the protest. Now people are not on-ly asking for the president’s reconsideration of his policies, but also for his impeachment, freedom of speech, and democracy in South Korea. Already people are referring to the protest as a recurrence of the democratic protest that happened 28 years ago in May in Gwang-Ju, a city in South Korea, against military dictatorship. While the president, the government, and the media remain silent, ignoring the wills of the people, Koreans themselves are collaborating to uphold the first rule of the national constitution, which clearly states that Korea’s sovereignty lies in its people, and all state power comes from the people.
http://blogs.msdn.com/bkchung/archive/2008/05/26/korean-people-s-anger-against-the-government-flames-out.aspx
crawl-002
refinedweb
564
52.8
mailing. Owner: vahid | 3.0.4 | Feb 18, 2017 | Package | Issues | Source | License: Apache-2.0 dependencies { compile 'org.grails.plugins:mailinglist:3.0.4' } mailinglist 0.34 mailing. For a walk through guide on how to install this plugin goto : Installation for grails 2.4+ assets based sites: Add plugin Dependency in BuildConfig.groovy : compile ":mailinglist:0.34" Installation for grails 3+ compile "org.grails.plugins:mailinglist:3.0.4" For grails 3 You will need to add bootstrap-datetimepicker.min.js to your grails-app/js/javascripts folder The file can be found here: or Under 2.4.0 you may need to review hibernate version and update to: runtime ":hibernate4:4.3.5.4" Please refer to example site grails 2: Please refer to example site grails 3: Installation for grails < 2.4 based resources sites 2.X -> 2.3.X Under Resources based application you can still use the latest code base, but you need to exclude hibernate. Something like this: compile (":maillinglist:X.XX") { excludes 'hibernate' } If you wish you could also use the very last build under compatible hibernate version built under resources: Add plugin Dependency in BuildConfig.groovy : compile ":mailinglist:0.19" Since 0.23 you also require: In the latest app I had to also enable fixes for export plugin, unsure why it did not pull it from within plugin... Under BuildConfig.groovy: repositories { ...... mavenRepo "" } dependencies { ..... compile 'commons-beanutils:commons-beanutils:1.8.3' } The two extra lines one to repositories and one to dependencies. Resources based sites : (Grails pre 2.4 ) grails-app/layouts/main.gsp update: jquery, jquery-ui libraries: your layouts main.gsp: (add jquery-ui and jquery - or add them into ApplicationResources.groovy and ensure you refer to it in your main.gsp or relevant file <g:javascript <g:javascript … … <g:layoutHead/> <mailinglist:loadbootstrap/> </head> You will also notice mailinglist:loadbootstrap/ this loads up bootstrap to make modalbox work - if you already have bootstrap then change this to <mailinglist:loadplugincss/> I have found using this method of calling bootstrap within one of my projects to have caused a problem when looking at source it was loading before jquery, so by moving this block further below end head tag resolved the issue. Assets based sites : (Grails 2.4+ ) grails-app/layouts/main.gsp update: A default site just add the mailingList line below application.js to grails-app/layouts/main.gsp <asset:stylesheet <asset:javascript <mailinglist:loadbootstrap/> Or if you already have bootstrap initialised : <mailinglist:loadplugincss/> replace the loadboostrap to loadplugincss Now with that all in place open grails console or from the command line run grails mlsetup org.example.com 5 Where org.example.com is your package and 5 is the amount of dynamic schedule jobs to generate, Assuming package was labelled as above org.example.com and schedule jobs as 5, install script will create Views under views/mailingList/_addedby.gsp Jobs under org.example.com/ScheduleEmail0Job.groovy org.example.com/ScheduleEmail1Job.groovy org.example.com/ScheduleEmail2Job.groovy org.example.com/ScheduleEmail3Job.groovy org.example.com/ScheduleEmail4Job.groovy Services under org.example.com It will update QuartzEmailCheckerService to only schedule physical jobs ScheduleEmail[0-4]Job The domains generated in your application extend base domains within plugin, besides this the rest of the controllers etc are pushed to your own application for you to do what you like with it. i18n support From 1.17 you can configure your i18n/messages_{locale}.properties to include translations for terms used within this plugin, to get the latest running terms for translation please refer to the wiki Version changes 0.34 @idiengaid identified issue with bulk emails and templates, earlier work from 0.32 needed additional if check around template 0.33 @idiengaid spotted instance with missing i 0.32 Pull request martofeld added some commits 5 hours ago @martofeld Add support for using templates in the mail 5495ef2 @martofeld Avoid parsing if values are already a List + fix typo ed30889 @martofeld Missed some implementations of the new template a3a5601 0.31 #3 Improvement of the mlsetup script and produced services If you have refreshed mlsetup script as part of 0.30, its worth doing it again. This will produce tidier services. 0.30 #3 further tidyup of cron expression rule checking 0.29 #3 Cron expressions introduced so either send via cron schedule or specify date time 0.28 minor change update modaldynamix to 0.28 and pluginbuddy 0.3 0.27 minor change update to modaldynamix ver 0.27 0.26 Updated to 2.4.2, cleaned up end user app verification by using pluginbuddy. 0.25 latest modaldynamix called - pop up boxes loading correctly according to screen size 0.24 Fixed datetime issue under assets based sites. 0.23 Latest modaldynamix plugin version used - modalboxes resized according to requirement - colour added to modalbox button callers. 0.22 Excess css entries removed from MailingList.css - causing larger buttons and unnessary spacing issues. 0.21 Missing jquery-ui js file manually inserted in for assets based sites. 0.20 Release of assets version - identical to 0.19 but hibernate bumped to match assets based sites. 0.19 last release for resources based sites. to keep upto date update your underlying site to assets 0.18 i18n support added to services - further tidy up of contact a person page. 0.17 Tidy up of mailSent view on main menu, added i18n support to most of the calls. 0.16 latest ckeditor added 0.15 mailinglist.warn.duplicate and mailinglist.warn.period added, issue with search mailingList fixed. Duplicate email warnings to same contactGroup set to show on preview screen 0.14 fixed pagination / export features on mailinglist page. 0.13 issue with list - export feature was not working - format was not being passed - format now set to extension params 0.12 Changed ckeditor to 4.4.0.0-SNAPSHOT 0.11 Removal of non thread safe calls within QuartsStatusService ret_triggerName ret_triggerGroup ret_jobName, now returned as map and parsed as params back in modSchedule 0.10 more tidying up fixes to minor broken calls 0.9 tidyup to taglib/service and gsps 0.8 minor changes to _list1-top.gsp - called correct controller to display more information on scheduled jobs 0.7 updates to default db table names, readme updates, correct ckeditor call for in index.gsp, giving upload feature for images 0.6 minor fix MailingList controller save wrong parameter for categories 0.5 minor fix gsp listing wrong domainClass in mailingList/_form.gsp 0.4 moved out all of the manual modalbox calls and called modaldynamix plugin 0.3 Missing images, alerts left in java scripts tut tut, contactclients gsp page had lots of bugs now fixed, scheduling looks a lot healthier. 0.2 moved most back into actual plugin - bug with existing used schedule issues whilst attempting to schedule something for now whilst others queued. 0.1 release - nearly everything written to clients project Config.groovy changes Required Config.groovy configurations: /* * Optional values to override DB table names for this plugin: * mailinglist.table.attachments='mailing_list_attachments' * mailinglist.table.categories='categories' * mailinglist.table.mailinglist='mailing_list' * mailinglist.table.schedule='mailing_list_schedule' * mailinglist.table.senders='mailing_list_senders' * mailinglist.table.templates='mailing_list_templates' * These options define if there should be a warning to confirm an email was sent to same group within defined period * mailinglist.warn.duplicate='Y' * --- Periods are: | H for Hours | D for days | M for minutes | m for months | y for years | * mailinglist.warn.period='2H' * These are all the local tables created that in turn extend domainClasses from this plugin. * Check out your domainClass folder under the package you provided after you run the mlsetup command. */ // Your date format that matches input of jquery datepicker config //mailinglist.dtFormat='dd/MM/yyyy HH.mm' ckeditor { //config = "/js/myckconfig.js" skipAllowedItemsCheck = false defaultFileBrowser = "ofm" upload { // basedir = "/uploads/" baseurl="${grails.baseURL}"+'/uploads/' basedir = "${externalUploadPath}" overwrite = false link { browser = true upload = false allowed = [] denied = ['] } image { browser = true upload = true allowed = ['jpg', 'gif', 'jpeg', 'png'] denied = [] } flash { browser = false upload = false allowed = ['swf'] denied = [] } } } jqueryDateTimePicker { format { java { datetime = "dd/MM/yyyy HH.mm" date = "dd/MM/yyyy" } picker { date = "'dd/mm/yy'" time = "'H.mm'" } } } grails.mime.types = [ html: ['text/html','application/xhtml+xml'], xml: ['text/xml', 'application/xml'], text: 'text-plain', js: 'text/javascript', rss: 'application/rss+xml', atom: 'application/atom+xml', css: 'text/css', csv: 'text/csv', pdf: 'application/pdf', rtf: 'application/rtf', excel: 'application/vnd.ms-excel', ods: 'application/vnd.oasis.opendocument.spreadsheet', all: '*/*', json: ['application/json','text/json'], form: 'application/x-www-form-urlencoded', multipartForm: 'multipart/form-data' ] You will notice grails.baseURL externalUploadPath within ckeditor, this was done to externalise image uploads so upon a redployment the images were still available, the approach I took to this was to run values from setenv.sh within tomcat and pass this values in as variables into Config.groovy as per below: // configuration for plugin testing - will not be included in the plugin zip // In my tomcat setenv.sh //UPLOADLOC="$CATALINA_HOME/uploads" //JAVA_OPTS="$JAVA_OPTS -DUPLOADLOC=$UPLOADLOC" //HOSTNAME=$(hostname) //JAVA_OPTS="$JAVA_OPTS -DSERVERURL=$HOSTNAME" Produces running tomcat with the following values: // -DUPLOADLOC=/opt/tomcat7/tc1/uploads // -DSERVERURL=my.server.com In my Config.groovy at the top I have this if (System.getProperty('UPLOADLOC')) { externalUploadPath=System.getProperty('UPLOADLOC')+File.separator } if (System.getProperty('SERVERURL')) { grails.baseURL='http://'+System.getProperty('SERVERURL') } else{ grails.baseURL='' } Now those values are valid within the ckeditor configuration Boostrap changes An example BootStrap call to requeue outstanding or interuppted schedules is to add something like this : import grails.plugin.mailinglist.core.ScheduleBase class BootStrap { def mailingListEmailService def init = { servletContext -> def getEmails = ScheduleBase.findAllByScheduleCompleteAndScheduleCancelled(false,false) getEmails.each { params -> if (params.dateTime && params.emailMessage) { println "RESCHEDULING MAIL QUEUE ${params?.id} -- ${params?.mailFrom}---${params?.recipientToGroup}--${params?.recipientToList}" mailingListEmailService.rescheduleit(params) } } } } addedby within forms There is a field passed around through the application and by default it is blank, this is due to a file called views/mailingList/_addedby.gsp Take a look at this, if your existing application has some form of user and current user is being returned via session or another method i.e. params or something then update this page to refer to this value. This should fix the issue all around the site, no guarantee haha. conf/UrlMappings.groovy & plugin default holding page If this plugin is the only purpose of your site, then simply update your url mappings to point to the holding page of this plugin: "/" { controller = "MailingList" action = "index" } // Commented out default and put in above //"/"(view:"/index") The plugin has a menu which can be found under: This is the main menu, the two core options on the top left hand side, Email a person and contact clients. The rest of the menu are the manual methods of reviewing email list, or removing attachments etc. This is what to expect when emailing a person The now button defaults to now, other than that choose actual date time you wish to email this person. It will just sit in that queue you can stop the job or force it play now from that same scheduling menu. This is the look and feel of contact group, subject is the only thing defined, everything else is clickable or uploadable. At the top are some green buttons, each one will update this form dynamically. Adding a new template, if you do not have a preset template to use for sending emails then create a new one from the first green button at the top of the page. This is if you wish to attach files like documents to be sent with email. Attachments run in iframes, so for changes to take effect on main form you need to use the close button on the top of the page. CSV Uploader which will be your group of users to contact, please note it will always miss out on the first line since on exports usually the first line is the field name The senders from group emails come from the Senders DB table, so you need to register it once set it should remain for reuse on next use. Set the time you wish to email to this group, you have now selected and ticked everything else including once template was uploaded you clicked the select box to choose it which then popped open your presaved template. Since emailing a group of people usually requires more care, there has been a preview screen added to ensure you are happy with what is being done. if so click confirm sending email otherwise click edit to go back, This now contains our previous job which is set in a few hours plus our new job for now, we will now choose Completed schedules from the drop down to see: This group email as completed This is my email log confirming it sent an email from set email to the uploaded csv which had 3 gmail emails, it bounced cos my sendmail is not configured and just as well considering the amount of junk I been sending haha #Common Issues: After attempting to run mlsetup org.example.com 5 you must referesh the project and run grails refresh-dependencies If your in ggts you may still see red asterix you can run: grails clean These are the manual command lines goto project right click grails tools, grails command wizard will help you with those or actual command prompt below just drop the grails in front of all of the above. Date Format: Trying to schedule and can not ? dd/MM/yyyy HH.mm You may see this : Could not queue job please check quartz queue to ensure schedule slots are free If you look at the console logs you will see it could not parse and it shows a date and time, look closely at the time you will find it has a : seperating the hour and mins. I know I should have set this as the default right :) This is the defaults sadly so please review main config and ensure your jquery date time config is set properly to match what is needed: mailinglist.dtFormat='dd/MM/yyyy HH.mm' jqueryDateTimePicker { format { java { datetime = "dd/MM/yyyy HH.mm" date = "dd/MM/yyyy" } picker { date = "'dd/mm/yy'" time = "'H.mm'" } } } This is in the main config above, but worth a remention, so if you want to set a different input type for date time, then define this value in your config to match aboves config to get around the standard config which is a dot seperating hours and minutes. mailinglist.dtFormat='dd/MM/yyyy HH.mm' Ensure all of above tallies up for it all work properly Pop up Modal boxes within contact clients Take a look at follow the guide then refer to pages within this plugin to get a better idea on how to use it all together. Finally A big thank you as always to Burt Beckwith for cleaning up the code: Unfortunately due to issues with merging repo was cleaned up, original code cna be found here: Those changes are here: @martofeld martin For adding template support to the plugin Sergey Ponomarev For cleaning up and adding formating to the README.md Thank you all for you contributions. If you wish to contribute or add stuff I be happy to add you as a project member. I am no longer using this project so will not be getting much updates from me.
https://plugins.grails.org/plugin/vahid/mailinglist
CC-MAIN-2019-47
refinedweb
2,575
55.13
Simulated Annealing Tutorial Simulated: $$P = \exp\left(\frac{-\Delta E}{k_b T}\right)$$. . Example Problem and Source Code Find the minimum to the objective function $$obj = 0.2 + x_1^2 + x_2^2 - 0.1 \, \cos \left( 6 \pi x_1 \right) - 0.1 \cos \left(6 \pi x_2\right)$$ by adjusting the values of `x_1` and `x_2`. You can download anneal.m and anneal.py files to retrieve example simulated annealing files in MATLAB and Python, respectively. Download Simulated Annealing Example Files # Import some other libraries that we'll need # matplotlib and numpy packages must also be installed import matplotlib import numpy as np import matplotlib.pyplot as plt import random import math # define objective function def f(x): x1 = x[0] x2 = x[1] obj = 0.2 + x1**2 + x2**2 - 0.1*math.cos(6.0*3.1415*x1) - 0.1*math.cos(6.0*3.1415*x2) return obj # Start location x_start = [0.8, -0.5] # Design variables at mesh points i1 = np.arange(-1.0, 1.0, 0.01) i2 = np.arange(-1.0, 1.0, 0.01) x1m, x2m = np.meshgrid(i1, i2) fm = np.zeros(x1m.shape) for i in range(x1m.shape[0]): for j in range(x1m.shape[1]): fm[i][j] = 0.2 + x1m[i][j]**2 + x2m[i][j]**2 \ - 0.1*math.cos(6.0*3.1415*x1m[i][j]) \ - 0.1*math.cos(6.0*3.1415*x2m[i][j]) # Create a contour plot plt.figure() # Specify contour lines #lines = range(2,52,2) # Plot contours CS = plt.contour(x1m, x2m, fm)#,lines) # Label contours plt.clabel(CS, inline=1, fontsize=10) # Add some text to the plot plt.title('Non-Convex Function') plt.xlabel('x1') plt.ylabel('x2') ################################################## #/math.log(p1) # Final temperature t50 = -1.0/math.log(p50) # Fractional reduction every cycle frac = (t50/t1)**(1.0/(n-1.0)) # Initialize x x = np.zeros((n+1,2)) x[0] = x_start xi = np.zeros(2) xi = x_start na = na + 1.0 # Current best results so far xc = np.zeros(2) xc = x[0] fc = f(xi) fs = np.zeros(n+1) fs[0] = fc # Current temperature t = t1 # DeltaE Average DeltaE_avg = 0.0 for i in range(n): print('Cycle: ' + str(i) + ' with Temperature: ' + str(t)) for j in range(m): # Generate new trial points xi[0] = xc[0] + random.random() - 0.5 xi[1] = xc[1] + random.random() - 0.5 # Clip to upper and lower bounds xi[0] = max(min(xi[0],1.0),-1.0) xi[1] = max(min(xi[1],1.0),-1.0) DeltaE = abs(f(xi)-fc) if (f(xi)>fc): # Initialize DeltaE_avg if a worse solution was found # on the first iteration if (i==0 and j==0): DeltaE_avg = DeltaE # objective function is worse # generate probability of acceptance p = math.exp(-DeltaE/(DeltaE_avg * t)) # determine whether to accept worse point if (random.random()<p): # accept the worse solution accept = True else: # don't accept the worse solution accept = False else: # objective function is lower, automatically accept accept = True if (accept==True): # update currently accepted solution xc[0] = xi[0] xc[1] = xi[1] fc = f(xc) # increment number of accepted solutions na = na + 1.0 # update DeltaE_avg DeltaE_avg = (DeltaE_avg * (na-1.0) + DeltaE) / na # Record the best x values at the end of every cycle x[i+1][0] = xc[0] x[i+1][1] = xc[1] fs[i+1] = fc # Lower the temperature for next cycle t = frac * t # print solution print('Best solution: ' + str(xc)) print('Best objective: ' + str(fc)) plt.plot(x[:,0],x[:,1],'y-o') plt.savefig('contour.png') fig = plt.figure() ax1 = fig.add_subplot(211) ax1.plot(fs,'r.-') ax1.legend(['Objective']) ax2 = fig.add_subplot(212) ax2.plot(x[:,0],'b.-') ax2.plot(x[:,1],'g--') ax2.legend(['x1','x2']) # Save the figure as a PNG plt.savefig('iterations.png') plt.show() clear; close all; %% Generate a contour plot % Start location x_start = [0.8, -0.5]; % Design variables at mesh points i1 = -1.0:0.01:1.0; i2 = -1.0:0.01:1.0; [x1m, x2m] = meshgrid(i1, i2); fm = 0.2 + x1m.^2 + x2m.^2 - 0.1*cos(6.0*pi*x1m) - 0.1*cos(6.0*pi*x2m); % Contour Plot fig = figure(1); [C,h] = contour(x1m,x2m,fm); clabel(C,h,'Labelspacing',250); title('Simulated Annealing'); xlabel('x1'); ylabel('x2'); hold on; %%/log(p1); % Final temperature t50 = -1.0/log(p50); % Fractional reduction every cycle frac = (t50/t1)^(1.0/(n-1.0)); % Initialize x x = zeros(n+1,2); x(1,:) = x_start; xi = x_start; na = na + 1.0; % Current best results so far % xc = x(1,:); fc = f(xi); fs = zeros(n+1,1); fs(1,:) = fc; % Current temperature t = t1; % DeltaE Average DeltaE_avg = 0.0; for i=1:n disp(['Cycle: ',num2str(i),' with Temperature: ',num2str(t)]) xc(1) = x(i,1); xc(2) = x(i,2); for j=1:m % Generate new trial points xi(1) = xc(1) + rand() - 0.5; xi(2) = xc(2) + rand() - 0.5; % Clip to upper and lower bounds xi(1) = max(min(xi(1),1.0),-1.0); xi(2) = max(min(xi(2),1.0),-1.0); DeltaE = abs(f(xi)-fc); if (f(xi)>fc) % Initialize DeltaE_avg if a worse solution was found % on the first iteration if (i==1 && j==1) DeltaE_avg = DeltaE; end % objective function is worse % generate probability of acceptance p = exp(-DeltaE/(DeltaE_avg * t)); % % determine whether to accept worse point if (rand()<p) % accept the worse solution accept = true; else % don't accept the worse solution accept = false; end else % objective function is lower, automatically accept accept = true; end % accept if (accept==true) % update currently accepted solution xc(1) = xi(1); xc(2) = xi(2); fc = f(xc); xa(j,1) = xc(1); xa(j,2) = xc(2); fa(j) = f(xc); % increment number of accepted solutions na = na + 1.0; % update DeltaE_avg DeltaE_avg = (DeltaE_avg * (na-1.0) + DeltaE) / na; else fa(j) = 0.0; end end % cycle) fa_Min_Index = find(nonzeros(fa) == min(nonzeros(fa))); if isempty(fa_Min_Index) == 0 x(i+1,1) = xa(fa_Min_Index,1); x(i+1,2) = xa(fa_Min_Index,2); fs(i+1) = fa(fa_Min_Index); else x(i+1,1) = x(i,1); x(i+1,2) = x(i,2); fs(i+1) = fs(i); end % Lower the temperature for next cycle t = frac * t; fa = 0.0; end % print solution disp(['Best candidate: ',num2str(xc)]) disp(['Best solution: ',num2str(fc)]) plot(x(:,1),x(:,2),'r-o') saveas(fig,'contour','png') fig = figure(2); subplot(2,1,1) plot(fs,'r.-') legend('Objective') subplot(2,1,2) hold on plot(x(:,1),'b.-') plot(x(:,2),'g.-') legend('x_1','x_2') % Save the figure as a PNG saveas(fig,'iterations','png') Save as f.m x1 = x(1); x2 = x(2); obj = 0.2 + x1^2 + x2^2 - 0.1*cos(6.0*pi*x1) - 0.1*cos(6.0*pi*x2); end
https://apmonitor.com/me575/index.php/Main/SimulatedAnnealing
CC-MAIN-2020-24
refinedweb
1,160
60.72
SeqIO Revision as of 12:11, 9 June 2009 and write, with the Biopython version where this was first supported. this we have a function Bio.SeqIO.to_dict() to turn a SeqRecord iterator (or list) into a dictionary:. Finally the function Bio.SeqIO.to_alignment() can be used to turn a SeqRecord iterator (or list) into an alignment object - provided all the sequences are the same length: from Bio import SeqIO handle = open("opuntia.aln", "rU") alignment = SeqIO.to_alignment(SeqIO.parse(handle, "clustal")) handle.close() for column in range(alignment.get_alignment_length()) : print "%s column %i" % (alignment.get_column(column),column) In the future it may be possible to do this directly via the Alignment object. See also the Bio.AlignIO module for working directly with Alignment objects.") SeqIO.write(sequences, output_handle, "fasta") output_handle.close() input_handle.close() Or more concisely, without explicitly closing the handles, just: from Bio import SeqIO SeqIO.write(SeqIO.parse(open("cor6_6.gb", "rU"), "genbank"), \ open("cor6_6.fasta", "w"), "fasta") for record in SeqIO.parse(open("ls_orchid.gbk"), "genbank") : print record.format("fasta") The format method will take any output format supported by Bio.SeqIO where the file format can be used for a single record (e.g. "fasta", "tab" or "genbank"). If you are having problems with Bio.SeqIO, please join the discussion mailing list (see mailing lists). If you think you've found a bug, please report it on bugzilla.
http://biopython.org/w/index.php?title=SeqIO&diff=2716&oldid=2715
CC-MAIN-2015-48
refinedweb
233
54.49
rob...@garrettfamily.us wrote: > (Apologies in advance if I've sent this to an inappropriate list) > > Is it possible to pass an instance of an object from an externally > called routine back to the parent routine? If so, how? > > Example: > Assume two separate REXX routines (separate files): MAIN.rex and > LOGGER.rex. > I'd like to be able to, from MAIN, call LOGGER (passing it a file > name), and have LOGGER create an instance of a stream object, open the > file, and then pass the stream object back to MAIN at which point MAIN > would be able to use the stream object to write to the file (or > perhaps pass it to other external routines that would also be able to > use it). > I'm already doing this with LOGGER being a routine that is part of > MAIN (both located in the same file), but I want to be able to break > LOGGER out into a separate file. > > Is this possible? Sure. Break out the routines add the keyword "PUBLIC" to each routine in LOGGER.rex. Then, before using the public routines which now reside in LOGGER.rex you need to "CALL LOGGER", which will cause its public routines (and public classes) to become visible. 'Thereafter you can access all those routines as if they were defined in MAIN.rex. > > I've been writing and using REXX for many years in the mainframe > environment so I'm quite familiar with the core language, but the > facilities of ooREXX are still somewhat new to me. If you are developing a logging facility for Rexx you might want to learn about an ooRexx implementation of the log-framework that originates from the Java world. Here's an article to that ooRexx framework, demonstrating how to use it: <>. The ooRexx code of the "log4rexx" framework can be downloaded from: <>, in case it is of interest for you. HTH, ---rony ------------------------------------------------------------------------------ This SF.net email is sponsored by: SourcForge Community SourceForge wants to tell your story. _______________________________________________ Oorexx-devel mailing list Oorexx-devel@lists.sourceforge.net
https://www.mail-archive.com/oorexx-devel@lists.sourceforge.net/msg01712.html
CC-MAIN-2019-43
refinedweb
341
70.33
Hi On Mon, Jun 18, 2007 at 03:55:23PM -0000, Wolfram Gloger wrote: > Hi, > > Here is a patch originally by Steve Lhomme from last year which I have > used successfully for a while and kept forgetting to submit. > > I believe I've adressed all of the comments that were made at the time > (':' as file name sparator, support for arbitrary seeking). I left > the Windows-specific 'stat' handling as it was but cannot judge whether > it is necessary (from my POV it could just as well be omitted). [...] > diff -Naur trunk/libavformat/file.c ffmpeg-wg/libavformat/file.c > --- trunk/libavformat/file.c 2007-02-17 12:24:51.000000000 +0100 > +++ ffmpeg-wg/libavformat/file.c 2007-05-02 13:14:02.000000000 +0200 > @@ -22,7 +22,11 @@ this should be in a seperate file not in file.c also it should not be specific to the file protocol but rather work with all, its kinda silly if we next add a httpconcat then a filehttpconcat ... [...] > +/* multiple file protocol */ > + > +struct fileconcat_info { no doxygen comment [...] > + strstart(filename, "cat:", &filename); > + > + if (flags & URL_RDWR) { > + access = O_CREAT | O_TRUNC | O_RDWR; > + } else if (flags & URL_WRONLY) { > + access = O_CREAT | O_TRUNC | O_WRONLY; > + } else { > + access = O_RDONLY; > + } > +#if defined(__MINGW32__) || defined(CONFIG_OS2) || defined(__CYGWIN__) > + access |= O_BINARY; > +#endif this is duplicated relative to existing code from file.c [...] > +#if defined(CONFIG_WIN32) && !defined(__CYGWIN__) > + _fstat64(fd, &fstats); > +#else > + fstat(fd, &fstats); > +#endif i think such ifdef hell should not be accepted in new patches configure or some other appropriate thing should check availability of _fstat64/stat and provide a working stat() or set HAVE__STAT64 or: <>
http://ffmpeg.org/pipermail/ffmpeg-devel/2007-June/030932.html
CC-MAIN-2016-22
refinedweb
263
52.7
Unique identifiers The Atom XML format for blogs and other syndicated feeds requires each entry to have a unique ID enclosed in an id element. Atom requires that the ID be a syntactically correct URI. It also requires that this ID not only be unique within the document where it appears, but also be globally unique across all documents, on all servers, for all time. That's a pretty strong requirement. However, it's necessary, because Atom feeds are frequently chopped into pieces, republished by other sites like Bloglines, and accumulated with content from other sites in aggregators and news clients like Vienna. For example, in this real-world entry, the ID is the rather unwieldy value: Listing 1. Sample Atom entry <entry> <title>The Eclipse Project has released AspectJ 5.0.</title> <content type="xhtml"> <div xmlns=""> <p> The Eclipse Project has released <a href="">AspectJ</a> 5.0. AspectJ is a derivative of Java that allows programmers to write code that applies across multiple classes. The AspectJ compiler requires Java 1.3, but can generate code for Java 1.1 and later. ." </p> </div> </content> <link href="#news2005December21"/> <id> http___eclipse.org_aspectj#news2005December21</id> <updated>2005-12-21T09:00:01-05:00</updated> </entry> (Actually, the real ID is even longer and uglier, but it needed to fit on this page.) This ID starts with the URL of the page from which the Atom feed is extracted,. Next, a query string is appended with one parameter, tag. The value of this parameter is formed by first concatenating all the URLs referenced in the entry and then replacing all URL reserved characters (such as the colon) with the underscore. This distinguishes different entries from the same page. Finally, the date is appended as a fragment identifier in case earlier or later entries contain the same set of URLs. It's ugly, long, and hard to read; but it's reliably unique. Atom isn't the only protocol that requires globally unique URI identifiers. RDF, OWL, and the semantic Web all assume that URIs can be assigned to any item -- not just Web pages, but people, pets, planets, paramecia, DNA sequences, medical diagnoses, dates, and anything else you can imagine. For the semantic Web to work, it's important that the same URI not be used to identify Pluto the dog and Pluto the planet. You'll find URIs used as identifiers in many other contexts, including SAX feature and property names, XML namespaces, RDDL natures and purposes, algorithms in XML digital signatures, SVG feature strings, and more. All URLs are URIs, and HTTP URLs like the one in the earlier example serve perfectly well as identifiers. The problem with using them as identifiers is that users expect to be able to follow HTTP URLs. Even if a URL only appears in an Atom feed document not meant for human consumption, people will type it into a Web browser. In the immortal words ofXML luminary. In addition to annoying users, placing unresolvable HTTP URLs in a document tends to fill up server error logs with 404s for the URLs you thought no one would try to find. Even if users don't find them, a broken robot somewhere will. Consequently, it would be nice to have a URI scheme purely for identification purposes that doesn't look like an HTTP URL. This is where tag URIs come in. Tag syntax It's probably impossible to define a globally unique identifier syntax without some form of centralized registration system to avoid conflicts. However, you don't need more than one such registry -- and fortunately, a registry already exists that almost everybody with a computer participates in: the domain name system. Like XML namespaces and Java package names, tag URIs piggyback off DNS to guarantee uniqueness. Each tag URI includes either a domain name or an e-mail address. Domain names are sold, expired, snatched, and stolen on a regular basis, so a date is also included in the URI. Presumably, not more than one person or organization owns any given domain name or e-mail address on any given day. Finally, an arbitrary string is added to the URI so that one person on one day can create any number of tag URIs. Here are a few example tag URIs: - tag:elharo@ibiblio.org,2006:javafaq/slides - tag:elharo@ibiblio.org,2005-12:Elliotte - tag:elharo.com,2006-01-25:ElliotteHarold:presentations:Javapolis2005-12-14 - tag:elharo.com,2005:double In URI terminology, these are all opaque URIs -- that is, they don't follow the hierarchical system used in HTTP, HTTPS, file, and FTP URLs. However, they do have their own distinct structure. In particular, each such URI is composed of three parts separated by colons: scheme:tagging entity:specific identifier The scheme is always tag. That's simple. Although URI schemes are case insensitive, the tag RFC (see Resources) recommends the lower-case form. The specific identifier is optional. If included, it can hold any content within the limits of URI syntax. In brief, this means it's allowed to contain ASCII alphanumeric characters and a few punctuation marks, but no whitespace, no reserved characters [like colon (:) and slash (/)], and no non-ASCII characters. No particular meaning is assigned to the specific identifier. You can store anything here that seems useful, although you should endeavor to make it meaningful and obvious to humans. That is, strings like "sr_8_xs_ap_i2_xgl14" (taken from a real URL at one of the largest e-commerce sites) are discouraged. The tag RFC encourages strings made up of real words. The tagging entity is where the meat is. This is the part that guarantees uniqueness. The tagging entity is based on domain names. However, because domain names change hands, there's also a date component. For example, the entity macfaq.com,2005 refers to the person or organization who owned the domain name macfaq.com in 2005. If that domain changes hands in 2006, then macfaq.com,2006 refers to the new owner, but the previous owner can still use macfaq.com,2005. If the domain name changes owners in the middle of a year, months and even days can be added, separated from the year by a hyphen. (This is the customary date format defined in ISO 8601 and endorsed by the W3C.) For example, macfaq.com,2005-12-21 refers to the entity that owned macfaq.com on December 21, 2005. All years must use four digits, and all days and months must use two. For example, to create a tag URI on New Year's Day 2006, you write macfaq.com,2006-01-01 rather than macfaq.com,06-1-1. The date doesn't have to be the date the URI was first created, but it often is. You can also pick a date in the past, as long you owned the domain then. However, you shouldn't create tag URIs that include a date in the future, because the ownership of the domain name or e-mail address may change unexpectedly. Although you can add a time component to the tagging entity, doing so is discouraged because differing time zones can cause overlap and conflicts. If a domain name does change hands, then it's best to only assign tag URIs 48 hours before or after the switch to remove all doubt about the ownership. Not everyone owns a personal domain name, but most people have an e-mail address. If you don't own a domain name, or if your organization is so large that sorting out the usage of URIs between branches and divisions is tricky, use a full e-mail address instead: for example, tag:elharo@ibiblio.org,2006:javafaq/slides. In this case, the tagging entity is now the owner of the elharo@ibiblio.org e-mail address in 2006, rather than the owner of the ibiblio.org domain name in 2006. Summary Tag URIs finally let URIs do what they were meant to do: identify without implying any sort of location or behavior that they don't have. They're easy to create, they're human legible, they work with existing systems, they're an open standard, and they don't have any backward compatibility issues. What's not to like? The only thing that might suggest using an HTTP URL instead of a tag URI is if you want to put a page at the other end of the URL, either now or in the future. HTTP URLs let you do this. Tag URIs don't. However, the vast majority of HTTP URLs intended for use as identifiers (as opposed to locators) produce 404 Not Found errors when plugged into a browser. If you know you're not going to put a page at the end of the URL, choose tag URIs as identifiers rather than HTTP URLs. Resources - Participate in the discussion forum. - Read the official tag RFC. - Visit the tag URI Web site. - Unique, reliable, stable identifiers are just one reason to prefer Atom over RSS. - Decide whether Pluto is or isn't a planet. - Read Atom feeds with RSSOwl. - developerWorks XML zone: Find more XML resources here, including articles, tutorials, tips, and standards..
http://www.ibm.com/developerworks/xml/library/x-mxd6/index.html
CC-MAIN-2014-52
refinedweb
1,539
64.41
I have been trying to work out a problem for the last few hours with little success. In the following code, using ConfigFile, I obtain the results of the configuration file, but in the main function I am trying to get the Config type out of the case statement. I need to be able to generate that error, but it means the two branches of the case are not the same type. I am not particularly attached to this direction, I am quite willing to do any way that works. I might be adding more configuration in the future. Any ideas? iæfai -- import Network.Shed.Httpd import Network.URI import Data.Either import Data.ConfigFile as C import Control.Monad.Error import Control.Applicative import ChessBoard data Config = Config { documentRoot :: String } deriving (Read, Show) main :: IO () main = do opt <- getConf "./config" config <- case opt of Left (_, err) -> ioError (userError err) Right (config) -> config docPath <- documentRoot config putStrLn "Starting up httpd." server <- initServer 6666 request return () request :: Request -> IO Response request req = do putStrLn $ "Recieved " ++ (show $ uriPath $ reqURI req) return $ Response 404 [] "Not found." --"
http://www.haskell.org/pipermail/beginners/2009-November/002602.html
CC-MAIN-2013-48
refinedweb
184
58.69
bug at jsf 2.0 f:setPropertyActionListener f:setPropertyActionListener works after action, but must work before action. It seems like bug at mojarra It's simple test which I tried to undestand this problem. What message should appear when click on test button? I think there should be "heyMan", but if you'll try you see "heynull" at first click. And only after second click you'll see right message @ManagedBean(name="testBean") @SessionScoped public class TestBean implements Serializable{ private String name; private String message; public void test(ActionEvent e) { message = "hey" + name; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } } xmlns: [b]actionListener[/b]s are called in the order in which they are specified on the page. Since your button's [b]actionListener[/b] precedes the [b]setPropertyActionListener[/b] on the page, it's called first. As a workaround, you could replace the [b]actionListener[/b] with [b]action[/b]. You should return null from the action method, so that you'll remain on the same page. I suppose you could also do something like this: [code] [/code] Thus, the [b]setPropertyActionListener[/b] precedes the [b]actionListener[/b]. However, I'm not at my PC at the moment and won't be there for several more hours, so I'm just writing this without having tested it first. I just think it should work. Could you show your code? I tried a commandButton with an action and sPAL, and it worked properly, but I may be doing something completely different than you. You may also wish to read this:...
https://www.java.net/node/701686
CC-MAIN-2014-10
refinedweb
279
65.32
It's not the same without you Join the community to find out what other Atlassian users are discussing, debating and creating. I have the following scripted field that I'm using to create a numerical value of the difference between the date an issue was created in JIRA vs the DueDate of that item. But it seems like the clearTime() function may be inappropriately also clearing the time of the actual created date of the issue as it appears on JIRA. When I use this script it correctly gives me the difference between due date and created date, but for some reason my "Created Date" timestamp value in JIRA becomes 12:00 AM. Why would a function call on an isolated date variable alter the value of my issue's created time? import com.atlassian.jira.issue.MutableIssue use(groovy.time.TimeCategory) { MutableIssue issue = (MutableIssue) issue try{ def date1 = issue.getDueDate() def date2 = issue.getCreated() def dueDate = date1.clearTime() def createDate = date2.clearTime() def duration = dueDate - createDate return "${duration.days}".toDouble() } catch(NullPointerException e) { return 0.toDouble() } } Update: I believe have I isolated this issue. I noticed today I was seeing certain requests come through with good timestamps. After running some tests on different request types I've found out that any time a "due date" is populated on an issue, my Created Date timestamp zeroes out. If I remove the "due date" from the ticket, the created date immediately returns to a proper value which tells me that it still exists in the system and isn't getting cleared out. It seems to be a visual effect that whenever there's a due date populated, the created date timestamp clears out. This does still seem related to the script, as I removed the script from one of my projects and specifically populated a due date and the created date seems to populate. When I add the scripted field back on, the created date immediately goes to 12:00 AM unless I clear the due date, in which case it reverts to the proper time. I answered my own issue after some trial and error. Apparently the clearTime() function also executes on the object you call it from in addition to returning a date value to be stored in a variable. I fixed my issue by cloning the date objects so that any changes I made would change the clone, not the original. import com.atlassian.jira.issue.MutableIssue use(groovy.time.TimeCategory) { MutableIssue issue = (MutableIssue) issue try{ def date1 = issue.getDueDate().clone() def date2 = issue.getCreated().clone() def dueDate = date1.clearTime() def createDate = date2.clearTime() def duration = dueDate - createDate return "${duration.days}".toDouble() } catch(NullPointerException e) { return 0.toDouble() } } clearTIme clears the time part on the object you you call it, and returns that, which I eventually worked out from So your original code would modify the issue object in the current thread, but not actually store any changes to the.
https://community.atlassian.com/t5/Jira-questions/ClearTime-Date-function-is-clearing-JIRA-values/qaq-p/143218
CC-MAIN-2018-17
refinedweb
493
55.03
Opened 12 years ago Closed 12 years ago Last modified 11 years ago #802 closed defect (duplicate) add a spam-filter callback facility to comments Description The comment system currently doesn't provide any way to make use of the is_public and approved flags - but I think they could be used for good. For example an approved comment could be shown with active links, while an unapproved one would be shown without active links. And a is_public=False one wouldn't be shown at all. This could be managed manually by the admin in the Django admin interface, but I think that's cumbersome for sites with heavy comment traffic (or with a heavy comment-spam problem!). So I think there should be something like in the settings that would allow users to hook up several filters that are run on free comments before they hit the database. The sample one would just use the number of links in the comment to decide wether it might be spam or not. There could be others that do other checks on comment data and request data. Those filters would need to get the request object passed in, so they can look at headers (as those are often a giveaway on spammers). Sure, an alternative would be to switch to a registered comment system, but not everybody likes that. Free comments are a nice and uncomplicated way, but we already know for sure that free comments will sooner or later be hit by comment spam, so we should at least provide the infrastructure to hook up spam filters. Change History (3) comment:1 Changed 12 years ago by comment:2 Changed 12 years ago by Sure, that's ok - but you can't use them with get_comment_count, as that doesn't take it into account and so you say "3 comments" on your front page while the actual page only shows one comment, because only that one is public :-) Actually this targets more #801, as that is about inconsistency in the comments app. The "spam filter hook" idea was just something that sprang to mind while writing that one - it would be quite cool if there was a way to handle at least part of the hassel of comment moderation automatically. Sure, I can do that with cronjobs and external tools just fine, but it would still be useful, I think, to have something like that integrated. is_public and approved flags are for use in templates. {% if comment.is_public %}Display the comment{% endif %}
https://code.djangoproject.com/ticket/802
CC-MAIN-2017-26
refinedweb
420
60.79
Syntax: #include <cstring> char *strncpy( char *to, const char *from, size_t count ); namespace std { using ::strncpy; } The strncpy function copies at most count characters of from to the string to. If from has less than count characters, the remainder is padded with '\0' characters. The return value is the resulting string. Warning: If you read the definition carefully, you will see that strncpy may not NULL terminate the resulting string! This is a surprise to many people, but it has a very good reason, and leads us to the idiomatic use of strncpy: #include <cstring> #include <cstdlib> int main(int agrc, char *argv[]) { if (argc!=2) { return EXIT_FAILURE; } char buff[6]; strncpy(buff, argv[1], sizeof(buff)); // Here comes the idiomatic part, that // must not be missing from code using strncpy: if (buff[sizeof(buff)-1] != '\0') { // We have overflow. You may decide to give an error: return EXIT_FAILURE; // or to truncate your string: buff[sizeof(buff)-1]='\0'; } // but in any case, make sure that at this line // you string is NULL (zero) terminated! } The use of strncpy in itself does not result in safer code. It has to be used correctly (as above), otherwise a later code, which assumes that a buffer of 6 may contain maximum 5 characters, will fail, and may fail in a way that results in a security risk (crash or worse). An alternative way that always NULL-terminates the string is to use strncat: #include <cstring> #include <cstdlib> int main(int agrc, char *argv[]) { if (argc!=2) { return EXIT_FAILURE; } char buff[6] = ""; strncat(buff, argv[1], sizeof(buff)-1); } Related Topics: memcpy, strchr, strcpy, strncat, strncmp Another set of related (but non-standard) functions are strlcpy and strlcat.
http://www.cppreference.com/wiki/c/string/strncpy
crawl-002
refinedweb
285
57.71
Java objects’ state and behavior In Java, instances of a class are known as objects. Every object has state and behavior in the form of instance fields and methods respectively. public class Person { // state of an object int age; String name; // behavior of an object public void set_value() { age = 20; name = "Robin"; } public void get_value() { System.out.println("Age is " + age); System.out.println("Name is " + name); } // main method public static void main(String [] args) { // creates a new Person object Person p = new Person(); // changes state through behavior p.set_value(); } }. public class Person { int age; String name; // Constructor method public Person(int age, String name) { this.age = age; this.name = name; } public static void main(String[] args) { Person Bob = new Person(31, "Bob"); Person Alice = new Person(27, "Alice"); } } Java dot notation In Java programming language, we use . to access the variables and methods of an object or a Class. This is known as dot notation and the structure looks like this- instanceOrClassName.fieldOrMethodName public class Person { int age; public static void main(String [] args) { Person p = new Person(); // here we use dot notation to set age p.age = 20; // here we use dot notation to access age and print System.out.println("Age is " + p.age); // Output: Age is 20 } } Constructor Method in Java Java classes contain a constructor method which is used to create instances of the class. The constructor is named after the class. If no constructor is defined, a default empty constructor is used. public class Maths { public Maths() { System.out.println("I am constructor"); } public static void main(String [] args) { System.out.println("I am main"); Maths obj1 = new Maths(); } } Creating a new Class instance in Java In Java, we use the new keyword followed by a call to the class constructor in order to create a new instance of a class. The constructor can be used to provide initial values to instance fields. public class Person { int age; // Constructor: public Person(int a) { age = a; } public static void main(String [] args) { // Here, we create a new instance of the Person class: Person p = new Person(20); System.out.println("Age is " + p.age); // Prints: Age is 20 } } Reference Data Types A variable with a reference data type has a value that references the memory address of an instance. During variable declaration, the class name is used as the variable’s type. public class Cat { public Cat() { // instructions for creating a Cat instance } public static void main(String[] args) { // garfield is declared with reference data type `Cat` Cat garfield = new Cat(); System.out.println(garfield); // Prints: [email protected] } } Constructor Signatures A class can contain multiple constructors as long as they have different parameter values. A signature helps the compiler differentiate between the different constructors. A signature is made up of the constructor’s name and a list of its parameters. // The signature is `Cat(String furLength, boolean hasClaws)`. public class Cat { String furType; boolean containsClaws; public Cat(String furLength, boolean hasClaws) { furType = furLength; containsClaws = hasClaws; } public static void main(String[] args) { Cat garfield = new Cat("Long-hair", true); } } null Values null is a special value that denotes that an object has a void reference. public class Bear { String species; public Bear(String speciesOfBear;) { species = speciesOfBear; } public static void main(String[] args) { Bear baloo = new Bear("Sloth bear"); System.out.println(baloo); // Prints: [email protected] // set object to null baloo = null; System.out.println(baloo); // Prints: null } } The body of a Java method In Java, we use curly brackets {} to enclose the body of a method. The statements written inside the {} are executed when a method is called. public class Maths { public static void sum(int a, int b) { // Start of sum int result = a + b; System.out.println("Sum is " + result); } // End of sum public static void main(String [] args) { // Here, we call the sum method sum(10, 20); // Output: Sum is 30 } }. public class Maths { public int sum(int a, int b) { int k = a + b; return k; } public static void main(String [] args) { Maths m = new Maths(); int result = m.sum(10, 20); System.out.println("sum is " + result); // prints - sum is 30 } } Java Variables Inside a Method Java variables defined inside a method cannot be used outside the scope of that method. //For example, `i` and `j` variables are available in the `main` method only: public class Maths { public static void main(String [] args) { int i, j; System.out.println("These two variables are available in main method only"); } } Returning info from a Java method A Java method can return any value that can be saved in a variable. The value returned must match with the return type specified in the method signature. The value is returned using the return keyword. public class Maths { // return type is int public int sum(int a, int b) { int k; k = a + b; // sum is returned using the return keyword return k; } public static void main(String [] args) { Maths m = new Maths(); int result; result = m.sum(10, 20); System.out.println("Sum is " + result); // Output: Sum is 30 } } Declaring a Method Method declarations should define the following method information: scope (private or public), return type, method name, and any parameters it receives. // Here is a public method named sum whose return type is int and has two int parameters a and b public int sum(int a, int b) { return(a + b); }
https://www.codecademy.com/learn/learn-java/modules/learn-java-object-oriented-java-u/cheatsheet
CC-MAIN-2021-21
refinedweb
898
62.27
#include <rpl_gtid_persist.h> Compress the gtid_executed table completely by employing one or more transactions. Read each row by the PK(sid, gno_start) in increasing order, compress the first consecutive range of gtids. For example, 1 1 2 2 3 3 6 6 7 7 8 8 After the compression, the gtids in the table is compressed as following: 1 3 6 6 7 7 8 8 Compress the gtid_executed table, read each row by the PK(sid, gno_start) in increasing order, compress the first consecutive range of gtids within a single transaction. Delete all rows in the gtid_executed table. Encode the current row fetched from the table into gtid text. Fetch gtids from gtid_executed table and store them into gtid_executed set. Fill a gtid interval into fields of the gtid_executed table. Get gtid interval from the the current row of the table. Delete all rows from the table. Insert the gtid set into table. Insert the gtid set into table. Insert the gtid into table. Update a gtid interval in the gtid_executed table. Push a warning to client if user is modifying the gtid_executed table explicitly by a non-XA transaction. Push an error to client if user is modifying it explicitly by a XA transaction. Write a gtid interval into the gtid_executed table.
https://dev.mysql.com/doc/dev/mysql-server/latest/classGtid__table__persistor.html
CC-MAIN-2022-21
refinedweb
214
58.18
This is the final item in my series on Matching Algorithms and Reproductive Health, and it brings the story full circle, returning to the algorithms side of the show. Today I’ll demonstrate how to actually find minimum-weight perfect matchings in Python, and toss in a little story about . In case you’re new to this saga, when I say matching, I’m talking graph theory, and I mean a subgraph where every node has degree at most 1. If I have a graph where every edge has a real number as a weight, then one fun thing to look for is a minimum-weight perfect matching, a matching where every vertex has degree 1 and the sum of the edge weights is minimum among all such matchings. A vertex graph has perfect matchings, so for n of any interesting size you can’t wait for a computer to search through all of them. Fortunately, you don’t have to. Unlike my last ACO in Python tutorial, however, finding minimum-weight perfect matchings in general graphs is not a reasonable assignment for a programming class, even a very advanced one. If you are reading this page trying to get homework answers, you should double check what exactly was assigned. Either you’ve misunderstood the problem, or your professor is a cruel, cruel mathematician. Fortunately, a Python hacker named Joris van Rantwijk got obsessively interesting solving this too-hard-to-assign problem, and coded up mwmatching.py (and also a Perl version). Now we can enjoy the fruits of his labor. In [1]: from mwmatching import maxWeightMatching In [2]: maxWeightMatching([ (0,1,10), (1,2,15), (2,0,17) ]) Out[2]: [2, -1, 0] Can you guess what this output is saying? You might now know that this is not quite what I promised; I’ve found the maximum-weighted matching in a triangle with edge weights 10, 15, and 17. That’s not a minimum-weight perfect matching. But a feature and a trick save the day. The feature is a flag that Joris included in maxWeightedMatching, maxcardinality. Behold: In [3]: maxWeightMatching([ (0,1,10), (1,2,15), (2,0,17), (2,3,3) ], maxcardinality=True) Out[3]: [1, 0, 3, 2] The trick is a little sign-changing. If we find the maximum-weight maximum-cardinality matching in a graph with edge weights , then we’ve also found the minimum-weight maximum-cardinality matching in the graph with edge weights . Now I’m almost ready to show off something really cool. But we have to change one option in the mwmatching.py file first: """Weighted maximum matching in general graphs. The algorithm is taken from "Efficient Algorithms for Finding Maximum Matching in Graphs" by Zvi Galil, ACM Computing Surveys, 1986. It is based on the "blossom" method for finding augmenting paths and the "primal-dual" method for finding a matching of maximum weight, both due to Jack Edmonds. Some ideas came from "Implementation of algorithms for maximum matching on non-bipartite graphs" by H.J. Gabow, Standford Ph.D. thesis, 1973. A C program for maximum weight matching by Ed Rothberg was used extensively to validate this new code. """ # If assigned, DEBUG(str) is called with lots of debug messages. DEBUG = None """def DEBUG(s): from sys import stderr print >>stderr, 'DEBUG:', s """ # Check delta2/delta3 computation after every substage; # only works on integer weights, slows down the algorithm to O(n^4). CHECK_DELTA = False # Check optimality of solution before returning; only works on integer weights. CHECK_OPTIMUM = True def maxWeightMatching(edges, maxcardinality=False): """Compute a maximum-weighted matching in the general undirected weighted graph given by "edges". If "maxcardinality" is true, only maximum-cardinality matchings are considered as solutions. Edges is a sequence of tuples (i, j, wt) describing an undirected edge between vertex i and vertex j with weight wt. There is at most one edge between any two vertices; no vertex has an edge to itself. Vertices are identified by consecutive, non-negative integers. Return a list "mate", such that mate[i] == j if vertex i is matched to vertex j, and mate[i] == -1 if vertex i is not matched. This function takes time O(n ** 3).""" ... Line 27, says CHECK_OPTIMUM = True, but line 26 says that this only works for integer edge weights. So change it to read CHECK_OPTIMUM = False. Now, in the last two installments of this series, I shared some of the reasons why finding low-weight matchings is helpful in understanding reproductive health interventions. This practical problem has also inspired some beautiful, useless mathematics. For example, in the mid-80s, statistical physicists Marc Mezard and Giorgio Parisi got interested in the weight of the minimum-weight perfect matching when n vertices were joined to n other vertices by edges with weights drawn i.i.d. at random from the exponential distribution Exp(1). They made a conjecture, which was later extended by Don Coppersmith and Greg Sorkin, that as , the weight converges to . After years of work and inventing a whole new framework for analysis of random structures, David Aldous rigorously proved… that the limit exists! Since then there have been independent proofs by Aldous and others that the limit is indeed $\pi^2/6$, and that the expectation of the weight for finite-size instances is exactly as conjectured. I’ve always wanted a plot of that: And the numbers for that plot are easy to get: from mwmatching import maxWeightMatching from numpy.random import exponential as Exp def random_instance(a, b): """Generate an bipartite minimum-weight matching instance with random Exp(1) edge weights between {0, ..., a - 1} and {a, ..., a + b - 1}. """ edges = [] for ii in range(a): for jj in range(a,a+b): edges.append([ii, jj, Exp(1.)]) return edges def min_weight_pm(n): edges = random_instance(n,n) neg_edges = [(i,j,-wt) for i,j,wt in edges] match = maxWeightMatching(neg_edges, maxcardinality=True) return sum([wt for (i,j,wt) in edges if match[i] == j]) Since pictures of matchings look totally amazing, I’ll close with this math art I’ve been working on, a portrait of matcher Jack Edmonds, as a matching: 4 responses to “ACO in Python: Minimum Weight Perfect Matchings (a.k.a. Matching Algorithms and Reproductive Health: Part 4)” “Can you guess what this output is saying?” I can’t interpret the output. Could you please elaborate (quote “I can’t interpret the output. Could you please elaborate”) In [2]: maxWeightMatching([ (0,1,10), (1,2,15), (2,0,17) ]) Out[2]: [2, -1, 0] The output is a tuple of the respective mates for each vertex. Vertex 0 is matched to vertex 2, 1 to none (-1), 2 to 0. Hi, How did you do the math art? All with matplotlib and networkx. The code is lost in the sands of time, unfortunately.
http://healthyalgorithms.com/2009/03/23/aco-in-python-minimum-weight-perfect-matchings-aka-matching-algorithms-and-reproductive-health-part-4/
CC-MAIN-2015-06
refinedweb
1,143
62.68
WiPy 2.0 to send data to dweet.io and then display the data into freeboard.io - dgzgonzalez last edited by Hi All, I'm trying to send data from my WiPy device to the dweet.io site using a "post" call. I'm using the following lib: And I wrote the following code (Note, the indentation does not work here and I used .... instead) import urequests import json myData = {'Value_1': 20, 'Value_2': 300} try: ....response = urequests.post("", data = json.dumps(myData)) ....print(response.text) except Exception as e: .....print(e) I'm receiving back the following message {"this":"succeeded","by":"dweeting","the":"dweet","with":{"thing":"TheThing","created":"2017-07-19T16:52:41.547Z","content":{},"transaction":"5c436c5d-c772-4ab7-8dbd-b05321a47265"}} As you can see the payload ({'Value_1': 20, 'Value_2': 300}) is not passed through and I'm running out of idea on why this is happening. Does anyone has an idea or suggestion ? Thank you in advance for your help. Diego
https://forum.pycom.io/topic/1521/wipy-2-0-to-send-data-to-dweet-io-and-then-display-the-data-into-freeboard-io
CC-MAIN-2018-47
refinedweb
162
52.36
To create a neural network, you need to decide what you want to learn. Here, I’m going to choose a fairly simple goal: to implement a three-input XOR gate. (It’s an exclusive OR gate.) The table shows the function we want to implement as an array. I will use the information in the table below to create a neural network with python code only: for the Neural Network Before I get into building a neural network with Python, I will suggest that you first go through this article to understand what a neural network is and how it works. Now let’s get started with this task to build a neural network with Python. Also, Read – GroupBy Function in Python. Neural Network with Python: I’ll only be using the Python library called NumPy, which provides a great set of functions to help us organize our neural network and also simplifies the calculations. Now, let start with the task of building a neural network with python by importing NumPy: Code language: JavaScript (javascript)Code language: JavaScript (javascript) import numpy as np Next, we define the eight possibilities of our inputs X1 – X3 and the output Y1 from the table above: Code language: PHP (php)Code language: PHP (php) # X = input of our 3 input XOR gate # set up the inputs of the neural network (right from the table) X = np.array(([0,0,0],[0,0,1],[0,1,0], \ [0,1,1],[1,0,0],[1,0,1],[1,1,0],[1,1,1]), dtype=float) # y = our output of our neural network y = np.array(([1], [0], [0], [0], [0], \ [0], [0], [1]), dtype=float) We must now choose a value to predict: Code language: PHP (php)Code language: PHP (php) # what value we want to predict xPredicted = np.array(([0,0,1]), dtype=float) X = X/np.amax(X, axis=0) # maximum of X input array # maximum of xPredicted (our input data for the prediction) xPredicted = xPredicted/np.amax(xPredicted, axis=0) Save our squared loss results in a file to be used by Excel by epoch: Code language: PHP (php)Code language: PHP (php) # set up our Loss file for graphing lossFile = open("SumSquaredLossList.csv", "w") Build the Neural_Network class for our problem. The table above shows the network we are building. You can see that each of the layers is represented by a line in the network: Code language: Python (python)Code language: Python (python) class Neural_Network (object): def __init__(self): #parameters self.inputLayerSize = 3 # X1,X2,X3 self.outputLayerSize = 1 # Y1 self.hiddenLayerSize = 4 # Size of the hidden layer Now set all the weights in the network to random values to start: Code language: PHP (php)Code language: PHP (php) # build weights of each layer # set to random values # look at the interconnection diagram to make sense of this # 3x4 matrix for input to hidden self.W1 = np.random.randn(self.inputLayerSize, self.hiddenLayerSize) # 4x1 matrix for hidden layer to output self.W2 = np.random.randn(self.hiddenLayerSize, self.outputLayerSize) The function below implements the feed-forward path through our neural network: Code language: PHP (php)Code language: PHP (php) def feedForward(self, X): # feedForward propagation through our network # dot product of X (input) and first set of 3x4 weights self.z = np.dot(X, self.W1) # the activationSigmoid activation function - neural magic self.z2 = self.activationSigmoid(self.z) # dot product of hidden layer (z2) and second set of 4x1 weights self.z3 = np.dot(self.z2, self.W2) # final activation function - more neural magic o = self.activationSigmoid(self.z3) return o And now we need to add the backwardPropagate function which implements the real trial and error learning that our neural network uses: Code language: PHP (php)Code language: PHP (php) def backwardPropagate(self, X, y, o): # backward propagate through the network # calculate the error in output self.o_error = y - o # apply derivative of activationSigmoid to error self.o_delta = self.o_error*self.activationSigmoidPrime(o) # z2 error: how much our hidden layer weights contributed to output # error self.z2_error = self.o_delta.dot(self.W2.T) # applying derivative of activationSigmoid to z2 error self.z2_delta = self.z2_error*self.activationSigmoidPrime(self.z2) # adjusting first set (inputLayer --> hiddenLayer) weights self.W1 += X.T.dot(self.z2_delta) # adjusting second set (hiddenLayer --> outputLayer) weights self.W2 += self.z2.T.dot(self.o_delta) To train the network at a particular time, we will call the backwardPropagate and feedForward functions each time we train the network: Code language: PHP (php)Code language: PHP (php) def trainNetwork(self, X, y): # feed forward the loop o = self.feedForward(X) # and then back propagate the values (feedback) self.backwardPropagate(X, y, o) The sigmoid activation function and the first derivative of the sigmoid activation function are as follows: Code language: PHP (php)Code language: PHP (php) def activationSigmoid(self, s): # activation function # simple activationSigmoid curve as in the book return 1/(1+np.exp(-s)) def activationSigmoidPrime(self, s): # First derivative of activationSigmoid # calculus time! return s * (1 - s) Then save the epoch values of the loss function to a file for Excel and the neural weights: Code language: PHP (php)Code language: PHP (php) def saveSumSquaredLossList(self,i,error): lossFile.write(str(i)+","+str(error.tolist())+'\n') def saveWeights(self): # save this in order to reproduce our cool network np.savetxt("weightsLayer1.txt", self.W1, fmt="%s") np.savetxt("weightsLayer2.txt", self.W2, fmt="%s") Next, we run our neural network to predict the outputs based on the weights currently being trained: Code language: PHP (php)Code language: PHP (php) def predictOutput(self): print ("Predicted XOR output data based on trained weights: ") print ("Expected (X1-X3): \n" + str(xPredicted)) print ("Output (Y1): \n" + str(self.feedForward(xPredicted))) myNeuralNetwork = Neural_Network() trainingEpochs = 1000 #trainingEpochs = 100000 What follows is the main learning loop that crosses all requested eras. Edit the trainingEpochs variable above to vary the number of epochs you want to train your network: Code language: PHP (php)Code language: PHP (php) for i in range(trainingEpochs): print ("Epoch # " + str(i) + "\n") print ("Network Input : \n" + str(X)) print ("Expected Output of XOR Gate Neural Network: \n" + str(y)) print ("Actual Output from XOR Gate Neural Network: \n" + \ str(myNeuralNetwork.feedForward(X)) # mean sum squared loss Loss = np.mean(np.square(y - myNeuralNetwork.feedForward(X))) myNeuralNetwork.saveSumSquaredLossList(i,Loss) print ("Sum Squared Loss: \n" + str(Loss)) print ("\n") myNeuralNetwork.trainNetwork(X, y) Save your training results for reuse and predict the output of the requested value: Code language: CSS (css)Code language: CSS (css) myNeuralNetwork.saveWeights() myNeuralNetwork.predictOutput() Now after running your python file, you will see the program start to cycle through 1000 training epochs, print the results of each epoch, and then finally show the final input and output. Epoch # 999 Network Input : [[0. 0. 0.] [0. 0. 1.] [0. 1. 0.] [0. 1. 1.] [1. 0. 0.] [1. 0. 1.] [1. 1. 0.] [1. 1. 1.]] Expected Output of XOR Gate Neural Network: [[1.] [0.] [0.] [0.] [0.] [0.] [0.] [1.]] Actual Output from XOR Gate Neural Network: [[0.93419893] [0.04425737] [0.01636304] [0.03906686] [0.04377351] [0.01744497] [0.0391143 ] [0.93197489]] Sum Squared Loss: 0.0020575319565093496 Predicted XOR output data based on trained weights: Expected (X1-X3): [0. 0. 1.] Output (Y1): [0.04422615] Also, Read – Lung Segmentation with Machine Learning. So this is how to build a neural network with Python code only. I hope you liked this article on building a neural network with python. Feel free to ask your valuable questions in the comments section below. You can also follow me on Medium to learn every topic of Machine Learning and Python.
https://thecleverprogrammer.com/2020/09/07/neural-network-with-python-code/
CC-MAIN-2021-43
refinedweb
1,279
51.89
Introduction ============ You receive this message because you are subscribed to the MinGW mailing list. This is reminder/mini-FAQ sent once a month. If you want to unsubscribe, please visit . Have your password handy (if you can't find it, you'll be offered an option to have it mailed to you). What is MinGW? ============== MinGW stands for "Minimalist GNU for Windows" and is development package (as well as target) which allows to compile software for "native" Windows 32-bit platforms. Please visit for more information. Who is author of MinGW? How is it maintained? What is licensing? ================================================================ MinGW was created by Colin Peters and put by him in public domain. There is no centralized force behind MinGW - it is maintained by volunteers and its development directed by the user community. MinGW uses free GNU C/C++ compiler, its core libraries/headers are in public domain and it uses vendor-supplied runtime library, so in short, you can use it to develop royalty-free software, either open- or close-sourced. For more comprehensive licensing terms, please visit Can MinGW be used to compile GNU or OpenSource software? MSVC one? ================================================================== MinGW runtime library adheres to ANSI C standard and offers some bits of POSIX compatibility, so many software packages can be compiled with little or no changes. However, most GNU software (and OpenSource sofware in general) nowadays uses GNU configure-based build procedure, which cannot be handled by MinGW directly. The solution is to cross-compile to MinGW from more complete environment. MinGW was specifically created to allow "native" (read: MSVC-hosted) source to be compiled with GCC. Most projects compile without any changes. Still, some changes to build procedure may be required. Tools for automated conversion of MSVC projects exist. Support ======= MinGW's web site is . There, you can find general information, download and installation instructions, links to ported software, FAQ, history and news, etc. MinGW mailing list () is a place to aks questions, discuss MinGW-related issues and announce availability of software. Before posting questions, please make sure that it is not covered in comprehnsive FAQ (). Searching mailing list archives may be laso helpful (archives accessible from the mailing list homepage). Reporting bugs and contributing =============================== MinGW, Sorry(for duplication). In previous posting I didn't descriibe probem . Now full description: While using mingw 2.95.2-1; msvcrt, tnext program works incorrect way: /******* test.cpp ********/ /* command line: g++ -mthreads test.cpp -lwsock32 */ #include <winsock2.h> #include <stdio.h> int main() { WSASetLastError(10048); int t1 = WSAGetLastError(); int *t = new int; int t2 = WSAGetLastError(); printf("%d, %d\n", t1, t2); return 0; } /* EOF */
https://sourceforge.net/p/mingw/mailman/mingw-users/?viewmonth=200010&viewday=7
CC-MAIN-2017-51
refinedweb
432
59.4
Testing IT Professionals On Job Interviews? 1057 An anonymous reader writes "After having my university degrees, a couple of IT certifications, and over ten years of work experience in the industry, with 2-4 years of verifiable employment with each employer, working with a wide range of technologies,? More importantly, why do IT professionals accept being treated less favorably than members of other professions? Should IT professionals start to refuse to be treated as not real professionals?" No, it is not reasonable. (Score:5, Interesting) I won't take them. I have turned down several jobs over it. Re:No, it is not reasonable. (Score:5, Insightful) If you are going to be that flexible in the interview its probably good for both you and the employer that you aren't working for them ;) Re:No, it is not reasonable. (Score:5, Insightful) That is true. I am interviewing them just as much as they are interviewing me. Life is too short to work someplace where I wont be happy. 99.9% of the time the person doing the interview won't understand the answers anyway. Maybe I am just getting old. Re:No, it is not reasonable. (Score:5, Insightful) If you weren't an Anonymous Coward, I'd mod you up. If you weren't a poster on slashdot, I'd give you a big hug and a wet Bugs Bunny kiss. It breaks my heart to see talented young people walking into a job interview as if they were being called to the principal's office. Re:No, it is not reasonable. (Score:5, Insightful) Re:No, it is not reasonable. (Score:5, Interesting) Right because being burned by incompetence doesn't happen in any other field right? It couldn't be the fact that most companies haven't a clue how to properly manage IT and grasp for any available opportunity to quantify work done and qualify decisions made even if doing so grossly inappropriate. Re:No, it is not reasonable. (Score:5, Insightful) Right because being burned by incompetence doesn't happen in any other field right? Actually it does happen in other fields, the whole premise of this article is wrong. I'm a statistician/epidemiologist and every post I've ever applied for has had some kind of techincal test. Some have been more formal than others. Anyway if I was applying for a post that needed a high level of technical knowledge I would expect to be tested on it. Re:No, it is not reasonable. (Score:5, Insightful)... Re:No, it is not reasonable. (Score:4, Insightful) Giving a "job talk" is fine. When I've interviewed people that's usually what I've focused on... what did you do in your last job, and how did you do it? How well can you explain it? If you can't explain to me how your project worked, or it sounds like BS, that's a pretty clear danger sign. Just because you know the details of some programming language or can write a loop in Perl that doesn't mean you can get the job done. And personally, I have to deal with so many languages in one day that I'm lousy at remembering syntax, or the differences between java io library and C# io library, I have to use cheat sheets that I've built up. Doesn't mean I'm a crappy programmer. Re:No, it is not reasonable. (Score:4, Funny) Correct. And any test that doesn't accept pseudocode is retarded. Re:No, it is not reasonable. (Score:4, Interesting) See,not that kind of questioning I have NO problem with,as that would mean you would have to have a grasp of what was going on and could actually have a conversation with me about it without my having to "dumb down" or try to fill it with techno babble buzz words. Sadly though too many places are leaving such things up to HR people who have NO clue and are only looking for the "buzzword o' the day" and trying to explain anything to them is like trying to take a room full of Pentium 90MHz and run Vista on it. In the end all you do is get a really nice skull thumping headache for your troubles. I mean look at my example. Some HR genius said "Well this test worked for our last opening. We should use it again." even though the test have nothing at all whatever to do with the actual position being filled. See I would have no problem sitting down an discussing computers with someone that knew what they were talking about. In fact the last interview I had like that me and the guy ended up laughing about how much fun it was trying to chase down VxD errors in Win9X and how much fun it was dealing with Pre SP2 XP compared to Win2K. But sadly you are seeing less and less of that,and more and more of "HR says jump through this hoop". Which is why I'll end up going back to school for economics while I make extra cash running my little PC shop. Because clueless tests and BS certs have really started to take the fun out of IT for guys like me that work on computers because we love the technology and learning new things. While my friends play WoW I fire up a VM just to try some weird new OS just to play with its insides and see what it does. Now THAT is fun to me. But as always this is my 02c,YMMV Re:No, it is not reasonable. (Score:5, Insightful) Additionally, they do have to take a test. It's called Bar Exam, CPA certification, etc... These are standardized tests that everyone agrees is robust enough to demonstrate competence. There is no standardized test for IT workers. No, passing MSCE and A+ crap does not count. A+ is somewhat standardized, but honestly there is no IT test that is worth a crap. Arguably some of the Cisco tests are adequate to demonstrate Networking knowledge, but that doesn't mean you are worth a crap when it comes to fixing a broken down Unix machine or even a Windows machine. It also doesn't mean you can build/rebuild a computer. The field of IT is so broad that coming up with a standardized test is not really feasible. The technology field also moves so fast that a standardized test would be outdated by the time it was developed and agreed upon. Since you only have 2 - 4 years of verifiable employment at each company, I would question your abilities as well. 2 - 4 years is just enough to get a job and for the company to find out you are totally incompetent and then fire you. If you had said 6 - 8 years per company, then you might have a case. Re:No, it is not reasonable. (Score:5, Insightful) I remember, in particular, a 2002 ad looking for people with 5 or more years of Windows 2000 server experience. Or the people looking for 10+ years of experience in JAVA in 2003 (which only debuted in 1995. . . do the math. . .) The real problem, is the clueless tyrants in HR. . . Re:No, it is not reasonable. (Score:4, Insightful) Those are fake jobs, used to justify the need to import (cheap) labor, principally from India (as far as IT goes, nurses get hammered by H1B visa's too). They advertise a job, no one applies since the requirements are mathematically impossible to fulfill and the "vacancy" is filled by an H1B. Note: I'm not against immigration, I say if they are really worth it (H1B visa), give them a permanent green card immediately. Make the company pay for it (verification, testing, etc) and make them hold a bond equivalent to a foreign investor visa. That saves the taxpayer, the immigrant who can now freely change jobs w/o need for further sponsorship and the native worker who would otherwise have to compete with non-free labor. H1B's require sponsorship to stay, so they are not free as in freedom workers. Re:No, it is not reasonable. (Score:5, Insightful) Re:No, it is not reasonable. (Score:5, Insightful) The biggest problem I run into when hiring an "IT Professional" is that a good 60% of them either outright lie or hilariously exaggerate about their experience/training. I'd much rather hire a person whose honest about what skills he/she does/doesn't have but demonstrates solid problem solving skills. If you've never administrated a SAN, don't tell me that you have and not expect me to ask a few probing questions.... Referring to yourself as an ESX guru but then not knowing what vmotion is won't win you any friends (or a return interview). As a general rule, before my boss is going to let anybody loose in the server room, expect to spend a couple of hours in a conference room in front of a white board. Expect to be asked about your experience and expect to demonstrate problem solving skills related to those skills. Expect to be given some theoretical problems and be asked to solve them. Also, an answer of "I'd have to check google" is actually okay. Re:No, it is not reasonable. (Score:4, Insightful) It's also an easy way to filter out the bullshitters. About nine years ago I had to help hire for an entry level web programming job. Every asswipe that could spell HTML had 4 years of it on his resume. A test might have saved everyone some pain. And you don't have to look at testing as a punishment. It's just another way to show off your skills. And it can be a valuable insight into the company - a stupid test may warn of PHBs in your future. Besides, I think we would all be better off if all professionals (especially CIOs) were given tests prior employment. Re:No, it is not reasonable. (Score:5, Insightful) Or maybe your company bothering to check references would have saved everyone some pain! Sure. So they have to go through a dozen "references" for every Tom, Dick and Harry who's claimed to make a website. "Yeah, see? I designed that. Yeah, yeah, I designed that one. Oh, and here's a list of ten more rando.. er.. samples of my work!" Takes way too much investigative research to find fakes from reality. It's much, much easier to just give someone a simple test. Here's an example layout, here's content. Do x, y, and z with the content. Make this part dynamic. Would you like a coffee or tea while you work? My final exam for Web Page Authoring in college was essentially like that. Here's a range of data; create a simple database, input the information, make the webpage give me data based on this list of criteria and lay it out in a functional manner. I got delayed because there were no working computers left so I lost the first 30 minutes of a 90 minute exam session but I was still the first one done. If you know the material it'll be a breeze. If you don't you'll flounder around and you won't get the job. Wait - wasn't it a complaint of IT professionals that every jackass with a home computer came into the IT industry and called themselves a pro?!? Since we don't have a trustworthy certification body for the industry wouldn't it be prudent to expect skills tests to assure an employer that you're an actual professional rather than somebody's nephew who, like, really knows computers and stuff? If doctors were that bad, it would be manslaughter (Score:5, Interesting) Re:If doctors were that bad, it would be manslaugh (Score:5, Interesting) I went to a job interview in '99 for a contract doing Network Admin for a pretty major bank; I had no certs, no degree at the time, but I had been working off and on with Tek systems for several years and they knew I had extremely extensive experience. The Bank didn't want to interview me, but the recruiter sort of insisted; they were asking for people qualified in NT, Solaris and OS/2, and I was really about the only person they had available at that time with the right mix. It was a working lunch interview; They started asking questions, and I started answering. then came the question, "what command would you use to upgrade a NT workstation machine to NT server?" I replied that you would probably be best off formatting the drive, then installing it, as there was no good way to upgrade; Microsoft said you couldn't do it at all, and the workarounds were more trouble than they were worth. The interviewers sort of grinned, and told me that of the 20+ people they interviews, all of which had at least a MCSE or a comp sci degree, not a single one of them had answered the question correctly. At the time I had problems believing it, but as time went on and I got in to situations where I was doing interviews it got more believable; in the late 90's if you worked on computers, it was probably because you were a computer enthusiast and actually more or less enjoyed working with them; after about '98, you started running into people that were just doing it because it paid well; they might be damned smart people, but you lose something when you don't actually enjoy working with computers. I also saw a lot of people who just were not smart enough, but were somehow able to cheat or memorize well enough to get a degree; when you asked them something that wasn't in anything they had studied, they didn't have the core of hands-on knowledge that would enable them to make an educated guess at the answer. So, yeah, I have to agree, interview everybody no matter what their credentials are. Re:If doctors were that bad, it would be manslaugh (Score:5, Insightful) In 2001 I worked as a supervisor in a callcenter(by now bankrupt and bought out) that specialized in tech-support for consumer software and hardware. At one point our recruiter asked me to test an applicant she didn't have a good feeling about. The applicant had numerous impressive looking certifications on her resume and quite a confident demeanor about her abilities. She claimed to be specialized in Microsoft operating systems. Note that this was your typical callcenter full of pc enthusiasts, many of whom had no formal education in IT whatsoever. Long story short, at the time we also did support for a company that distributed a number of very popular pc games, so I gave the applicant a game consisting of 3 cd-roms and asked her to install it on a typical win98 workstation. After watching her struggle for about 10 minutes, while completely ignoring the big autorun window with the huge "Install game" button on it, we decided perhaps hiring her would not be such a good idea after all... Re:If doctors were that bad, it would be manslaugh (Score:5, Insightful) FizzBuzz is great; we use it on every single interview for a programming position, regardless of experience. I've seen people come in with 10+ years of programming experience, and completely screw it up. More importantly than just showing whether or not somebody can code, it shows whether or not they can handle simple tasks under pressure. I'm sure most of those applicants could have completed it at home when they're not being watched, but if they can't do it in an interview, then how are they going to perform on-site at a client, when a major bug just popped during a production push? FizzBuzz (Score:5, Funny) CAN HAS STDIO? I HAS A NADA ITZ 0 I HAS A VAR IM IN YR LOOP UP VAR!!1 I HAS A ANZER ITZ "" BOTH SAEM MOD OF VAR AN 3 AN NADA, O RLY? YA RLY ANZER "Fizz" OIC BOTH SAEM MOD OF VAR AN 5 AN NADA, O RLY? YA RLY SMOOSH ANZER AN "Buzz" MKAY OIC BOTH SAEM ANZER AN "", O RLY? YA RLY VISIBLE VAR NO WAI VISIBLE ANZER OIC VISIBLE ":)" BTW DAS A NEWLINE IZ VAR BIGGER THAN 100? KTHXBYE BTW IMMA SO GUNNA GET HIRED! IM OUTTA YR LOOP KTHXBYE Re:If doctors were that bad, it would be manslaugh (Score:5, Informative) Re:If doctors were that bad, it would be manslaugh (Score:4, Funny) Re:If doctors were that bad, it would be manslaugh (Score:4, Funny) I got a job by refusing the test (Score:5, Insightful) 1996, and I'm being interviewed by Chrysler (over the phone, no less, as I was 2000 km away) for a position as a web application designer. The interview is going well, and then the interviewer starts asking a rapid fire sequence of obscure programming trivia questions - things like the arguments to certain system functions, that sort of thing. After about the third or fourth punt (these questions were really obscure), I started to get a little angry, and I told the interviewer that if that particular question ever came up in my code, that it wasn't necessary for me to have the answer memorized. Man pages and paper manuals exist for a reason (this was before the all-knowing Google) and if I really needed to know the answer, I would look it up. In fact, even if I was reasonably confident of the answer, I'd STILL look it up because the time spent looking up the answer and ensuring it was right was very much less than the time spent guessing, getting it wrong, and debugging the error. "Real work" I said "is an open-book test". The next thing she said was "When can you start?" I don't need to have an answer immediately at hand to every question. What I need is to know how to FIND the answer to a question as quickly as possible given the resources at hand. If you want to test me during an interview, I'll look at the test. If it is related to problem solving or general concepts (ie, explain the differences between a "foreach", "while", and "do until" loop) - OK, I'm game. But if it is trivia, I won't play, and I'll explain why. If you insist... I will seek employment elsewhere, because I'm not interested in working for someone who insists on procedure for procedure's sake. DG Re:No, it is not reasonable. (Score:5, Insightful) Please, please people, remember that a job interview is also your chance to evaluate an employer. If there's any aspect of a job interview that makes you feel like you are being disrespected, you can bet that this will be a company that will show you little respect as an employee. Humiliation on a job interview is an excellent indicator of future happiness at that company. If you believe in your skills, if you believe yourself to be valuable, do not be afraid to say "no thanks". The reason many workers feel like they are being treated badly is because they are being treated badly. You are going to be spending the major part of your waking hours at your job. You should be choosing very carefully. Re: (Score:3, Insightful) Umm. Surely being given an opportunity to demonstrate one's skill/flair isn't disrespectful? Don't you want to show off? Re:No, it is not reasonable. (Score:5, Interesting) I sat down and looked at it for maybe 5 minutes. Nobody came out and introduced themselves to me or asked me any questions about myself. I thought, "Is this the sort of place I want to work?", decided the answer was "no", got up and walked out. That was the last I heard of them. That sort of treatment of a potential employee is disrespectful. If they'd interviewed me, decided they liked me and wanted to verify some skills and asked if I would take a test, that would be completely different. On a sort of related note, I had an employer later on who was considering making potential hires take a personality test. He asked us for our feedback and I told him that if he'd asked me to take one before being offered a job, I would refuse. In an interview, I have no idea who these people are, and if they're qualified to read a personality test. Those things in the wrong hands are a weapon to limit you more than anything. If the test says you're below par at problem solving, or people skills, or whatever, prepare to be pigeonholed for the rest of your time there, if you're lucky enough to get the job. I'm not saying they're useless in all cases, but it takes a trained psychologist to correctly asses the results and determine where they can be usefully applied and where they cannot. I think almost any reasonable person reading this discussion would agree that some sort of verification of an interviewee's credentials is a good idea during the interview process. It's how it's done that's up for discussion. Re:No, it is not reasonable. (Score:5, Informative) Surely being given an opportunity to demonstrate one's skill/flair isn't disrespectful? It depends on how it's done. Exactly. I'm in the camp that says some sort of programming test is fair for any level. If you're really a "Senior software engineer" with "excellent $LANGUAGE skills" then writing something like fizzbuzz will only take you two minutes, right? The number of people I've seen come to an interview making that sort of claim who could not code fizzbuzz is scary. Perhaps unsurprisingly, my tolerance for taking this sort of test myself increased significantly when I crossed from being an experienced developer who just found them patronising to having the kind of role that also involves sitting on the other side of the table from time to time and seeing what some of the other candidates are like. On the other hand, I rather doubt I'll ever be working for the kind of place that has a whole-day interview process that consists of solving an endless series of trivial programming problems, followed by a load of "Have you seen this one before?" questions like the 1/2/5/10 problem. These tests are only useful as a block for the low end prankster, not as a way of gauging how good someone competent really is. After the first couple, if it seems like there are going to be more, I will take control of the interview and, usually, end it shortly thereafter. This is a valuable reminder that interviewing is a two-way process, and that those applying for higher positions with more responsibility should be entitled to ask "difficult" questions that any competent employer should have no difficulty answering, too. Just as a significant proportion of interviewees are a joke, so are a significant proportion of interviewers/employers. These days, I'll basically let a prospective employer run the first interview, but if I'm called back for a second interview so I know they are serious, I will ask to see a sample of their production code and a sample of their development documentation, I'll ask straight questions about their software development process, company culture and working conditions, and if I'm still ambivalent perhaps I'll ask to speak privately with a current employee who is doing a similar job to the one I'm applying for. Re:No, it is not reasonable. (Score:4, Insightful) I agree. I had no problems going up to a white board and writing my pseudo code to solve problems. I've also talked about my personal coding style and given detailed summaries of my thesis. I can't understand why you'd object to your potential employer wanting to make sure you'll be adequate for the job before sinking tens of thousands of dollars into hiring you.... If someone refuses, then either they have a really poor attitude (the same kind of person who wouldn't dress nicely for a job interview because "hey, it shouldn't matter"), or you are really trying to snow your way into a job. Comparing it to other industries sounds like my kids whining. You don't need to worry about accounting or the legal offices where you work, you just worry about your IT job. Besides, most certifications in other fields are more worthwhile than something like an MCSE, anyway. Face it, we don't have a good certification for Software Engineer because the subject is too broad to have one... even if you are well schooled on techniques (how to solve a problem), you may not know networking, or UI programming, or 3D graphics, or something specific the company needs, and it's impossible to know everything in this field. Re:No, it is not reasonable. (Score:5, Insightful) It can be annoying, but I hardly think it's that big of a deal. I don't work in IT, I work as a creative in advertising, but I've had to take 'tests' when applying for a job. I'm given a sample brief and asked to come up with a campaign concept. I'm given those tests because agencies work differently with different accoutns and some people are just not good fits from one to another. I would imagine the potential exists for an IT professional with a glowing CV to still be a poor choice in a particular company. At least they're not testing your social skills as well. Re: (Score:3, Interesting) A FLOSS(ed) resume helps avoid them. Work on the free/open source programs that you like, then point your employers at commit diffs (as well as your responses to idiotic questions on the respective mailing lists showing that your tolerant and work well with others). 8/10 times, in my experience .. an employer is just as happy to browse my Mercurial repositories as they are to give me a test. Sometimes, though .. they make the test a little harder after viewing my repos :) When you run into 'head hunters' , th Re:No, it is not reasonable. (Score:5, Interesting) It is entirely reasonable. Having a degree, and even several (perhaps many) years of verifiable / verified "experience" says very little about your actual qualifications. One of the best developers I know has a degree in history, and within 6 months of beginning development was producing better quality work than some guys who have been developing for years. Also the number of people who lie about their qualifications is unbelievable. Many previous employers are afraid of getting into legal trouble and so will never give a real reference, either positive or negative. They'll basically only confirm dates of employment. Finally, this industry is full of really excellent snow job men. People who have convinced their previous employer that they're really a cracker-jack developer, when in fact they are only barely able to cobble together code examples from other people. Also it's not infrequent for several candidates to have what looks like reasonably similar experience on paper, yet differ widely on actual performance skills. Last month, we interviewed a guy for a ColdFusion developer job, and when we asked him what the difference between a Struct and an Array were (one is associatively indexed, and does not preserve insert order, the other is sequentially numerically indexed and of course does preserve insert order - an equivalent to a HashMap and a Vector), he sputtered and stammered for a few seconds, then proceeded to read us search results from Google (we all followed along on our end) which were not an answer to the question ("Let's see, you can append a Struct. Oh, but then you can append an Array"). Some consultant firms make money only for placing a body in a seat. So some of these firms actually falsify resumes and provide references which are also false (they employ the people who answer the phone or respond to the email when you check the reference). They even go so far as to have a handful of guys who do the phone interviews - and these are not the same guy who shows up. Some times the guy who shows up has no experience with the technology at all. Plus, who told you other professions don't get tested? Some jobs even come with personality tests - maybe they're looking for someone hyper aggressive, maybe they're looking for a peace maker. Though such tests are usually for higher up positions, and usually only for the short list of candidates. It's not degrading in the least to be required to take a test to prove your qualifications. If you have the qualifications you profess to have, you should have no problem with the test. It's safeguarding the company at hand, and if you wanted to refuse to take the test, we would want to not hire you. It's a matter of there being too many slime balls and con men out there in the world, we can't take you at your word until we know you. Until then we need to ask you to prove yourself to us. Re:No, it is not reasonable. (Score:5, Funny) What is the difference between an Apple and a Pear?! You have Ten seconds to answer! Go! Re:No, it is not reasonable. (Score:5, Interesting) It's even worse than that: As a computer scientist, I pick up new stuff up quickly. So what that I've been doing Java for the last N years, give me a C project and I'll do it (without memory leaks, I know what a pointer is and can use valgrind --- Oh, and exactly this happened this year and I delivered.). That however, seems to be beyond the comprehension of anyone hiring people. Getting a well rounded computer scientist is better than getting someone who knows the buzzwords and can code a bit in one language. However, I'm sure I'd fail on any Java test or C test. The details (what's usually asked in such tests) do not matter, you'll find them quickly with a Google search because you're trained to know what to search for. Frankly, I don't get it. Re:No, it is not reasonable. (Score:4, Funny) "However, I'm sure I'd fail on any Java test or C test." I thought that, too, but now I'm convinced you'd do okay. I took a test recently for Java (the company insisted, even though Java wasn't on my resume at all, and I relented), and I scored "Master - Can mentor others" even though I've never done anything serious in Java (maybe played around with it a few years ago). For someone who knows C-family languages, the tests are cake. I guess they're only intended to weed out those who truly know nothing at all. Re:No, it is not reasonable. (Score:4, Insightful) I think you're assuming that everyone applying for a programming job is a CS major. Not the case, and this is why you might not understand. IT is a profession where people come from varying backgrounds and have learned the skills they posses through necessity or just desire. I myself hold a B.Arch, but I have been around computers since 1975 and been programming since about 1980. There are plenty of us that aren't CS majors that also pick up things quickly, have the math chops and the experience of coding multiple projects across varying languages and vertical markets. You never know where the good people are going to come from, so, you test. Re:No, it is not reasonable. (Score:5, Funny) Re:No, it is not reasonable. (Score:4, Funny) Even worse, he didn't even see if his code would compile (preview) before checking in (submitting) his work. Tisk tisk tisk. Re:No, it is not reasonable. (Score:5, Funny) So you're saying she'll be an average lawyer? Re:Interview question - universal answer!! (Score:5, Insightful) Interviewer: OK, so you know C? what is the result of i=0; i=i++; Joe Blow: Uhhhh...I....uuhhhh...it's compiler dependent!! Is the correct answer! Without an output statement you'll never know, a compiler could legally optimize the whole lot away! Re:Interview question - universal answer!! (Score:5, Insightful) It doesn't matter if it's compiler-dependent or not. The correct answer to that question is: "This code is badly written. It never makes sense to write i = i++. You probably mean i++." Re:Interview question - universal answer!! (Score:4, Informative) Script started on Mon Sep 15 07:59:50 2008 ./test bash-3.2$ cat test.c #include <stdio.h> int main(void) { int i = 0; i = i++; printf("i = %d\n\n", i); return 0; } bash-3.2$ gcc test.c -o test bash-3.2$ i = 1 bash-3.2$ exit exit Script done on Mon Sep 15 08:00:04 2008 Re:Interview question - universal answer!! (Score:5, Informative) Why not get the compiler to do the work for you: $ gcc -o test -Wall -W -ansi -pedantic test.c test.c: In function `main': test.c:5: warning: operation on `i' may be undefined $ Lo and behold. It's undefined behaviour. $ i = 0 $ And look. I don't get the same results as you. (Probably depends on the precise version of gcc and also maybe the optimizations selected.) Tim.. Re. No, its not. However, the craft of coding can be tested in an interview. Software engineering mostly cant (because it includes strategic and long termn decisions). There is not much craft in "most other fields" - they depend more on virtues like thoroughness etc. - which cant be tested in an interview. Skills can be tested in an interview, virtues less so. Re: (Score:3, Interesting) It is true that it is difficult for an employer to tell a good employee from a bad employee. Sadly, this has lead to what I can only call "hiring voodoo" -- the irrational belief without evidence that a relatively untrained interviewer will mysteriously be able to find out more about "what a candidate is really like" in an hour than the candidate's university or co-workers (references) found out in several years. Even stranger beliefs have cropped up over the years -- eg that artificial toy questions lik Re:Blame it on the idiots who can sell themselves (Score:5, Interesting) Wrong. It is only that incompetence in IT is much harder to cover up than in those professions. When IT systems fail, they can fail spectacularly and effect wide numbers of people. An incompetent IT persons mistake will cause an essential server or the like to fail. If they're not competent to fix it promptly, it will show. Inversely, when a lawyer, accountant, sales, HR person, etc screws up, the screw up will not be noticed as much unless it reaches epic proportions. It's easier to mask a mistake in these fields, and with the softer ones, e.g. PR, their metrics are so fuzzy that the difference between competence and incompetence is blurry anyway. Plus they are trained in buzz speak which they blurt out like a frighted squid spurts out ink to mask their escape. Re:Blame it on the idiots who can sell themselves (Score:5, Informative) I have used "effect" as both a noun and a verb for the majority of my life, in both the written and spoken word. "to effect" is a verb. The only problem is that it is synonymous to "to cause", and not to "to impact". "The effects of an earthquake can effect large numbers of people." Which, when replacing "to effect" with its synonym, becomes: "The effects of an earthquake can cause large numbers of people." Yes, I assume that after an earthquake, there's not much else to do until the electricity comes back on. The "correct" form however, offers no justification for itself other than its own inertia. The "correct" form offers the justification that it has a completely different meaning than the incorrect one. That should be sufficient. Let me give an example (Score:5, Interesting) 1. Yep. Let me even give an example. It didn't happen in a team I was in, but I know several people from that team. So they got a new guy who had some outstanding experience, according to his resume. He had worked on major enterprise projects, been an architect, ate Enterprise Java Beans for breakfast, etc. Turns out he was utterly incompetent. He spent about a month just getting used to their architecture and IDE and everything, apparently everything they did or the way they did it was new to him, and he needed some time to accomodate. Fair enough. Then started working on something, but never was quite done with it. Eventually they started asking to see some results. He started randomly changing files and checking them back in. The first few times he even had a good excuse, like "oops, I hadn't worked with this particular versioning system before" or "oops, I forgot some other file that mine depends on." There go a few more weeks, before it's obvious that his changes can't possibly even compile, because they have elementary syntax errors. Eventually they fire him, but by now he's got several months of "experience" there. Then someone finds his updated resume online. The guy claimed he singlehandedly improved their architecture, increase performance X times, got project management back on track, etc. 2. 'Nother example, my ex-coworker Wally. Spent two years on a trivial module, whose core someone else rewrote from scratch in 6 hours. It took another two weeks or so, mostly of testing, to get it bug-for-bug compatible with his, since a couple of teams already had their own workarounds for them. (Trying to get him to fix it was a bit like negotiating with the terrorists.) The rewrite was also benchmarked as 40 times faster than Wally's on large data sets. Literally. Measured. The thing everyone remembers fondly about him, is how he asked for 2 weeks just to estimate the effort to fix a trivial bug. He got it too. (His team leader was a bit a Mr Testicle: technically he was involved, but he kept out of it as much as possible;) He also massively practiced obfuscation. Any of his modules contained half the techniques from How To Write Unmaintainable Java code (literally) and megabytes of files copied from unrelated stuff to pad the number of lines of code per day. Obviously, it worked on his team leader. Then he got moved through the maintenance of two other programs (one at a time), and just managed to make them both worse. There we go, that's his provable 2-4 years employment. Well, ok, 5 in his case. 3. Example number 3: Old Father Williams. I got to think of him that way after a particular fortune on my linux box: Pretty much spent 6 years in a place complaining about everything that everyone else did. Coding style, IDE, OS, _everything_. His first choice of a whine was Windows, which might even have had a point, but when Linux was finally allowed and half the team switched to Linux, plus the servers actually went Linux... he proclaimed Linux to be sell-out crap for idiots, and switched to preaching BSD. He also caused a reformat-and-commit war in which he was preaching _three_ space tabs, as spaces. And wasn't affraid to check out someone else's project and reformat it, to make his point. He spent two years, just "modernizing" the build process. Nobody knows what he experimented with on his c Re:Let me give an example (Score:5, Interesting) 4. Abdul, the apprentice of Wally. He got hired through a workaround, since hiring more coders was on hold at that corporation. So someone hired him as a web designer, then hastily dubbed him programmer. Ironically, he seemed actually decent at web design. As a programmer, the consensus is that he's too stupid to piss holes in snow. Seriously, he doesn't understand even the elementary basics, and is constantly on the look out for someone to pass solving anything onto. Has that job for some 4 years now, since firing him would face the same problem with hiring a replacement. So he's keeping his job by sheer virtue of being marginally better than nothing. Companies are really bad at dealing with this. I was in a company who gave a web developer a shot at a trainee programming position. She was an excellent web designer, but a really poor programmer. I was her team leader, so I asked her if she was happy with her new position, and she said "no, I just don't seem to think that way. It is difficult and seems to be quite tedious". I asked her if she would like to move back to her old position, and she said yes. I thought this would be no problem, as we were noticing that the look & feel of the public site was not as polished since she left that group. I hadn't counted on HR. "you can't go from a trainee programmer to a senior web developer, that's two level's difference. She will have to move sideways to trainee web developer" They said. I pointed out her experience, the fact that she had done the job before and had excellent reviews but it was to no avail. They made a "concession" that she could move to "web developer" with a promise of promotion to "senior web developer" with in a year "if she performed OK", but anything else would contravene the HR procedures manual! We lost her. I don't blame her, she took a senior position in a small web company. Career wise this has been a good move for her, the company has done well and she is now in charge of a department. It was our loss though, sometimes the company is so stupid. Re:Blame it on the idiots who can sell themselves (Score:5, Insightful) Man you guys who think this is an IT only thing, really need to get out and look around. Yes you can't test for everything, but you can get a decent feel if if the person has some competency with the code for a programmer. I've seen mechanical engineers asked to design a solution to a problem. I've seen drafters/designers given tests with the software they use. Welders get tested before being hired. Divers get tested before being hired. I don't understand what the big problem is. Programmers write code and can at least be tested on their ability to write code. Maybe they can't engineer a program, but at least they can weed out the idiots just selling themselves. What are you going to test an accountant on? Can you add 2+2? Seriously, accounting has a lot of rules, but it's quite honestly easy, boring as fuck, but easy. How are you going to test your attorney? How are you going to test an HR or sales person? This is why a lot of jobs usually have a 30/60/90 day trial/probation period. Re:Blame it on the idiots who can sell themselves (Score:5, Informative) And it is so hard for your references to know if you're really any good or not because unless you're in a large technical group a lot of them wouldn't really know what it is that you actually do, or how to tell if you do it well. Most companies won't provide a reference other than "Person X worked for us from (date) to (date)." It's just too easy to say something which could be misconstrued as being negative and used to sue the company which issued the reference. because you never know (Score:5, Insightful) because you (the employer in this case) never know. a person can work in various places, have diplomas... and still be unbelievably stupid. i'd argue that other professions should gain some tests (i know a lot of them actually do, though those tests usually involve more generic skillset, like being able to work in a stressful conditions or under external noise, ability to quickly analyse particular information of the field etc). Re:because you never know (Score:4, Interesting) My experience is that the majority of employers and the majority of employees are equally stupid and deserve each other. If you're at an interview and they seem retarded then you probably want to move on. Anyway, a person can pass the kind of stupid tests given at interviews and still be a retard. I wouldnt't give such stupid tests to people I hire and wouldn't submit to such a test. The best thing an employer can look for is a portfolio. Look the work over, ask questions about the work, double check that it isn't just stolen from some open source project. If their work is good, even if unrelated to what you're doing, then they'll be good. If not, or if they lack a portfolio, then toss them. If you're going to claim to know Java then write a program in Java and put it in your portfolio. If you're going to claim to know Linux then write some tools to make managing a Linux server easier and show you know common command-line programs and config files. Do that sort of thing and then employers can know what you know. Measurability (Score:5, Insightful) A simple answer is that IT knowledge is a more quantitatively measurable than many other professions. Another factor is the high percentage of self-learned IT professionals. You don't see any "self-learned" lawyers, but self-learned IT pros are commonplace. Lawyers have been tested previously (bar exam) while the IT pro may never have passed any formal testing. Re: (Score:3, Informative) Re:Measurability (Score:5, Informative) Re: (Score:3, Informative) Another factor is that having a degree or certification in IT, or ven ten years of job experience, doesn't actually mean that you know anything. There is no easy way to judge an IT job candidate on paper. Tests are a poor method also though - better to look at a portfolio and ask the right questions about the work in the portfolio. Re: (Score:3, Interesting) BTW, I prefer self learners as programmers (read: coders) over people with degrees. My experience is that they are more dedicated and know more about real world problems. That's simply because a CS degree is not focused on making you a programmer but a more general problem solver. So when you want a coder you have to check what he really knows, not what diplomas he's having (that only gives a hint). Story is completely different if you're looking for someone higher up the food chain, of course. Possibly to weed out the fakers? (Score:5, Insightful) When I've been holding interviews, I always make up a set of tests just to make sure what they put on their CV is accurate. The number of times I've had someone put on their CV they can do something we are after, but in reality they know Sh*t about it, has only really come out when they do the test. It also helps to pick up those who are good at taking exams but don't know how to handle themselves in the real world. Unlike the other professions, IT doesn't have a legal backing. i.e. lawyers and accountants have qualifications that are backed by some law or another so if they write bullshit on their CV then it can come back on them. Not with IT unfortunately. Re: (Score:3, Insightful) Are you sure a bout that? Seems to me you are just presenting another exam to them, which by your own definition, they know how to handle. Re: (Score:3, Informative) Are you sure a bout that? Seems to me you are just presenting another exam to them, which by your own definition, they know how to handle. Not quite. With the exams, they have resources available to give them the answers (i.e. textbooks, MCSE Cram's etc), but with a test within the interview, they won't necessarily know the answer until they see the test. The tests I use are more real world as they are usually based on a problem I have had within the previous couple of weeks, not something they would get from a text book but something they would know from experience. Re:Possibly to weed out the fakers? (Score:5, Interesting) Not quite, at school you can guess quite well what the questions will be, so with a bit of 'educated guesswork' you can pass any exam without really knowing 'everything', let alone 'understanding' it. Heck, you spend over 10 years learning to 'work' the system, it's no surprise one gets good at it. When we hire people we try to prune out those that either simply wrote the right words on their CV and/or those that worked their way through education purely based on the above way. Not because we think they 'cheated', but because we are looking for people to help us with a certain task that involves certain skills. (This is for development job, I'm not sure how the Sales department does it's selection =) It's amazing how often people will write to be 'very good' at eg. SQL while all they know is that it stands for "Structured Query Language". When asked to write a query 'out of thin air' to get the most recent date from a simple agenda-like-table and they are unable to come up with ANYTHING, then we both know where are wasting each others time. Before we tested people, we got burned once too often by people who bluffed themselves into the company but turned out to be more of a burden than a helping hand =( By introducing simple tests we now only waste time at the interview level, we don't have to put time into educating them something they claim to be expert in already. That said, we sometimes DO hire people who /fail/ the test, simply because they show potential and we ARE willing to put time & effort in them. You'll find though that this will is a lot less present when the candidate's CV turns out to be 90%+ 'vapoorware'. Re:Possibly to weed out the fakers? (Score:4, Interesting) CV: Two Years Oracle Database Experience Real life: I wrote some hibernate code that ran against an Oracle database. CV: Experience of XML and XSLT Real life: I configured tomcat, that's XML. XSLT? Isn't that the same thing? CV: 5 years. Java, C and Python. Real life: I wrote some C five years ago and changed it again recently. (his Java experience was fine). I edited a python program once when the input format changed, no I really couldn't write anything from scratch. One of these actually got the Job, because he apologised for his CV and then gave a real account of what he knew that matched our tests. He said the agency put all that rubbish in after he filled in a check-box questionnaire! The why... (Score:5, Funny) Because unlike Accountants, Lawyers, etc we actually have to work for a living... If we're bad then stuff just doesn't get done. If an accountant is bad they still get $100k a year. Doctors still have to prove themselves multiple times just to be able to get into the interview. Years and training and testing. I like to think of us more like Doctors than professional bureaucrats. The underlying assumption is not true (Score:5, Interesting) thus the whole question is futile. Skill assessment is done in almost all kinds of professional employment situations . yet it depends mostly on the hiring policy of the department of that particular firm if there will be an assessment. And quite franky, I think there is a good reason why this is done with IT jobs more often: analytic and associative thinking and problem solving are not skills you can learn. Plus, IT jobbers tend to be more annoyed by moron colleagues than non-IT employees. And lets not forget that there is a huge amount of moronness out there - I myself did Job interviews with certified whatevers, who applied for a sysadmin position and couldn't tell me what information a notation like "192.168.38.1/24" provides. And thats just the very basic for such a job, but it already weeded out two thirds of the applicants, *completely unrelated* to their educational history or other certified qualifications. And last but not least, it always depends on the quality of the respective management if such an evaluation is done: and speaking for me and my experience, a company should do it in *all* sorts of positions, no matter how professional, experienced and well educated an applicant is. Re:The underlying assumption is not true (Score:5, Insightful) As long as you're tested by a human who understands the very background for the questions asked, tests are good. However, that's not what happens out there. The hiring companies have multiple-choice tests that are evaluated by a system, and the humans administering the test don't understand it. And more to the point, the people who made the tests didn't understand the questions either, but looked them up in a book. So very many of the questions are based on semantics and finding the exact phrase a certain text book used for a situation, instead of testing the understanding. In your example, the typical test that's being used would likely have asked: In 192.168.38.1/24, what does "/24" mean? 1 [ ] Subnet mask 2 [ ] CIDR 3 [ ] C Class network 4 [ ] Shorthand for 0.255.255.255 in IOS 10 or newer Of these, only one will be accepted. And more likely than not, the wrong one. I flunked one of these tests on DNS knowledge. Despite having written a DNS server, and installing and running multiple ISPs' DNS servers. Thousands of domains, including split internal/external, IPv6 and secure updating from DHCP. I can query a DNS using UDP from the command line, without requiring "host", "nslookup" or other specialized tools. I can write BIND zone files from scratch if I have to. I know DNS, dammit -- better than most sysadmins out there. The reason I failed (well, scored less than 50%, which I call failed) was that I couldn't answer questions like "Approximately, how many DNS servers are operating world wide?", "Does an active domain controller resolve DNS queries?", "What is the command for looking up your current WINS server?" and "Which Windows versions support running without netbios?". Apparently the test maker had looked up some questions in some DNS for Windows Dummies type book, and thought that was what it was all about. Not a single question reflected real DNS knowledge. Other tests ask you questions that you don't bother to remember, because it's so easy to look it up. Like parameters to commands. /path /path /path /path How do you list the size of a file system in 4k blocks in Unix? 1 [ ] df -b 4096 2 [ ] df -B 4096 3 [ ] df -s 4096 4 [ ] df -s 4k Only those who don't know what they're doing have to remember these things. The rest of us would try "--help", "-h" or look at the man page to check command syntax, and not bother to remember little used options. Only those with a need to memorize everything because they can't figure out how to look up things would know this. Or those who by chance happened to do this yesterday. As is, the tests are not very useful. They might weed out some of those that know absolutely nothing about a subject, but they also weed out those who understand the subject better than the test author, but don't bother remembering irrelevant or OS-specific details. Careful there.. (Score:4, Insightful) The "professional" bs is just a way to put you on salary rather than an hourly wage. While "professional" sounds nice, there are only a few real professions. A nice law passed a few years back reclassified several technical fields as professional, allowing employers to really screw their employees by changing their pay to salary from hourly. Re:Careful there.. (Score:5, Funny) As a consultant, I consider myself part of the world's oldest profession. After all: I charge an extortionate rate I'll be whatever you want me to be I spend a lot of time in hotel rooms I have a pimp that gives me a fraction of what I make and sends me to do things that I really don't want to do Credibility of professional qualifications (Score:4, Interesting) Better environment? (Score:5, Insightful) Mopping up after some idiot with "university degrees, a couple of IT certifications, and over ten years of work experience in the industry, with 2-4 years of verifiable employment with each employer, working with a wide range of technologies" that's a total clueless retard isn't my idea of fun and rewarding employment. why not (Score:5, Insightful) The reason it's done is a combination of great variability in skill among IT applicants, compared to professions with time-tested accreditation bodies like lawyers and accountants, and skills that are fairly amenable to formal testing, compared to professions like sales and HR, at least with respect to weeding out duds (if someone can't write a simple program in an afternoon, given a language reference, they should not be hired). More generally, I can't imagine why it's unreasonable for an employer to test skill. Competent IT professionals accept it because it's in fact beneficial to them to be distinguished from their less competent peers. (If the test itself is poor, they complain about that, and don't whine about the indignity of taking a test in general.) Paternalism is forcing someone to do something for their own good. This is not. I can assure of I have no intention of refusing tests of skill when applying for jobs. Employment history, certifications, and degrees do not ensure competence. Probably most of the people on The Daily WTF [thedailywtf.com] passed such basic screening. Why not take a test? (Score:5, Insightful) I frequently interview programmers, and having them take a short test (approx 30 minutes) and then discussing this with them in their interview is incredibly useful to determine their skillset. I could ask similar questions directly and have them work through the answers on a board, but then they would be under pressure to provide an answer on the spot to questions that probably deserve some thought before providing a solution. None of the questions on the test are unduly taxing - any person we interview who has a few years professional c++ experience under their belt should be able to provide at least a working solution, with potential better solutions open to discussion face to face. I've had 15 years doing what I do, and I'd be happy to take a test if asked - if I can't pass whatever hurdle the company sets, then I'd rather not sit there for a few more hours trying to win them over with my sparkling personality, and if the test is a pile of rubbish I know early on that I probably don't want to work there. Where's IT's "Professional Body"? (Score:4, Insightful) Accountants and Lawyers have professional bodies (or whatever it is called) that tests candidates wanting to call themselves "accountant" and "lawyer", so do doctors, nurses, engineers, etc, so employers don't need to test the candidates themselves when they want to hire one. if people call themselves "lawyer" or "accountant" without the proper certification, they could be jailed. Which is the corresponding organization that tested and certified you as an "IT professional"? Can your employer file complaints to that organization and have your certification removed if you displayed incompetence or is negligent in your job? And would anyone risk jail time if they call themselves "IT Professional" without any such certification? Don't kid yourself, an IT worker is hardly any more "professional" than a secretary or a salesman. Anyone sitting in front of a monitor for the past 10 years can call himself an "IT Professional" with 10 years of experience. Heck, someone who had NOT been sitting in front of a monitor for the past 10 years can also do so! Until we have a widely recognized professional body to certify us (and to de-certify or penalize us if we display incompetence), it is the employers' responsibility to assess our capability and testing us is one way to do it. I am sure many working in the field would prefer their employers had properly tested themselves and their co-workers, rather than having to fix up problems caused by other less-than-competent "IT Professionals". Re: (Score:3, Insightful) I'm looking to join the BCS in the next couple of weeks as I'm unhappy with the lack of professionalism in the IT industry. Unfortunately I will be the only one in a department of 20 people to care. The situation isn't likely to improve until it becomes sought after in interviews. My wife is in HR and they need to be CIPD qualified to progress in their career. Hopefully the problem with IT is due to the immaturity of the industry and that things will improve in time. Because so few know how to conduct interviews (Score:5, Insightful) In my experience, which ia way more than your 10 years, very few folks in IT actually know how to interview and what traits to look for. Being tech folks and not having people skills, they think that some test will tell them what they need to know about a potential applicant. Not true. A lot of the tests are language lawyer things (knowing about public static final in Java) which doesn't get to what they really need to know. There are lots of folks who know the language lawyer tricks that will be lousy employees. You need folks that are bright, have a demonstrated track record of being able to learn new things and that will fit with your culture/environment. Others are tested (Score:3, Insightful) There are two obvious reasons why people get tested in IT 1) People might have passed exams, but can they actually code 2) People might have been on a project where technology X was used, but did they use it? The first is the case where you have a graduate with a degree in computing and it turns out they did all the "soft" options. So lots of theory but not practice and they don't even know what a compiler is. The second is the case where you are looking for people with a given skill (say Java) and you want to check that they have that skill. Its not true to say that other people don't have to sit tests, its just that a lot of the time those tests aren't written tests but are more open, indeed I prefer to test people using such open assignments. Set them a problem (design a system to do X) and then have them respond. This is exactly the same way that lawyers are often tested by their new chambers, they have to defend (or prosecute) a given perspective to show how they would perform and lay out their approach of constructing the case. The point is that for most jobs they are "soft" jobs where a specific exam makes no sense once you have the qualification and therefore you do soft interview tests. In IT however we have lots of "hard" jobs where a specific skill is required and a specific level of performance is required. This isn't about professional v unprofessional its about the nature of an industry where there are millions of different technologies arriving every year and where the average ability level has been plunging for the last 20 years. So get off your high horse and stop complaining. You are in an industry that changes, that means that the degree you did gives you a theoretical basis (hopefully) but your practical skills will need to be evolved. I did Ada, LISP, 68k and Prolog at University. Guess what? My first job meant I had to learn C in 1 week to prove I knew it and my 3rd job was the last one where I used any of those languages (I'm now on my 7th job). So did I mind being tested to prove I knew C/Java/XML/MQSeries/etc? No I didn't. Do I test people to prove they really have the skills they say? You bet, I wouldn't trust an IT CV statement further than I'd trust Dick Cheney at a bird shoot. All interviews test in any areas where its worth having a job. IT interviews test more because IT changes more and your qualifications become out of date more quickly. Now for the real question though: Why isn't there a written test for high office, especially a geography test for US Presidents and VPs. I think it's a good thing (Score:3, Interesting) A CV can be read in many ways. I think that testing is a good way to see that the skills, CV and open position match. That being said, testing can be done in many ways. Someone recommended me to Google once, and the Google HR department obviously read my CV looking for the skills they were after. While I had them to a degree, that was only part of the truth. A later phone interview with one of their engineers clarified the situation a lot: He tested my skill set with a bunch of oral test questions that made it obvious to both that my skills were of the right sort but at the wrong layer of abstraction. (Scripting vs. assembly-level knowledge.) That test saved both parties a lot of time. But like I said, there is good testing and bad testing. Often tests test passive knowledge, but not problem solving skills. Unfortunately the hardest to quantify stuff is also the most essential in terms of actual productivity. Re:Good Testing == Getting Paid. (Score:4, Funny) Thank you, NEXT! Re:Good Testing == Getting Paid. (Score:4, Interesting) I didn't get the job, but found out several weeks later that they implemented my exact solution, as the guy they hired for the job EMAILED ME WITH QUESTIONS and quoted the entire email. I submitted it to their billing department at my standard consulting rate and minimum bill, with a note attached that since there was prima facie evidence that they were using my solution. . .it was pay or go to court. The check arrived via FedEx the next morning . . . "Professionals"? (Score:4, Insightful) This type of test is fairly commonplace in certain engineering fields, and should be. Specific technical knowledge, trivial to test for, are much more important and much simpler to test for in engineers and technicians than they are in professional workers. If you can easily and efficiently test the skill level and prior training given a technical worker, for whom training is often quite area-specific and expensive, why on earth wouldn't you? This isn't paternalism, and is not a show of disrespect. I, for one, will neither stop giving nor refuse to take this sort of interview. The suggestion that we should seems ludicrous to me. On a related note, just exactly what did you think a traditional business interview is designed to do? They are little more than a version of the skills tests that you're complaining about, but designed to measure the aptitude of managers and the like. They are more open-ended in nature, but not because those job candidates are somehow worthy of more respect. The questions are more subjective because the topics at hand are far more difficult to objectively measure than technical knowledge. Furthermore, you must also consider those organizations (especially within the government) that subject teachers, managers, lawyers, policy experts, etc. to standardized testing of some sort prior to hiring them. To be honest you sound like an arse (Score:3, Insightful) If you are the sort of person who is won't put up with a simple test, which seems to me to be quite a reasonable request (where you seem to think it is all "how dare you question my magnificence), you certainly aren't the sort of person I want to employ. I don't want someone who is not willing to pitch in with whatever is needed. In this case, I think the test has provided a useful function. Too many morons in IT. (Score:4, Interesting) Sadly, a lot of the "IT Professionals" I encounter are plain idiots. Even in-depth interviews can't guarantee that you have someone capable in front of you, but it does filter out those idiots. I work for a small (5 ppl) IT-only company and when we hire someone, while he will get some basic training, he is supposed to work pretty independantly. But once in such a position you can pretend doing a lot while doing almost nothing, and still make things appear to 'work'. You'd be amazed what an incompetent guy can pretend to be and produce results that on the first glance seem to be OK. And then when his software goes into production you suddenly notice that he didn't use an XML parser, but expected certain data on certain lines and filtered it out using regular expressions - and NO, not using the standard regular expression library - but doing something like this in C: sprintf(cmdbuf, "/usr/bash /bin/sed -e \"s/%s//\" > /tmp/filename", inputbuffer); ... system(cmdbuf); fp = fopen("/tmp/filename", "r"); You get the picture. He btw didn't even write a function to do this, but copy-pasted stuff like this a few 100 times... Software worked in test, client changed 1 insignificant thing in their XML generation (added a tag we didn't use), and our entire system went down. I ended up rewriting this guy's stuff after he was fired. And that's the main problem with IT jobs, you only notice they're incompetent when things start to go wrong. And then it's too late. So if I have to interview someone for an IT position, I want to be as sure as possible we don't end up in such a situation again. Masking incompetence in an IT position is just too easy. Re:Too many morons in IT. (Score:5, Insightful) Standard of "professionalism" is lower in IT (Score:5, Insightful) I speak as a member of "IT" as well, so I'm accusing myself here too, fairly and squarely. I don't know (nor care) about the non-technical professions, but the standard of professionalism in Computing is a lot lower than in Engineering. I can say that with confidence after a long career spanning both Electrical/Electronic Engineering and Computer Science, both in academia (PhD, postdoc, lecturer) and in industry. It took me the better part of a decade in the computing industry to realize that I had been (unwittingly) deluding my Software Engineering students when I taught them "Do it like this, or you will be laughed at as amateurs when you get out into industry." The sad fact is that 98% of computing in industry is utterly amateurish, as I eventually discovered for myself. Even huge, "properly" managed projects are in practice just hacks like all the rest, but with better documentation and QA/testing. While computing is my current love, and bread provider, I recognize that we're at the stage of gazing at chicken entrails in this discipline. It's a bit sad, although I still love it. But when they say "Bridges would fall down every other day if they were built like we build software", they are 100% right. Looking at it from the perspective of my old engineering days, it's a bit distressing, but that's how it is. We're still in the early days of Computing, and to call it a professional discipline is stretching the definition rather severely. Michael Chermside (Score:4, Insightful) I don't know about you, but I would RATHER be tested during an interview. It would increase the chance that I would wind up working with competent co-workers. Michael Chermside [mcherm.com] ...because there are so many incompentent ones (Score:4, Insightful) You'd rather your company didn't test them...? (Score:5, Funny) How 'bout we start employing people based on what they claim, not what they can do? Sounds good to me. Tests help weed people out (Score:4, Informative) IT field is so wide and diverse with many people coming to it's ranks without any "true" background. I have a degree in Textiles. I manage and maintain a wide assortment of applications, servers, databases, email systems etc. I actually laughed at a lady on the phone a long time ago during an interview, who said that they were only looking for MCSE's. When I laughed she seemed so surprised and asked me why? I told her "You do understand that you can get one of those in 2 weeks offline right now right?". People have become so dependent on "certifications" that they don't actually test those individuals skills. I don't limit it to IT either. The same thing applies to MBA's. I wound up being involved in a round table interview (2+ applicants at the same time) and everyone but me had a certification. When asked what the difference between mirroring and clustering in databases was one of the answers was (I joke you not) something oracle can only do. Additionally, I find that now, most companies don't truly involve their IT groups in the hiring process. They ask for "specs" for a job and then try to match them up. This doesn't work in reality. It might with a secretary, or blockbuster video clerk... but not in IT. IT skills are quantifiable. There's no "bullshit" answer. There are several different levels of gray but if you ask a programmer what Model View Controller or what a framework is... there's no bs answer that isn't wrong. When I create questions for a prospective employee I'm not trying to ramrod them. I ask only questions that I believe they should know 100%. For example, a ColdFusion programmer position is about to be placed here are some of the questions I plan to ask. I don't necessarily believe they need to know how to do all of them, but they MUST know what they are. This position will be updating a slew of applications written in ColdFusion 5 and fixing about 30 databases that were converted from Access to MSSQL and 99% of the fields are NVARCHAR. 1) What is SQL injection and what built in features of coldfusion protect applications from it? .cfm and a .cfc? ... 2) Write an inner join query? 3) Whats the difference between a 4) What is an SVN repository? 5) What is the datatype NVARCHAR used for? 6) You get the idea. However, my reasoning for asking these questions isn't just for the answers! 1) How well did they answer the questions? Enunciation, quickness to respond, accuracy in describing solutions 2) What is their personality like when pressured? 3) When they don't know an answer how do they respond. This is a big one for me. I expect you to say that you don't know. Bonus points for you writing it down and emailing me the answer later. This lets me know you didn't forget, and that you are trying to improve yourself. A lot of times I'll throw in a question I KNOW they shouldn't know just to trip them up. I want to see how people react under pressure. We have 125 employees all depending on these applications for our business functions. If something screws up I need them to be quick, calm and attentive to the problem. Imagine this on a much larger scale, like 10,000, or 100,000. Businesses need to depend on these employees. So, tests are necessary and frankly I'd like to see them in more positions. Better qualifiying (Score:4, Insightful) *After* earning their actual degree, Lawyers have to pass the gruelling bar exam. Doctors have to do the medical board exams and a guelling internship. Engineers have to get their certifications. IT graduates, just have to carry their piece of paper home. Sure you can get your Microsoft and other vendor-sponsored certifications, but these are generally jokes-marketing tools. At the very best they qualify you for some specific experience with some specific products, and don't thoroughly test your general IT skills. I've seen Cisco certified engineers leave me with bottlenecks due to looping routes, and generally trashed my network. I've seen MSCE's that are totally useless. It always strikes me odd, that an engineer building anything has to build to standards, which are externally verified and permits obtained through inspections, etc.. Software engineers and IT staff can implement mission-critical systems without any standards or oversight. I know the software/computer hardware world makes things so incredibly flexible that it'd be hard to defines standards to regulate against; that's likely the problem. (If I want a bridge, everyone can pretty much agree upon what is wanted, a copy of something that has been done before, and approved, standardized. Not so much for a new application. For IT infrustructures, a case could be made for more standardization, I guess.) But this flexibility it also results in some pretty horrible work being done out there. Also, the standards in other fields allow for greater accountability. If an engineer, Doctor, lawyer, is incompetent and not providing the standard of care their industry demands, you can sue them for such. (I'm likely to sue my former lawyer for incompetence and ignorance of the law and my case.) But try suing a software engineer or IT person. There's just no clear standards of competence with which to judge him or her. Having tests to weed through some bad ones, makes sense, and I see why it comes about. It's not perfect, but it tries to address a shortcoming in our field. Professional certification (Score:4, Interesting) "Why are IT professionals treated differently and in such a paternalistic way? More importantly, why do IT professionals accept being treated less favorably than members of other professions? Should IT professionals start to refuse to be treated as not real professionals?" Others have already pointed out that lawyers and accountants (CPAs at least) submit to testing and are certified by professional organizations. You can't market yourself as a lawyer, CPA, or even an engineer in some places without having the backing of a professional guild. What I'd like to know is why, in the face of offshoring and job losses, the IT industry hasn't coelesced around a professional society or guild. A professional guild, with some rigid certification testing, would be more effective than even unionizing since it produces a win-win for both employees and employers. Is it just that the need isn't perceived to be there yet? With professional certification, employers would know they are getting skills without expensive testing and competent IT professionals can be assured that they won't be working with "IT Professionals" whose sole IT experience is that they took one Visual Basic course. There are lots of vendor specific certs (MS, Novell, Oracle, IBM) but to me, that's more akin testing accountants for having skill in using QuickBooks. The Open Group has IT Architect certification () which looks to be a start, but it doesn't appear to have gained much momentum. IBM offers cross-certification of its internally certified architects but even within IBM, not all departments bother to pay the fee for TOG certification. I also see that there's an Institute for Certification of Computer Professionals () that's been around since 1973, and a lot of people on its web page have important looking letters next to their names (CCP, CDMP) but outside of this web page, I've never run across an IT person with this on their business card nor a company that insists on this certification. So I ask the exact opposite question that the poster asks, "Why don't we insist on recognized industry certification testing for IT professionals?" JoAnn IT workers are not professionals (Score:4, Insightful) Lawyers, accountants, etc ARE professionals, they are regulated by professional organizations and have to prove their qualifications in order to be licensed to practice. IT workers have no such regulation. In effect the State tests your lawyer for you. I agree the tests for programmers are almost universally stupid and worthless, but if it makes some PHB someplace happy, who cares? My company uses an essay question, doesn't work (Score:4, Interesting) Then, as part of the interview process, we have a few questions we ask you to write essays for. One is based on design of a product we already built, one is based on design of a product we're currently building, and third... Is actually a riddle. My project manager came up with this idea, his thinking is "Let's see what kind of inductive/deductive reasoning this guy will use". Sounds like a good idea. Turns out? All this crap is worthless. Case in point... We have a guy fresh out of college (no experience in the trenches) who we interview, and later get hired. His code is quite beautiful at a glance (not breaking down every line to profile it or anything), plenty of comments, nice style, etc. His essays are OK, they're passable. But, he sits down, and we've got -multitude- problems. Let's start with one example: We're web developers, and in the first couple weeks, he needed to modify UI. In this case, he needed to use a few images for something. What kind of images did he put into our repo for versioning? BITMAPS! No, no, not a proper raster file-types like a PNG or a JPG, a bitmap -- BMP. Just cause Professor Dinglethorpe requires you to comment and indent your code properly doesn't mean you have a clue what really happens when you get down to production. But, the real problem? COMMUNICATION! The kid just can't freakin' communicate with us. If he were bad AND would take the time to talk to us about what he's working on, we could stand it. We'd know what was happening when he did jacked up stuff in the code, and we later have to maintain his mess. However, he doesn't take time to communicate with anyone. He's too busy leaving important meetings to take phone calls from his ultra insecure live-in girlfriend who calls him 18 times a day (for such important things as "Should we make lentil soup tonight?" and "What are we going to name this cat?"), reading I can has cheezburger and the failblog. Meanwhile, he slips under the radar. Our company plays to your competency level. So while I have taken on huge projects, become a stand-in for our system administrator, and the liason between customer service and information services (a pretty important role, they buy the important bugs -first-) -- this kid is getting assigned tasks like "We need to put hyphens between these words per the marketing dept". Good thing we get paid the same. Nice to get paid the same as the guy who's mastered reading I can has cheezburger. He can has cheeseburger, and I'll be the one to shove it up his... nose. So, don't believe a technical test is going to determine if the next guy you work with is legitimate, and competent. If he can't communicate, and he has no work ethic -- frankly, you're screwed. It matters what kind of test (Score:4, Insightful) When it comes down to it, the entire process is a test. Creating a well-designed, brief, and informative resume is a test. Tying a damned tie (a skill that a trained monkey can do without cursing, but I can't), is a test. Interviewing is a test. If you're going to be tested on all these other things, then I am not going to complain about the test that focuses on whether you can do the job. I have been tested for two of the three companies I worked for and a few others that I applied for. Two of them were in the vein of "We want you to write a simple script that can do X, and email it back to us". This was an effective test. Another one was a multiple choice test that focused on syntax. The questions were things like "How do you terminate an IF statement" It was a terrible test because they weren't looking at your ability to logically think through a problem, but were instead more concerned about whether you may confuse programming language A with programming language B. I did reasonably well, but that still, if you are going to test you employees, don't get hung up on things like "does this guy remember the modulus operator" (for Fizzbuzz tests) or "Does he remember how to use function X without looking it up". Re:Sheesh (Score:5, Insightful) Taking a test during a job interview means that they are serious about the situation. The worst thing isn't tests at job interviews it's the work climate at the site where you are going to be located. Is it micro managed or is it goal managed? And job satisfaction is very important for IT workers. The question is rather why other types of workers aren't tested as much. Why not test lawyers, accountants and administrators? Re: (Score:3, Funny) Re:Sheesh (Score:5, Informative) You mean like with the bar exam, cpa exam, the useless PMP exam, certified professional engineer, etc. Other professions are tested, but it is before the job interview.
https://it.slashdot.org/story/08/09/15/0210235/testing-it-professionals-on-job-interviews
CC-MAIN-2017-39
refinedweb
14,714
70.23
25 February 2009 11:28 [Source: ICIS news] LONDON (ICIS news)--INEOS NOVA intends to increase its polystyrene (PS) prices in ?xml:namespace> “INEOS NOVA needs to restore an acceptable margin in its business following the margin loss in February and pass on the expected feedstock increase in March,” said the statement. Other PS producers said they were also preparing price hikes for March based on increased feedstock costs and poor margins. Spot styrene was traded at $739/tonne (€576/tonne) FOB (free on board) ARA ( The February barge styrene contract stands at €615-620/tonne FD (free delivered) NWE (northwest Sources speculated over an increase of up to €50/tonne for March contracts but some said it was too early to tell where new styrene contracts would land. PS prices rose by around €45/tonne in February, short of the €60-65/tonne hike in February styrene contracts. General purpose PS (GPPS) was trading in the mid-€700s/tonne FD NWE at the end of February in the distribution sector. Buyers in the food-packaging sector still reported healthy demand, but one described the new PS targeted hikes as “aspirational”. February PS demand had been stronger than expected by most suppliers, but production was still cut back to accommodate a fundamental oversupply in the European PS market. European PS producers include INEOS NOVA, Dow, BASF, Total Petrochemicals and Polimeri Europa. ($1 = €0.78) For more on polysty
http://www.icis.com/Articles/2009/02/25/9195518/ineos-nova-targets-europe-march-ps-increase-of-60tonne.html
CC-MAIN-2014-42
refinedweb
238
57.3
Hi As you know, suspend function can call non-suspend function just fine but not vice versa. Then my question: why can’t we just make every function suspend by default and get rid of that keyword? Thanks a lot Hi As you know, suspend function can call non-suspend function just fine but not vice versa. Then my question: why can’t we just make every function suspend by default and get rid of that keyword? Thanks a lot I guess the main issue is interoperability with the existing code. Remember that great majority of libraries we use are Java libs, so they are not suspendable. That means they can’t easily invoke your suspendable code e.g. through callbacks. Also, while inside suspendable context, we can’t block the current thread. Classic code doesn’t have this limitation. So for now we can’t really stop thinking about the distinction between suspend and non-suspend. If functions were marked suspend by default, then you would have to mark non-suspending functions fast The byte code produced for a suspending function is much bigger and runs much less efficiently than the equivalent non-suspending function in most cases, especially where calls to other suspending functions are involved. It is not fully completely true. Suspend function without suspension points inside has only one additional implicit parameter, it does not complicate the code inside. But in more complex cases, it is true, asynchronous code is harder to optimize inside the JVM, harder to debug and profile. So suspension is not free and code coloring is justified. There is additional reason for coloring even outside of additional costs. Suspend functions have a slightly different mental model. In regular code, the next statement is executed after previous one. In asynchronous code, the next is executed when the one before is finished. The semantic difference is slight, but important. For example, it is quite possible, that previous action is never completed (is canceled or in infinite suspension). You work with suspended code in a different way. One of the Project Loom main selling points is that you do not need to color your functions. It is not better, that what we have in Kotlin. It is a different ideology. But if we made every function suspend by default then every single function call is a suspension point! Which will result in an influx of useless bytecode generated for functions that do not need it. Marking everything as fast or pure or whatever is bad because it takes extra mental overheard to mark them as such. Kotlin’s philosophy is to make the default option the “right” option, and having everything as suspend is not the right option (and again will cause lots of overheads in how those functions are converted to bytecode/JS/whatever) It is a good point. Another point is that even if we did not have to mark function as as suspended for machinery to work, we would have to mark functions that really suspends by some kind of annotations in order for user to see, which functions contains a suspension point. It is important to understand, when function could “wait” and where it could be canceled. The problem with this idea is that in many cases, whether or not a function suspends is not an intrinsic property of the function. Consider a text transformer, for example, that reads from a provided source of characters and writes to a provided sink. Does it suspend? That depends entirely on the source and sink. The function itself should be able to be used with both suspending sources and sinks as well as ones that don’t. Just marking it suspend is no solution, because then you can’t call it outside of a coroutine. If you think this is rare, it’s not that rare. This is why Kotlin has to essentially reimplement the entire Java streams framework for suspension. Similarly, all the vast quantity of code that exists for transforming InputStream and OutputStream, like GzipOutputStream needs separate suspending and non-suspending implementations for no good reason. Suspended functions are functions that have suspension point inside or intended to have it in future (for API design). I don’t see point in your example. Really? If you were to undertake the considerable task of writing a GZip stream compressor, would you write it for suspending or non-suspending streams? You don’t see a problem with having to decide? You will have to use non-suspending version for two reasons: And then you’ll find that you can’t use it to stream compressed responses out of your asynchronous web server without buffering the whole response first. Unacceptable, so you’ll have to write a new stream compressor for the asynchronous cases. You can call non-suspending methods from suspending methods. You can even embed it safely with withContext(Dispatchers.IO). You can’t call suspending methods without going into suspending world explicitly and this design has its pros and cons. Any “regular” method could be considered a suspended method, but not vise versa. i think it could be managed by the compiler. if the function called from coroutine scope - use a suspend version, in other case - use a simple function. You can always make the function inline and have it take in a lambda for the input stream. Then, if your input stream is suspending, you can call that inline function just fine with a suspending stream as long as you’re in a suspend function already. import kotlinx.coroutines.* import kotlinx.coroutines.flow.* fun interface TextStream { fun getChar(): Char } fun interface SuspendingTextStream { suspend fun getChar(): Char } fun interface TextSink { fun writeChar(char: Char) } fun interface SuspendingTextSink { suspend fun writeChar(char: Char) } inline fun transformText(textIn: () -> Char, textOut: (Char) -> Unit) { while(true) { val char = textIn() if(char == '\u0000') break textOut(char) } } suspend fun printThisOutSomehow(text: Char) { delay(100) println(text) } suspend fun main() { val textFlow = sequence<Char> { "hello world".forEach { yield(it) } }.iterator() val textIn = TextStream { if(textFlow.hasNext()) textFlow.next() else '\u0000' } val textOut = SuspendingTextSink(::printThisOutSomehow) transformText({ textIn.getChar() }, { textOut.writeChar(it) }) } The compiler could generate two versions of every function and then call the suspending one in suspending contexts. That’s expensive, of course, but also not what you really want. You don’t want to call the “slow” version just because you’re in a coroutine. You want to call the slow version if it has a possible control flow path that suspends, and that can depend on arbitrary computations that decide parameters and dependencies, etc. The compiler can attempt to figure this out, but a couple layers deep it would usually become intractable. Maybe something around marking objects as suspending/non-suspending could actually work… but again it’s quite expensive. An inline gzip compressor? Your answer is clever, but the “you can always…” part is not true. Also, the code coloring problem isn’t about what you can do – all languages are Turing complete, anyway. It’s about what interfaces/contracts you can define and implement. You can always factor out all the I/O or blocking operations from an object or function, but this does violence to the interface and is effectively implementing coroutines yourself. Project Loom looks promising. I really liked Kotlin until coroutines were added. This may make some angry, …, it is an awful dev experience. Maybe I will come back to Kotlin, but for me it lost a tremendous amount of appeal. All YouTube videos that still don’t properly teach it and so many missing docs, examples, like Java Promisees integration and so on. Library authors already do this, put suspend on everything. Forcing consumers to deal with all the hastle. This thread alone is priceless, thanks
https://discuss.kotlinlang.org/t/why-not-make-every-function-suspend-by-default/25224
CC-MAIN-2022-33
refinedweb
1,295
63.49
This content has been marked as final. Show 53 replies 15. Re: 802.11 parameters843849 Jun 20, 2005 2:59 PM (in response to 843849)I am looking for the JWRAPI binaries for almost a month. Author does no reply to any of the several mails I have sent. Could anyone be so kind as to send them to me @my email ? Thanks 16. Re: 802.11 parameters843849 Jul 21, 2005 1:47 AM (in response to 843849)I was also looking for this JWRAPI and sent the author an email ... but got no reply. Is there any chance of getting the binaries here? Could anyone send them to streybem at student.ethz.ch? It would be greatly appreciatet! Thanks 17. Re: 802.11 parameters843849 Jul 21, 2005 1:51 AM (in response to 843849)I'm sorry, I don't even get my email typed correctly. It should be steybem at student.ethz.ch Thanks. 18. Re: 802.11 parameters843849 Jul 26, 2005 11:00 AM (in response to 843849)Can any one send me the JWRAPI binaries? I sent an e-mail to author but I fear to attend so much... My mail address is claudio.buda@studio.unibo.it Thank you a lot. 19. Re: 802.11 parameters843849 Jul 27, 2005 5:32 AM (in response to 843849)Can any one send me the JWRAPI binaries? I sent an e-mail to author but I fear to attend so much... romantic916@gmail.com 20. Re: 802.11 parameters843849 Aug 18, 2005 7:43 AM (in response to 843849)Hello everybody I have the same problem as most of the people in this thread. I would like to check out the JWRAPI library, but the author doesn't answer my mail. I would be very happy if someone could send me the binaries or the password for the download. My email is: cool_marcelaaaa@web.de Thank you very much! marcel 21. Re: 802.11 parameters843849 Aug 30, 2005 2:57 PM (in response to 843849)Could someone please send me the JWRAPI binaries? I sent an email to the author a couple of weeks ago but have had no response. My mail address is cjrueda@gmail.com Thanks 22. Re: 802.11 parameters843849 Sep 5, 2005 11:33 AM (in response to 843849)Hola chicos buena noticia tengo donde consegir los binarios javawrapi.jar, con las demas herramientas, lo que nesesito que me ayuden como hacer funcionar. Hello boys good the news I have where to consegir the binary ones to javawrapi.jar, with demas tools, which nesesito that helps ds me like making work javawrapi.jar : JavaWrapi.dll : ndisprot.inf and ndisprot.sys: my problem is: // import java.io.IOException; import wrapi.JavaWrapi; import wrapi.NDISDevice; import wrapi.DOT11API; /** * Print the SSID of current Access Point. * * Created: Mon Jan 08 10:41:18 2000 * * @author Johan Kristiansson * @version $Name: $ $Revision: 1.1 $ * @date $Date: 2003/11/01 15:13:28 $ */ public class PrintAP { /** * Tests all available methods. */ public static void main( String args[] ) { try { // get an instance of JavaWrapi JavaWrapi jWrapi = JavaWrapi.getInstance(); // locate a 802.11 device NDISDevice dot11NIC = jWrapi.getDOT11Device(); jWrapi.openNDISDevice( dot11NIC ); // get the dot 11 api DOT11API dot11API = jWrapi.getDOT11API(); System.out.println( "Current SSID (AP) is <" + dot11API.getSSId() + ">" ); } catch( Exception e ) { e.printStackTrace(); }//*/ } } // PrintAP javac PrintAP .java ok no problem Pero : java PrintAP Exception in thread "main" java.lang.UnsatisfiedLinkError: D:\jdk1.5.0_04\bin\JavaWrapi.dll: Can't find dependent libraries92) at wrapi.DOT11APIImpl.<init>(DOT11APIImpl.java:52) at wrapi.JavaWrapi.<init>(JavaWrapi.java:52) at wrapi.JavaWrapi.getInstance(JavaWrapi.java:183) at PrintAP.main(PrintAP.java:26) Boys since aid collaborates to them as are my error please. 23. Re: 802.11 parameters843849 Sep 19, 2005 9:16 AM (in response to 843849)Hello!! I am almost desperate.... :�- ( I have tried to access the web with de javawrapi jar but it doesn't work. And i have no respone from the author. Can anyone send me the binaries? please!!!! please!!!! Thank you very very much!!! Glo. 24. Re: 802.11 parameters843849 Sep 19, 2005 9:17 AM (in response to 843849)ok, If i post the email is easy.. je,je,je Thanks again!!!! 25. Re: 802.11 parameters843849 Sep 23, 2005 1:36 AM (in response to 843849)I have sent the request to the author but no reply from him yet, may be he is quite busy at the moment. Would be very appreaciated if anyone can send me the binary file. TIA. my email: blueocean3@cheerful.com 26. JWRAPI binaries843849 Sep 23, 2005 2:58 AM (in response to 843849)Hello everyone I think you can stop asking for the binaries because I don't think that anyone would send them to you ... we should respect the authors will of him controlling access to his libraries. I wrote him an email and got no response ... so I tried again and after a week he sent me the password. (if you really don't get any reply, try googling for javawrapi.jar -> ) So, using the jwrapi library, I have encountered some problems with retrieving a list of access points in range: Only the first entry in the list is correct and all the rest is just nonsense! I tried to figure out what this might be all about because I faced the same problem when using WMI. As I found out, it seems to be a problem with NDIS and Microsoft's SP2 for WinXP! I found posts stating that all worked well with WinXP SP1, but as soon as SP2 was installed, the NDIS API was somehow corrupted and did not return a correct list of reachable access points. Does anyone know what the real problem is and how to solve it??? Meanwhile I am using the placelab library (the wifi-spotter) in order to retrieve a list of access points in range, which works quite well! thanks 27. Re: JWRAPI binaries843849 Sep 24, 2005 10:04 AM (in response to 843849)Hello, 28. Re: JWRAPI binaries843849 Sep 25, 2005 1:41 PM (in response to 843849) Hello,add the folder containing these dlls to your system's PATH variable 29. Re: JWRAPI binaries843849 Sep 27, 2005 1:18 PM (in response to 843849)Thank you very much for the binaries!!!! Ok, once i had all installed i started proving the examples. Now i have a problem, when i run any example i got a NullPointerException in the sentence jWrapi.openNDISDevice( dot11NIC ); the problem is in NDISDevice dot11NIC = jWrapi.getDOT11Device(); because doesn't return anything anyone knows what is the problem? thaks everybody!!!! Glo.
https://community.oracle.com/message/7272892
CC-MAIN-2015-35
refinedweb
1,107
76.11
Missing something in arm g++ I installed the CodeSourcery g++ toolchain and tried to compile a simple hello world program: #include <iostream> using namespace std; int main() { cout << "Hello World" << endl; return 0; } And got a lot of errors from the linker $ arm-none-eabi-g++ helloworld.cpp -o helloworld.exe bin/ld: warning: cannot find entry symbol _start; defaulting to 0000000000008018 lib/libc.a(lib_a-abort.o): In function `abort': abort.c:(.text.abort+0x10): undefined reference to `_exit' lib/libc.a(lib_a-fstatr.o): In function `_fstat_r': fstatr.c:(.text._fstat_r+0x1c): undefined reference to `_fstat' lib/libc.a(lib_a-openr.o): In function `_open_r': openr.c:(.text._open_r+0x20): undefined reference to `_open' lib/libc.a(lib_a-sbrkr.o): In function `_sbrk_r': sbrkr.c:(.text._sbrk_r+0x18): undefined reference to `_sbrk' lib/libc.a(lib_a-signalr.o): In function `_kill_r': signalr.c:(.text._kill_r+0x1c): undefined reference to `_kill' lib/libc.a(lib_a-signalr.o): In function `_getpid_r': signalr.c:(.text._getpid_r+0x4): undefined reference to `_getpid' lib/libc.a(lib_a-writer.o): In function `_write_r': writer.c:(.text._write_r+0x20): undefined reference to `_write' lib/libc.a(lib_a-closer.o): In function `_close_r': closer.c:(.text._close_r+0x18): undefined reference to `_close' lib/libc.a(lib_a-isattyr.o): In function `_isatty_r': isattyr.c:(.text._isatty_r+0x18): undefined reference to `_isatty' lib/libc.a(lib_a-lseekr.o): In function `_lseek_r': lseekr.c:(.text._lseek_r+0x20): undefined reference to `_lseek' lib/libc.a(lib_a-readr.o): In function `_read_r': readr.c:(.text._read_r+0x20): undefined reference to `_read' collect2: ld returned 1 exit status What library am I missing here? The GCC toolchain is only half of what you need to create a working executable*. The other half is the runtime library. The runtime includes crt0.o, which contains the entry point (the code that calls main()), and generally a libc that contains the standard C functions (strcmp(), memcpy(), etc) as well as the system calls (open(), read(), and others). You need to find a source for these. If you're targeting an embedded Linux or BSD machine, you'll have to find out what libc your target is using. It's probably either GNU libc, BSD libc, newlib, or uclibc. You can get these and build them yourself, or they may be available already with your OS. *unless you're building a freestanding binary, but this doesn't look to be what you're doing. Missing /bin/arm-none-eabi-g++ after SAM boards installed on , Missing /bin/arm-none-eabi-g++ after SAM boards installed on fallen victim of my own ignorance :D (and learned something in the process). Tingling and numbness in your arm could be caused by a number of conditions such as carpal tunnel syndrome, peripheral neuropathy, or cervical radiculopathy. Many are relatively simple for your Basing on the cross compiler it appears that end target is bare metal. The default gcc libraries (OS dependent) will not work here. You can use the NewlibC or NewlibC-Nano. This generally will be shipped along with the cross compiler tool chain. Look for lib folder which has precompiled NewlibC. Once that is done, This statement might help you to an extent. arm-none-eabi-gcc --specs=rdimon.specs \ -Wl,--start-group -lgcc -lc -lc -lm -lrdimon -Wl,--end-group $(OTHER_OPTIONS) Don't forget to provide the path of looking the libraries -L(path). Missing or Incompletely Formed Limbs, Missing or Incompletely Formed Limbs - Learn about the causes, symptoms, diagnosis & treatment from the Merck Manuals - Medical Consumer Version. 2020 FAQ Contact Us. Health Topics & Chapters. A. B. C. D. E. F. G. H Abnormalities of the arms and legs may occur in a horizontal fashion (for No. Muscle Defects� If your arm hurts, you may first think it’s injured. But pain in one part of the body can sometimes originate elsewhere. A pain in your left arm could mean you have a joint injury, pinched nerve I had this same problem. It turns out there are a handful of options you can send to the linker to make it start working, but the one that had the least splash damage in my code base was -nostartfiles Christophe Lyon, You said you tested arm-none-eabi, so I'm probably missing something? Christophe > > We g++.dg/ext/arm-fp16/fp16-return-1.c: Update expected output. DISCOUNTEDARTIST HALF MY ARM IS MISSING MATEY! OKAY, I'LL GET YOU SOMETHING HERE, I GOT YOU SOMETHING – popular memes on the site ifunny.co Muscle Cramps Are Body's Signal That Something is Missing , A charley horse is an involuntary contraction of a muscle that a person can experience in their arm or leg. According to one local physician, it is� Something in the water: N.S. man unsure what creature broke his arm in St. Margarets Bay Glenn Singleton of Dartmouth had his arm broken while swimming in St. Margarets Bay recently, although he Vanessa Guillen Investigation: Arrest in Case of Missing Fort Hood , Arrest Is Made in Connection With Missing Fort Hood Soldier the armory room where she had been at work repairing small arms and artillery. Find GIFs with the latest and newest hashtags! Search, discover and share your favorite Am I Missing Something GIFs. The best GIFs are on GIPHY. Sore arm turns into dangerous medical mystery, 'When I tell people what happened, they freak out': A sore arm results in 4 surgeries and 8 days in a hospital Sandra G. Boodman “I try not to be too reflective about the whole thing,” said Zelin of the events of May 2018,� missing something 9395 GIFs Sort: Relevant Newest freeform, shadowhunters, shadowhunters season 2, am i missing something # freeform # shadowhunters # shadowhunters season 2 # am i missing something - Looks like it's missing the runtime. Maybe something like crt0.o, or -lc? - @Kerrek SB, -lcdidn't help and I don't have crt0.oin libgcc directory, only crtbegin.o, crtend.o, crti.o, crtn.othat start with crt. - Try running the compiler with the -vflag and looking at the output. You should see the actual arguments to collect2there which should contain things like -lcand .../crt1.o. If they don't, your compiler is misconfigured, try reinstalling it. - Can you post the generated assembly code? Use the -Sflag. - Also, try a C program, not a C++ program. I think I recall someone having issues with C++, but not C in a similar hello-world configuration. - I'm targeting GNU/Linux with arm-elf file formats. where can I find the runtime for that? - Depending on who created the distribution, your libc may be one of the ones I mentioned (for example, Debian uses glibc but Android uses BSD libc). It's most likely glibc, but you should find out.
https://thetopsites.net/article/59365036.shtml
CC-MAIN-2021-25
refinedweb
1,131
59.4
!. Historical note: this is the third major revision of the GHC build system. The first incarnation was based on "jmake", a derivative of X11's .file which typically contains the build instructions for that directory. - The top-level of the build system is in Makefileand ghc.mk. - Other parts of the build system are in mk/*.mk as normal, and then the result is interpreted by make as makefile code. This means the body of the define gets expanded twice. Typically this means we need to use $$ instead of $ everywhere in the body of define. Now, the build-package macro may need to define local variables. There is no support for local variables in macros, but we can define variables which are guaranteed to not clash with other variables by preceding their names with a string that is unique to this macro call. A convenient unique string to use is directory_build_; this is unique as long as we only call each macro with a given directory/build pair once. Most macros in the GHC build system take the directory and build as the first two arguments for exactly this reason. For example, here's an excerpt from the build-prog macro: define build-prog # $1 = dir # $2 = distdir # $3 = GHC stage to use (0 == bootstrapping compiler) $1_$2_INPLACE = $$(INPLACE_BIN)/$$($1_$2_PROG) ... So if build-prog is called with utils/hsc2hs and dist for the first two arguments, after expansion make would see this: utils/hsc2hs_dist_INPLACE = $(INPLACE_BIN)/$(utils/hsc2hs_dist_PROG) The idiom of $$($1_$2_VAR) is very common throughout the build system - get used to reading it! Note that the only time we use a single $ in the body of define is to refer to the parameters $1, $2, and so on. Idiom:to generate make-dependencies for Haskell source files, and similarly gcc -Mto do the same for C files. The dependencies are normally generated into a file .depend, which is included as normal. package-data.mk. Many of the components of the GHC build system are also Cabal packages, with package metadata defined in a foo.cabalfile. For the GHC build system we need to extract that metadata and use it to build the package. This is done by the program ghc-cabal(in utils/ghc-cabalin the GHC source tree). This program reads foo.cabaland produces package-data.mkcontaining the package metadata in the form of makefile bindings that we can use directly. Now, we also want to be able to use make to build these files, since they have complex dependencies themselves (in order to build package-data.mk we need to first build ghc-cabal etc., and Makefiles before restarting - it doesn't know how to restart itself earlier when there is a dependency between inc1.mk : Makefile echo "X = C" >$@ ifneq "$(PHASE)" "0" include inc2.mk inc2.mk : inc1.mk echo "Y = $(X)" >$@ endif just-makefiles: @: # do nothing clean : rm -f inc1.mk inc2.mk each time make is invoked, it first invokes inc.mk with PHASE=0. This brings inc1.mk up-to-date (and only inc1.mk). The second time we invoke make, we can be sure that inc1.mk is up-to-date and proceed to generate inc2.mk. This is not at all pretty, and re-inovking make every time is slow, but we don't know of a better workaround for this problem. In the case of the GHC build system we need 4 such phases, see the ghc.mk for details..
https://ghc.haskell.org/trac/ghc/wiki/Attic/Building/BuildSystem/New?version=7
CC-MAIN-2017-09
refinedweb
581
65.83
#include "config.h" #include "gromacs/gpu_utils/cuda_arch_utils.cuh" This file defines the PME GPU compile-time constants/macros, used both in device and host code. As OpenCL C is not aware of constexpr, most of this file is forwarded to the OpenCL kernel compilation as defines with same names, for the sake of code similarity. Solving kernel max block width in warps picked among powers of 2 (2, 4, 8, 16) for max. occupancy and min. runtime (560Ti (CC2.1), 660Ti (CC3.0) and 750 (CC5.0))) false: The atom data GPU buffers are sized precisely according to the number of atoms. (Except GPU spline data layout which is regardless intertwined for 2 atoms per warp). The atom index checks in the spread/gather code potentially hinder the performance. true: The atom data GPU buffers are padded with zeroes so that the possible number of atoms fitting in is divisible by PME_ATOM_DATA_ALIGNMENT. The atom index checks are not performed. There should be a performance win, but how big is it, remains to be seen. Additional cudaMemsetAsync calls are done occasionally (only charges/coordinates; spline data is always recalculated now).
https://manual.gromacs.org/documentation/2019-beta2/doxygen/html-full/pme-gpu-constants_8h.xhtml
CC-MAIN-2021-17
refinedweb
189
59.4
On 20/03/12 08:00, Ray Satiro wrote: > Actually it looks like there is a problem with some later versions. > > ---request begin--- > GET /fedora/releases/16/Fedora/i386/iso/Fedora-16-i386-DVD.iso HTTP/1.1 > Range: bytes=-2147483648- > User-Agent: Wget/1.13.1 (mingw32) > Accept: */* > Host: mirrors.kernel.org > Connection: Keep-Alive > > ---request end--- > > The 1.11.4 version I have from gnuwin32 looks fine though > > ---request begin--- > GET /fedora/releases/16/Fedora/i386/iso/Fedora-16-i386-DVD.iso HTTP/1.0 > Range: bytes=2147483648- > User-Agent: Wget/1.11.4 > Accept: */* > Host: mirrors.kernel.org > Connection: Keep-Alive > > ---request end--- > > > If you want the latest version the maintainer of mypaint compiled Wget/1.13.4 > (mingw32) > > go here > > click on wget-1.13.4 > > So it looks there was (and probably still is) a problem with the fstat > replacement. I don't see anything submitted. Confirmed. It is still present in trunk. The only big OS affected is probably windows 32 bit (maybe some non __USE_LARGEFILE64 systems are, too). The bug is on line 3058 of http.c hstat.restval = st.st_size; st_size is a 32 bit off_t, being sign-extended to a 64 bit wgint. I don't think it can be fixed at that point. I would replace the stat to stati64. In fact, wget code seems designed to do that, see the struct_stat comment in sysdep.h I was able to build a wget without the issue by adding this to mswindows.h > --- src/mswindows.h 2011-08-13 08:43:43 +0000 > +++ src/mswindows.h 2012-03-20 19:20:01 +0000 > @@ -102,6 +102,11 @@ > # define fstat(f, b) fstat_alias (f, b) > #endif > > +#define struct_stat struct _stati64 > +#define struct_fstat struct _stati64 > +#undef stat > +#define stat _stati64 > + > #define PATH_SEPARATOR '\\' > > /* Additional declarations needed for IPv6: */ > This bypasses gnulib stat, though.
http://lists.gnu.org/archive/html/bug-wget/2012-03/msg00067.html
CC-MAIN-2015-40
refinedweb
309
69.07
TIME(3) BSD Programmer's Manual TIME(3) time - get time of day #include <time.h> time_t time(time_t *tloc); The time() function returns the value of time in seconds since 0 hours, 0 minutes, 0 seconds, January 1, 1970 ("the Epoch"), Temps Atomique Inter- national (TAI), counting leap seconds.. The following error codes may be set in errno: [EFAULT] An argument address referenced invalid memory. gettimeofday(2), ctime(3) A time() function appeared in Version 2 AT&T UNIX and used to return time in sixtieths of a second in 32 bits, which was to guarantee a crisis every 2.26 years. Since Version 6 AT&T UNIX, time() scale was changed to seconds, extending the pre-crisis stagnation period up to a total of 68 years. On MirOS, the value equals the kernel time, or the result of gettimeofday(2) with no timezone information provided. Counting leap seconds, instead of jumping over them, while calculating the result, violates POSIX, but is the only way to get legal and lawful time. Since MirOS #8, the time_t type has been extended to 64 bit in order to prevent the year 2036 and 2038 crisises..
http://www.mirbsd.org/htman/i386/man3/time.htm
CC-MAIN-2015-14
refinedweb
194
56.79
Animated Drag and Drop with React NativeJavaScript With the ability to start work and build apps quickly, it’s easy to see why React Native is so awesome! However, when you want to add nice animations and effects it can be tricky, especially because the documentation for animations is limited, and it might be difficult to grasp the concepts. Recently, we explored the React Native layout system using flex and we’ve discussed the different options and properties to create all kinds of layouts. Once we have the perfect layout, it is time to add some interaction. In this tutorial, we will learn how to animate an element, drag it around, and drop it. The idea here is to understand how animations in React Native works. Let’s start by creating a new project in your terminal. Type the following command: $ react-native init DragAndDrop Once we have our new project created, let’s open the ios/DragAndDrop.xcode file in xCode to build and run the project in the iOS simulator. Creating the views Before we start coding, let’s create a folder called app, where we will create all our components and classes for this example. Inside this app folder create a new file called Viewport.js. This is where we will write all our code. This way, we can share this component for both iOS and Android apps. Open the index.ios.js file in your favorite editor, remove the original code, and add the following. import React from 'react-native'; import Viewport from './app/Viewport'; React.AppRegistry.registerComponent('DragAndDrop', () => Viewport); This will import React Native and our Viewport, and then register the app. If we want to create an Android app, we can do exactly the same for the index.android.js file. Now we can create the UI for this example. We are going to create a simple container at the top of the screen and a circle at the middle. We will allow the user to drag the circle and drop it on the top area. If the user drags the circle somewhere else, then we will animate the circle back to the middle of the screen. Let’s start coding the Viewport component. For now, we are just going to create the elements and the required styles. Add the following code inside the Viewport.js. import React,{ Component, StyleSheet, View, Text, PanResponder, Animated, Dimensions } from 'react-native'; First, we have to import all the components we are going to need. If you have been following my previous posts about the layout system, you should be familiar with the Component, StyleSheet, View and Text components. - The PanResponderis necessary to help us with the dragging. We are going to need this component to allow the middle circle to move around. - The Animatedclass is the one responsible for the animations. We will use it to animate the circle back to the original position. Dimensionsis a utility class and we will use it to get the size of the device. Based on that, we will calculate the center of the screen to set the top and left of the circle. Next, we will create the Viewport component to display something on the screen. export default class Viewport extends Component{ render(){ return ( <View style={styles.mainContainer}> <View style={styles.dropZone}> <Text style={styles.text}>Drop me here!</Text> </View> {this.renderDraggable()} </View> ); } renderDraggable(){ return ( <View style={styles.draggableContainer}> <Animated.View style={styles.circle}> <Text style={styles.text}>Drag me!</Text> </Animated.View> </View> ); } } Inside the render method we will create the drop zone which is just a view with some text inside. We will also create the circle that we will drag around. Notice that we are using the Animated.View to display the circle. If we want to animate an element, we need to use the Animated.* class. React Native give us three animatable components: Animated.View, Animated.Image and Animated.Text. These classes add the needed support to run fluid animations on these three components. Finally, we need to add the styles to the views — colors, margins, positions, etc. let CIRCLE_RADIUS = 36; let Window = Dimensions.get('window'); let styles = StyleSheet.create({ mainContainer: { flex : 1 }, dropZone : { height : 100, backgroundColor:'#2c3e50' }, text : { marginTop : 25, marginLeft : 5, marginRight : 5, textAlign : 'center', color : '#fff' }, draggableContainer: { position : 'absolute', top : Window.height/2 - CIRCLE_RADIUS, left : Window.width/2 - CIRCLE_RADIUS, }, circle : { backgroundColor : '#1abc9c', width : CIRCLE_RADIUS*2, height : CIRCLE_RADIUS*2, borderRadius : CIRCLE_RADIUS } }); Nothing complicated here, simply adding styles and setting the center of the circle using the size of the device. We also defined a CIRCLE_RADIUS variable to set the size of the circle. If we run our code in the simulators, we should see something like this. Dragging elements Now that we have the main elements on screen, let’s add the drag functionality to the green circle. For that, we need to use the PanResponder class. constructor(props){ super(props); this.state = { pan : new Animated.ValueXY() //Step 1 }; this.panResponder = PanResponder.create({ //Step 2 onStartShouldSetPanResponder : () => true, onPanResponderMove : Animated.event([null,{ //Step 3 dx : this.state.pan.x, dy : this.state.pan.y }]), onPanResponderRelease : (e, gesture) => {} //Step 4 }); } - In step one, create an instance of Animated.ValueXY. This component will take care of interpolating X and Y values. We will run the animations by setting these values to the style of the element to animate. - In step two, create the PanResponder, which is responsible for doing the dragging. We are setting the handlers when the user moves and releases the element. - In step three, the handler will trigger when the element is moving. We need to set the animated values to perform the dragging correctly. - In step four, write the code to execute when the element is released. For now it is empty, but soon we will animate the circle back to the center. Once we have the configurations ready, we need to set these handlers and the animation values to the element that we want to animate. renderDraggable(){ return ( <View style={styles.draggableContainer}> <Animated.View {...this.panResponder.panHandlers} //Step 1 style={[this.state.pan.getLayout(), styles.circle]}> //Step 2 <Text style={styles.text}>Drag me!</Text> </Animated.View> </View> ); } - In the first step, we assign the handlers of the PanResponderto the Animated.View. We are using the spread syntax to avoid assigning one by one. - In the second step, we set the styles to animate from the animation. The getLayout method returns the left and top properties with the correct values for each frame during the animation. We are ready to test our code, save the changes, and run the simulator. You should be able to move the circle around the screen. PanRespondercallback on the constructor. this.panResponder = PanResponder.create({ //... onPanResponderRelease : (e, gesture) => { Animated.spring( //Step 1 this.state.pan, //Step 2 {toValue:{x:0,y:0}} //Step 3 ).start(); } }); - The first step is to use the Animated.springmethod to run the animation. This method will run the animation at a constant speed and we can control the friction and tension. - The first parameter accepts the animation values. - The second parameter is a configuration object. Here, we are defining only the toValue, which is the origin coordinates. This will return the circle to the middle. If you refresh the simulator, you should see something similar to the following image. Animated.springmethod, we also have Animated.decayand Animated.timing. The decay method runs an animation which starts fast and gradually decrease until it stops. The timing method runs the animation based on the time. Dropping the element We’re almost done! All we need now is to set the drop area. When the user drops the green circle inside of the drop zone, we will remove the element from the view. First, we are going to define a state property to know if we will render the green circle or not. Let’s add the following code to our Viewport class. constructor(props){ super(props); this.state = { showDraggable : true, //Step 1 dropZoneValues : null, pan : new Animated.ValueXY() }; //... } renderDraggable(){ if(this.state.showDraggable){ //Step 2 return ( <View style={styles.draggableContainer}> //... </View> ); } } We first define two new properties on the state object. showDraggable will hide or show the green circle. By default this is true, which mean it’s going to be visible. We will change the value to false if the user drops the circle inside the drop zone. In the second step, we render the green circle based on the showDraggable value. Next, we need to set the value of the dropZoneValues property dynamically and we need to know the width and height (or x and y) from the drop zone container . These values will change based on the device. setDropZoneValues(event){ //Step 1 this.setState({ dropZoneValues : event.nativeEvent.layout }); } render(){ return ( <View style={styles.mainContainer}> <View onLayout={this.setDropZoneValues.bind(this)} //Step 2 style={styles.dropZone}> <Text style={styles.text}>Drop me here!</Text> </View> {this.renderDraggable()} </View> ); } - First, we first define a callback where we set the values for the property. - Second, we set the callback to the onLayoutevent. This event will be fired when the view gets rendered on the screen and contains all the sizing based on the assigned styles. - The last step is to check if the green circle coordinates match the coordinates of the drop zone. For that, we need to modify the release callback from the PanResponderas follows. constructor(props){ //... this.panResponder = PanResponder.create({ //... onPanResponderRelease : (e, gesture) => { if(this.isDropZone(gesture)){ //Step 1 this.setState({ showDraggable : false //Step 3 }); }else{ Animated.spring( this.state.pan, {toValue:{x:0,y:0}} ).start(); } } }); } isDropZone(gesture){ //Step 2 var dz = this.state.dropZoneValues; return gesture.moveY > dz.y && gesture.moveY < dz.y + dz.height; } - In the first step, we check if the released element is inside the drop zone. For that, we have defined a function. If the element was released on the drop zone, we need to hide the element, otherwise run the animation. - In the second step, we do the actual checking. We are just comparing the Y coordinates. - In the third step, we hide the green circle by setting the showDraggableproperty to false. Conclusion Animation support in React is great. We have control of every single style property, giving us the opportunity to create very customizable animations and effects. Unfortunately, the React documentation for animations is very limited, but in this tutorial I’ve tried to explain the required steps to use the animation API. All the code written in this tutorial will work on iOS and Android devices. What I personally like about React Native is the performance. Animations run very smoothly on the actual device, allowing us to deliver awesome experiences to users. If you have any questions, please leave a comment or catch me on Twitter. You can also find the code for this tutorial on Github. Happy Coding!
https://moduscreate.com/blog/animated_drag_and_drop_with_react_native/
CC-MAIN-2019-04
refinedweb
1,806
60.01
{-# OPTIONS_GHC -cpp -fglasgow-exts #-} -- arch-tag: 1498020a-9de2-44e3-ae69-14bb1febb77e {- |. regular expressions: these may be strings, which are interpreted as regular expressions, or Regex's from the Text.Regex module. or any other instance of the RegexLike class. when using strings, you may prefix the regex by "(?flags)" where flags is one of 'i' for a case insensitive match and 'm' means a multi-line match. other flags may be available depending on your implementation advanced features: not just strings can be matched, but rather lists of anything a matcher is defined for. RegexLikeImp data class can be used for in-place code generated by template haskell for compile-time checked regular expresions -} module RRegex.Syntax( RegexLike(..), RegexContext(..), (!~~), MatchResult(..)) where import Data.Array import RRegex.PCRE as PCRE --import RRegex import Data.Maybe import Control.Monad import System.IO.Unsafe -- | instances of this class may be used as regular expressions with this syntax. class RegexLike r a | r -> a where -- | Test whether the regex matches at all matchTest :: r -> [a] -> Bool -- | Count the number of times the regex matches matchCount :: r -> [a] -> Int -- | return all matches matchAll :: r -> [a] -> [(Array Int (Int,Int))] -- | match once matchOnce :: r -- ^ Regular Expression -> [a] -- ^ String to match -> Bool -- ^ Whether we are at the begining of the string (as opposed to continuing a previous match) -> Maybe (Array Int (Int,Int)) -- ^ array of matched expression matchShow :: r -> String -- ^ Used for error messages matchTest r xs = isJust (matchOnce r xs True) matchCount r xs = length (matchAll r xs) matchAll r xs = f 0 xs where f t xs = case matchOnce r xs (t == 0) of Nothing -> [] Just a | l == 0 -> [na] | otherwise -> na:f (t + x) (drop x xs) where (o,l) = a!0 x = o + l na = fmap (adj t) a adj t (x,y) = ((,) $! x + t) $! y matchShow _ = "Unknown" data MatchResult a = MR { mrBefore :: [a], mrMatch :: [a], mrAfter :: [a], mrSubList :: [[a]], mrSubs :: Array Int [a] } instance RegexLike PCRE.Regex Char where matchOnce re cs bol = unsafePerformIO (PCRE.execute re cs (if not bol then pcreNotbol else 0)) matchShow _ = "PCRE Regex" class RegexContext x a where -- | match a list against a regular expression, changing its behavior based on its result type. (=~) :: RegexLike r x => [x] -> r -> a -- | Monadic version of (=~). behaves identically, except it causes the monad to fail when the expression does not match, rather than returning a default value. (=~~) :: (Monad m, RegexLike r x) => [x] -> r -> m a -- | check if regular expression does not match (!~~) :: RegexLike r x => [x] -> r -> Bool s !~~ re = not (s =~ re) regexFailed :: (RegexLike r a, Monad m) => r -> m b regexFailed re = fail $ "regex failed to match: " ++ matchShow re -- | return number of expressions matched instance RegexContext x Int where s =~ re = matchCount re s s =~~ re = case (s =~ re) of 0 -> regexFailed re xs -> return $ xs instance RegexContext x ([x],[x],[x]) where s =~ re = maybe (s,[],[]) id (s =~~ re) s =~~ re = case matchOnce re s True of Nothing -> regexFailed re Just a -> let (o,l) = a!o in return (take o s,take l (drop o s),drop (o + l) s) instance RegexContext x ([x],[x],[x],Array Int [x]) where s =~ re = maybe (s,[],[], listArray (1,0) []) id (s =~~ re) s =~~ re = case s =~~ re of Nothing -> regexFailed re Just z -> return (mrBefore z,mrMatch z, mrAfter z, mrSubs z) instance RegexContext x (MatchResult x) where s =~ re = maybe MR {mrBefore = s,mrMatch = [],mrAfter = [],mrSubs = listArray (1,0) [], mrSubList = []} id (s =~~ re) s =~~ re = case matchOnce re s True of Nothing -> regexFailed re Just z -> return $ MR {mrBefore = take o s, mrAfter = drop (o + l) s, mrMatch = a!0, mrSubs = a, mrSubList = tail (elems a) } where a = fmap f z f (o,l) = take l (drop o s) (o,l) = z!0 {- instance RegexContext x [Either [x] [x]] where s =~ re = map f $ matchAll re s where f (Left s) = Left s f (Right (x,_)) = Right x s =~~ re = case (s =~ re) of [Left _] -> regexFailed re xs -> return $ xs -} extract :: [a] -> (Int, Int) -> [a] extract s (x,y) = take y (drop x s) instance RegexContext x [x] where s =~ re = case s =~~ re of Nothing -> [] Just z -> mrMatch z s =~~ re = liftM mrMatch (s =~~ re) -- useful in non-monad context instance RegexContext x Bool where s =~ re = matchTest re s s =~~ re = case s =~ re of False -> regexFailed re True -> return True -- useful in monad context instance RegexContext x () where _ =~ _ = () s =~~ re = case s =~ re of False -> regexFailed re True -> return () instance RegexContext x [[x]] where s =~ re = [extract s (a!0) | a <- matchAll re s] s =~~ re = case (s =~ re) of [] -> regexFailed re xs -> return xs instance RegexContext x [Array Int [x]] where s =~ re = [fmap (extract s) x | x <- matchAll re s] s =~~ re = case (s =~ re) of [] -> regexFailed re xs -> return xs {- instance RegexContext x [Array Int (Int,Int)] where s =~ re = matchAll re s s =~~ re = case (s =~ re) of [] -> regexFailed re xs -> return xs -} instance RegexContext x [Array Int ([x],(Int,Int))] where s =~ re = [fmap (\z -> (extract s z,z)) x | x <- matchAll re s] s =~~ re = case (s =~ re) of [] -> regexFailed re xs -> return xs instance RegexContext x (Array Int [x]) where s =~ re = maybe (listArray (1,0) []) id (s =~~ re) s =~~ re = case s =~~ re of Nothing -> regexFailed re Just z -> return $ mrSubs z instance RegexLike String Char where matchOnce re xs bol = matchOnce (c re) xs bol where c s = unsafePerformIO $ PCRE.compile s 0 >>= \x -> case x of Left (i,err) -> fail $ "PCRE Regular Expression Error:\n" ++ re ++ "\n" ++ replicate i ' ' ++ "^ " ++ err Right p -> return p matchShow s = s {- instance RegexLike Regex Char where matchOnce re xs = fmap f (matchRegexAll re xs) where f (x,y,z,ls) = MR { mrBefore = x,mrMatch = y ,mrAfter = z,mrSubs = listArray (1,length ls) ls} matchShow _ = "Regex" instance RegexLike String Char where --matchOnce re xs = fmap f (matchRegexAll (mr re) xs) where -- f (x,y,z,ls) = (x,y,z,listArray (1,length ls) ls) matchOnce re xs = fmap f (matchRegexAll (mr re) xs) where f (x,y,z,ls) = MR { mrBefore = x,mrMatch = y ,mrAfter = z,mrSubs = -}
http://hackage.haskell.org/package/pugs-hsregex-1.0/docs/src/RRegex-Syntax.html
CC-MAIN-2015-35
refinedweb
1,025
62.35
SCTP_SEND(3) Linux Programmer's Manual SCTP_SEND(3) sctp_send - Send a message from a SCTP socket. #include <sys/types.h> #include <sys/socket.h> #include <netinet/sctp.h> int sctp_send(int sd, const void * msg, size_t len, const struct sctp_sndrcvinfo *sinfo, uint32_t flags); sctp_send is a wrapper library function that can be used to send a message from a socket without the use of the CMSG header structures. sd is the socket descriptor from which the message pointed to by msg of length len is sent. sinfo is a pointer to a sctp_sndrcvinfo structure. flags parameter is composed of a bitwise OR of the flags that can be be passed as the 3rd argument of a standard sendmsg() call. On success, sctp_sendmsg returns the number of bytes sent or -1 if an error occurred. sctp(7) sctp_bindx(3), sctp_recvmsg(3), sctp_recvv(3), sctp_peeloff(3), sctp_getpaddrs(3), sctp_getladdrs(3), sctp_opt_info(3), sctp_sendmsg(3), sctp_sendv_SENDmsg(3), sctp_sendv(3), sctp(7)
https://www.man7.org/linux/man-pages/man3/sctp_send.3.html
CC-MAIN-2022-33
refinedweb
158
56.15
Provided by: libzip-dev_1.5.1-0ubuntu1_amd64 NAME zip_source_filep, zip_source_filep_create — create data source from FILE * LIBRARY libzip (-lzip) SYNOPSIS #include <zip.h> zip_source_t * zip_source_filep(zip_t *archive, FILE *file, zip_uint64_t start, zip_int64_t len); zip_source_t * zip_source_filep_create(FILE *file, zip_uint64_t start, zip_int64_t len, zip_error_t *error); DESCRIPTION The functions zip_source_filep() and zip_source_filep_create() create a zip source from a file stream. They read len bytes from offset start from the open file stream file. If len is 0 or -1, the whole file (starting from start) is used. If the file stream supports seeking, the source can be used to open a read-only zip archive from. The file stream is closed when the source is being freed, usually by zip_close(3). RETURN VALUES Upon successful completion, the created source is returned. Otherwise, NULL is returned and the error code in archive or error is set to indicate the error. ERRORS zip_source_filep() fails if: [ZIP_ER_INVAL] file, start, or len are invalid. [ZIP_ER_MEMORY] Required memory could not be allocated. SEE ALSO libzip(3), zip_add(3), zip_replace(3), zip_source(3) HISTORY zip_source_filep() and zip_source_filep_create() were added in libzip 1.0. AUTHORS Dieter Baron <dillo@nih.at> and Thomas Klausner <tk@giga.or.at>
http://manpages.ubuntu.com/manpages/eoan/man3/zip_source_filep.3.html
CC-MAIN-2020-29
refinedweb
196
58.69
C++ Program to Count Number of Digits in an Integer Grammarly In this post you will learn how to Count Number of Digits in an Integer This lesson will teach you how to count the number of digits in a number, with a while loop, increment operator and mathematical functions using the C++ Language. Let’s look at the below source code. How to Count Number of Digits in an Integer? Source Code #include <iostream> using namespace std; int main() { int num, temp; int count = 0; cin >> num; cout << "Enter any number : "<<num<<endl; temp = num; while(temp != 0) { count++; temp /= 10; } cout << "/nTotal digits in " <<num<< " is : " <<count; return 0; } Input 23456 Output Enter any number : 23456 Total digits in 23456 is : 5 The statements #include<iostream>, using namespace std, int main are the main factors that support the function of the source code. Now we can look into the working and layout of the code’s function. - Declare the variables int, temp, count as integers and assign the value 0 for the integer count - Get the value and store it in int and display the output statement using cout<<and the Insertion Operators'<<‘ . - Using the assignment operator ‘=’, we assign the value in int to temp. - We create a while loop with the condition (temp != 0)where the value of temp should not be equal to 0. - When this condition is satisfied the loop statement is executed where the count with the initial value 0 is incremented and then the mathematical expression temp /= 10is executed - In the mathematical function when the number is divided by ten when turns the number into a decimal number and the number after the decimal point is neglected. - Then the while loop is executed continuously until the condition is false and each time the loop is executed the number is reduced slowly and the count value is incremented. - After the execution is completed the answer is displayed.
https://developerpublish.com/academy/courses/c-programming-examples-2/lessons/c-program-to-count-number-of-digits-in-an-integer/
CC-MAIN-2021-49
refinedweb
323
55.27
Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected. You have to either create an instance of class B to reference the value:You do NOT have to create an instance of a class to refer to a public static member. You simply refer to a static member by prefacing it with the class name, and not an instance name. string value = B.FIRSTCONST; namespace helloprogram { class A { public void displaymethod() { Console.writeline(B.FIRSTCONST ); } } } namespace helloprogram { class B { public const string FIRSTCONST = "Hello"; } } Declare it as a constant, not as a variable, so you will be able to use it straight on the class, without having to initialize an object for no reason.Static members are initialized when they are first referenced. You would not need to create an instance of the object in order to have a static member initialized--the first reference to the variable would invoke the class' static constructor (and static initializers). I took the question as it was asked: class B contains a constant FIRSTCONST.Ah, I missed "constant" in the OP. The original code, sans constant and your previous statement are in conflict, which is why I posted my comment. Taking the addition of the const modifier into account, then it makes a bit more sense = ) Although they can be used in a similar way, static variables and constants are not the same thing.Ne'er claimed they were ; ) If you are experiencing a similar issue, please ask a related question Join the community of 500,000 technology professionals and ask your questions.
https://www.experts-exchange.com/questions/27344495/parameter-class.html
CC-MAIN-2018-05
refinedweb
284
60.24
if_comp - ps Start an if bool - ps...else - ps...endif - ps block, with a condition based on values that could be computed in a shader. This instruction is used to skip a block of code, based on a condition. Syntax Where: - _comp is a comparison between the two source registers. It can be one of the following: - src0 is a source register. Replicate swizzle is required to select a component. - src1 is a source register. Replicate swizzle is required to select a component. Remarks This instruction is used to skip a block of code, based on a condition. Be careful using the equals and not equals comparison modes on floating point numbers. Because rounding occurs during during floating point calculations, the comparison can be done against an epsilon value (small nonzero number) to avoid errors. Restrictions include: - if_comp...else - ps...endif - ps blocks (along with the predicated if blocks) can be nested up to 24 layers deep. - src0 and src1 registers require a replicate swizzle. - if_comp blocks must end with an else - vs or endif - vs instruction. - if_comp...else - ps...endif - ps blocks cannot straddle a loop block. The if_comp block must be completely inside or outside the loop block. Example This instruction provides conditional dynamic flow control. Show:
https://msdn.microsoft.com/en-us/library/windows/desktop/bb174582.aspx
CC-MAIN-2015-22
refinedweb
209
68.47
20+ Spring Interview Questions and Answers: Overview Spring Interview Questions and Answers Q1 - Q14 are FAQs Spring framework is very vast, widely used and often beginners get overwhelmed by it. If you are pressed for time, try to learn at least the core basics in this post and the first two links shown below. Learning the fundamentals described can save you a lot of frustrations, especially knowing the DI and IoC basics, bean life cycle and bean scopes. Q1. What do you understand by the terms Dependency Inversion Principle (DIP), Dependency Injection (DI) and Inversion of Control (IoC) container ? A1. - Dependency Inversion Principle (DIP) is a design principle which is in some ways related to the Dependency Injection (DI) pattern. The idea of DIP is that higher layers of your application should not directly depend on lower layers. Dependency Inversion Principle does not imply Dependency Injection. This principle doesn’t say anything about how higher la yers know what lower layer to use. This could be done as shown below by coding to interface using a factory pattern or through Dependency Injection by using an IoC container like Spring framework, Pico container, Guice, or Apache HiveMind. The Dependency Inversion Principle (DIP) states that - High level modules should not depend upon low level modules. Both should depend upon abstractions. - Abstractions should not depend upon details. Details should depend upon abstractions. Firstly define the abstraction layer. package principle_dip2; public interface AnimalHandler { public abstract void handle( ); } package principle_dip2; public interface AnimalHelper { public abstract void help( ); } Now the implementation that depends on the abstraction as opposed to the implementation. package principle_dip2; public class CircusService { AnimalHandler handler; public void setHandler(AnimalHandler handler) { this.handler = handler; } public void showStarts( ) { //code omitted for brevity handler.handle( ); } } package principle_dip2; public class TigerHandler implements AnimalHandler{ AnimalHelper helper; public void setHelper(AnimalHelper helper) { this.helper = helper; } public void handle( ){ //... helper.help( ); //... } } package principle_dip2; public class TigerHelper implements AnimalHelper{ public void help( ){ //...... } } - Dependency Injection (DI) is a pattern of injecting a class’s dependencies into it at runtime. This is achieved by defining the dependencies as interfaces, and then injecting in a concrete class implementing that interface to the constructor. This allows you to swap in different implementations without having to modify the main class. The Dependency Injection pattern also promotes high cohesion by promoting the Single Responsibility Principle (SRP), since your dependencies are individual objects which perform discrete specialized tasks like data access (via DAOs) and business services (via Service and Delegate classes) . - The Inversion of Control Container (IoC) is a container that supports Dependency Injection. In this you use a central container like Spring framework, Guice, or HiveMind, which defines what concrete classes should be used for what dependencies throughout your application. This brings in an added flexibility through looser coupling, and it makes it much easier to change what dependencies are used on the fly. The basic concept of the Inversion of Control pattern. The real power of DI and IoC is realized in its ability to replace the compile time binding of the relationships between classes with binding those relationships at runtime. For example, in Seam framework, you can have a real and mock implementation of an interface, and at runtime decide which one to use based on a property, presence of another file, or some precedence values. This is incredibly useful if you think you may need to modify the way your application behaves in different scenarios. Another real benefit of DI and IoC is that it makes your code easier to unit test. There are other benefits like promoting looser coupling without any proliferation of factory and singleton design patterns, follows a consistent approach for lesser experienced developers to follow, etc. These benefits can come in at the cost of the added complexity to your application and has to be carefully manged by using them only at the right places where the real benefits are realized, and not just using them because many others are using them. Note: The CDI (Contexts and Dependency Injection) is an attempt at describing a true standard on Dependency Injection. CDI is a part of the Java EE 6 stack, meaning an application running in a Java EE 6 compatible container can leverage CDI out-of-the-box. Weld is the reference implementation of CDI. Q2. In your experience, why would you use Spring framework? A2. - Spring has a layered architecture with over 20 modules to choose from. This means, use what you need and leave what you don't need now. Spring simplifies JEE through POJO programming. There is no behind the scene magic in Spring as in JEE programming. POJO programming enables continuous integration and testability. - Spring framework's core functionality is dependency injection (DI). Dependency injection promotes easy unit testing and more maintainable and flexible code. DI code is much easier to test. The functionality expressed by the object can be tested in a black box by building 'mock' objects implementing the interfaces expected by your application logic. DI code is much easier to reuse as the 'depended' functionality is extrapolated into well defined interfaces, allowing separate objects whose configuration is handled by a suitable application platform to be plugged into other objects at will. DI code is more flexible. It is innately loosely coupled code to an extreme. This allows the programmer to pick and choose how objects are connected based exclusively on their required interfaces on one end and their expressed interfaces on the other. - Spring supports Aspect Oriented Programming (AOP), which enables cohesive development by separating application business logic from system services. Supporting functionalities like auditing, gathering performance and memory metrics, etc can be enabled through AOP. - Spring also provides a lot of templates which act as base classes to make using the JEE standard technologies a breeze to work with. For example, the JdbcTemplate works well with JDBC, the JpaTemplate does good things with JPA, JmsTemplate makes JMS pretty straightforward. The RestTemplate is simply awesome in it's simplicity. Simplicity means more readable and maintainable code. - When writing software these days, it is important to try and decouple as much middleware code from your business logic as possible. The best approach when using remoting is to use Spring Remoting which can then use any messaging or remoting technology under the covers. Apache Camel is a powerful open source integration framework based on known Enterprise Integration Patterns with powerful Bean Integration. Apache Camel is designed to work nicely with the Spring Framework in a number of ways. - It also provides declarative transactions, job scheduling, authentication, a fully-fledged MVC web framework, and integration to other frameworks like Hibernate, iBatis, JasperReports, JSF, Struts, Tapestry, Seam, Quartz job scheduler, etc. - Spring beans can be shared between different JVMs using Terracotta. This allows you to take existing beans and spread them across a cluster, turn Spring application context events into distributed events, export clustered beans via Spring JMX, and make your Spring applications highly available and clustered. Spring also integrate well with other clustering solutions like Oracle's Coherance. - Spring favors unchecked exceptions and eliminates unsightly try, catch, and finally (and some times try/catch within finally itself) blocks. The Spring templates like JpaTemplate takes care of closing or releasing a database connection. This prevents any potential resource leaks and promotes more readable code. - It prevents the proliferation of factory and singleton pattern classes that need to be created to promote loose coupling if not for using a DI framework like Spring or Guice. A3. - Spring has become very huge and bulky. So, don't over do it by using all its features because of the hype that Spring is good. Look at what parts of Spring really provides some benefits for your project and use those parts. In most cases, it is much better to use proven frameworks like Spring than create your own equivalent solution from a maintenance and applying the best practices perspective. For example, all spring templates (jdbc, rest, jpa etc.) have the following advantages -- perform common setup routines for you, let you skip the boilerplate and concentrate on the logic you want. - Spring MVC is probably not the best Web framework. There are other alternatives like Struts 2, Wicket, and JSF. Having said this, Spring integrates well with the other Web frameworks like Struts, JSF, etc. - The XML files can get bloated. This can be minimized by carefully considering other options like annotations, JavaConfig, and having separate XML configuration files. Q4. What are the different types of IoC (dependency injection) ? A4. There are three types of dependency injection: - Constructor Injection (e.g. Spring): Dependencies are provided as constructor parameters. - Setter Injection (e.g. Spring): Dependencies are assigned through JavaBeans properties (ex: setter methods). - Interface Injection (e.g. Avalon): Injection is done through an interface. Q. Have you used any other Dependency Injection (DI) frameworks? A. Yes, Guice, Hivemind, and Seam. - Spring Interview Questions and Answers : Spring Bean life cycle, DI, and IOC - Understanding Spring bean scopes -- Singleton Vs. Prototype - Spring Interview Questions and Answers: read properties file - Spring and hibernate simple JDBC example - Spring Interview Questions and Answers: Hibernate integration - Spring Interview Questions and Answers: JNDI, JMS and Other - Hibernate Interview Questions and Answers: with annotations and Spring framework - Spring and Hibernate Interview Q&A: AOP, interceptors, and deadlock retry - Batch processing in Java with Spring batch - part 1 - JSONP and jQuery with Spring MVC, RESTful Web Service and Maven - CORS and jQuery with Spring MVC RESTful Web Service 23 Comments: Thanks for this interview questions and answers. Interview Questions Real good question and What I like most is detailed explanation. The main benefit offered by Spring is dependency Injection which leads to loosely coupled design and that has been clearly explained in point 1. By the way you can also see this list of spring questions asked in Java interviews for practice. Really good article. Very detailed and unique one. Its really really helpful for a person like me who daily uses spring but unaware of its architecture details. Keep posting such articles. Great work ! Regards, Amir Dear Arulkumaran Kumaraswamipillai , I don't have much more knowledge to justify your work, or to suggest you something , but just one thing i realized when i go through your all books ,blogs ,suggestions, you are God of Java :) your hard work pays not only to you , it pays to many one like me ....... God bless you .. and thanks a lot for your great work and also for your hard work. Your efforts are truly amazing and incredible ...... Thanks Again Arulkumaran Sir Tks very much for post: I like it and hope that you continue posting. Let me show other source that may be good for community. Source: Hr sample interview questions Best rgs David Good tips Web Designer in Bangalore Dear ArulKumar am your fan i have more interest learn new technology, i learned all your Book i was gained lot of knowledge from your blogs thank you so much arulkumaran sir Thanks. What is Spring MVC ? What are the suitable request flow diagram of Spring MVC? Learn the MVC web design pattern. Spring MVC is a web framework, like Struts. refer why do you think spring mvc is not considered as a good web framework? I did not say it is bad. There are 15+ web frameworks in Java and some are more popular than the others. Each has its pros and cons. The current trend is to build single page RIA with JavaScript frameworks like AngularJS, HTML5, and CSS3. I have question what is difference between java scheduler and spring scheduler i am new to spring pls could you explain what is mean a pattern of injecting a class’s dependencies into it at runtime start with a tutorial: there are more tutorials in this blog. Follow the links and use the search bar at the top. There are different scheduling frameworks like Quartz, Spring task executor, etc to run a job asynchronously at a pre-determined time or interval, as a result of an event, etc. thank you very much. i have senario to develope scheduler job class which can call a java program on daily basis and program internally call a webservice for this which is best frameworks develope schedular. Have a look at Quartz. Also, check if your organization uses commercial tools like control-M. thank you so much for replies. i want go with Quartz and i started sample programs and i found which is easy simple configuration changes. how avoid code changes which i am updating application context file everytime if want to change my schedular dates and timings. i have created pool size minimum 1 and maximum 5 but i m getting this exception can you please advise on this error : org.jboss.util.NestedSQLException: No ManagedConnections available within configured blocking timeout ( 30000 [ms] ); - nested throwable: (javax.resource.ResourceException: No ManagedConnections available within configured blocking timeout ( 30000 [ms] )) What database are you using? Why spring is not supporting interface injection?
http://java-success.blogspot.com.au/2011/10/spring-interview-questions-and-answers.html
CC-MAIN-2016-26
refinedweb
2,165
54.52
ncl_ftitle man page FTITLE — Used for unscrolled movie or video titles. It reads, from standard input, the information necessary to define the desired title frames, and then calls STITLE to create those frames. Synopsis CALL FTITLE (MTST) C-Binding Synopsis #include <ncarg/ncargC.h> void c_ftitle (int mtst) Description - MTST (an input expression of type INTEGER) is a switch indicating whether this is a "real" run or a "practice" run: - 0 means "real run". - 1 means "practice run". During real runs, each title frame is repeated as many times as necessary to display it for a user-specified time period (at ´NFS´ frames per second). Blank frames are placed before the first title frame (´TM1´ seconds worth of them), between consecutive title frames (´TM2´ seconds worth of them), and after the last title frame (´TM2´ + ´TM3´ seconds worth of them). Blank frames are to allow for splicing. If the user has turned on fade-in (by setting the internal parameter ´FIN´ non-zero), and/or fade-out (by setting the internal parameter ´FOU´ non-zero), the required fade-in and fade-out frames will be generated, as well. During practice runs, each title frame will occur from one to three times (once for fade-in, once for the stationary holding time, and once for fade-out); each of these frames will have a legend indicating how many seconds the frame represents in a real run. Each sequence of blank frames will be replaced by a single frame with a message indicating how many seconds worth of blank frames it represents. C-Binding Description The C-binding argument description is the same as the FORTRAN argument description. Usage FTITLE reads data from the unit specified by the internal parameter ´ICU´, which has the default value 5, to specify standard input; this parameter can be given a different value to specify that another unit should be read instead. The input data are read in groups. Each group represents one title frame. There can be any number of groups. FTITLE keeps processing groups until a group with NCDS = 0 is read or an end-of-file is encountered. A group consists of the following: A header line from which variables NCDS, TIME, and SIZE are read, using the FORTRAN format "(I5,2F5.1)". NCDS is the number of text lines that follow. If NCDS = 0, FTITLE quits (returns to the calling routine without doing anything else). TIME is the time, in seconds, that the title frame should be displayed (not including fade-in and fade-out, if any). SIZE is the desired character size, given as a multiplier of the default height specified by the value of the internal parameter ´PSZ´, the default value of which is 21 (out of 1023). Values of SIZE from .75 to 2.5 are recommended. - Text lines, each containing one line of the title frame. PLOTCHAR function codes may be used as specified in the documentation for that package. Characters should not appear beyond column 80. The internal parameters 'ALN', 'BGB', 'BGC', 'BGF', 'BGG', 'BGR', 'FGB', 'FGC', 'FGF', 'FGG', 'FGR', 'FIN', 'FOU', 'GSZ', 'ICO', 'ICU', 'LOG', 'LX1', 'LX2', 'LY1', 'LY2', 'MAP', 'NFS', 'NXE', 'NXS', 'ORV', 'PSZ', 'SBK', 'SFG', 'TM1', 'TM2', 'TM3', 'VPB', 'VPL', 'VPR', 'VPT', and 'WID' all affect the behavior of FTITLE in one way or another. Some of these have been mentioned above; all are described in the "man" page for "scrolled_title_params". Example: Suppose the input file contains the following three lines 3 3. 1.5 A Frame of Titles The resulting title frame has three lines of text. It is displayed for three seconds. Characters have a size of 1.5 times the default character size. FTITLE allows a maximum of 80 characters per line of text including Plotchar function codes. No more than 120 lines of text can be displayed on a single frame. Titles are centered horizontally unless you have changed the value of the internal parameter 'ICO'. Vertical spacing is automatically determined using the current value of the internal parameter 'GSZ'. For more detailed control of titles, use the routine STITLE, which can be used to generate either fixed or scrolled titles. Examples Use the ncargex command to see the following relevant example: slex02. Access To use FTITLE or c_ftitle,: plotchar, scrolled_title, scrolled_title_params, slgeti, slgetr, slogap, slrset, slseti, slsetr, stitle, ncarg_cbind. Hardcopy: NCAR Graphics Fundamentals, UNIX Version; User's Guide for NCAR GKS-0A Graphics University Corporation for Atmospheric Research The use of this Software is governed by a License Agreement.
https://www.mankier.com/3/ncl_ftitle
CC-MAIN-2017-26
refinedweb
750
62.88
Congress and. Pradhan Mantri Mudra Yojana: finance ministry ties up with e-commerce firms to give loans. Over 39 lakh new jobs created in 7 months till March, reveals EPFO payroll data). E-way bill alert: country-wide system to be mandatory from this date.. He said Bangladesh also successfully used the same strategies but Pakistan could not put its own plans to use as the decade was lost to political instability. He was speaking at the inauguration of Pakistan National Centre for Cyber Security here yesterday. USD 33 billion while we are at USD. Rs 450-crore input tax credit: intelligence unit unearths fake gst bills business The intelligence unit for the goods and services tax (GST) has unearthed a nexus among businesses that use fake bills to claim input tax credit (ITC). Given the value of the fictitious purchases is estimated to be around `2,500 crore, the undeserved ITCs pocketed by these firms are seen to be `450 crore at an average GST rate of 18%. Sources said that the fake bill provider is absconding but the government has started issuing summons to businesses that produced these counterfeit bills to claim tax credits. One such notice issued by the Directorate General of Goods and Services Tax Intelligence (DGGSTI) unit in Meerut has been reviewed by FE. It has invoked the erstwhile excise, service tax as well as the new GST Acts and has asked the taxpayer to “give evidence truthfully on such matters concerning the enquiry as you may be asked and produce the documents and record mentioned in the schedule for the examination”. The invocation of service tax law ensures that the department can look into documents for the last five years as well. The modus operandi involves businesses buying invalid bills, which enables them to claim input tax credit on the fictitious supply. A portion of this amount is paid to the providers of such bills as commission. “Based on a fake invoices of supplies worth Rs 118, say, of goods attracting 18% GST, a taxpayer can claim Rs 18 as ITC. It pays Rs 3-5 to the fake bill seller and pockets the rest,” a source explained. He said such invoices usually show supplies of white goods or other commodities attracting higher rates. “The racket has hampered the tax collections, as many suppliers have converted their B2C (business-to-consumer) sales into B2B (business-to-business) sales, thereby passing on the input tax credit to the recipient. The tax so paid under B2C supplies is an accrued revenue for the government, whereas taxes paid under B2B supplies is a liability which would be adjusted till a final B2C supply occurs,” said Rajat Mohan, partner, AMRG & Associates. The government has long suspected large-scale evasion in credit claims including transitional credit, which was claimed on tax-paid goods brought to GST regime after July 1. taxpayers have claimed over Rs 1.6 lakh crore as transitional credit till December last year when the window for such claims closed. Thereafter, the Central Board of Indirect Taxes and Customs (CBIC) culled out the top 50,000 such claimants, who are responsible for nearly 90% of the claims, for detailed verification. This exercise is stipulated to run through out this year. Similarly, in the absence of an invoice-matching system of return-filing, taxpayers have been allowed to file a monthly summary return (GSTR-3B) with self-declared tax liability and ITC availability. Although they are required to file sales invoices also under GSTR-1 return, the matching of inward and outward supplies have been hampered leading to evasion. Tax officials say that enforcement action is not in full swing yet as the government believes assessees need more time to adjust to the new system, matching of large amount of taxpayer data is resulting in exposing anomalies. India’s billionaire count to rise 3 times by 2027, says report Ind. Over the next 10 years, while India is expected to create 238 additional billionaires, its neighbour China is likely to add as 448 such individuals. By 2027, the United States is likely to have the maximum number of billionaires at 884, followed by China (697), and India (357) in the second and third positions, respectively. Billionaires refer to individuals with net assets of USD 1 billion or more. Other countries that are expected to create significant number of billionaires over the next decade include Russian Federation (142), United Kingdom (113), Germany (90) and Hong Kong (78). Globally, there are 2,252 billionaires at present, and this number is expected to increase to 3,444 by 2027. In terms of “total wealth” — the private wealth held by all the individuals living in each country — India is the sixth wealthiest country in the world with a total wealth of USD 8,230 billion. The US is the wealthiest country in the world with a total wealth of USD 62,584 billion, followed by China (USD 24,803 billion) and Japan (USD 19,522. Meanwhile, global wealth is expected to rise by 50 per cent over the next decade, reaching USD 321 trillion by 2027. The fastest growing wealth markets are expected to be Sri Lanka, India, Vietnam, China, Mauritius, the report said.
http://www.pakistaneconomist.com/2018/05/28/india-22-18/
CC-MAIN-2018-47
refinedweb
873
56.69
Michael has done a great job introducing Dryad. Now, let us take a look at what DryadLINQ is. DryadLINQ provides a new programming model for large scale data-parallel computing. The most unique feature of DryadLINQ is its complete integration with a traditional high-level programming language: the data model of DryadLINQ is just typed .NET objects, and a DryadLINQ program is just a sequential program (written in C#, VB, or F#) composed of LINQ queries. The beauty of this approach is that there is not much difference in writing programs for a single computer or a compute cluster. All .NET developers should be able to write a DryadLINQ program with minimal additional learning. Perhaps, it would be helpful to show a concrete example. So, here is a complete DryadLINQ program: public class LogEntry { public string user; public string ip; public string page; public LogEntry(LineRecord line) { string[] fields = line.line.Split(' '); this.user = fields[8]; this.ip = fields[9]; this.page = fields[5]; } } public class PageCount { public int count; public UserPageCount(string user, string page, int count) { this.user = user; this.page = page; this.count = count; public class Demo { public static void Main(string[] args) { string tableUri = "dfs://sherwood/yuanbyu/logs.pt"; var logs = PartitionedTable.Get<LineRecord>(tableUri); var q = TopPages(logs, "michael"); foreach (var x in q) { Console.WriteLine(x); } static IQueryable<PageCount> TopPages(IQueryable<LineRecord> logs, string name) { return logs.Where(x => x.line.Contains(name)) .Select(x => new LogEntry(x)) .GroupBy(x => x.page) .Select(x => new PageCount(name, x.Key, x.Count())) .OrderByDescending(x => x.count).Take(10); The above program computes, from a web server log, the top 10 most frequently visited web pages by Michael. The program looks no different from your normal LINQ programs: you get to use .NET classes to define your data types and familiar language constructs such as methods and loops to write the program. You also get to use the big collection of .NET libraries in your programs. Because LINQ queries are integrated into the language, invoking a LINQ query is just a method call and within a LINQ operator you can easily invoke any arbitrary .NET methods. Perhaps, I am biased, but this is the best data-parallel programming model I have seen so far. So, how do we get the LINQ queries in a program like above magically run on a large compute cluster of thousands of machines? This is where Dryad and DryadLINQ come in. Dryad is our distributed execution engine that provides efficient and reliable execution of programs on large compute clusters. DryadLINQ automatically and transparently translates the LINQ queries in the program into a distributed execution plan and hands the plan and program to Dryad for execution. In some sense, DryadLINQ is the parallel compiler and runtime, and Dryad is the ‘operating system’ of a compute cluster. The basic DAG computation model that Dryad uses looks to me like the ‘instruction set’ of a compute cluster. As mentioned by Michael in his recent post, Dryad has been doing the heavy-lifting for all of Bing’s data-mining. While DryadLINQ is still a research system, it has been used within Microsoft by many people for many applications. (We will probably write a number of blogs about the applications in the near future.) The system has been reasonably stable. We are actively improving both Dryad and DryadLINQ based on our users feedback. In this post, we barely touched on the technical details of the Dryad and DryadLINQ systems. In future posts, we will get into the technical details of the systems. But if you are eager to learn more about the systems, take a look at our project web page, which contains many papers and presentations about the systems. Dryad and DryadLINQ are also available free for non-commercial use from this site. So, please try it out!
http://blogs.msdn.com/b/dryad/archive/2009/12/07/what-is-dryadlinq.aspx
CC-MAIN-2013-20
refinedweb
644
65.93
Description ## Features of PSpider - Support multi-threading crawling mode (using threading and requests) - Support distributed crawling mode (using threading, requests and red spider - instances module: define classes of fetcher, parser, saver for multi-threading spider - concurrent module: define WebSpiderFrame of multi-threading spider and distributed spider PSpider alternatives and similar packages Based on the "Web Crawling" category. Alternatively, view PSpider alternatives based on common mentions on social networks and blogs. Scrapy9.9 9.1 L4 PSpider VS ScrapyScrapy, a fast high-level web crawling & scraping framework for Python. pyspider9.6 0.6 L3 PSpider VS pyspiderA Powerful Spider(Web Crawler) System in Python. requests-html9.2 0.0 PSpider VS requests-htmlPythonic HTML Parsing for Humans™ portia9.1 0.0 L2 PSpider VS portiaVisual scraping for Scrapy MechanicalSoup7.8 6.1 L4 PSpider VS MechanicalSoupA Python library for automating interaction with websites. RoboBrowser7.6 0.0 L4 PSpider VS RoboBrowserA simple, Pythonic library for browsing the web without a standalone web browser. cola6.7 0.0 L3 PSpider VS colaA high-level distributed crawling framework. Grab6.6 4.0 L3 PSpider VS GrabWeb Scraping Framework Scrapely6.4 0.0 PSpider VS ScrapelyA pure-python HTML screen-scraping library gain6.4 0.0 PSpider VS gainWeb crawling framework based on asyncio. feedparser5.7 7.4 L3 PSpider VS feedparserParse feeds in Python Sukhoi4.4 3.9 PSpider VS SukhoiMinimalist and powerful Web Crawler. MSpider4.1 0.0 PSpider VS MSpiderSpider spidy Web Crawler3.0 0.0 PSpider VS spidy Web CrawlerThe simple, easy to use command line web crawler. brownant2.6 0.0 PSpider VS brownantBrownant is a web data extracting framework. Crawley2.6 0.0 PSpider VS CrawleyPythonic Crawling / Scraping Framework based on Non Blocking I/O operations. Google Search Results in PythonGoogle Search Results via SERP API pip Python Package Demiurge1.9 0.0 L5 PSpider VS DemiurgePyQuery-based scraping micro-framework. reader1.8 9.4 PSpider VS readerA Python feed reader library. Pomp1.5 0.0 L5 PSpider VS PompScreen scraping and web crawling framework FastImage0.9 0.0 L4 PSpider VS FastImagePython library that finds the size / type of an image given its URI by fetching as little as needed Mariner0.4 5.6 PSpiderSpider or a related project? README PSpider A simple web spider frame written by Python, which needs Python3.5+ Features of PSpider - Support multi-threading crawling mode (using threading and requests) - Support multi-processing in parse process, automatically (using multiprocess multi-threading spider - instances module: define classes of Fetcher, Parser, Saver for multi-threading spider - concurrent module: define WebSpiderFrame of multi-threading spider Procedure of PSpider [](procedure.png) ①: Fetchers get url from UrlQueue, and make requests based on this url ②: Put the result of ① to HtmlQueue, and so Parser can get it ③: Parser gets item from HtmlQueue, and parses it to get new urls and items ④: Put the new urls to UrlQueue, and so Fetcher can get it ⑤: Put the items to ItemQueue, and so Saver can get it ⑥: Saver gets item from ItemQueue, and saves it to filesystem or database ⑦: Proxieser gets proxies from web or database, and puts proxies to ProxiesQueue ⑧: Fetcher gets proxies from ProxiesQueue if needed, and makes requests based on this proxies Tutorials of PSpider Installation: you'd better use the first method (1)Copy the "spider" directory to your project directory, and import spider (2)Install spider to your python system using python3 setup.py install See test.py TodoList - More Demos - Distribute Spider - Execute JavaScript
https://python.libhunt.com/pspider-alternatives
CC-MAIN-2021-31
refinedweb
588
53.21
Hello! This is my first post on the Arduino forums, so bear with me as I get acclimated. I am working on a project that is basically a simplistic clone of a CatEye style bicycle computer. I want to monitor speed and distance and so on. Ive been making great progress recently, and I have a pretty complete first version. The next goal is clean up some quirks and maybe get some slop out of the sketch. As you’ll see in my sketch, MOST of my processing happens when the sensor activate. A few quirks, I’d like help with: - I run lcd.clear() every time I switch screens, and it isn’t a very quick method. Is there a faster way? - There is a boolean called ‘checked’ that I use to prevent the main logic from calculating more then once when the reed switch closes, is that the best method? - On the speed screen, the mph doesn’t update until the reed switch closes, so if you stop, it will sit with a false reading until you move. Someone it needs to display zero if you stop, more specifically after a set delay. - Is a switch/case the best method for handling my separate screens? - In the switch/case where I display the output, it seems unneeded to repeatedly reprint the labels for the values, can easily prevent that? - In the same area, when I display the values, I print out space characters to make sure the previous value is fully erased. That cant be proper. This is my first major sketch and I think its looking pretty good. Hopefully you guys will have some input on improving it. I tried to throw in some helpful comments, so the code is easier to parse. #include <LiquidCrystal.h> LiquidCrystal lcd(12, 11, 5, 4, 3, 2); //button reference int but1 = 1; int but2 = 0; int but3 = 10; int but4 = 6; int rotations = 0; //track wheel rotations for averaging int screen = 2; //value to differenciate screens in switch statement double curMils = 0; //current milliseconds double prevMils = 0; //previously stored milliseconds double mph = 0; double dist = 0; //values for tracking average speed double mphTotal = 0; double mphAvg = 0; boolean checked = false; //prevents multiple calcultions when the reed closes void setup() { //print splash screen lcd.begin(16, 2); lcd.print("Mason's v0.1"); lcd.setCursor(3,1); lcd.print("Bike Computer"); //set reed switch pin to input pinMode(8, INPUT); //set button pins to inputs pinMode(but1, INPUT); pinMode(but2, INPUT); pinMode(but3, INPUT); pinMode(but4, INPUT); } void loop() { //reset distance traveled or average speed if button 4 is pressed if (digitalRead(but3) == LOW) { switch(screen) { case 0: mphTotal = 0; rotations =0; break; case 1: dist = 0.00; break; } } //change screen value if button is pressed if (digitalRead(but1) == LOW) { lcd.clear(); screen = 0; } else if (digitalRead(but2) == LOW) { lcd.clear(); screen = 1; } //do calculations when the reed closes if (digitalRead(8) == LOW && !checked) { //keep track of rotations of wheel rotations++; //calculate current mph curMils = millis(); mph = (4873.591953413029) / (curMils - prevMils); prevMils = curMils; //calcult distance traveled dist = dist + 0.000430921; //calculate the average speed mphTotal = mphTotal + mph; mphAvg = mphTotal / rotations; //mark that calculations have occures for this rotation checked = true; //display output to lcd switch(screen) { case 0: lcd.setCursor(0,0); lcd.print("MPH: "); lcd.print(" "); lcd.setCursor(5,0); lcd.print(mph); lcd.setCursor(0,1); lcd.print("Avg: "); lcd.print(" "); lcd.setCursor(5,1); lcd.print(mphAvg); break; case 1: lcd.setCursor(0,0); lcd.print("Total Distance: "); lcd.setCursor(7,1); lcd.print(dist); lcd.print("mi"); break; default: lcd.print("Mason's v0.1"); lcd.setCursor(3,1); lcd.print("Bike Computer"); break; } } if (digitalRead(8) == HIGH && checked) { checked = false; } if ((millis() - prevMils) >= 1000) { mph = 0; //lcd.print(" "); //lcd.setCursor(5,0); //lcd.print(mph); } }
https://forum.arduino.cc/t/trying-to-make-my-sketch-more-efficient/177693
CC-MAIN-2022-21
refinedweb
639
62.38
Django versus Flask with Single File Applications2019-04-03 A lot of people pick Flask over Django because they believe it is simpler to start with. Indeed, the Flask front page includes an 8 line “hello world” application, while the Django default project has 172 lines in 5 files, and still doesn’t say “hello world”! (It does show you a welcome rocket and have a full admin interface though, both are pretty fun). It is also possible to make a single file “hello world” application in Django, although it’s probably something most Django developers haven’t seen done. It takes a bit more code than Flask, but it’s still quite understandable. Let’s take a look at the Flask and Django implementations and use them to compare the two frameworks. Application We’ll be using the simple “hello world” application from the Pallets page on Flask (plus a security fix). It has one page which gets a name from the URL or the default “world”, and returns that with a “hello” message. For example: In Flask Here is the code, 10 lines long, tested on Flask 1.0.2 and Python 3.7.2: (I added html.escape to the Flask example, to fix a security problem.) import html from flask import Flask, request app = Flask(__name__) @app.route('/') def hello(): name = request.args.get("name", "World") return f'Hello, {html.escape(name)}!' We run it with: $ FLASK_APP=app.py FLASK_ENV=development flask run Here’s what’s happening: - An application object is created with the name equal to the module’s import name, the special variable __name__. - The decorator @app.route('/')is applied to the function hello(). This means that when the URL /is visited, that function will be run to generate a response. - The hello()function does two things. First it gets the value of the nameparameter from the URL arguments, or the default value “World”. Then it returns a string which contains that value, which Flask turns into an HTTP response. Not too much to understand! In Django This is a bit longer at 31 lines, but stay with me, all will be explained! Here is the code, tested on Django 2.1.7 and Python 3.7.2: import html import os import sys from django.conf import settings from django.core.wsgi import get_wsgi_application from django.http import Http ) def index(request): name = request.GET.get("name", "World") return HttpResponse(f"Hello, {html.escape(name)}!") urlpatterns = [ path("", index), ] app = get_wsgi_application() if __name__ == "__main__": from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) We run this with: $ DEBUG=1 python app.py runserver Here’s what’s happening: - We configure Django’s settings. Normally Django’s settings get defined in a separate file, but here we’re using settings.configure()to set them directly (which has a small caveat). - We set DEBUGto be Truewhen the DEBUGenvironment variable is set to "1". This is not strictly necessary but it’s very useful to switch on debug mode when developing. - We set ALLOWED_HOSTSto accept any host in URL’s. This lazily disables Django’s Host header validation, a security feature which protects against types of attack. In a valuable application we’d set this correctly to contain only the application’s domain name. - We set ROOT_URLCONFso the current module (again the __name__magic variable) will be used by Django for the URL configuration. This is normally a separate file too. Django imports the named module and accesses its urlpatternsattribute to get the URL mapping in the application, which is why we have it later in this file. - We set SECRET_KEYto a random string. As the comment says, it’s needed by Django but here we aren’t using any of the features that depend on it. Currently the random key changes every time the application starts, which would cause some security features to not work properly, such as logins being invalidated. Normally we would be using the security features, so we’d set this to a single random string that we’d store securely, not in the source code, but for example, in an environment variable. - We create a view function index()that implements the functionality to say “hello” to the name in the URL. This is passed an instance of Django’s HttpRequestclass, from which the URL argument “name” is retrieved, and returns an HttpResponsewith the content we want. - We define the urlpatternslist which maps the empty path, equivalent to /, to the indexfunction. - We create the WSGI application object. Django can create this for us in development mode but not for deployment in production. - We add the Python idiom if __name__ == "__main__"to call Django’s commandline entrypoint to run when the file is executed directly. This allows us to run python app.py runserver, as well as python app.py --helpand any of Django’s other commands. There’s a bit more code doing a few more things, but it’s still less than 10 steps. Comparison This is a limited example, so it doesn’t show every way the frameworks differ. However I do think it shows some of the most important ways, especially as we consider ways to extend the application into doing something a bit more useful. Here are seven different parts of both frameworks that I’d like to take a closer look at: 1. Application Objects In Flask, we create an application object as our first step, and later attach our route to it. The application is the top-level “thing” we configure, and also the WSGI application that we can use in production. If we were extending the application, we’d also attach other things like error handlers or settings to this object. This also lets us have more than one application in the same Python process, if we ever need to. Django, by contrast, only allows us to have a single application per process, and it’s implicitly created for us. The top-level “thing” we are configuring is Django itself, which we do when we configure django.conf.settings to let Django discover the other parts of the application such as the URL’s. The WSGI application object comes across as a bit of an afterthought. Django can automatically create one for us in development, and it’s only needed for production so that common WSGI servers can run the application. Overall here I’d say the Flask method of explicitly creating your application object and attaching things to it is clearer. That said, once you’ve created an application in one module, in some situations Python makes it hard to import it in another file, and Flask has a “workaround” global object flask.current_app to fix this. Also while Flask allows multiple applications in a single process, I’ve not seen the need (except it could make certain test situations easier). 2. View Functions This is the key code you write web applications, taking a request and returning a response. Everything a web framework does for you is, simply, either wrapping around your views or providing some kind of help for you to write those views quicker. Our example views are short and similar, but differ in two key ways. First, in Flask we import and use flask.request to get the headers, while in Django we are directly passed the request. Flask uses some magic to maintain this global variable flask.request (a proxy object), which changes each time the function is run (and in each thread). The first time you read the code this might surprise you, as normally in Python imported objects don’t change. Django uses normal Python semantics, which reduces the confusion for beginners. Global variables have been considered harmful by many programmers for a long time. While they are convenient, they’re an easy place for bugs to lurk as any part of the program could change them at any point. Second, in Flask we return a string, while in Django we return an HttpResponse. Flask actually supports multiple return types, including its own response class, but Django always requires you to explicitly return a response. This is a philosophical difference between the two. Django tends to follow Python’s TOOWTDI slogan (There’s Only One Way To Do It) (pronounced “toody”), while Flask often provides several extra shortcuts. Django does provide some shortcuts but you have to explicitly import and use them. 3. URL Configuration Flask lets us set up URL’s with the route() decorator, which also takes other arguments such as restricting which HTTP methods the route accepts. Again though, Flask has more than one way to do it, with three ways to add URL’s, the last being a URL map similar to Django’s URL conf. Django only supports a URL conf, which can add URL’s from other URL confs with include(). This made us write a few more lines in our single file application, but it is a single way of doing URL’s and a technique that can scale to big sites. Our single application uses the most basic URL, so we didn’t get to see URL syntax, but I want to briefly point out both support a syntax like /users/<int:user_id>/profile/. Originally Django supported only regular expression based URL’s, but this can get really complicated and make beginners run for the hills. Django version 2.0 copied Flask’s simpler URL syntax as a new, default option, so now they both work similarly. 4. Development Mode Both frameworks support a development mode, to use when developing the application locally. Each provides a web server, automatic reloading the code changes, and debugging information in the browser when things break. Flask even includes an in-browser debugger which can be added to a Django project as well. Flask asks us to set FLASK_ENV=development when we run our application with flask run in order to activate its development mode. Another option is to set app.debug directly. Django only checks the settings DEBUG flag to activate development mode, and it’s up to us how that is set. Some projects use separate settings files for development and production, while others use in-file mechanisms, like checking an environment variable. I prefer the latter, and that’s what we’ve done in our single file example. This follows the well-known 12 factor methodology. Besides this, Django also needs some boilerplate code under if __name__ == "__main__" to support running the application. This boilerplate still exists in larger projects in a file called manage.py but it is generated for us when we run the startproject command. Flask avoids the boilerplate by having flask run always work. Going beyond basic development mode, it’s popular to extend Django’s debug mode with the django-debug-toolbar package. It displays several extra types of debug information and is well maintained by the community. There’s a similar package for Flask called flask-debugtoolbar but it seems to have fewer features and at time of writing hasn’t been updated in a year. 5. Security Both applications do some work to avoid HTML injection, by using html.escape to safely output the URL input from the user. This is pretty standard, and in larger applications we’d probably use a template system which would do this for us automatically (more later). Another security feature we saw is host validation. Django has it built-in by default and we have to configure it to work, but in this example we deliberately disabled it. Flask, as far as I know, has no such feature, so while we saved doing work to configure it, it may be less secure here (it depends on how the application is deployed). Another security feature which Django makes us think of up-front is adding a secret key. Flask also has this concept in app.secret_key. Both frameworks use their keys for cryptographic functions, like encrypting user sessions, it’s just that Django requires one to start. It’s just a rare case that our single file application doesn’t use it in any way, and while in theory Django could be changed to not require a key, it’s probably not worth it. Both frameworks also have security pages in their documentation: Django / Flask. We can see the philosophical differences again on these pages. Django follows Python’s “batteries included” philosophy, while Flask either refers to other libraries, such as Google’s Flask-Talisman, or gives you a code snippet and asks you to finish the implementation yourself. Django has a dedicated Security Team and security policies that detail such things as how to report security vulnerabilities without making them public. As far as I can tell, Flask has no equivalent. 6. More Batteries Both frameworks do include some “batteries” which can help you build your application faster, although Flask only provides a minimum. Django also tends to provide its extras as pluggable backends so you can swap them out for those from third party packages, for example using an unofficial database backend. If we had larger pages in our example, we’d probably want to use a templating system to keep the content in multiple files, and manage inserting the data without doing HTML escaping each time. Both frameworks provide template system integrations. Django has a pluggable backend system which includes support for its own Django Template Language, while Flask only supports Jinja2. Jinja2 is essentially Django Template Language rebuilt for performance by Armin Ronacher, but with enough differences that it’s not fully compatible. However Django also provides a backend for using Jinja2, so you can use it there. Nearly every web application needs some kind of data storage. Django includes a very fully featured database layer, including migrations. Flask doesn’t include anything but it’s very common to use it with SQLAlchemy + Alembic. Besides these examples, Django includes many extra tools beyond Flask, for things like translations, site maps, and geographic data (many are in its contrib packages). 7. Ecosystem Both frameworks have ecosystems providing extra integrated tools in third party packages. Django has the site djangopackages which lists and compares several thousand packages. The Flask website has a moderated list of just 68 packages. Overall it seems there are many more Django-specific packages, although this is in keeping with Flask’s minimalist/DIY philosophy. Conclusion Overall, I prefer Django. This is probably not so very surprising, given I’m a core contributor, but I hope this has shown I have some reasoning behind this viewpoint! I must admit though I’m not a Flask expert, I’ve only worked on a few projects using it for short-term engagements, and I learned a lot about it while composing this blog post. If I’ve misrepresented anything please let me know. According to the Python Developers Survey 2018, Flask and Django have about even usage at the moment, at 47% and 45% respectively. I think part of the preference for Flask is that it’s easy to start with just a single file, so I hope my example shows this isn’t necessarily the case. Using Django shouldn’t be hard for small applications, though there’s probably some work we can do to make it easier. Enjoy creating web applications whichever framework you use, —Adam Thanks to Jazeps Basko, Markus Holtermann, and Tom Grainger for reviewing this post. - Where to Learn Django in 2019 - How to Score A+ for Security Headers on Your Django Website Tags: django
https://adamj.eu/tech/2019/04/03/django-versus-flask-with-single-file-applications/
CC-MAIN-2021-04
refinedweb
2,595
55.44
What does it means ? if (vw_get_message(buf, &buflen)) for (i = 0; i < buflen; i++) { Serial.print((char)buf[i]); Serial.print(" "); } QuoteWhat does it means ?In a nutshell, see if there's any data to read, read it Code: [Select] if (vw_get_message(buf, &buflen)), and then print it Code: [Select]for (i = 0; i < buflen; i++) { Serial.print((char)buf[i]); Serial.print(" "); }. uint8_t vw_have_message ( ) Returns: true if a message is available to read it means the code sometimes will fail to execute ? Am I correct ? So from this can I say uint8_t is like a data type ? Quoteit means the code sometimes will fail to execute ? Am I correct ?During development, code will always sometimes fail to execute as we expect it to.But, no, you are not correct. "Blocking" means the code will loop waiting until a message is received. This may or may not be a problem for you.The great thing about the Arduino is that you can try things, and if they don't work, try something different.The frequency of your questions leads me to suspect you're not trying the things you're asking about. #include <VirtualWire.h>#undef int#undef abs#undef double#undef float#undef roundvoid setup(){ Serial.begin(9600); // Debugging only Serial.println("setup"); // Initialise the IO and ISR vw_set_ptt_inverted(true); // Required for DR3100 vw_setup(2000); // Bits per sec vw_rx_start(); // Start the receiver PLL running pinMode(13, OUTPUT);}void loop(){ uint8_t count; if(count==true){ count = false;} count = vw_wait_rx_max(2000);// Non-blocking if (true) { digitalWrite(13, HIGH); // Flash a light to show received good message delay(500);// Message with a good checksum received, dump it. digitalWrite(13, LOW); delay(500); } else if(false) { digitalWrite(13, HIGH); delay(100); digitalWrite(13,LOW); delay(100); } } void loop(){ uint8_t count; if(count==true) if (true) if(false) Please enter a valid email to subscribe We need to confirm your email address. To complete the subscription, please click the link in the Thank you for subscribing! Arduino via Egeo 16 Torino, 10131 Italy
http://forum.arduino.cc/index.php?topic=144027.msg1082903
CC-MAIN-2016-44
refinedweb
339
66.03
Odoo Help Odoo is the world's easiest all-in-one management software. It includes hundreds of business apps: CRM | e-Commerce | Accounting | Inventory | PoS | Project management | MRP | etc. How to inherit class partner_balance to change functions? Hi, I'm trying to inherit class partner_balance(report_sxw.rml_parse, common_report_header) from the file addons/account/account_partner_balance.py, but it isn't like the other inherits of osv.osv ... I want to change this function def set_context(self, objects, data, ids, report_type=None) and `this def lines(self).... Do you know how can I change those functions ? Thanks About This Community Odoo Training Center Access to our E-learning platform and experience all Odoo Apps through learning videos, exercises and Quizz.Test it now
https://www.odoo.com/forum/help-1/question/how-to-inherit-class-partner-balance-to-change-functions-50713
CC-MAIN-2018-17
refinedweb
121
52.46