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 |
|---|---|---|---|---|---|
Understanding Struts Action Class
Understanding Struts Action Class
In this lesson I will show you how to use Struts Action... the mappings in the struts-config.xml. Our Action Class returns
Struts
;Basically in Struts we have only Two types of Action classes.
1.BaseActions... class indirectly.These action classes are available...Struts why in Struts ActionServlet made as a singleton what
no action mapped for action - Struts
no action mapped for action Hi, I am new to struts. I followed...: There is no Action mapped for action name HelloW
*;
<pre>
Struts Action Chaining
Struts Action Chaining Struts Action Chaining
Struts 2 action-validation.xml not loading
Struts 2 action-validation.xml not loading Hi All,
I am getting...-validation.xml is package/src/class name/action-validation.xml
Could you please let me... error
SERVER : Caught exception while loading file package/action-validation.xml
The password forgot Action is invoked... password action requires user name and passwords same as you had entered
during it is thread safe? if no, how to make it thread safe? Please give me with good...://
for later use in in any other jsp or servlet(action class) until session exist... in struts?
please it,s urgent........... session tracking? you mean session management?
we can maintain using class HttpSession.
the code follows
Action Configuration - Struts
Action Configuration I need a code for struts action configuration in XML
DispatchAction class? - Struts
/understandingstruts_action_class.shtml class? HI, Which is best and why either action class or dispatch class. like that Actionform or Dynactionform . I know usage
Struts
STRUTS ACTION - AGGREGATING ACTIONS IN STRUTS
STRUTS ACTION - AGGREGATING ACTIONS IN STRUTS... of Action classes for your project. The latest version of struts provides classes... action. In this article we will see how to achieve this. Struts provides four 2 Redirect Action
Struts 2 Redirect Action
In this section, you will get familiar with struts 2 Redirect
action...;/html>
Step 3 : Create an Action class.
Login.java
package
Struts Action Classes
Struts Action Classes 1) Is necessary to create an ActionForm to LookupDispatchAction.
If not the program will not executed.
2) What is the beauty of Mapping Dispatch Action
java - Struts
java what is the default Action class in struts
Setter methods of form bean class in Struts applications who calls the setter methods of form bean class in struts applications
struts 2.0 - Struts
struts 2.0 I have written print statement in action class. It is printing data 2 times. Why it is happening
how to forward select query result to jsp page using struts action class
how to forward select query result to jsp page using struts action class how to forward select query result to jsp page using struts action class struts DAO - Struts
java struts DAO hai friends i have some doubt regarding the how to connect strutsDAO and action dispatch class please provide some example to explain this connectivity.
THANKS IN ADVANCE
Struts-It
Action class
other Struts-related classes like configuration... to create all Struts artifacts
like Form-bean, Action, Exception, etc... Struts-It
Struts Forward Action Example
an Action Class
Developing the Action Mapping in the struts-config.xml... Struts Forward Action Example
...-mapping. Note that we do not create any action
class,Please check easy to follow example at dispatchaction vs lookupdispatchaction What is struts
struts - Struts
struts when the action servlet is invoked in struts? Hi Friend,
Please visit the following link:
Thanks error - Struts
*;
import javax.servlet.http.*;
public class loginaction extends Action{
public...java struts error
my jsp page is
post the problem...*;
import javax.servlet.http.*;
public class loginform extends ActionForm{
private <html:select> - Struts
, allowing Struts to figure out the form class from the
struts-config.xml file... with the action.
For example, the class attribute might be specified...struts i am new to struts.when i execute the following code i am
Action in Struts 2 Framework
. Actions are mostly associated with a HTTP request of User.
The action class..., and select the view result page that should send back to the user
action class... { return "success"; }
}
action class does not extend another class and nor - can we write class A extend String?
No, we can not extend the String
*) Action class
public class MyAction extends...java how can i get dynavalidation in my applications using struts... :
*)The form beans of DynaValidatorForm are created by Struts and you configure
Struts Tutorial
the
information to them.
Struts Controller Component : In Controller, Action class...In this section we will discuss about Struts.
This tutorial will contain the various aspects of Struts such as What is Struts, features of str
Need acode for struts implementation - Struts
Need acode for struts implementation I want a code to generate dynamic table with a text field and a drop down list and to retrieve that data in the action class and store in the data base
configuration - Struts
.
Action class:
An Action class in the struts application extends Struts...://... class,ActionForm,Model in struts framework.
What we will write in each
Unable to understand Struts - Struts
= "success";
/**
* This is the action called from the Struts...
*/
public class AddBookStruts extends org.apache.struts.action.Action...
*/
public class AddBookServlet extends HttpServlet
About Struts processPreprocess method - Struts
that the request need not travel to Action class to find out that the user...About Struts processPreprocess method Hi java folks,
Help me... will abort request processing.
For more information on struts visit
Struts - Struts
Struts Hi All,
Can we have more than one struts-config.xml... in Advance.. Yes we can have more than one struts config files..
Here we use SwitchAction. So better study to use switchaction class
Servlet action is currently unavailable - Struts
Servlet action is currently unavailable
Hi,
i am getting the below error when i run the project so please anyone can help me..
HTTP Status 503 - Servlet action is currently unavailable
Java + struts - Struts
java.sql.ResultSet;
public class ImportingAction extends Action {
public ActionForward... org.apache.struts.upload.FormFile;
public class ImportFileBean extends ActionForm
struts 2 testing
struts 2 testing can i get an example for struts 2 action class unit test
java - Struts
zylog.web.struts.actionform.LoginForm;
public class LoginAction extends Action... friend,
Check your code having error :
struts-config.xml
In Action...:
Submit
struts
struts - Struts
struts how to solve actionservlet is not found error in dispatch action
Struts - Struts
Struts is it correct to pass the form object as arg from action to service
Struts - Struts
in struts 1.1
What changes should I make for this?also write struts-config.xml... javax.servlet.http.*;
import java.io.*;
import java.sql.*;
public class loginservlet...,
For read more information,Tutorials and Examples on Struts visit to :
http
Implementing Actions in Struts 2
the many Action classes and
interface, if you want to make an action class for you... the following Action class by implementing Action
interface.
TestAction.java...;roseindia" extends="struts-default">
<action name="
struts - Struts
struts how to handle multiple submit buttons in a single jsp page of a struts application Hi friend,
Code to help in solving... are different.So,
it can be handle different submit button :
class MyAction extends
Struts validation not work properly - Struts
to advise, i face it for almost a week now...
this is my action class...
========================================
public class ExampleAction extends Action...Struts validation not work properly hi...
i have a problem
Time Picker in struts 2 - Struts
Time Picker in struts 2 How to create Time Picker in Struts 2 ? ...;</ul>2. struts.xml (Add the following code)<action name=".../requiredFieldValidatorError.jsp</result> </action> <action name="
java - Struts
class LoginAction extends Action
{
public ActionForward execute...
config
/WEB-INF/struts-config.xml
1
action
*.do
Thanks...!
struts-config
Advertisements
If you enjoyed this post then why not add us on Google+? Add us to your Circles | http://www.roseindia.net/tutorialhelp/comment/18021 | CC-MAIN-2015-18 | refinedweb | 1,304 | 58.08 |
CoxeterGroup / coxeter3 trouble
I'm having some trouble using the optional coxeter3 package - can somebody see what I'm doing wrong?
I just built a clean version of sage 8.0, freshly cloned from github, on my ubuntu machine. Then I ran
sage -i coxeter3
as one does; it installed with no errors. It seems to have worked: installed_packages(), for instance, has the line
'coxeter3': '1.1',
and there's a sage.libs.coxeter3 module in the namespace. But, for instance, when I try to use coxeter3 as per the instructions on the Coxeter Groups page in the sage documentation (can't provide a link as karma is too low), I get a RuntimeError:
sage: W = CoxeterGroup(["A",2], implementation='coxeter3') --------------------------------------------------------------------------- RuntimeError Traceback (most recent call last) <ipython-input-12-4f0efd988562> in <module>() ----> 1 W = CoxeterGroup(["A",Integer(2)], implementation='coxeter3') /home/bjy/build/sage/local/lib/python2.7/site-packages/sage/combinat/root_system/coxeter_group.pyc in CoxeterGroup(data, implementation, base_ring, index_set) 142 from sage.libs.coxeter3.coxeter_group import CoxeterGroup 143 except ImportError: --> 144 raise RuntimeError("coxeter3 must be installed") 145 else: 146 return CoxeterGroup(cartan_type) RuntimeError: coxeter3 must be installed
Any help is appreciated! I don't know enough even to start troubleshooting, though I tried the usual kinds of google searches and such.
===============
Updates: 'coxeter3' ISN'T in dir(sage.libs) for me, so it looks like the package didn't "fully install", or something. It's entirely possible that I didn't install the package correctly; I still haven't managed to find a clear set of intallation instructions. I did try doing "make build" after 'sage -i coxeter3" as per FrédéricC's comment; my computer churned away for a while, but ultimately it didn't change anything.
Maybe I can more precisely target my question. Where can I find a clear set of instructions for how to install the optional Coxeter3 spkg in a current sage build?
================
Update 2: So, apparently the ting to do is to say
sage -f Coxeter3 sage -b
whereupon everything works - except that dir(sage.libs) still has no mention of Coxeter3, so I'm not sure what's up with that.
For those following along at home: as far as I can see, the first command causes Coxeter3 to be forcefully reinstalled, regardless of what I did beforehand to mess things up; presumably the "-b" in the second command is "build" in some capacity.
Thanks folks!
Is the relevant package shown using
dir( sage.libs )?
I do not have coxeter3 installed... However, pari should be always in the list, let me use it instead. In my case, to test if pari is there i would try:
First of all, is
coxeter3(instead of pari) in there?
(Next we can check which would be an other reason for an
ImportError...)
aha! you are right, coxeter3 is NOT in dir(sage.libs)! I've done something wrong in the installation process, then. Thank you! Do you know whether there is a clear set of instructions, somewhere, for how to install an optional spkg? I had a lot of difficulty looking this up in the manual.
Did you do "make build" after 'sage -i coxeter3" ?
Installation works for me. Try
actually, yeah, that did work! That said, there's STILL no mention of Coxeter3 in dir(sage.libs), but suddenly everything works. I did not know the incantation "sage -b". Thanks so much! | https://ask.sagemath.org/question/39389/coxetergroup-coxeter3-trouble/ | CC-MAIN-2018-17 | refinedweb | 570 | 65.52 |
Logins and authentication
Now you have a taxonomy browser that anyone can edit. Is that what you really want? Is it okay for someone to add "puddy cat" to the Felis silvestris (tax id 9683) entry? Or add "buy Viagr* at example.com" to the entry for humans? The answer could be yes if the application is only accesible by a few people. But if you expect it will be popular in the future then you need to support security early in the development process.
TurboGears comes with a simple, flexible identity authentication system. You don't have to use it if you don't want to - it's just a lot easier. Unfortunately it isn't quite as simple as saying "enable user authentication" and everything works. It needs a data model in the database and a few other configuration changes to work.
The easiest way to get started with it is to redo the TurboGears quickstart. I had hoped I could write over my existing project and use subversion to figure out my changes but that didn't work. Here's what happened when I tried it:
[~/nbn/taxonomy] % tg-admin quickstart TaxonomyServer Enter package name [taxonomyserver]: Do you need Identity (usernames/passwords) in this project? [no] yes A directory called 'TaxonomyServer' already exists. Exiting.Instead I renamed the existing project directory to "TaxonomyServer.old", did the new quickstart, and renamed the directories a bit more:
[~/nbn/taxonomy] % mv TaxonomyServer TaxonomyServer.old [~/nbn/taxonomy] % tg-admin quickstart TaxonomyServer Enter package name [taxonomyserver]: Do you need Identity (usernames/passwords) in this project? [no] yes ... lots of output removed ... [~/nbn/taxonomy] % mv TaxonomyServer TaxonomyServer.tmp [~/nbn/taxonomy] % mv TaxonomyServer.old/ TaxonomyServer
NOTE! You do not need to do this. You can start a brand new project and copy in only those parts from the old project that you want. I'm showing you all this so you have some idea of how to do this sort of thing.
I used 'diff' to figure out the differences between the two directories. To minimize the number of differences I removed some Python byte-compiled files (the .pyc files) and my editor's backup files
[~/nbn/taxonomy] % rm TaxonomyServer/*.pyc [~/nbn/taxonomy] % rm TaxonomyServer/*/*.pyc [~/nbn/taxonomy] % rm TaxonomyServer/*~ [~/nbn/taxonomy] % rm TaxonomyServer/*/*~ [~/nbn/taxonomy] % rm TaxonomyServer/*/*/*~ [~/nbn/taxonomy] % diff -r TaxonomyServer.tmp TaxonomyServer | lessIt changed two files that I had never modified from the original quickstart so I copied the new files over into the existing project
[~/nbn/taxonomy] % cp TaxonomyServer.tmp/taxonomyserver/config/app.cfg TaxonomyServer/taxonomyserver/config/app.cfg [~/nbn/taxonomy] % cp TaxonomyServer.tmp/taxonomyserver/json.py TaxonomyServer/taxonomyserver/json.pyYou should read the 'app.cfg' file to see what it does.
It did not create any new files so the remaining differences are changes to dev.cfg, controllers.py and model.py.
There's only one change to 'dev.cfg' which is to revert my change to the database filename. I'll keep my edited file.
In controllers.py it did a "from turbogears import identity" and added two new functions, "login" and "logout". I'll copy them over into my project's controller.py. NOTE: your login and logout interface can look different than this.
The biggest change was to model.py to add the data model for identity and visit tracking. I copied the five new classes to the bottom of my model.py file. I also added
from datetime import datetime from turbogears import identityat the top of model.py
With that I restarted the server and got it working again. I reloaded one of my taxonomy browser pages and noticed the "Login" button on the upper right. That takes me to a fancy login window, but of course I have no account on the machine.
The User/Group data model
The TurboGears account configuration information is stored in tables in your database. If they don't already exist then TG will add them for you.
The model is pretty simple. Permissions are given to groups and not to individual people. People can be in multiple groups, because people may have multiple roles in a project. Using groups simplifies administration because usally there are many fewer distinct roles on a project than there are people. For example, you can have groups like "curator" and "administrator", each with special privledges. Some people may be both curators and administrators while others may only have one, or no roles to play.
TurboGears also allows anonymous users.
I'm going to create a group named "curator" and add myself as a user in the group. If you can get the TurboGears toolbox working this would be very easy in CatWalk because it's all GUI driven. Instead I'll do it the old-fashioned way: type it.
>>> from model import Group, User >>> from model import hub >>> g = Group(group_name="curators", display_name="Taxonomy Curators") >>> g <Group 1 group_name=u'curators' display_name=u'Taxonomy Curators' created='datetime.datetime...)'> >>> u = User(user_name="dalke", display_name="Andrew Dalke", ... password="12345", email_address="dalke@dalkescientific.com") 2006-07-24 00:02:59,107 turbogears.identity.soprovider INFO Succesfully loaded "taxonomyserver.model.User" 2006-07-24 00:02:59,109 turbogears.identity.soprovider INFO Succesfully loaded "taxonomyserver.model.Group" 2006-07-24 00:02:59,111 turbogears.identity.soprovider INFO Succesfully loaded "taxonomyserver.model.Permission" 2006-07-24 00:02:59,114 turbogears.identity.soprovider INFO Succesfully loaded "turbogears.identity.soprovider.TG_VisitIdentity" 2006-07-24 00:02:59,116 turbogears.identity.soprovider INFO Identity provider not enabled, and no encryption algorithm specified in config. Setting password as plaintext. >>> u <User 1 user_name=u'dalke' email_address="u'dalke@dalkescie...'" display_name=u'Andrew Dalke' password=u'12345' created='datetime.datetime...)'> >>> g.addUser(u) >>> hub.commit()
Now I'll see if it works. Head back to the login window ... Cool beans! I'm logged in and the upper right-hand corner says "Welcome Andrew Dalke. Logout".
Where does that bit of text come from? Look in the master.kid template for the answer. Again, your interface doesn't need to look like this. You could, for example, ask for the username and password on the corner of every page and not use a special login page.
Because you can change the user/group table just like changing anything else in the database it's straight-forward to add a registration page, password administration page, etc. in TurboGears.
Restricting pages
The authentication system uses the decorator @identity.require to annotate functions and restrict them to a given group, a set of groups, a host name, and a few other possibilities. I'll modify the controller.py file to say that 'edit_alises' and 'update_aliases' can only be accessed by members of the 'curator' group.
@expose(template="taxonomyserver.templates.edit") @identity.require(identity.in_group("curators")) def edit_aliases(self, tax_id): return dict(taxon=Taxonomy.get(tax_id)) @expose() @identity.require(identity.in_group("curators")) def update_aliases(self, tax_id, alias=[]): # one input alias -> a string # multiple input aliases -> a list of strings if isinstance(alias, basestring): aliases = [alias] else: aliases = alias ....It worked (after I fixed a couple of mistakes in what I did). That is, I can go to those pages without problems when I'm logged in as "dalke" but cannot when I'm logged out.
I'm not quite done yet. If I'm not logged in, or I'm not a member of the "curators" group then I don't want to see the "edit aliases" link on the detail page. I'll change the template for that.
The current identity information is always accessible via the turbogears.identity.current object. This works even on multi-threaded systems by using thread-local variables. Don't worry if you don't know what that means. To get the groups for the logged-in person use "current.groups" and for the actual user record use "current.user". (For example, the person's name is "current.user.display_name".)
This is a Python object so I can pass it in through the template's dictionary or have the template get the object itself. The documentation recommends the latter.
A template can embed Python code by using the special <? syntax ?>. Put the following somewhere near the top of the details.kid template. I put it just after the <body> tag:
<?python from turbogears import identity ?>Now the template can use 'curators' in identity.current.groups as the test to see if the current user is allowed to see the edit page. Here's the latest code to show the list of aliases and only show curators the link to 'edit_aliases'. I'm showing the first part of the HTML body so you can see things in context:
<body> <?python from turbogears import identity ?> <a href="/">Start a new search</a> <h2>${taxon.scientific_name}</h2> <P> Taxon identifier: ${taxon.id}<br /> Genetic Code: ${taxon.genetic_code.name}<br /> Aliases: ${", ".join([alias.alias for alias in taxon.aliases])} <span py: [<a href="/edit_aliases?tax_id=${taxon.id}">edit aliases</a>] </span>${identity.current.user.display_name}<br />
Try it out. Give it a whirl.
Visit tracking
When you enable logins you also enable visit tracking. To turn it off or configure it edit the file config/app.cfg under your application directory. (That's the one with model.py in it.) Every person visiting your server gets a cookie. That's a bit of text passed back and forth between the browser and the server. If the server gets an old cookie back in less than 20 minutes then it assumes the user is still active and it returns an updated cookie.
TG stores the tracking information in the database so you can see who logged in and roughly for how long. Here's one example:
sqlite> select * from tg_visit; 1|1c4db003925d9bdaa7f5c094d1799b6bd4be85ef|2006-07-23 23:45:50|2006-07-24 00:41:19 sqlite> select * from tg_visit_identity; 1|1c4db003925d9bdaa7f5c094d1799b6bd4be85ef|1The first table says that a user first visited at 11:45pm and was still active at 12:21am (the second timestamp is the expiration, which is configured to be 20 minutes after the last visit). The second table says the vistor was user 1 (that's me!).
Permissions
One last thing. TurboGears' security model is a bit more flexible than what I described. Users are members of groups and groups have permissions, which are strings. Often these are things like "read", "write", and "edit" which break things up by function. Why? Consider a curational database with quarterly releases. When doing the release you may want to shut off write access to the database to keep it stable. It's easier to remove "edit" permission from the "curators" group than it is to move everyone to a different group.
| http://www.dalkescientific.com/writings/NBN/authentication.html | CC-MAIN-2018-34 | refinedweb | 1,785 | 51.85 |
This paper is meant for the beginner to use as a reference in order to understand ADO.NET.
Sometimes the student of the .NET Framework will find it difficult to understand direct database access using requests to the appropriate SQL commands. Certain individuals might not have the experience in languages like T-SQL to query a database and therefore go on to learn about ADO.NET. ADO.NET is actually comprised of the classes contained in the System.Data namespace of the FCL. Based on the original ADO (ActiveX Data Objects), ADO.NET adds, amongst other things, the DataSet. The DataSet is a collection of all of the relevant database objects: tables, columns, relations, constraints, stored procedures, etc. These concepts will be explained shortly. This paper will focus on building a C# Windows Forms application that resides on top of the actual permanent database on the hard disk to avoid having the user access a database directly. The logic behind building an application that accesses a database is to simplify the database access process, avoid possible database access restrictions, and complex queries. This, of course, assumes that we are dealing with a monolithic application that resides on the same machine as the database access code. The utility will be a Windows Forms application that accesses a Microsoft Access database file through the System.Data.OleDb .NET data provider. In fact, there are four managed .NET data providers:
System.Data
DataSet
DataSet
System.Data.OleDb
System.Data.SqlClient
System.Data.Oledb
System.Data.Odbc
System.Data.Oracle
These four .NET managed providers provide five main objects:
Connections
Commands
DataReaders
DataSets
DataAdapters
Rather than access the database directly, the Windows Form will load and access the data. We begin by building a simple C# Windows Forms application, and calling it, say, "UserData".
UserData
Having built the form, we now want to choose the "Data" choice on the toolbar to click "Add New Data Source". This invokes the Data Source Configuration Wizard:
Then we click next to choose the data store (database), which is a Microsoft Access database file. Notice that the .NET Framework’s managed data provider is System.Data.OleDb. This is because we have not chosen to use the SQL Server nor any SQL database file. We are choosing an Access file to keep things simple:
Typical Microsoft Office files, such as Word, Excel, or Access are based on ActiveX technology, which in turn is based on the Component Object Model. COM is a set of programming standards based on around nine technologies that comprise OLE 2, or Object Embedding and Linking 2.0. The .NET Framework Data Provider is therefore for OLE DB. After we click OK, we see a dialog box that asks us to browse for that Access file. This file is included in the downloadable zip file and the contents should be extracted to the working directory where you keep project files. After we test the connection to the database file and succeed, we then save the connection string:
After we test the connection and it succeeds, we save the connection string:
At this point, we should stop and note the steps that we have taken. We first built a Windows Form. Anyone familiar with Windows Forms or even Web Forms knows that the toolbox has a rich set of controls that can be dragged and dropped onto the Forms' surface in order to set their properties. In this application, we are databinding data to user interface controls. We then choose to locate a new data source, a Microsoft Access file. Next we built a connection string in order to connect to the database. But our goal is to build an application that accesses the database. This means the UI must have controls that function as data access components, for we want to databind data to the UI controls. Databinding is a feature of the user interface controls that allow them to retrieve data from a data source, such as a database. This brings us to one of the most important features of AD0.NET: the data access components. Notice the dialog box shown after we click "Next":
Remember that our Windows Form application was meant to access the database and in order to accomplish this, our goal was to DataBind data onto user interface controls. That data binding means data referenced by your DataBindingSource and binding it to a control. In other words, the control will receive data from your data access components, and the data will be automatically displayed in the control for the user to see and manipulate.
DataBind
DataBindingSource
Notice that we chose two tables, Departments and Instructors. These chosen database objects will constitute the DataSet. The difference between the DataSet and permanent database on hard disk in the DataSet is a cached or in-memory view of the database. When we have to make changes to the database, we do it to the in-memory copy of the database. That is, if we delete, modify, update, or add a record (row), these changes will copy onto the permanent database. But how can tabular data be temporarily stored in memory in the form of tables? Well, in addition to storing data in tables, the DataSet component is similar to a small engine that can store data in memory and be rich in metadata. This includes things like table and column names, data types, and the information needed to undo changes to data. All of the data is represented in memory in XML. A DataSet can be saved to an XML file and then loaded back into memory. It can be passed in XML format over networks including the Internet.
Departments
Instructors
To reiterate, ADO.NET manages the connection to the database, in this case, a Microsoft Access file. Establishing a connection to the data source involves the process of location of that database, either by file system or network protocol. A DataSet is considered a disconnected recordset as it has no knowledge of the data store. Since we are building an application that has a user interface, we can keep the connected open to the DataSet while the application is running. That is, once the connection is established, the Windows Forms application can begin speaking with the database. As part of the managed platform of the .NET Framework, ADO.NET manages both the requests for the data and the responses from the data source. A DataAdapter object connects to the database and fills the DataSet object. Then it connects back to the database to update the database based on the operations performed while the DataSet held the data. While the DataSet has no knowledge of the data source, the managed provider has detailed and specific information. Its role is to connect, fill and persist the DataSet to and from the database. Persist means keeping the object's state persistent because it is accessed regularly. Persistence is accomplished through object serialization.
DataAdapter
When we click finish, we see that the Students.mdb is the permanent database file. If we double-click the XML schema files, we get a designer view of the files, and also see the one to one correlation between the objects in the Database explorer and the XSD files:
Notice the XSD files have a TableAdapter component. This is the DataAdapter component stated about earlier. The TableAdapter contains the query that is used to select data from your data source as well as connection information for connecting to your database. Being a DataAdapter object, it is sort of at the center of the approach to provide a bridge to retrieve and save data between its DataSet and its source data store. Normally it accomplishes this by means of requests to the appropriate SQL commands made against the database. Notice the methods named immediately below the TableAdapter.
TableAdapter
TableAdapter
The BindingSource component acts like a bridge between your DataSet and your data-bound controls. The BindingNavigator provides a standard UI component that allows you to navigate through the rows that are in your data source. This data access component is bound to the BindingSource component much as the DataGridView component is. Arrows on both the Instructor and the Department components in the Database Explorer view should be clicked to give you the DataGrid view choice. After choosing that for both of them, you can drag and drop them onto the form: both tables will bind to the UI because they have relation. How? By choosing "Add Relation" from the Data selection on the toolbar. The relational dialog box is shown below:
BindingSource
BindingNavigator
DataGridView
Instructor
Department
DataG. | http://www.codeproject.com/Articles/25796/ADO-NET?fid=1281400&df=90&mpp=10&sort=Position&spc=None&tid=4028345 | CC-MAIN-2015-48 | refinedweb | 1,436 | 63.39 |
Embedded Resource Files
Introduction
ASP.NET Boilerplate provides an easy way of using embedded Razor views (.cshtml files) and other resources (css, js, img... files) in your web application. You can use this feature to create plugins/modules that contains UI functionality.
Create Embedded Files
First, we should create a file and mark it as embedded resource. Any assembly can contain embedded resource files. The progress changes based on your project format.
xproj/project.json Format
Assume that we have a project, named EmbeddedPlugIn, as shown below:
To make all files embedded resource under Views folder, we can add such a configuration to project.json:
"buildOptions": { "embed": { "include": [ "Views/**/*.*" ] } }
csproj Format
Assume that we have a project, named EmbeddedPlugIn, as shown below:
I select Index.cshtml file, go to properties window (F4 as shortcut) and change it's Build Action to Embedded Resource.
You should change build action to embedded resource for all files you want to use in a web application.
Add To Embedded Resource Manager
Once we embed our files into the assembly, we can use startup configuration to add them to embedded resource manager. You can add such a line to PreInitialize method of your module:
Configuration.EmbeddedResources.Sources.Add( new EmbeddedResourceSet( "/Views/", Assembly.GetExecutingAssembly(), "EmbeddedPlugIn.Views" ) );
Let's explain parameters:
- First parameter defines root folder for files (like here). It matches to root namespace.
- Second parameter defines the Assembly contains files. This code should be located in the assembly containing embedded files. Otherwise, you should change this parameter accordingly.
- And the last one defines root namespace of files in the assembly. This is the default namespace (generally, the assembly name) plus see, it's same as regular controllers and works as expected.
Consume Embedded Resources
To consume embedded resources (js, css, img...), we can just use them in our views as we normally do:
@section Styles { <link href="~/Views/Blog/Index.css" rel="stylesheet" /> } @section Scripts { <script src="~/Views/Blog/Index.js"></script> } <h2 id="BlogTitle">Blog plugin!</h2>
I assumes that the main application has Styles and Scripts sections. We can also use othe files (like images) as normally we do.
ASP.NET Core Configuration
ASP.NET MVC 5.x projects will automatically integrate to embedded resource manager throught Owin (if your startup file contains app.UseAbp() as expected). For ASP.NET Core projects, we should PreInitialize of your module as shown below:
Configuration.Modules.AbpWebCommon().EmbeddedResources.IgnoredFileExtensions.Add("exe");
Override Embedded Files
One important feature of embedded resource files is that they can be overrided by higher modules. That means you can create a file with same name in the same folder in your web application to override an embedded file (your file in the web application does not require to be embedded resource, because static files have priority over embedded files). Thus, you can override css, js or view files of your modules/plugins in the application. Also, if module A depends on module B and module A defines an embedded resource with the same path, it can override an embedded resource file of module B.
Notice that: For ASP.NET Core projects, you should put overriding files to the wwwroot folder as the root path. | http://aspnetboilerplate.com/Pages/Documents/Embedded-Resource-Files | CC-MAIN-2017-09 | refinedweb | 533 | 50.53 |
Liam McSherry won our TechNet Wiki contest! Here is a sample of the winning article...
Microsoft Small Basic, while a good language for a beginner, is rather limited once you really get into programming. If you feel you're rather advanced with Small Basic, but you also feel that you're being limited by it, you may want to write an extension. You may also wish to write an extension simply to help the Small Basic community by expanding what they have available to them.To write an extension for Small Basic, you'll have to select a CLR-compatible language to write in. This tutorial will be using Microsoft C#, but there is a large selection of languages compatible with the CLR which can be used to write a Small Basic extension (and we have a tutorial for writing an extension in Visual Basic.NET here). This tutorial will assume that you have a grasp of using Visual Studio, which is the preferred environment for developing for the CLR. Microsoft Visual Studio 2012 Professional will be used in this tutorial.
Small Basic is built for version 3.5 SP1 of the .NET Framework, and won't be compatible with extensions in any other versions of it. You will want to create a class library (as outside of Small Basic "extensions" are generally referred to as libraries, or libs for short). You'll have to select ".NET Framework 3.5" from a dropdown at the top of the "New Project" window, and you'll have to select "Class Library", as shown below.
You will also need to add a reference to SmallBasicLibrary.dll, which can be found inside the directory you installed Small Basic to. We need this library because it allows us to flag classes with an attribute that makes the Small Basic IDE show them. Once you have added the reference. you'll also want to include the namespace in your code file.
=============
To read the rest, including instructions about how to program your extension, check out Liam's article on TechNet Wiki:
Small Basic: How to Create an Extension Using C#
Thanks to Liam and everyone who has made Small Basic articles on TechNet Wiki!
- Tall Basic Ed | http://blogs.msdn.com/b/smallbasic/archive/2012/11/05/featured-article-small-basic-how-to-create-an-extension-using-c.aspx?Redirected=true&t=Featured%20Article%20-%20Small%20Basic:%20How%20to%20Create%20an%20Extension%20Using%20C | CC-MAIN-2015-06 | refinedweb | 371 | 64.2 |
04 March 2011 01:51 [Source: ICIS news]
HOUSTON (ICIS)--?xml:namespace>
While the company gave no explanation for the sales allocation, a buyer said ExxonMobil was running at reduced rates in the aftermath of plant issues suffered earlier in the year.
ExxonMobil operates two BD plants in the
It was not immediately known how long the sales allocations would continue.
BD is a raw material that is used primarily in the production of styrene butadiene rubber (SBR), as well as some chemical intermediates and polymer resins.
The sales allocations could further tighten the market, since new vehicle sales – the largest end-use sector for BD – rose more than 27% in February.
US Gulf March BD settled at 104 cents/lb ($2,293/tonne, €1,651/tonne), as assessed by ICIS.
In addition to
($1 = €0.72)
For more on butadiene visit ICIS chemical intelligence | http://www.icis.com/Articles/2011/03/04/9440706/us-bd-producer-exxonmobil-announces-sales-allocations.html | CC-MAIN-2014-35 | refinedweb | 145 | 54.32 |
Front-End Adventures in AEM: Part I
What’s in a Clientlib?
I’ve been a Web Designer and Developer since 2003. I’ve seen things and I’ve written things. But the area of the web I’ve always found the most fascinating and interesting is the Front-End. Whether it’s debating CSS architecture/convention, finding cool new tricks with Service Workers, or playing with Houdini, the Front-End is an endless challenge where we balance priorities like design/ux, browser-support, accessibility and SEO.
Like many purveyors of the web, I’ve benefited greatly from online blogging and Q&A forums like Stack Overflow. I’ve gleaned valuable tips and tricks on how to stretch web technologies to their limits to accomplish client objectives. However, in 2018 I landed on a platform and project unlike any before: To launch a site on top of a proprietary content management system by Adobe called “Adobe Experience Manager” or colloquially “AEM”.
What is it that makes AEM so fundamentally different for building front-ends on other platforms like Drupal/WordPress, Spring, or Apollo?
Nobody writes about the Front-End and AEM…
So here we are. The purpose of this article series is to describe my experiences working within AEM to provide modern Front-End tooling and workflows to my fellow developers. With a little ingenuity, AEM developers can have niceties like PostCSS, Webpack/Rollup and even Hot Module Replacement (HMR).
There’s a lot to cover so I’ve broken this article into parts. If you’re already familiar with what AEM’s clientlibs are, go ahead and skip the rest of this article and move on to Part II (not yet available).
*note* — This article series is written with AEM 6.4 in mind but the concepts should apply to future versions and even some older (6.2) Touch UI versions.
*note* — Adobe is notorious for moving their documentation around and their helpx docs and forums often have broken links. I’ll occasionally link to their docs so if the links stop working let me know and I’ll try and update the article.
- Part I: What’s in a Clientlib? [this Article]
- Part II: SPA Day [Coming Soon!]
- Part III: What a Sightly [Coming Soon!]
- Part IV: The Bundling [Coming Soon!]
- Part V: Sync (and Hot Module Replacement!) [Coming Soon!]
- Part VI: That’s So Maven [Coming Soon!]
- Part VII: End Scene 7 [Coming Soon!]
The Client Library (Clientlib)
AEM ships front end assets to end users via Client Libraries or clientlibs. It composes these clientlibs via a
.content.xml file; and then optionally a
css.txt file, a
js.txtfile, and zero to many
.css/
.less and
.js source files that are listed in their respective .txt file. I’ll cover these files in more detail later in this article.
These files are stored in the JCR or Java Content Repository and updating the files in the JCR usually results in an updated clientlib (depending on your caching settings). For
.less files, AEM processes them using the LESS compiler via Rhino. The exact Rhino and LESS version depends on your AEM version and service pack.
AEM then attempts to minify and obfuscate (JS) your files before concatenating them into their associated clientlibs. By default, this is done with YUI. It can also be configured to Google’s Closure Compiler or “none” which simply concatenates the files.
*tip* - Do not use YUI for any of your clientlibs. YUI is a largely antiquated tool that can eat unknown CSS selectors/rules and can blow up on ES5 rules that are perfectly valid for your target browsers. I recommend using Google Closure Compiler for AEM core component dependencies and the “none” option for any dependencies handled by Webpack or Rollup. Instead, let your bundler handle the processing in those situations.
A clientlib’s .content.xml file
A clientlib’s
.content.xml file is kind of like the blueprint of a clientlib. Let’s break it down:
XML Namespaces: xmlns:cq and xmlns:jcr
The xmlns:cq and xmlns:jcr attributes are XML namespaces used to identify the
jcr and
cq properties and values used in the rest of the document. They’re often seen listed above the rest as they’re often set then forgotten. Both the namespaces above are required for setting the
jcr:primaryType of the current folder.
jcr:primaryType
For clientlibs this needs to be
cq:ClientLibraryFolder. This registers the parent folder for AEM as a Client Library.
categories
An array of categories that this clientlib belongs to. Typically, a clientlib will only have one category and you can almost think of it as a name that this clientlib will be referenced by later. However, additional categories can supplied as well.
A common predefined category that you may see clientlibs added to is
cq.authoring.dialog. This is a special category that loads for all authoring dialogs in the Touch UI editor which I’ll touch on more later. You can see all of the categories available to your AEM instance by visiting the dumplibs page () while your AEM instance is running. You may need to change your host/port depending on your configuration.
*tip* - For loading clientlibs in the editor, I’ve found it useful to have a single clientlib dedicated to the
cq.authoring.dialogcategory and then specifying all the clientlibs I want loaded there in the dependencies array. This clientlib should only have a .content.xml file. This prevents AEM from bundling all my clientlibs into a single large package for the editor and allows me to target the individual clientlibs via Hot Module Replacement.
dependencies
This is an array of categories that this clientlib relies on. For example, if you rely on a separate dependencies/vendor bundle, you would list it here. This field helps AEM determine the load order of all the clientlibs so be sure you keep your dependencies up-to-date.
embed (not pictured above)
Similar to dependencies, embed is used to specify clientlib categories that this clientlib relies on. However, unlike dependencies, embed actually merges these clientlibs together. Generally speaking, you should almost always prefer dependencies to embed. Failing to do so can result in duplicate code across clientlibs or overly bloated clientlibs. However, “embedding code is useful for providing access to libraries that are stored in secured areas of the JCR”. Think of embed as an npm
require or
import. Since you’re probably using some sort of Front-End build setup, just handle your embedding there.
cssProcessor and jsProcessor
The helpx site has a great write up about the technical details here, but I want to cover the bullet points. Basically, these two properties consist of an array of two values. The first, specifies what kind of processing you want to do by default, or “not in production”. The second, is what it should do when the clientlib should be minified.
In general, consider setting everything to
["default:none", "min:none"] for your authored clientlibs and then set a default of
cssProcessor: ["default:none", "min:yui"] and
jsProcessor: ["default:none", "min:gcc;compilationLevel=advanced"] in the config manager. This way, we can handle minification and obfuscation through something like Webpack for our code and Adobe’s library clientlibs can be handled via the default configuration.
*tip* - We should always minify and obfuscate (if possible) our code for production but where we do that depends on the clientlib’s purpose. For default, you should probably always specify none. This makes it easier to debug your code while in development. For minification, the answer is a bit more nuanced:
If your clientlib has an embed — Turn on Google Closure Compiler for JS with as much obfuscation as possible. For CSS, do not use YUI for anything other than embedded CSS. To reiterate, YUI is notorious for silently eating CSS selectors and rules.
If your clientlib does not have an embed — Consider turning off everything for both CSS and JS. Instead, have Webpack, Rollup, or whatever build process you use handle the minification and obfuscation for you. You’ll be able to achieve better results with something tailored for your code.
allowProxy
If a client library is located under /apps (everything under /apps is protected), this property allows access to it via proxy servlet. You can read more here but the gist is that this property must be set if your clientlib is under /apps and it should be under /apps because it makes more sense organizationally. There’s also a strong possibility that clientlibs won’t work under /etc moving forward as Adobe shifts more and more code out of /etc.
longCacheKey
This property is poorly documented but can be very useful. It’s an optional string that allows you to fingerprint your clientlibs (i.e.
clientlib.FINGERPRINT.js). It even supports placeholders in the value (i.e.
${project.version}-${buildNumber}). This does require the build-helper-maven-plugin to be configured (see examples).
*tip* - Fingerprinting your clientlibs is a performance must. An alternative to longCacheKey for fingerprinting is Versioned Clientlibs from ACS AEM Commons. The advantage of this solution is that it will hash your JS file and CSS files independently even as a part of the same clientlib unlike with longCacheKey. However, it does require an additional dependency, only supports MD5 hashes as of this writing, and requires setup to help AEM determine the hash. longCacheKey is ultimately more flexible but would require you to have separate clientlibs for JS/CSS if you wanted to provide them separate values.
Resources Folder
Your clientlibs may have external dependencies. For example, a CSS file may depend on a WOFF file for a custom font or a SVG file for a background image. Similarly, a JS file may have an asynchronous JavaScript dependency that loads in at a certain viewport location. In AEM, these are considered “resources” and belong in a resources sub directory under the clientlib’s directory.
So if your clientlib exists here in the JCR: /apps/myproject/clientlibs/main
then your resource would exist here in the JCR: /apps/myproject/clientlibs/main/resources/font.woff
You could then access this font like so in your clientlib’s css file:
@font-face {
font-family: "Open Sans";
src: url("resources/font.woff") format("woff");
}
You can also nest additional directories underneath resources depending on your organizational needs so the above font url could be resources/fonts/font.woff.
*tip* - You can put any static file inside the resources folder, it doesn’t just have to be an asset for a clientlib to reference. For example, sometimes I’ll have large external SVG’s (like sprites) that I don’t want stored in the DAM because I rely on them in my components. Storing them in a clientlib’s resource folder gives me a consistent reference point that I can use anywhere.
Conclusion
Clientlib’s take a little getting used to for the first-time Front-End AEM Developer. It’s not as simple as dropping your static assets in a bin and referencing them with
<script> and
<style> tags. But now that we know the in’s and out’s of making clientlib’s tick we can build on that foundation to build truly inspiring and accessible experiences. | https://medium.com/@soluml/front-end-adventures-in-aem-part-i-fdf4a7ffb2c5 | CC-MAIN-2019-30 | refinedweb | 1,879 | 63.8 |
.
Apple recently promoted Swift - a new programming language for iOS and OSX development, to version 1.0. Apple’s Swift is not to be mistaken with the older parallel scripting language. Swift comes to make iOS and OSX development simpler and more fun. In this article, I will explain what I think are the top 5 killer features of Swift; and why - while it is still in beta - it’s absolutely worth checking out.
Apple already had a programming language, Objective-C. So why introduce yet another programming language? Well, while Objective-C might have been quite different and modern when it was created, it does not convey today’s taste for languages. On the consumer side for example, scripting languages like Ruby have been highly adopted to a large extent thanks to the clean syntax that the language offers. In the enterprise world, strongly typed (type safe) languages with type inference seem to be preferred and big efforts have been seen in languages like C# and Java (or Scala) to bring concepts typically found in functional languages like functions as objects and Lambdas. Objective-C is lacking some of these things like a clean syntax (and Syntactic sugar) and type inference. Swift tries to fill this gap.
This is not to say that Objective-C is not a good programming language. As a matter of fact, it is a great language. But I do see clear signals of enough room for alternatives to Objective-C to succeed. To take things even further, and thanks to how good Swift is, I wouldn’t be surprised if the adoption of Swift s spreads like wildfire.
Now let’s focus on what Swift has to offer. From a language perspective, Swift is awesome. Apple took note of modern languages like Scala or C# and built a super simple and yet powerful language. It provides a super sweet mix between object-oriented and functional programming paradigms - saying that Swift is a functional language is a big stretch though. Let’s move on to the top 5 killer features of Swift.
#1: Syntax Goodies
Syntactically speaking, Swift is superb. It is an extremely simple and clean language with an awesome readability even by today’s standards. You can see right away that simplicity was key when designing the language. Take for instance, the famous semi-colon at the end of statements. Apple decided to make it optional. While it may not seem extremely relevant, it conveys the effort they did to keep the syntax as clean as possible.
Other examples of this are string interpolation, and the language support for dealing with arrays and loops.
String interpolation
var message = "Hello World" "The message is \(message)" //The message is Hello world var a = 1, b = 2 "The sum is \(a + b)" //The sum is 3
Loops
var length = 10 for i in 0..<length { //Do something with i }
Arrays
var list = ["a", "b"] list += ["c", "d"]
These are just a handful of examples of how Swift has language support for doing these types of things. Notice, for example, that concatenating arrays can also be done with the “append” method on the Array class, but the fact that Apple went the extra mile to build this as part of the language demonstrates what their goal is with Swift.
If you want to learn Swift, and test some of these sample codes, I couldn’t stress enough how cool the new Playground in Xcode 6 is. The Playground allows you to test your code as you are typing it in real-time. It will execute everything you type in the Playground, and give detailed information about the values of the variables, the returned values of function calls, and how many times specific code blocks were executed. Opening the Playground in Xcode 6 is very simple:
(Click on the image to enlarge it)
And here is how the Playground looks:
(Click on the image to enlarge it)
#2: Functions are First-Class Objects
Functions as first-class objects and higher-order functions, can be found in more and more languages. For example, Java 8 recently introduced Lambdas. The concept is simple, let functions take other functions as parameters, and/or return functions as well. In it’s simplicity lays the power of this concept, since it allows for greater abstractions. Take a “filter” function applied to an array as an example. A filter function allows you to filter a given array based on which of those items meet a certain criteria passed as a parameter. The key for having a super generic method, is to be able to receive a function as a parameter. Let’s go through the syntax for defining functions.
Swift has a syntax for defining Functions that somewhat resembles those from typically functional languages like Haskell (it’s not exactly the same, but similar). On the left side of an arrow (->) you have the parameters and on the right side of the arrow you have the return Type. In our example, we want to filter a list of numbers, so based on a given number we want to return a Bool. In this case, the type of the function will be:
(Item:Int) -> Bool
Meaning you receive an Int, and return a Bool. Obviously, you could have multiple parameters, but less obviously, you can also return multiple values without having to create a container object. In the latter case, the function will return a tuple.
The definition of a function for filtering integers could be:
funct bigNumbersOnly (item:Int) -> Bool { return item > 3 }
Now that we have our function, let’s take a look at the “filter” function which takes a function as parameter.
var numbers = [1, 2, 3, 4, 5] var bigOnes = numbers.filter(bigNumbersOnly)
In this example, filter is a higher order function, because it takes a function as a parameter. In Swift functions are also objects, which means that we can define the function inline…
var numbers = [1, 2, 3, 4, 5] var bigOnes = numbers.filter({(item:Int) -> Bool in return item > 3})
… or we can also assign the function to a variable and use it later.
//define two variables of type function var biggies = {(item:Int) -> Bool in return item > 3 } var threes = {(item:Int) -> Bool in return item == 3 } //decide which one to apply at runtime var result = numbers.filter(onlyThrees ? threes : biggies)
Treating functions as objects you can reference and pass them as parameters is pretty standard nowadays. But again, you can tell by the simplicity of how this is done in Swift, that it’s a core concept that gets even better with type inference.
#3: Strongly-Typed with Type Inference
In the enterprise world, we are very much accustomed to working on top of our strongly typed (or type safe) safety net. While strongly typed languages can give you that extra bit of confidence that (usually) things won’t break if they compile, it is typically a better experience when these languages also do type inference. So for example, I could do:
//Without Type inference var x:String = "bar" //With Type inference var y = "bar"
Notice, the lack of a type in the second statement. Because Swift knows that “bar” is a string, I don’t have to explicitly define it that way (although I could, like in the first statement). This might not seem a huge deal, but it certainly becomes more interesting when it is the Type of functions that is inferred.
So how can we define the functions from our previous examples, without defining the type? Let’s see how Swift pulls this one off.
//$0 will map to the first parameter, $1 to the second... var result = numbers.filter({ return $0 == 3})
Doesn’t get much cleaner than that! If you had more than one parameter and would like to reference parameters by name instead, you could do it like this:
{a, b in return a > b }
#4 Generics
Another feature available in the language, which can be extremely handy, is generics. In the enterprise world, generics were first introduced in C#, and later made it to Java after gaining a lot of traction. Using generics you can sometimes get rid of type casts. They allow the compiler to run certain type checks usually not available in languages without generics (it’s also true that generics did generate some controversy when introduced in C#, but it was overall accepted in the C# and Java communities).
Generics provide a way to defer the definition of a type, usually (but not limited to) of parameters and return types. While it sounds complex, it’s actually pretty simple to understand with a simple example.
//At the moment of creating this function //I am not defining what T is. The actual //Type of T will be deferred to the call //of the doNothing function. func doNothing<T> (item:T) -> T { return item } //When I call doNothing, I am implicitly //setting the type of T to the Type of the
//parameter I am sending. In this case, //an Array. //Notice how the compiler knows, that the //return type is an Array. doNothing([1, 2, 3]).count
While it’s not a very realistic example, you can see the convenience of knowing the type of the object inside the Array at compile time. For a simpler example, notice how the compiler knows that the Array contains Strings:
var list = ["hello", "world"] list[0].uppercaseString //HELLO
Generics are not limited to parameters, you can define generic classes, enumerations and structures. As a matter of fact, in the previous example, the type of list is Array<String>.
You might think generics in Swift are like protocols in Objective-C, however despite the similarities in the syntax, the concepts are quite different. Objective-C does not support generics. Protocols provide a way to declare that a certain implementation conforms to a messaging contract, but the contract has to be specified in advance. For example, you can't enforce that every item in an array be of the same type (no matter which type) with protocols, but can you can do that with generics. Apart from the fact that these two concepts are different, Swift does support protocols in pretty much the same way to how Objective-C does.
#5 Tuples
Tuples is a very simple concept, you can define an ordered group of values. Tuples can be very useful when having to pass more than one value around - as a parameter or as the result of invoking a function. Tuples don’t require you to define any types for its values, everything gets inferred and type checked at compile time. The syntax for defining a tuple is the following:
(1, "Two", ["Three"])
In this case, we have a tuple with three values, the first being an integer, the second a String, and the third one is an Array of Strings. At first glance this might look very similar to Arrays, however the concept is different. You can’t append or remove an item from a Tuple, and notice how the compiler knows the exact types of every value:
You can reference the different values of a tuple either by it’s location inside of the Tuple, like the image suggests, or you can give names to each of these values. This is very handy when a function needs to return several values, and it might be an overkill to define a Class or Struct just for that function. Let’s see an example of such case.
func info(items:[Int]) -> (avg:Int, min:Int, max:Int) { var sum = items.reduce(0, { $0 + $1 }) var min = items.reduce(Int.max, { $0 > $1 ? $1 : $0}) var max = items.reduce(Int.min, { $0 < $1 ? $1 : $0}) return (sum / items.count, min, max) } var result = info([1, 2, 3, 4, 5, 6]) result.avg //3 result.min //1 result.max //6
Tuples provide a very simple way to work with multiple values without having the extra work of defining a class or struct.
And there’s more…
The language comes with some other great features worth checking out, such as property observers, optional chaining, and extensions.
I believe Swift has all the necessary conditions to quickly become a popular programming language for iOS and OSX in both the enterprise and consumer worlds. The strongly-typed with type inference characteristic of the language will make it specially suitable for the enterprise, while the simple and clean syntax will attract those on consumer projects. | https://www.infoq.com/articles/apple-swift/ | CC-MAIN-2019-43 | refinedweb | 2,087 | 60.95 |
In this java tutorial section, you will learn how to determine the HCF (Highest Common Factor) or GCD (Greatest Common Divisor) of three numbers. As you already know that HCF or GCD is the largest positive integer that can exactly divide each one of the number.
Suppose there are three numbers 4,8 and 12.
Factors of 4=1,2,4
Factors of 8=1,2,4,8
Factors of 12=1,2,3,4,6,12
Here 4 is the highest number that can exactly divide both 4 and 8 and 12, so 4 is the HCF of 4,8 and 12.
Here is the code:
import java.util.*; public class HCFOFNumbers { public static int hcf(int a, int b) { if (b == 0) return a; else return hcf(b, a % b); } public static int hcf(int a, int b, int c) { return hcf(hcf(a, b), c); } public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter Number 1: "); int num1 = input.nextInt(); System.out.print("Enter Number 2: "); int num2 = input.nextInt(); System.out.print("Enter Number 3: "); int num3 = input.nextInt(); int hcfOfNumbers = HCFOFNumbers.hcf(num1, num2, num3); System.out.println("HCF of three numbers " + num1 + "," + num2 + " and " + num3 + " is: " + hcfOfNumbers); } }
Output: | http://www.roseindia.net/tutorial/java/core/findhcf.html | CC-MAIN-2014-52 | refinedweb | 211 | 57.06 |
Schematics is a tool from the Angular team that allows you to manipulate projects with code. You can create files, update existing files, and add dependencies to any project that has a
package.json file. That's right, Schematics aren't only for Angular projects!
Table of Contents
- Schematics: Manipulate Projects with Code
- Build Schematics with Vue
- Add Dependencies with Schematics
- Create, Copy, and Update Files
- Test Your BootstrapVue Installer
- Verify Your Vue Schematic Works
- Schematics with Angular
- Use Vue Schematics to Add Authentication with OpenID Connect
- Create an OpenID Connect App on Okta
- Learn More about Vue, Schematics, and Secure Authentication
In this post, I'll show you how to use Schematics to modify a project created with Vue CLI. Why Vue? Because it's fast and efficient. Its default bundle size is smaller than Angular and React too!
See The Baseline Costs of JavaScript Frameworks for more information about Vue's speed. I also think it's cool that Vue inspired a Wired magazine article: The Solo JavaScript Developer Challenging Google and Facebook.
Bootstrap is a popular CSS framework, and Vue has support for it via BootstrapVue. In this tutorial, you'll learn how to create a schematic that integrates BootstrapVue. It's a straightforward example, and I'll include unit and integrating testing tips.
Schematics: Manipulate Projects with Code
Angular DevKit is part of the Angular CLI project on GitHub. DevKit provides libraries that can be used to manage, develop, deploy, and analyze your code. DevKit has a
schematics-cli command line tool that you can use to create your own Schematics.
To create a Schematics project, first install the Schematics CLI:
npm i -g @angular-devkit/schematics-cli@0.13.4
Then run
schematics to create a new empty project. Name it
bvi as an abbreviation for Bootstrap Vue Installer.
schematics blank --name=bvi
This will create a
bvi directory and install the project's dependencies. There's a
bvi/package.json that handles your project's dependencies. There's also a
src/collection.json that defines the metadata for your schematics.
{ "$schema": "../node_modules/@angular-devkit/schematics/collection-schema.json", "schematics": { "bvi": { "description": "A blank schematic.", "factory": "./bvi/index#bvi" } } }
You can see that the
bvi schematic points to a factory function in
src/bvi/index.ts. Crack that open and you'll see the following:
import { Rule, SchematicContext, Tree } from '@angular-devkit/schematics'; export function bvi(_options: any): Rule { return (tree: Tree, _context: SchematicContext) => { return tree; }; }
There's also a test in
src/bvi/index_spec.ts.
import { Tree } from '@angular-devkit/schematics'; import { SchematicTestRunner } from '@angular-devkit/schematics/testing'; import * as path from 'path'; const collectionPath = path.join(__dirname, '../collection.json'); describe('bvi', () => { it('works', () => { const runner = new SchematicTestRunner('schematics', collectionPath); const tree = runner.runSchematic('bvi', {}, Tree.empty()); expect(tree.files).toEqual([]); }); });
One neat thing about Schematics is they don't perform any direct actions on your filesystem. Instead, you specify actions against a
Tree. The
Tree is a data structure with a set of files that already exist and a staging area (of files that will contain new/updated code).
Build Schematics with Vue
If you're familiar with Schematics, you've probably seen them used to manipulate Angular projects. Schematics has excellent support for Angular, but they can run on any project if you code it right! Instead of looking for Angular-specifics, you can just look for
package.json and a common file structure. CLI tools that generate projects make this a lot easier to do because you know where files will be created.
Add Dependencies with Schematics
The BootstrapVue docs provide installation instructions.
These are the steps you will automate with the
bvi schematic.
npm i bootstrap-vue bootstrap
- Import and register the
BootstrapVueplugin
- Import Bootstrap's CSS files
You can use Schematics Utilities to automate adding dependencies, among other things.
Start by opening a terminal window and installing
schematic-utilities in the
bvi project you created.
npm i schematics-utilities
Change
src/bvi/index.ts to add
bootstrap and
bootstrap-vue as dependencies with an
addDependencies() function. Call this method from the main function.
import { Rule, SchematicContext, Tree } from '@angular-devkit/schematics'; import { addPackageJsonDependency, NodeDependency, NodeDependencyType } from 'schematics-utilities';); return tree; }; }
Create, Copy, and Update Files
Create a
src/bvi/templates/src directory. You'll create templates in this directory that already have the necessary Bootstrap Vue imports and initialization.
Add an
App.vue template and put the following Bootstrap-ified code in it.
<template> <div id="app" class="container"> <img alt="Vue logo" src="./assets/logo.png"> <b-alert </div> </template> <script> import HelloWorld from './components/HelloWorld.vue' export default { name: 'app', components: { HelloWorld } } </script>
Create a
main.js file in the same directory with the Bootstrap Vue imports and registration.
import Vue from 'vue' import App from './App.vue' import BootstrapVue from 'bootstrap-vue' import 'bootstrap/dist/css/bootstrap.css' import 'bootstrap-vue/dist/bootstrap-vue.css' Vue.use(BootstrapVue) Vue.config.productionTip = false new Vue({ render: h => h(App), }).$mount('#app')
Modify the
bvi() function in
src/bvi/index.ts to copy these templates and overwrite existing files.
import { Rule, SchematicContext, Tree, apply, url, template, move, forEach, FileEntry, mergeWith, MergeStrategy } from '@angular-devkit/schematics'; import { addPackageJsonDependency, NodeDependency, NodeDependencyType } from 'schematics-utilities'; import { normalize } from 'path';); const movePath = normalize('./src'); const templateSource = apply(url('./templates/src'), [ template({..._options}), move(movePath), // fix for forEach((fileEntry: FileEntry) => { if (tree.exists(fileEntry.path)) { tree.overwrite(fileEntry.path, fileEntry.content); } return fileEntry; }), ]); const rule = mergeWith(templateSource, MergeStrategy.Overwrite); return rule(tree, _context); }; }
Test Your BootstrapVue Installer
In order to add dependencies to
package.json, you have to provide one in your tests. Luckily, TypeScript 2.9 added JSON imports, so you can create a testable version of
package.json (as generated by Vue CLI) and add it to
Tree before you run the test.
In the
bvi/tsconfig.json file, under compiler options, add these two lines:
{ "compilerOptions": { "resolveJsonModule": true, "esModuleInterop": true } }
Create
vue-pkg.json in the same directory as
index_spec.ts.
{ "name": "bvi-test", "version": "0.1.0", "private": true, "dependencies": { "vue": "^2.6.6" }, "devDependencies": { "@vue/cli-plugin-babel": "^3.4.0", "@vue/cli-plugin-eslint": "^3.4.0", "@vue/cli-service": "^3.4.0", "babel-eslint": "^10.0.1", "eslint": "^5.8.0", "eslint-plugin-vue": "^5.0.0", "vue-template-compiler": "^2.5.21" } }
Now you can import this file in your test, and add it to a
UnitTestTree. This allows you to verify the files are created, as well as their contents. Modify
src/bvi/index_spec.ts to match the code below.
import { HostTree } from '@angular-devkit/schematics'; import { SchematicTestRunner, UnitTestTree } from '@angular-devkit/schematics/testing'; import * as path from 'path'; import packageJson from './vue-pkg.json'; const collectionPath = path.join(__dirname, '../collection.json'); describe('bvi', () => { it('works', () => { const tree = new UnitTestTree(new HostTree); tree.create('/package.json', JSON.stringify(packageJson)); const runner = new SchematicTestRunner('schematics', collectionPath); runner.runSchematic('bvi', {}, tree); expect(tree.files.length).toEqual(3); expect(tree.files.sort()).toEqual(['/package.json', '/src/App.vue', '/src/main.js']); const mainContent = tree.readContent('/src/main.js'); expect(mainContent).toContain(`Vue.use(BootstrapVue)`); }); });
Run
npm test and rejoice when everything passes!
Verify Your Vue Schematic Works
You can verify your schematic works by creating a new Vue project with Vue CLI's defaults, installing your schematic, and running it.
Start by installing Vue CLI if you don't already have it.
npm i -g @vue/cli@3.4.1
Run
vue create test and select the default preset.
Run
npm link /path/to/bvi to install your BootstapVue Installer. You might need to adjust the
bvi project's path to fit your system.
cd test npm link ../bvi
Run
schematics bvi:bvi and you should see files being updated.
UPDATE /package.json (956 bytes) UPDATE /src/App.vue (393 bytes) UPDATE /src/main.js (287 bytes)
Run
npm install followed by
npm run serve and bask in the glory of your Vue app with Bootstrap installed!
Schematics with Angular
Angular CLI is based on Schematics, as are its PWA and Angular Material modules. I won't go into Angular-specific Schematics here, you can read Use Angular Schematics to Simplify Your Life for that.
This tutorial includes information on how to add prompts, how to publish your Schematic, and it references an OktaDev Schematics project that I helped develop. This project's continuous integration uses a
test-app.sh script that creates projects with each framework's respective CLI. For example, here's the script that tests creating a new Vue CLI project, and installing the schematic.
elif [ "$1" == "vue" ] || [ "$1" == "v" ] then config=$(cat <<EOF { "useConfigFiles": true, "plugins": { "@vue/cli-plugin-babel": {}, "@vue/cli-plugin-eslint": { "config": "base", "lintOn": [ "save" ] }, "@vue/cli-plugin-unit-jest": {} }, "router": true, "routerHistoryMode": true } EOF ) vue create vue-app -i "$config" cd vue-app npm install ../../oktadev*.tgz schematics @oktadev/schematics:add-auth --issuer=$issuer --clientId=$clientId npm run test:unit fi
This project has support for TypeScript-enabled Vue projects as well.
Got a minute? Let me show you how to create a Vue + TypeScript project and add authentication with OIDC and Okta.
Use Vue Schematics to Add Authentication with OpenID Connect
Run
vue create vb, select Manually select features and choose TypeScript, PWA, Router.
While that process completes, create an OIDC app on Okta.
Create an OpenID Connect App on Okta
Log in to your Okta Developer account (or sign up if you don't have an account) and navigate to Applications > Add Application. Click Single-Page App, click Next, and give the app a name you'll remember, and click Done.
The next screen should look similar to the following:
Go back to the terminal window where you created the
vb app. Navigate into the directory and run the app to make sure it starts on port 8080.
cd vb npm run serve
TIP: If it starts on port 8081, it's because you already have a process running on 8080. You can use
fkill :8080 to kill the process after installing
fkill-cli.
Stop the process (Ctrl+C) and add OIDC authentication to your app with the following commands:
npm i @oktadev/schematics schematics @oktadev/schematics:add-auth
When prompted, enter your issuer (it can be found in Okta's dashboard under API > Authorization Servers) and client ID. When the installation completes, run
npm run serve and marvel at your Vue app with authentication!
Click login, enter the credentials you used to signup with Okta, and you'll be redirected back to your app. This time, a logout button will be displayed.
Learn More about Vue, Schematics, and Secure Authentication
I hope you've enjoyed learning how to create Schematics for Vue. I found the API fairly easy to use and was pleasantly surprised by its testing support too. If you want to learn more about Okta's Vue SDK, see its docs.
You can find the example schematic for this tutorial on GitHub.
We've written a few blog posts on Schematics and Vue over on the Okta Developer blog. You might enjoy them too.
- Use Angular Schematics to Simplify Your Life
- Build a Basic CRUD App with Vue.js and Node
- Build a Simple CRUD App with Spring Boot and Vue.js
- Bootiful Development with Spring Boot and Vue
- If It Ain't TypeScript It Ain't Sexy
Follow @oktadev on Twitter to learn about more leading-edge technology like Schematics, Vue, and TypeScript. | https://scotch.io/bar-talk/schematics-a-plug-in-system-for-javascript-projects?utm_source=scotch&utm_campaign=share&utm_medium=reddit | CC-MAIN-2019-30 | refinedweb | 1,910 | 50.23 |
Out the box Sitecore ships with a number of reports pre-configured. Some of these will show data without you doing anything. e.g. The pages report will automatically start showing the top entry and exit pages as a page view is something Sitecore can track.
Other’s like the internal search report will just show a message of no data to display, which can be confusing/frustrating for your users. Particularly when they’ve just spent money on a license fee to get great analytics data only to see a blank report.
The reason it doesn’t show any information is relatively straight forward. Sitecore doesn’t know how your site search is going to work and therefore it can’t do the data capture part of the process. That part of the process however is actually quite simple to do.
Sitecore has a set of page events that can be registered in the analytics tracker. Some of these like Page Visited will be handled by Sitecore. In this instance the one we are interested in is Search and will we have to register it manually.
To register the search event use some code like this (note, there is a constant that references the item id of the search event). The query parameter should be populated with the search term the user entered.
using Sitecore.Analytics; using Sitecore.Analytics.Data; using Sitecore.Data.Items; using Sitecore.Diagnostics; using SitecoreItemIds; namespace SitecoreServices { public class SiteSearch { public static void TrackSiteSearch(Item pageEventItem, string query) { Assert.ArgumentNotNull(pageEventItem, nameof(pageEventItem)); Assert.IsNotNull(pageEventItem, $"Cannot find page event: {pageEventItem}"); if (Tracker.IsActive) { var pageEventData = new PageEventData("Search", ContentItemIds.Search) { ItemId = pageEventItem.ID.ToGuid(), Data = query, DataKey = query, Text = query }; var interaction = Tracker.Current.Session.Interaction; if (interaction != null) { interaction.CurrentPage.Register(pageEventData); } } } } }
Now after triggering the code to be called a few times, your internal search report should start to be populated like this.
One thought on “Populating the internal search report in Sitecore” | https://himynameistim.com/2017/09/13/populating-the-internal-search-report-in-sitecore/ | CC-MAIN-2020-40 | refinedweb | 331 | 50.84 |
Hello everyone,
I wrote a script to help me code in python and learn RhinoCommon and decided to share it with you
As you may know, the rhinoscriptsyntax library is written in Python and uses rhinocommon functions, also in Python, under the hood. In order to look up the underlying code you can open up the full python file, you can use the
inspect module or you can save the script below to your computer and run it each time you want to look up a particular function. For instance if you search for ‘bounding’ you get the following options:
And by clicking on the 3rd option you get the underlying source code, which you can read in the box, copy elsewhere, …
get_source_v1.py (883 Bytes)
get_source_v3.py (1.2 KB) : Clarified some text, PEP8 compliance, typo…
All comments, improvements and suggestions welcome !
from inspect import getsource, getmembers, isfunction import rhinoscriptsyntax as rs """ Script to view the source code for rhinoscript modules in Rhino 5 + 6 By Graham Knapp for personal use and for the McNeel Discourse forums 13/6/2019 """ def get_source(): search_term = rs.StringBox('Function name to search for', title='rhinoscriptsyntax' ).lower() if not search_term: return functions = {name: obj for name, obj in getmembers(rs) if isfunction(obj) and search_term in name.lower()} # (tuples of name, fuction) if not functions: return selected = rs.ListBox(functions.keys(), title='rhinoscriptsyntax') if not selected: return the_source = getsource(functions[selected]) box_result = rs.EditBox(the_source, message='Press OK to copy to clipboard', title='Use the source') if box_result: rs.ClipboardText(box_result) return box_result if __name__ == '__main__': get_source() | https://discourse.mcneel.com/t/python-may-the-source-be-with-you/84655 | CC-MAIN-2019-26 | refinedweb | 264 | 51.07 |
marble
#include <FileStorageWatcher.h>
Detailed Description
Definition at line 113 of file FileStorageWatcher.h.
Constructor & Destructor Documentation
Creates a new FileStorageWatcher, which is a thread watching the space Marble takes on the hard drive and deletes files if necessary.
- Parameters
-
Definition at line 306 of file FileStorageWatcher.cpp.
Definition at line 323 of file FileStorageWatcher.cpp.
Member Function Documentation
Add
bytes to the current cache size.
So FileStorageWatcher is aware of the current cache size.
Definition at line 362 of file FileStorageWatcher.cpp.
Returns the limit of the cache in bytes.
Definition at line 354 of file FileStorageWatcher.cpp.
Setting current cache size to 0.
Definition at line 367 of file FileStorageWatcher.cpp.
The function being called at starting Thread.
The thread is started by QThread::start().
Reimplemented from QThread.
Definition at line 382 of file FileStorageWatcher.cpp.
Sets the limit of the cache in
bytes.
Definition at line 343 of file FileStorageWatcher.cpp.
Updates the name of the theme.
Important for deleting behavior.
- Parameters
-
Definition at line 372 of file FileStorageWatcher. | https://api.kde.org/4.14-api/kdeedu-apidocs/marble/html/classMarble_1_1FileStorageWatcher.html | CC-MAIN-2019-47 | refinedweb | 172 | 55.2 |
InvokeTarget
Since: BlackBerry 10.0.0
#include <bb/system/InvokeTarget>
To link against this class, add the following line to your .pro file: LIBS += -lbbsystem
The InvokeTarget class represents a remote application, card, or service that can be invoked.
Overview
Public Types Index
Public Functions Index
Public Types
The kinds of processes that can be targets.
BlackBerry 10.0.0
- Unspecified = 0x0
No target is specified.
- Application = 0x1
The target is an application accessible from the home screen.Since:
BlackBerry 10.0.0
- Card = 0x2
The target is an application that runs using the full screen of the device, on top of any windows of the invoking parent application.
When an application is invoked as a card, it is considered to be part of the invoking application rather than a separately-running application. As such, an application running as a card does not appear in the list of running applications on the home screen.Since:
BlackBerry 10.0.0
- Service = 0x8
The target is a background process in the operating system.Since:
BlackBerry 10.0.0
- Self = 0x10
Include a target even if the target is the same as the client.
This value is valid only for specifying target types for invocation target queries. An InvokeTarget will not have type InvokeTarget::Self.Since:
BlackBerry 10.0.0
- Headless = 0x40
The target is a headless application.Since:
BlackBerry 10.3.0
Public Functions
Creates a new InvokeTarget object.
BlackBerry 10.0.0
Creates a copy of an existing InvokeTarget object.
BlackBerry 10.0.0
Destructor.
BlackBerry 10.0.0
QUrl
Returns a path to a localized icon file that represents the target.
A path to a localized icon file that represents the target.
BlackBerry 10.0.0
QString
Returns the localized name of the target.
The localized name of the target.
BlackBerry 10.0.0
QString
Returns the identity of the target as stated in its BAR manifest.
Use value with InvokeRequest::setTarget().
The identity of the target.
BlackBerry 10.0.0
InvokeTarget &
Copies the data of an existing InvokeTarget object to this object.
The InvokeTarget instance.
BlackBerry 10.0.0
bb::system::SecurityPerimeter::Type
Returns the security perimeter of the target.
The target's security perimeter. See bb::system::SecurityPerimeter for the list of perimeters.
BlackBerry 10.0.0
Type
Returns whether the target is an application, or a card.
The kind of process represented by the target. See InvokeTarget::Type for the list of invocation target types.
BlackBerry 10.0.0
Got questions about leaving a comment? Get answers from our Disqus FAQ.comments powered by Disqus | http://developer.blackberry.com/native/reference/cascades/bb__system__invoketarget.html | CC-MAIN-2014-41 | refinedweb | 428 | 53.17 |
Comment: Re:Write-only code. (Score 1) 757
Fucking PermGen space. It's like they've specifically added a setting that's nothing more than a ticking time bomb, just to keep people on their toes.....
After three days of watching them argue I finally resolved the issue by dropping a few convenience methods and replacing the class with a NamedTuple.
Ah, the namedtuple, love that type, makes small property bags simple and efficient, and yet you still go nuts and sub-class it if you really have to
*checks*
Looking at my user-site directory, apparently write my own Properties class - actually, three different classes for some reason, all slightly different and way more complicated than the namedtuple
My only niggle is the declaration syntax with the redundant type name
Point = namedtuple("Point", "x y")
which just looks ripe for danger lol.
I think I know what you mean - once you get "under the hood" there really are ways to customise everything. Metaclasses, abstract base classes, descriptors, descriptors, context managers, types, properties... all on top of plain-old multiple inheritance
All that stuff came way later though, for going from zero to code Python is pretty simple - you don't need all that stuff for 98% of use cases.
That is something that would be a nifty construct. About the closest I can think of off the top of my head is using a nested generator expression
borbs = [b for b in (compute(orn) for orn in orns) if b > 12]
Which isn't too awkward IMO, it's pretty clear there's two stages: a map and then a filter, and it's more readable than e.g.
borbs = list(filter(lambda b: b > 12, map(compute, orns)))
It depends
If compute() is a "heavy" function, then the plain loop is the best, although I'd probably use the
borbs = [b for b in map(compute, orns) if b > 12]
construction LoneTech posted earlier.
If it's a small function in a throwaway script then probably just
borbs = [compute(orn) for orn in orns if compute(orn) > 12]
as you posted.
How about something like
from itertools import dropwhile
def compute(l):
for i in l:
yield i * 2
borbs = list(dropwhile(lambda b: b <= 12, compute(orns)))
All of what you stated is convention, documentation and community-agreed definition of Pythonic.
My point was that it's not just the community of people using Python, but that it's also part of the community of people who design Python, and has been from the start. The latter feeds into the former, and then vice versa, and without both sides you end up with at best where JavaScript is today - intense focus on making code better, but every single avenue has multiple options and you end up with a bewildering array of choices.
Never say you know a man until you have divided an inheritance with him. | http://slashdot.org/~spiralx | CC-MAIN-2015-22 | refinedweb | 489 | 50.91 |
Any chance for someone to convert this to Arma2 so i can block addons from the server without using the Sign File system crap
Any chance for someone to convert this to Arma2 so i can block addons from the server without using the Sign File system crap
I would like to flag the user to be able to either continue and overwrite or abort upload
I did a quick search, does the code work fine on ARMA2?
Is the Doctor planning to update DooACS for ARMA2?
Any alternatives?
Last edited by DenVdmj; Nov 23 2010 at 01:03.
Can't? / won't? or .. have not yet?... i think its the last option. If you are certain some non-mission included scripts are accessed by a user "when he wants" it might also be possible to sniff out these commands with the use of a HE tripwire (yes HE stands for High-Explosive). What i mean to say is that it would be great if there is a method of double checking that a script should be run in the first place. If you make a little black book Battleye can help to filter out these scripts and preform a certain action when this happens. It wont be easy but what has to be done is a pre-load sequence that will tell Arma what scripts are going to be run in todays game. If any scripts are called upon at a later stage this must be seen as an intrusion and a action to stop this > mute player sound then ExecuteUserSlowly, by taking them to the dune-sea and feed it to jabbas pet.
Example: Optimal would be a function like the "Windows user accounts" option where a sub-user or guest have limited to no access to these kind of functions in the first place. And of cource keep the back-door only for authorized personnel and add metal detectors there as well (yes safety first)
As i and my crew are very annoyed by hackers any other method would be considered. Like the Wireshark Method introduced by Kochleffel
Only this one eats away some resources, is more complicated on rented servers and takes some skill to use it correctly (if possible at all). This is in the end a much better and suitable solution then BIS offed: Password your server = NOGO (no gaming without MP for me)
@Kju: What do you mean use the ACE /nonACE DS crash bug to your advantage?
@DenVdmj: Could you shed some more light on the method used here? Is this done by the std. chatfunction?
This is done using namespaces, a stack of windows and the fact that at the time of disconnection from the server, still have connection. | http://forums.bistudio.com/showthread.php?63208-DAnti-Cheat-System/page13 | CC-MAIN-2013-20 | refinedweb | 458 | 70.06 |
#include "UT_API.h"
#include "UT_Matrix2.h"
#include "UT_Vector2.h"
Go to the source code of this file.
Definition at line 221 of file UT_OBBox2D.h.
Definition at line 220 of file UT_OBBox2D.h.
Definition at line 219 of file UT_OBBox2D.h.
Auxiliary function to compute the convex hull of a set of points in 2D. Unlike the implementation in UT_QuickHull, this is a robust implementation of Fortune's algorithm using exact predicates. Robustness implies that the resulting convex hull passes the counter-clockwise test with infinite precision for any edge of the convex hull and a third point in the input set.
The output of the algorithm is the indices of the points that appear on the boundary of the convex hull in the order they do.
If set to false, the optional parameter 'exclude_on_edge_pts' makes the algorithm return points that lie along the interior of convex hull edges in the output sequence. Otherwise, only strict convex hull vertices are returned, i.e. those that cannot be written as nontrivial convex combinations of other points.
The return value is the index of a convex hull point p1 which together with the first point p0 in the generated convex hull, have the property that the entire convex hull projects to the line p0p1 between p0 and p1. | http://www.sidefx.com/docs/hdk/_u_t___o_b_box2_d_8h.html | CC-MAIN-2018-39 | refinedweb | 216 | 64.91 |
Malloc Madness
malloc, does that ensure you actually allocated memory?
I was looking at some C code a year or so ago and I noticed that the programmer never checked the return values from calls like
malloc. Just to forestall any flames, I'm not suggesting this is a good idea. On the contrary, I always do a sanity check on anything I get back from any memory allocation call. However, it brought to mind an interesting question: If you get a good return from
malloc, does that ensure you actually allocated memory? Can you run out of memory but still get a good return from
malloc?
The answer is: It depends. On some simple systems, the answer is probably yes. If you have a pointer to a chunk of memory, it's yours and will be until you release it. On Linux, however, the answer is often no. By default, the kernel makes a guess about how much memory you'll really need and if it thinks it might have enough, it returns a pointer to you. What it doesn't do, in the interest of performance, is actually allocate any of that memory in physical pages. That doesn't happen until you actually try to use the memory, and even then only for the pages (usually 4K) that you are actually using. By that time, however, there might not be any memory and you get an exception, even though
malloc returned a good pointer.
One issue with using Linux for embedded systems programming is that most people are used to writing Linux for servers or desktops, and it shows. For example, embedded systems often don't have swap files (either there isn't enough space for one, or the only mass storage is subject to write wearing). Some people assume that means there is no virtual memory. That isn't exactly true.
The kernel is pretty smart. If it runs out of physical memory, it tries to decide if it has some pages sitting around that it can safely reclaim. Sometimes that means reducing things like the caches the system uses for files. Eventually, though, that's not enough and it starts stealing pages of memory from processes that haven't used the pages in a while. That's swap, right? Not exactly. Again, the clever kernel looks at the kind of page. If the page is something that has not changed since it was read from disk (say, part of your executable code), it just throws that page away. The kernel knows that if you need that page again, it can just reload it from the original. If the code was modified, then it will have to go to the swap file.
Even then, the kernel tries to do things intelligently. If it swaps a page out, and later brings it back, it will mark the swap file page as unused, but it tries not to reuse the page. That way, if the page gets swapped again with no more changes, the kernel can just mark the existing swap page as in-use again, which is not only faster, but means that swapping to flash is probably not as bad as you thought it was (of course, modern wear-leveling algorithms also mitigate the same problem). So it isn't like the first page of your swap file or device gets written to more than any other part of the swap file.
However, if you have no swap file at all, it means that any page that is "dirty" is locked in physical memory until you destroy it. That's a big hurdle. The corollary, though, is that having no swap file doesn't necessarily mean the system can't overcommit, since it can still discard clean pages.
The
overcommit_memory flag in /proc/sys/vm lets you turn off overcommit behavior, which might be a good idea. Usually, this is set to 2, which lets the kernel guess if it will have enough memory based on the amount of physical RAM and swap space along with a ratio (
overcommit_ratio). You can set it to 0, which is my preference for small, embedded systems. You can also set it to 1 so that
malloc never fails! That might be useful if you are allocating very sparse arrays that you never really plan to use, although if you do that, I have to wonder about your design!
Try this with the different flag settings:
#include <stdio.h> #include <stdlib.h> #define TOUCH 1 // 0 to not touch memory, 1 to touch #define SIZE 1024 // bytes to allocate at once (assume <1 page) int main(int argc, char *argv) { unsigned i=0; char *p; do { p=(char *)malloc(SIZE); if (p) printf("%u\r", ++i); else { printf("Malloc failed after %u calls\n",i); break; } #if TOUCH *p=0xAA; #endif } while (p); return 0; }
If you set
TOUCH to 1, you will get less memory under the normal settings because accessing the memory forces the kernel to actually give you the memory. When
TOUCH is 0, the return from
malloc is valid, but doesn't really point to real memory, so the kernel is just guessing it can give you enough memory.
If you prefer to code in Java, here's an interesting question to ask your JVM vendor: When you load (or JIT compile) some byte code, does it get stuck in physical memory if there is no swap file? Unless the JVM author took some very special pains, the answer will be yes.
On the other hand, for embedded systems, a common virtual machine these days is actually the Android Dalvik system. While Android is based on Linux, it has some unusual wrinkles about what it does when it actually runs out of memory. But I'll save that for next time. | http://www.drdobbs.com/embedded-systems/malloc-madness/231600776 | CC-MAIN-2014-10 | refinedweb | 974 | 68.5 |
Get column index from column name in python pandas
Accepted Answer
Sure, you can use
.get_loc():
In [45]: df = DataFrame({"pear": [1,2,3], "apple": [2,3,4], "orange": [3,4,5]}) In [46]: df.columns Out[46]: Index([apple, orange, pear], dtype=object) In [47]: df.columns.get_loc("pear") Out[47]: 2
although to be honest I don't often need this myself. Usually access by name does what I want it to (
df["pear"],
df[["apple", "orange"]], or maybe
df.columns.isin(["orange", "pear"])), although I can definitely see cases where you'd want the index number.
Read more... Read less...
DSM's solution works, but if you wanted a direct equivalent to
which you could do
(df.columns == name).nonzero()
When you might be looking to find multiple column matches, a vectorized solution using
searchsorted method could be used. Thus, with
df as the dataframe and
query_cols as the column names to be searched for, an implementation would be -
def column_index(df, query_cols): cols = df.columns.values sidx = np.argsort(cols) return sidx[np.searchsorted(cols,query_cols,sorter=sidx)]
Sample run -
In [162]: df Out[162]: apple banana pear orange peach 0 8 3 4 4 2 1 4 4 3 0 1 2 1 2 6 8 1 In [163]: column_index(df, ['peach', 'banana', 'apple']) Out[163]: array([4, 1, 0])
In case you want the column name from the column location (the other way around to the OP question), you can use:
>>> df.columns.get_values()[location]
Using @DSM Example:
>>> df = DataFrame({"pear": [1,2,3], "apple": [2,3,4], "orange": [3,4,5]}) >>> df.columns Index(['apple', 'orange', 'pear'], dtype='object') >>> df.columns.get_values()[1] 'orange'
Other ways:
df.iloc[:,1].name df.columns[location] #(thanks to @roobie-nuby for pointing that out in comments.) | https://ask4knowledgebase.com/questions/13021654/get-column-index-from-column-name-in-python-pandas | CC-MAIN-2021-10 | refinedweb | 300 | 56.35 |
Code: Select all
import pyb, machine, sensor, image, pyb, os # Create and init RTC object. rtc = pyb.RTC() if(os.listdir('/images') == []): # If there are not images in directory then set the RTC #datetime format: year, month, day, weekday (Monday=1, Sunday=7), hours (24 hour clock), minutes, seconds, subseconds (counds down from 255 to 0) rtc.datetime((2018, 3, 9, 5, 13, 0, 0, 0)) # Enable RTC interrupts every 10 seconds, camera will RESET after wakeup from deepsleep Mode. rtc.wakeup(10000) BLUE_LED_PIN = 3 newName='' sensor.reset() # Initialize the camera sensor. sensor.set_pixformat(sensor.RGB565) sensor.set_framesize(sensor.VGA) # or sensor.QQVGA (or others) sensor.skip_frames(time = 1000) # Let new settings take affect. pyb.LED(BLUE_LED_PIN).on() if(os.listdir('/images') == []): # If images directory is empty then first image is labeled image_0001.bmp newName='images/image_0001.bmp' with open("time.txt", "a") as timeFile: # Write text file to keep track of date, time and image number timeFile.write("Date and time format: year, month, day, weekday, hours, minutes, seconds, subseconds" + '\n') timeFile.write("date and time for image 1: " + ' '.join(str(s) for s in rtc.datetime()) + '\n') else : lastName=os.listdir('/images')[-1] # Get the last image file name then add 1 to file name newNumber = int(lastName.split('.')[-2].split('_')[-1])+1 newName='images/image_' + '%04d' % (newNumber) + '.bmp' with open("time.txt", "a") as timeFile: # Append to date, time and image number to text file timeFile.write("date and time for image " + str(newNumber) + ": " + ' '.join(str(s) for s in rtc.datetime()) + '\n') # Take photo and save to SD card sensor.snapshot().save(newName) pyb.LED(BLUE_LED_PIN).off() # Enter Deepsleep Mode. machine.deepsleep() | http://forums.openmv.io/viewtopic.php?f=6&p=4085 | CC-MAIN-2018-26 | refinedweb | 277 | 53.78 |
#include <wx/graphics.h>
Represents a collection of wxGraphicGradientStop values for use with CreateLinearGradientBrush and CreateRadialGradientBrush.
The stops are maintained in order of position. If two or more stops are added with the same position then the one(s) added later come later. This can be useful for producing discontinuities in the colour gradient.
Notice that this class is write-once, you can't modify the stops once they had been added.
Initializes the gradient stops with the given boundary colours.
Creates a wxGraphicsGradientStops instance with start colour given by startCol and end colour given by endCol.
Add a new stop.
Add a new stop.
Returns the number of stops.
Returns the end colour.
Returns the start colour.
Returns the stop at the given index.
Set the end colour to col.
Set the start colour to col. | https://docs.wxwidgets.org/3.0/classwx_graphics_gradient_stops.html | CC-MAIN-2018-51 | refinedweb | 137 | 62.54 |
In today’s Programming Praxis exercise, our goal is to solve two exercises from the MindCipher website (technically three, but the third one can be solved without programming). Let’s get started, shall we?
import Control.Monad import Data.List import System.Random
The first exercise is to see which pattern, on average, takes longer to come up when flipping a coin: heads, tails, heads or heads, tails, tails. First, we define a function to simulate single series of flips, counting the number of flips before the desired pattern is produced. Heads and tails are represented as booleans for the sake of convenience.
flipUntil :: [Bool] -> IO Int flipUntil pattern = fmap (length . takeWhile (not . isPrefixOf pattern) . tails . randomRs (False, True)) newStdGen
Next, we simulate an entire day by repeating this process 10000 times and taking the average.
day :: [Bool] -> IO Double day pattern = fmap (\cs -> fromIntegral (sum cs) / fromIntegral (length cs)) . replicateM 10000 $ flipUntil pattern
For the second exercise, we need to find the first year for which the sum of both groups of two digits is equal to the middle two digits. This is easily achieved via a simple brute-force search.
sumDay :: Maybe Integer sumDay = find (\d -> div d 100 + mod d 100 == div (mod d 1000) 10) [1979..]
Running our two algorithms shows that monday’s pattern takes longer on average and that the first year that satisfies the criteria is 2307.
main :: IO () main = do print =<< liftM2 compare (day [False, True, False]) (day [False, True, True]) print sumDay
Tags: bonsai, code, coin, coins, flip, Haskell, heads, kata, praxis, programming, tails, year | https://bonsaicode.wordpress.com/2013/05/10/programming-praxis-mindcipher/ | CC-MAIN-2017-22 | refinedweb | 264 | 71.04 |
Working of os.path.relpath() method in Python
We use the os module in Python for interacting with the operating system. The os module comes with various sub-modules that can be used depending upon the kind of task we need to perform.
One such sub-module in Python is the os.path sub-module, which is used for some common path manipulations. It provides functions to work with the absolute paths and the relative paths. Here we will look into the os.path.relpath() method of os module and how this method works.
Syntax for os.path.relpath() in Python
The syntax to call this method would be os.path.relpath(path, start).
This method takes two parameters. The first parameter is a mandatory one and is a path whose relative path has to be given. The start parameter is an optional parameter. The relative path of the path we are trying to get, is given with respect to the path passed as an argument while calling the relpath() function(which is the second parameter). If no starting path is mentioned, the relative path will be given to us with respect to the current working directory.
A point to note here is, that this method only computes the relative path, the existence of the given path or the given directory is not checked.
import os # with the start path path = "/home / User / Desktop / folder1 / file.ppt" init = "/home / User" rel_path = os.path.relpath(path, init) print(rel_path) # without the starting path path = "/home / User / Desktop / folder2 / subfolder / file.ppt" rel_path = os.path.relpath(path) print(rel_path)
Output:
..\ User \ Desktop \ folder1 \ file.ppt ..\..\home \ User \ Desktop \ folder2 \ subfolder \ file.ppt
- Here, the first relative path was computed with respect to the start path that was mentioned.
- Whereas, in the second one, we did not mention any start path. Therefore, the current directory was taken by default and hence the relative path was calculated.
Also read: Get the position of max value in a list in Python | https://www.codespeedy.com/os-path-relpath-method-in-python/ | CC-MAIN-2020-45 | refinedweb | 336 | 68.26 |
07-16-2019 07:51 PM
07-17-2019 06:15 AM
4 weeks ago
Customer needs to do some customizations and this DLL provides classes and interfaces for Gateway. Do you advise that they don't have to look for this DLL?
3 weeks ago
Search your NX installation folders for files containing "gateway". There is no NXOpen.Gateway.dll.
What "classes and interfaces" do you need, and why do you think they are located in a DLL with this name?
2 weeks ago
Hi!
I would like to use the NXOpen.Gateway.ImageExportBuilder / ImageCaptureBuilder class.
I want to write a runtime behavior in NX MCD to trigger a ‚simulated camera‘ to export an image in bmp format in a certain perspective and range. To do so, I recorded a journal that gives me the NXOpen.Gateway.ImageExportBuilder command in VB (attached).
In MCD, I have to use C# for runtime behaviors. So I translated the journal into my C# class but visual studio gives me an error for the NXOpen.Gateway.ImageExportBuilder class. When trying to use the constructors for the classes, VS shows ‘ ImageExportBuilder() is inaccessible due to its protection level’.
That's why I was wondering where to get the NXOpen.Gateway.dll from?
Thanks for any help!
2 weeks ago
2 weeks ago
Thanks Yamada for your response!
I figured out that I should probably use the following code:
NXOpen.UI theUI;
NXOpen.Gateway.ImageExportBuilder imageExportBuilder;
theUI = NXOpen.UI.GetUI();
imageExportBuilder = theUI.CreateImageExportBuilder();
However, here, Visual Studio gives me the following error message
CS7069 C# Reference to type claims it is defined in 'mscorlib', but it could not be found
which again seems like I am not using the correct libraries? So far, I only have
using System;
using NXOpen;
Thanks a lot for the help!
2 weeks ago - last edited a week ago
2 weeks ago
I gave you the line of code that produced it:
theUI = NXOpen.UI.GetUI();
imageExportBuilder = theUI.CreateImageExportBuilder();
Sorry if that was not clear.
I am attaching a screenshot here.
Wanted to send the code earlier but forum does not allow me.
Please let me know if that makes it more clear.
Thanks for the help!
a week ago - last edited a week ago | https://community.plm.automation.siemens.com/t5/NX-Programming-Customization-Forum/Where-do-I-get-the-NXOpen-Gateway-dll-file-from/m-p/609971 | CC-MAIN-2019-35 | refinedweb | 375 | 68.57 |
A Decade of PHP 452
digidave writes "It was slow to catch and a lot of people didn't get it. A lot of people still don't get it, but you can't argue with its success. June 8th, 2005 marks the tenth anniversary of PHP. Here's to ten more wonderful and exciting years."
Congratulations are in order! (Score:4, Insightful)
It was slow to catch and a lot of people didn't get it.
Ok, I'm with the slow-to-catch-on part, but what's this about people not getting it? The concept had to be one of the simplest ever designed. (Thus the reason why it's so common across web scripting languages.) Here is your HTML, here's a bit of Unix scripting langauge. Simple, see?
On a slightly different topic, one wishlist item that I would like to see in PHP is Abstract Database Access. It's not really a good thing to hard code your application to a specific database, especially if it's a redistributable application. (e.g. PHPBB) The ODBC calls sort of solve this, but they do require that ODBC is installed, properly configured, and compiled into your copy of PHP. (Does anyone know if any distros now have ODBC as a "standard" library?) This assumption can't be made for most OSS applications, so they tend to tell you to just use MySQL.
Re:Congratulations are in order! (Score:5, Informative)
Re:Congratulations are in order! (Score:5, Informative)
For others, PEAR can be found here:
PEAR Class Repository [php.net]
The Database classes of PEAR appear to be documented here:
Database Package [php.net]
Looking over the DB classes, it looks like they provide a fairly decent abstraction. Thanks Quinto, that will definitely be nice for future PHP projects.
There's also ADOdb (Score:4, Informative)
I've never used PEAR, so I can't compare the two, but ADOdb is quite nice from my experience.
Re:Congratulations are in order! (Score:3, Funny)
Actually, what I'd like to see is bitwise-operations on strings - my Ogg Vorbis decoder written in PHP is currently languishing at just a bare-bones Ogg demuxer 'cos unpacking all the Vorbis packets proved just too fiddly...
Re:Congratulations are in order! (Score:5, Insightful)
I realize that PHP can be cool at times, but one has to use the right tool for the job at hand.
Re:Congratulations are in order! (Score:2)
That was precisely the reason I chose PHP - because it was absolutely the wrong tool for the job.
Well, maybe not quite as bad as some. Anyone want a port to Javascript? BBC Basic? Befunge?
Re:Congratulations are in order! (Score:2)
Re:Congratulations are in order! (Score:2, Insightful)
For most simple apps (90% of what PHP apps are) you should stick with SQL-92 syntax when you write your queries. Then just write yourself some generic functions that you pass your query and a connection string to. The functions determine the db-specific query execution code to use. I always use parameterized queries. So I've even got functions to switch the parameter character ('?' or '@' etc) to the syntax of the target db.
Re:Congratulations are in order! (Score:4, Interesting)
Re:Congratulations are in order! (Score:3)
The "lowest common denominator" data storage/retrieval does not actually mean you can use your database like a Relational Database Management System.
If you don't want your database to do what Relational Database Management Systems do, and you're just going to use it for flatfile-like queries, why not just use SQL-Lite? SQL-Lite has familiar syntax, but can be bundled with the application. You don't have to worry about what databa
Re:Congratulations are in order! (Score:5, Interesting)
For example, if you use a database abstraction, you have to make a lot of performace- or feature-robbing choices. There are still hosting situations where MySQL is still on 3.23, so you can't use the better parts of the InnoDB storage engine. So no foreign key constraints, no stored procedures.
On the other hand, if you do hardcode for PostgreSQL, you put a burden on the end user, sure--but in return, you're giving them a more robust, more featureful application that is easier to support and maintain. I personally like PostgreSQL because it seems less haphazard than MySQL, but you could very easily do this with MySQL, so long as you restrict yourself to the later, non-crippled versions.
The Arsdigita folks did this with Oracle. Leaning on a $tens-of-thousands database application may put you out of the realm of everyday developers, but it's far from insane.
This is "all the time I've spent dealing with other people's code that doesn't have a foreign key to be found and all integrity checking is done in the PHP code" talking. It's infuriating.
Re:Congratulations are in order! (Score:3, Informative)
Not so good an idea (Score:4, Insightful)
Say, for example a "real" DBA writes a shopping cart schema / application, using a "genuine" (ACID-compliant) DB, the scalability will be phenomenal; The speed will be incredible because much of the code will be handed TO the database -- not parsed and parsed and parsed away at the PHP/Java/whatever-script level.
Now, let's say a "wannabe" DBA writes a shopping cart schema / application using MySQL. Then to "help" the Postgres folks out, the DBA adds an abstration layer. Woo hoo!!! Useless... Essentially, I'm offered a way to drive a Ferari (Postgres) down the sidewalk, negotiating with pedestrians all day, as if I were traveling by skateboard (MySQL).
Unfortunately, the number of examples of the later are a dime a dozen. The number of examples of the former are near zero. Think about why you'd even WANT abstraction. In most real-world cases it's rather useless and undesireable.
Database independence (Score:3, Insightful)
But it should be done by using standard SQL.
Unfortunately, that is not a losing battle, it is a lost battle.
The database vendors doesn't care about standard SQL.
Re:Database independence (Score:3, Insightful)
Some do, some don't. It's now possible to write 100% ANSI compliant systems in Oracle and MS-SQL amongst others (those are the two I know of for sure, I also know there are others). Obviously you can choose to use non-ANSI compliant code if you so wish. Sometimes there are good reasons to do so, using supplied packages to perform tasks that would otherwise have to be coded is one. As noted earlier, writing your code to fit a particular RDBMS will often result in faster code. It may also give you a fas
Re:Database independence (Score:3, Informative)
Re:Database independence (Score:3, Informative)
Looks interesting. It doesn't appear to be 100% accurate though. There are a number of features (e.g. E051-08, E021-06 and E021-04) that it says that Oracle 9 does not have but I know it does, or at least it has something matching the description given (maybe I'm misunderstanding something).
Stephen
Re:Database independence (Score:3, Informative)
It may be really picky and unforgiving, however, and even a minor deviation from the standard might disqualify a feature from being listed as supported for a certain database. I can't say that that isn't the case. All I'm saying is that they guys that made the list know what they are talking about.
Åke Persson is also a compiler expert and he wrote this tool:
Re:Congratulations are in order! (Score:3, Insightful)
I've never understood the fanaticism of database abstraction. There's good reason to hardcode to a specific database, especially if you hardcode to a Free database like PostgreSQL.
You took the words right outta my mouth. I tend to work on large projects, usually the app has its own server (or servers) to work on.
I've hard-coded to Postgres since 7.0 came out, and I've NEVER regretted it. The only problem I've had is when one of my clients demanded "cross-platform".
I had more problems with th
Re:Congratulations are in order! (Score:3, Insightful)
Good points in your reply. Thanks for that.
If I was interviewing someone and they presented me with sample code riddled with "pg_connect()" calls rather than abstracting that into its own library, my first question would be "tell me why it is bad to do this."
Well, it all depends, doesn't it?
First, there's a difference between coding an abstraction layer that facilitates interaction with your database, and coding an abstraction layer that handwaves away the peculiarities of any particular database.
PHP definitely does not follow the KISS principle (Score:5, Informative)
Are you smoking crack? PHP is more inconsistent than any other language I've encountered. I'm not disrespecting the team, as I'm sure they've worked hard, and it's great to celebrate ten years of an admittedly very useful language, but PHP is not an inherently easy language.. it's just one that lets you code sloppily and get away with it.
For a start, PHP functions seem to have no consistency at all. Sometimes you get verb/object, sometimes object/verb. Sometimes you get underscores, sometimes you don't. Consider.. is_object but isset. str_rot13 but strpos. php_uname but phpversion. There are hundreds of these. It's the reason I could never learn PHP, it's like learning Chinese, but I found Perl (and now Ruby) easy due to their relative consistency. Sometimes PHP uses "to", sometimes it uses "2".. huh what's that about?
Unlike Perl which has a few regular expression constructions and a handful of modifiers.. PHP has a whole glut of regular expression functions which have confusing names, some of which take certain modifiers, and some that don't. As someone who has mastered Perl's regular expressions I find it a major struggle when I have to tackle something in PHP (I admit, I've never 'learned' PHP, but I find it a very hard language to make quick fixes on for other people.. compared to, say, C, VB or Python, languages I don't know intimately but can easily hack).!
So if you were going to call any language "KISS", it'd be Ruby or Python.. but PHP? No way.
Re:PHP definitely does not follow the KISS princip (Score:2)
Nope, I'm just a realist. PHP was designed to be a web scripting language that wrapped Unix APIs. Nothing more, nothing less. I in no way agree with the fanaticism surrounding PHP (it doesn't make a good general purpose language people!), but it does what it was designed for in a straightforward, simplistic fashion. I usually prefer to do things in JSP/Java, but if it's not an option for some reason then I prefer to u
Re:PHP definitely does not follow the KISS princip (Score:3, Insightful)
I would agree that PHP makes a decent web scripting language for basic tasks (polls, counter, guest book, a bit of remote inclusion), but I am horrified to see people actually using it for serious stuff like enterprise level systems. That sort of stuff makes the blood freeze. I feel really sorry for the corporations who get sucked into it.
Re:PHP definitely does not follow the KISS princip (Score:2, Insightful)
Re:PHP definitely does not follow the KISS princip (Score:3, Informative)
I've been working with ColdFusion for about 5 years now. My sites don't crash- and I get 10-20 million hits per month. Not huge, but a pretty good number. (No...this is not the site that is in my sig...)
I *might* get 2 or 3 'unhandled exceptions' in a day. And those are always caused by search engines that are hitting templates with bad queries. It is interesting to see the queries they send, "hmm...why did they decide t
Re:PHP definitely does not follow the KISS princip (Score:3, Insightful)
Re:PHP definitely does not follow the KISS princip (Score:5, Informative)
Just a quick point--you can use Perl's regular expressions in PHP. And that's usually what I see people doing. As a matter of fact, it is recommended in the PHP documentation that Perl's regular expressions be used: Note: preg_match(), which uses a Perl-compatible regular expression syntax, is often a faster alternative to ereg().
Wrong, wrong, wrong (Score:3, Insightful)
Nope. You can't. Well, you can. Well, sortof. Sometimes. With some syntactical exceptions, and lots of thinking about escape sequences, and passing parameters a different way. And that's the gotcha. You start thinking it's going to be the same -- and it's not.
Re:PHP definitely does not follow the KISS princip (Score:3, Informative)
CGI::Session [cpan.org].
Re:PHP definitely does not follow the KISS princip (Score:4, Insightful)
People underestimate the power of those two things. CPAN is the number one reason why PERL is still so popular.
Re:PHP definitely does not follow the KISS princip (Score:4, Insightful)
Most of the functions in the PHP distribution are named after a function that does the same thing in the C library that PHP uses to implement the feature. PHP is designed so that if you're familiar with the C library that it is using, you can very easily get the hang of the PHP version.
This doesn't excuse some of the weirdnesses in the core library, though -- str_rot13 (and the other string functions with underscores in them) is clearly wrong, as the earliest string functions followed the standard C library naming conventions.
To address your other examples: isset() is an operator that looks syntactically like a function, and would have been named in this fashion to mirror the other such operators (sizeof(), unset()). is_object() et al are functions that were implemented independently of this, and at the time there was no conflict. I see no excuse for the php_uname/phpversion difference.!
I don't like to nitpick, but... those aren't all core functions. They're just functions that are distributed with the core, kind of like the applications that come with a Linux distribution. You can build a stripped down PHP without them, if you want.
Re:Congratulations are in order! (Score:2)
Hear! Hear! Thx Rasmus. I still remember one of my co-workers first encouraging me to use PHP for CGI scripting about 5 years ago, and me saying "Nah, Perl works a-ok for me." Well I also used the Bourne Shell for CGI scripting once upon a time too and moved along.
PHP really is the right tool for the job of building websites. It was designed with that in mind, so that's not a slam against Perl in any way.
To be fair, I should really check out Python and Ruby soon... The great thing about PHP now is that
Re:Congratulations are in order! (Score:2)
Re:Congratulations are in order! (Score:4, Insightful)
When you can explain the core language and primary namespace to an interested programmer in under 30 minutes, I'll be glad to revisit the topic. Until then, Python is simple. Perl is even reasonable simple. PHP is not simple in any way, shape, or form (unless you're using the facetious Simple from SMTP, SNMP, and other horridly complex standards).
Re:Congratulations are in order! (Score:2)
What's not to get? (Score:3, Insightful)
-Jesse
Re:What's not to get? (Score:2)
Re:What's not to get? (Score:2)
Then again, it could be that old Tandy / Commodore rivalry I always saw in the old computer users groups of the 80s. Don't worry, we always kick your Trash-80 asses.
Re:What's not to get? (Score:2)
-Jesse, still uses his C-64 on occasion.
Re:What's not to get? (Score:2)
Do these antiquities have any value?
Re:What's not to get? (Score:2)
The C-64, and probably VIC-20, versions were LOAD "*",8,1 for the attached disk drive.
-Charles
Re:What's not to get? (Score:2, Informative)
It did say in the manual that this would happen and how to get at the different data sources if you cared. {And you can do sneaky stuf
Good for them. (Score:4, Funny)
Re:Good for them. (Score:5, Funny)
You're absolutely right. I tried to do my PHP programming in BASIC once. Bad idea.
Re:Good for them. (Score:2)
-Jesse, not really old, but do like/use assembly daily.
I don't really like PHP that much... (Score:3, Insightful)
Re:I don't really like PHP that much... (Score:2)
Re:I don't really like PHP that much... (Score:2, Insightful)
PHP is good because it's easy. It might often not be the most sophisticated, structured, or easily maintained language, but it is often the quickest and simplest solution to a problem. In that respect it fills an important niche.
Re:I don't really like PHP that much... (Score:2)
What is so exciting about it? I can't find a single situation where it is better to use [Language X] than other programming languages. Why would anyone love [Language X]?
Every language has both strong and weak points. PHP is extremely easy to learn and works great for both web programming and simple command-line purposes. That is unless you are just trolling. (Why does PHP hate the internet?)
Congratulations PHP (Score:5, Funny)
Re:Congratulations PHP (Score:2)
Re:Congratulations PHP (Score:2)
Re:Congratulations PHP (Score:5, Insightful)
You're one of those people who don't get it. This is not a language issue. In the not-so-distant future, developers will think it crazy not to use an MVC web framework for their web applications.
Ruby on Rails just happens to be first with an elegant, easy-to-use, true-separation-of-concerns, MVC web application platform.
The Java, Python, and Perl (Catalyst) folks have seen the light and are busy working on Rails-style frameworks. Seems like the PHP community hasn't seen the need yet.
Re:Congratulations PHP (Score:4, Insightful)
You know, I heard the same thing about Java back in 1996 or so.
Don't get me wrong, Rails looks decent enough, but neither is it a panacea. You can put together a really fast RSS reader, or a DB-backed recipe application, but these are trivial applications. Solving trivial problems elegantly isn't worthless, but thus far I haven't seen any Rails projects that compare in scope to something like Zope, or Drupal or even PHPBB.
Going through the various How-Tos for Rails, I keep saying to myself, "...or, I could just download foo, which is written in Perl/PHP/Python/AWK, but already works and is proven and does the same thing." PHP hasn't seen the need for copying Rails because they have a robust and featureful set of applications already. Dropping everything and chasing the next sexy thing might be entertaining, but it doesn't do much to help me, the working Webmaster.
I guess I'm just suspicious of using MVC (or OOP, or some other trendy buzzword) as a talisman. It smacks of cheerleading, and accusing people of "not getting it" doesn't prove the point.
PHP vs JSP (Score:5, Interesting)
I tried PHP, but I didn't feel it gave me the rigid OO structure and sophisticated APIs I get from Java, JSPs & Servlets.
Not trolling, just saying I'm surprised that Java and Servlet hosting isn't as popular as PHP. I'm obviously missing some key point.
Sam
Re:PHP vs JSP (Score:5, Insightful)
but procedural is a valid way to structure your apps... especially for web-based ones where that have, by nature, a page-based model and a very linear flow. you can write serious software using php4 without oop!
Re:PHP vs JSP (Score:5, Insightful)
This is my basic gripe with PHP. It leads the unfortunate user down a path that suggests that each page is its own island, and any attempt to modularize or componentize that is, by PHP's nature, a secondary affair.
Take, as a counterpoint, something like TTK. Here, you are presented with a programming langauge in which you write your code, and a templating system in which you write pages for display and a set of tools for connecting the two.
It's not that a good programmer can't produce a workable system in PHP alone or PHP + other langauges (PHP backed by Perl or Java or C# is quite powerful, in fact), it's just that it seems that the majority of people writing PHP are hobbled by this unfortunate presentation of the language as a "page generator", and thus most of the code written in PHP is rewrite-fodder from day one.
As a templating system, PHP is quite nice, and I'd use it where appropriate.
Re:PHP vs JSP (Score:5, Insightful)
Re:PHP vs JSP (Score:3, Insightful)
Re:PHP vs JSP (Score:3, Informative)
Re:PHP vs JSP (Score:2)
Re:PHP vs JSP (Score:2)
After all that was done, well then it was up to if you liked Java or not. And I've come to realize that Java is a langua
Re:PHP vs JSP (Score:2)
The answer is: Two completely different markets.
JSP requires a minimum investment in hardware, resources, and server capabilities that PHP does not. JSP also tends to require more backend APIs than PHP, because you try to keep as much out of the JSP as possible. As a result, JSP tends to be the best solution for Mid to Enterprise class systems, while PHP makes a good choice for Per
Re:PHP vs JSP (Score:2)
Re:PHP vs JSP (Score:2)
The main reason, IMHO, is that PHP is much more easy to install on a typical Apache web server, and much more appropriate for mutualized hosting.
With PHP (as a module or CGI), once a HTTP request is finished, all the resources (memory, DB connections, file handles, etc.) are given back to the operating system. With Java, the JVM keeps running after a request, and might keep locks on resources without anyone noticing.
This is a key ad
Re:PHP vs JSP (Score:2)
It's not needed as noted , but if it helps you use the language then it's easy enough to imitate it .
Re:PHP vs JSP (Score:3, Funny)
Thanks for the career, PHP!! (Score:5, Insightful)
Re:Thanks for the career, PHP!! (Score:5, Insightful)
Student Suspended Over Suspected Use of PHP (Score:5, Funny)
One of pillars of success: manual (Score:5, Insightful)
So, in any way, PHP is such thing which just works.
Congrats!
Agreed - it's a great starter language (Score:2)
But I wanted to make a really cool web site for a game group I was in, and I dug into it. I found PHP, as it worked real easy with both apache and IIS.
I ran through some tutorials (there's a ton of them out there, online, free) and I started to get into it.
The PHP manual has a lot of information and detail about nearly everything the language can do. It's a reference but it's easy to read and you can sit down with it and learn a lot about PHP and programming in ge
Re:One of pillars of success: manual (Score:2, Informative)
As i recall, when i first started to get familiar with perl, i was using perl in 21 days, then switched to perldoc and cpan.org documentation.
Also, please note the difference between a manual, a book and a guide. Manuals don't necessarily need to be easy to understandable, just coherent and clear. They are intended for those already familiar with the language, or at least some degree familiar with it. Given that php has so many functions
Re:One of pillars of success: manual (Score:3, Insightful)
I think you got the causality backwards. If PHP's manual wasn't top-notch, then noone would ever be able to figure out the 15 variations on each function (each with arbitrarily different argument ordering). People didn't flock to the PHP manual because PHP is such a great language.
In other words, PHP leans on a strong document set just to make it usable. That's quite different than most other languages commonly in use.
PHP 1.0 - 2.0 - 3.0 ... (Score:2, Insightful)
I discovered and started using PHP by the time the first beta of PHP 2.0 had been released. What a pleasure this was to convert my old clunky C CGI scripts to PHP. No more compiling, no more mallocs. Weee
7 years (I think, maybe it's 6) later I'm still using PHP for everything at work, and I certainly don't plan to use anythin
Slow to catch... (Score:2, Funny)
Or is this a dupe from yesterday?
Success of PHP easy to understand (Score:5, Insightful)
1. It is very easy to learn
2. It is easy to use (unlike ASP.NET) and relatively simple
3. The syntax is derived from C and perl
4. It is free
Re:Success of PHP easy to understand (Score:2)
$test = null;
if ($test==null) {
echo "test is null";
}
$test = array("1","2");
if ($test==null) {
echo "test is null";
}
$test = array();
if ($test==null) {
echo "test is null";
}
reply with your suggested result
Re:Success of PHP easy to understand (Score:2)
Personally I like Python or Ruby way better. Variant types are just not acceptable.
Re:Success of PHP easy to understand (Score:3, Insightful)
If you use either if (is_null($test)) or if ($test === null) instead of if ($test == null) you get the expected results.
JP
Re:Success of PHP easy to understand (Score:3, Insightful)
5. It's fast.
6. It is easy for hosting providers to deploy. There are tons of hosting companies out there give customers PHP support because it is easier to support on a box running a bunch of vhosts. Other web scripting environmants either have security issues (mod_perl is really scary if you don't trust other people running on the same host), have limitations for what directories scripts are run from, or are just a PITA to deploy in a simple yet relatively secure way. (That's n
Looking forward (Score:4, Insightful)
One of the huge problems with PHP is the massive number of XSS and SQL injection vulns present in code. Partially because PHP is used by beginners, but mainly because PHP does not help the developer write secure code. It's fast and easy to write, but allows you to shoot yourself in the foot. Just like C. See this paper on precise tainting [virginia.edu] for an example solution to the problems. It would break compatibility with most software written in PHP, but that's not neccessarily a bad thing when most of it is insecure trash.
Re:Looking forward (Score:2)
Re:mysql_escape_string (Score:5, Interesting)
Your "not that hard" comment is rather amusing with this in mind.
Re:Looking forward (Score:3, Informative)
PHP: Hypertext Preprocessor (Score:2, Funny)
Sometimes One Feature is all it takes (Score:2)
But most PHP applications I've developed usually start simple but grow into a tangled mess of code. I've tried to seperate my programming logic using templating systems, but it's just so much e
All hail "worse is better" (Score:2)
I get it, but I don't want it (Score:3, Insightful)
It was very clever and very handy when it was first developed, but there are many much better systems for building web pages available today.
Its object-oriented features are kludgy, its syntax is a throwback to C, and it in a realm where string handling is ubiquitous, it provides you with such great functions as strtok() and strncmp(). I mean come on, haven't we evolved just a bit past using the C standard library for string handling in our freaking web applications?
Personal Home Pages is fine for whipping up a quick data-driven website, but if you want to build a large application it's crap.
So what... (Score:2, Funny)
Why I Like PHP (Score:3, Informative)
I like Perl because it uses different operators for string concatenation and addition. That doesn't sound like much of a reason, but a lot of the programming I'm doing seems to call for either adding numbers or concatenating strings.
Now, in some languages, strings and numbers are completely different types. Then it's sort-of OK to recycle an operator to mean something completely different, because the computer knows what you mean. But there are several dynamically-typed languages which use + to concatenate strings. Then the magic guesser gets its knickers in a twist with not being able to work out whether something is really a number or just a string that looks like a number. This causes problems when you try to add numbers and find yourself concatenating strings. I wasted the best part of a day on a stupid bit of JavaScript for a DHTML application with increment/decrement buttons.
In Perl {and in PHP}, 3 + 4 gives 7. "3" + 4 gives 7. 3 + "4" gives 7. And "3" + "4" gives 7. If you actually want to concatenate the 4 onto the end of the 3, you have to use the concatenation operator . instead of the addition operator +. 3 . 4 gives "34". "3" . 4 gives "34". 3 . "4" gives 34. And "3" . "4" gives "34". That is simple.
Perl is a bit of a 'mare for n00bs because everything is a shorthand representation. There is the wonderful $_ which avoids cluttering up your script with temporary variables. You don't need brackets round function arguments {like the British BASIC dialects of the '80s}. Everything is optimised for the hardcore hacker, not the beginner. It only looks pretty when you realise that simplicity is beauty.
PHP has a more consistent interface than Perl. So you can't just drop in a regular expression, you have to call a function with the regular expression inside a string. It also does more stuff automagically for you, like keeping hashes ordered {Perl doesn't bother, expecting you to keep a separate array if you really care} and dereferencing everything {Perl expects you to manually create and dereference references when you make multidimensional arrays}. So it's probably a bit slower running, but it's quicker to get an app up and running.
It's how you use it... (Score:5, Insightful)
It's all in how you use it. Do you hack together a bunch of pages with isolated scripts talking to html forms and databases in an ad-hoc manner? Or did you start with a solid application design model from the start and follow through with time-tested methodologies?
PHP gets a bad rep because of the large number of inexperienced developers using it with poor results. I've developed full CRM and ERP apps with it including invoicing and ticketing systems that scale beautifully and are a dream to maintain. PHP is fast, free, and easy to use.
It's the responsibility of the developers to use more mature practices when developing large apps- and to recognize the fact that small site admin areas often evolve into larger apps. Plan and design!
We brought the cake (Score:4, Funny)
Yeah, we're a bit over the top for PHP. The whole company had cake and ice cream to celebrate.
Easy php installation (Score:3, Informative)
Personally, I've set up a lot of moodle sites () which is the best free LMS I've found.
Check it out if anyone is into e-learning or web based training.
(Make sure you have a fast server if you want to put a lot of students on it. The quiz modules are very useful, but they use an ungodly amout of resources if you're teaching a class of +30 students.)
Still broken. (Score:3, Interesting)
Ten years and the == operator is still completely broken. Any hope of fixing it in the next ten?
Suppose A equals B, and also B equals C. Any reasonable person would expect that A equals C, right? Oh yeah?Try explaining that to a first-time programmer.
Re:First AC (Score:4, Informative)
Probably a troll, but just in case anyone else doesn't know: PHP is a scripting language designed for generating dynamically created web pages. It functions by mixing its scripting in with the HTML, thus allowing programmers to reuse existing page designs. The scripting APIs are centered around those commonly used on Unix systems. PHP is usually bundled with Apache, so no installation tends to be required.
PHP Homepage [php.net]
Standard practice! (Score:2)
--grendel drago
Re:Standard practice! (Score:2)
Re:Completely necessary (Score:2)
Try using < and > =) | http://developers.slashdot.org/story/05/06/09/127249/a-decade-of-php | CC-MAIN-2015-14 | refinedweb | 5,579 | 64.2 |
Hello, I'm having some issues with the saving and loading of inherited class scripts. I hope that makes sense but if not i'll try my best to explain it.
so I have an abstract class, lets say its called "Boo" and boo has a few variables:
using system;
public abstract class Boo : monobehavior
{
int x,y,z;
//and a abstract method too:
Private abstract bool ExampleMethod(int i);
}
now we have the classes that inherit from Boo lets say 1, 2 and 3
using system;
Public class 1 : Boo
{
//and an override for our abstract method
public override bool ExampleMethod (int i)
{
//do some stuff
}
}
so my problem is that I want to be able to store all of my inherited classes for saving and loading into a container object and have the correct class (1,2 or 3) chosen when its loaded so that its method overrides and values are the correct ones.
I should probably note that I do know how to do serialization of variables but i just cant figure out how to get the class to save and load.
Hopefully that explains my problem properly, I often seem to have difficulty with explaining and asking appropriate questions so sorry about that. (don't really have good people skills)
Okay, so after some research i have come up with this:
IEnumerable temp = AppDomain.CurrentDomain.GetAssemblies().Select$$anonymous$$any(assembly => assembly.GetTypes()).Where(type => type.IsSubclassOf(typeof(Boo)) && !type.IsAbstract);
Which allows me to get the correct classes (1,2,3) and ignore any abstract classes along the way. The only problem is that now I don't know how to create the gameobject from Ienumerable . I have tried the following:
foreach (Type t in temp)
{
Boo tmp = (Boo)Activator.CreateInstance(Boo);
}
however its giving an error because Boo itself inherrits from monobehavior. Is there a way to add a component to a game object based on a Ienurable?
Got the same problem, did you ever figure it out @LightShadow ??
Answer by streeetwalker
·
Apr 15, 2020 at 05:56 AM
@LightShadow & @AsclepiiusUnknown, Here is one way to think about it:
Save the state of objects, not classes. Classes are just definition templates for objects. You don't need to save them because those definitions exist from one game session to the next.
[edit for clarification] In the context of saving the state of a running game, saving a Class doesn't make sense if you think about it because MonoBehavior classes don't have any existence outside of the GameObjects they are attached to as Script Components. And a GameObject can have multiple scripts attached to them. The GameObject is not defined by the script class objects you attach to it. It is the GameObject that owns the scripts, not the other way around.[end edit]
Therefore, you need to come up with a scheme for serializing objects and their state, and that includes a "type" identifier of object (e.g. which prefab is used to instantiate it) and all of the variables values that are not part of the object script component's initialization code (e.g. you want to save an enemy's location mid-game, which has changed from a location defined in the Start function a script attached to the object).
You could use a integer or string that is assigned in the derived class definition when the object is instanced as the "type" identifier. Integers are efficient because they are small. Strings are nice if you want to be able to read the type as a string. Each type identifies a different prefab object, with their associated derived classes in script components.
For example, you have 3 different types of enemies and several instances of each at the time you save. Those instances are created from 3 different prefabs, with names Ghost, Goblin, Troll. So we associate 0,1 and 2 with each, respectively. When we go to Instantiate them, we assign 0, 1, or 2 to the type variable depending on which of the enemies prefabs we are using. (It is also a good idea to assign each instance a unique ID of some kind, and the gameobject.name can be used for that, but that is another discussion)
When you go to save, assuming you have kept a reference to each enemy instance in a list, array, or collection of some kind, you loop through all the enemy instances and for each instance read and save its type identifier, name, location, and any other variables that have been changed after the object was instantiated.
When you then load a session, you loop through all the saved elements (e.g. read from a json file) and get the saved object type identifier to use in a switch statement (or a bunch of if else) to Instantiate the object from the correct prefab, and then set up all of the values you have saved. This is really the same Instantiation code as when you first ran the game, only here you are reading from a file to determine which objects to instantiate and what their "restarting" values are.
Use the same strategy for non-MonoBehvior class instances.
Remember that derived classes inherit any values defined in their parent class, so there is no need to worry about parent Class values, unless you have declared static variables or something - in which case all Instances will have the same value for those
Does that make sense - address
304 People are following this question.
Instantiating objects only after a scene is loaded
1
Answer
BinaryFormatter - Save and Load lists of data?
0
Answers
How do I save custom variables?
1
Answer
Waiting for Saving/Loading?
2
Answers
Saveing and Loading Problem
0
Answers
EnterpriseSocial Q&A | https://answers.unity.com/questions/1300376/savingloading-inherited-class-scripts-c.html | CC-MAIN-2021-17 | refinedweb | 962 | 57.2 |
stats
stats.analysis
AveragePointwiseEuclideanMetric
QuickBundles
Streamlines
cKDTree
stats
stats.analysis
AveragePointwiseEuclideanMetric
dipy.stats.analysis.
AveragePointwiseEuclideanMetric
Bases:
dipy.segment.metricspeed.SumPointwiseEuclideanMetric
Computes the average of pointwise Euclidean distances between two sequential data.
A sequence of N-dimensional points is represented as a 2D array with shape (nb_points, nb_dimensions). A feature object can be specified in order to calculate the distance between the features, rather than directly between the sequential data.
It is used to extract features before computing the distance.
Notes
The distance between two 2D sequential data:
s1 s2 0* a *0 \ | \ | 1* | | b *1 | \ 2* \ c *2
is equal to \((a+b+c)/3\) where \(a\) is the Euclidean distance between s1[0] and s2[0], \(b\) between s1[1] and s2[1] and \(c\) between s1[2] and s2[2].
feature
Feature object used to extract features from sequential data
is_order_invariant
Is this metric invariant to the sequence’s ordering
Methods
__init__(*args, **kwargs)
Initialize self. See help(type(self)) for accurate signature.
QuickBundles
dipy.stats.analysis.
QuickBundles(threshold, metric='MDF_12points', max_nb_clusters=2147483647)
Bases:
dipy.segment.clustering.Clustering
Clusters streamlines using QuickBundles [Garyfallidis12].
Given a list of streamlines, the QuickBundles algorithm sequentially assigns each streamline to its closest bundle in \(\mathcal{O}(Nk)\) where \(N\) is the number of streamlines and \(k\) is the final number of bundles. If for a given streamline its closest bundle is farther than threshold, a new bundle is created and the streamline is assigned to it except if the number of bundles has already exceeded max_nb_clusters.
The maximum distance from a bundle for a streamline to be still considered as part of it.
The distance metric to use when comparing two streamlines. By default, the Minimum average Direct-Flip (MDF) distance [Garyfallidis12] is used and streamlines are automatically resampled so they have 12 points.
Limits the creation of bundles.
References
Garyfallidis E. et al., QuickBundles a method for tractography simplification, Frontiers in Neuroscience, vol 6, no 175, 2012.
Examples
>>> from dipy.segment.clustering import QuickBundles >>> from dipy.data import get_fnames >>> from dipy.io.streamline import load_tractogram >>> from dipy.tracking.streamline import Streamlines >>> fname = get_fnames('fornix') >>> fornix = load_tractogram(fname, 'same', ... bbox_valid_check=False).streamlines >>> streamlines = Streamlines(fornix) >>> # Segment fornix with a threshold of 10mm and streamlines resampled >>> # to 12 points. >>> qb = QuickBundles(threshold=10.) >>> clusters = qb.cluster(streamlines) >>> len(clusters) 4 >>> list(map(len, clusters)) [61, 191, 47, 1] >>> # Resampling streamlines differently is done explicitly as follows. >>> # Note this has an impact on the speed and the accuracy (tradeoff). >>> from dipy.segment.metric import ResampleFeature >>> from dipy.segment.metric import AveragePointwiseEuclideanMetric >>> feature = ResampleFeature(nb_points=2) >>> metric = AveragePointwiseEuclideanMetric(feature) >>> qb = QuickBundles(threshold=10., metric=metric) >>> clusters = qb.cluster(streamlines) >>> len(clusters) 4 >>> list(map(len, clusters)) [58, 142, 72, 28]
Methods
__init__(threshold, metric='MDF_12points', max_nb_clusters=2147483647)
Initialize self. See help(type(self)) for accurate signature.
cluster(streamlines, ordering=None)
Clusters streamlines into bundles.
Performs quickbundles algorithm using predefined metric and threshold.
Each 2D array represents a sequence of 3D points (points, 3).
Specifies the order in which data points will be clustered.
Result of the clustering.
Streamlines
dipy.stats.analysis.
Streamlines
alias of
nibabel.streamlines.array_sequence.ArraySequence
cKDTree
dipy.stats.analysis.
cKDTree(data, leafsize=16, compact_nodes=True, copy_data=False, balanced_tree=True, boxsize=None)..
The number of points at which the algorithm switches over to brute-force. Default: 16.
If True, the kd-tree is built to shrink the hyperrectangles to the actual data range. This usually gives a more compact tree that is robust against degenerated input data and gives faster queries at the expense of longer build time. Default: True.
If True the data is always copied to protect the kd-tree against data corruption. Default: False.
If True, the median is used to split the hyperrectangles instead of the midpoint. This usually gives a more compact tree and faster queries at the expense of longer build time. Default: True..
See also
KDTree
Implementation of cKDTree in pure Python
The n data points of dimension m to be indexed. This array is not copied unless this is necessary to produce a contiguous array of doubles. The data are also copied if the kd-tree is built with copy_data=True.
The number of points at which the algorithm switches over to brute-force.
The dimension of a single data-point.
The number of data points.
The maximum value in each dimension of the n data points.
The minimum value in each dimension of the n data points.
This attribute exposes a Python view of the root node in the cKDTree object. A full Python view of the kd-tree is created dynamically on the first access. This attribute allows you to create your own query functions in Python.
The number of nodes in the tree.
Methods
__init__(*args, **kwargs)
Initialize self. See help(type(self)) for accurate signature.
boxsize
count_neighbors(self, other, r, p=2., weights=None, cumulative=True)
argument. (See below)
The algorithm we implement here is based on [1]. See notes for further discussion.
The other tree to draw points from, can be the same tree as self.
The radius to produce a count for. Multiple radii are searched with
a single tree traversal.
If the count is non-cumulative(
cumulative=False),
r defines
the edges of the bins, and must be non-decreasing.
1<=p<=infinity. Which Minkowski p-norm to use. Default 2.0. A finite large p may cause a ValueError if overflow can occur.
and
other. For this to make sense,
self and
other must be the
same tree. If
self and
other are two different trees, a
ValueError
is raised.
Default: None
Whether the returned counts are cumulative. When cumulative is set to
False
the algorithm is optimized to work with a large number of bins (>10) specified
by
r. When
cumulative is set to True, the algorithm is optimized to work
with a small number of
r. Default: True measures the clustering signal in
D. [2]
For example, given the position of two sets of objects, == False does not scale with the total number of bins.
The algorithm for
cumulative == True scales).
Gray and Moore, “N-body problems in statistical learning”, Mining the sky, 2000,
Landy and Szalay, “Bias and variance of angular correlation functions”, The Astrophysical Journal, 1993,…412…64L
Sheth, Connolly and Skibba, “Marked correlations in galaxy formation models”, Arxiv e-print, 2005,
Hawkins, et al., “The 2dF Galaxy Redshift Survey: correlation functions, peculiar velocities and the matter density of the Universe”, Monthly Notices of the Royal Astronomical Society, 2002,…78H
data
indices
leafsize
m
maxes
mins
n
query(self, x, k=1, eps=0, p=2, distance_upper_bound=np.inf, n_jobs=1)
Query the kd-tree for nearest neighbors
An array of points to query.
The list of k-th nearest neighbors to return. If k is an integer it is treated as a list of [1, … k] (range(1, k+1)). Note that the counting starts from 1.
Return approximate nearest neighbors; the k-th returned value is guaranteed to be no further than (1+eps) times the distance to the real k-th nearest neighbor.
Which Minkowski p-norm to use. 1 is the sum-of-absolute-values “Manhattan” distance 2 is the usual Euclidean distance infinity is the maximum-coordinate-difference distance A finite large p may cause a ValueError if overflow can occur.
Return only neighbors within this distance. This is used to prune tree searches, so if you are doing a series of nearest-neighbor queries, it may help to supply the distance to the nearest neighbor of the most recent point.
Number of jobs to schedule for parallel processing. If -1 is given all processors are used. Default: 1.
The distances to the nearest neighbors.
If
x has shape
tuple+(self.m,), then
d has shape
tuple+(k,).
When k == 1, the last dimension of the output is squeezed.
Missing neighbors are indicated with infinite distances.
The locations of the neighbors in
self.data.
If
x has shape
tuple+(self.m,), then
i has shape
tuple+(k,).
When k == 1, the last dimension of the output is squeezed.
Missing neighbors are indicated with
self.n.
Notes
If the KD-Tree is periodic, the position
x is wrapped into the
box.
When the input k is a list, a query for arange(max(k)) is performed, but only columns that store the requested values of k are preserved. This is implemented in a manner that reduces memory usage.
Examples
>>> import numpy as np >>> from scipy.spatial import cKDTree >>> x, y = np.mgrid[0:5, 2:8] >>> tree = cKDTree(np.c_[x.ravel(), y.ravel()])
To query the nearest neighbours and return squeezed result, use
>>> dd, ii = tree.query([[0, 0], [2.1, 2.9]], k=1) >>> print(dd, ii) [2. 0.14142136] [ 0 13]
To query the nearest neighbours and return unsqueezed result, use
>>> dd, ii = tree.query([[0, 0], [2.1, 2.9]], k=[1]) >>> print(dd, ii) [[2. ] [0.14142136]] [[ 0] [13]]
To query the second nearest neighbours and return unsqueezed result, use
>>> dd, ii = tree.query([[0, 0], [2.1, 2.9]], k=[2]) >>> print(dd, ii) [[2.23606798] [0.90553851]] [[ 6] [12]]
To query the first and second nearest neighbours, use
>>> dd, ii = tree.query([[0, 0], [2.1, 2.9]], k=2) >>> print(dd, ii) [[2. 2.23606798] [0.14142136 0.90553851]] [[ 0 6] [13 12]]
or, be more specific
>>> dd, ii = tree.query([[0, 0], [2.1, 2.9]], k=[1, 2]) >>> print(dd, ii) [[2. 2.23606798] [0.14142136 0.90553851]] [[ 0 6] [13 12]]
query_ball_point(self, x, r, p=2., eps=0)
Find all points within distance r of point(s) x.
The point or points to search for neighbors of.
The radius of points to return, shall broadcast to the length of x.
Which Minkowski p-norm to use. Should be in the range [1, inf].).
Number of jobs to schedule for parallel processing. If -1 is given all processors are used. Default: 1.
Sorts returned indicies if True and does not sort them if False. If None, does not sort single point queries, but does sort multi-point queries which was the behavior before this option was added.
New in version 1.2.0.
Return the number of points inside the radius instead of a list of the indices. .. versionadded:: 1.3.0 = np.c_[x.ravel(), y.ravel()] >>> tree = spatial.cKDTree(points) >>> tree.query_ball_point([2, 0], 1) [4, 8, 9, 12]
query_ball_tree(self, other, r, p=2., eps=0)
Find all pairs of points whose distance is at most r
The tree containing points to search against.
The maximum distance, has to be positive..
For each element
self.data[i] of this tree,
results[i] is a
list of the indices of its neighbors in
other.data.
query_pairs(self, r, p=2., eps=0)
Find all pairs of points whose distance is at most r.
The maximum distance..
Choose the output container, ‘set’ or ‘ndarray’. Default: ‘set’
Set of pairs
(i,j), with
i < j, for which the corresponding
positions are close. If output_type is ‘ndarray’, an ndarry is
returned instead of a set.
size
sparse_distance_matrix(self, other, max_distance, p=2.)
Compute a sparse distance matrix
Computes a distance matrix between two cKDTrees, leaving as zero any distance greater than max_distance.
Which Minkowski p-norm to use. A finite large p may cause a ValueError if overflow can occur.
Which container to use for output data. Options: ‘dok_matrix’, ‘coo_matrix’, ‘dict’, or ‘ndarray’. Default: ‘dok_matrix’.
Sparse matrix representing the results in “dictionary of keys” format. If a dict is returned the keys are (i,j) tuples of indices. If output_type is ‘ndarray’ a record array with fields ‘i’, ‘j’, and ‘v’ is returned,
tree
dipy.stats.analysis.
afq_profile(data, bundle, affine, n_points=100, profile_stat=<function average>, orient_by=None, weights=None, **weights_kwarg)
Calculates a summarized profile of data for a bundle or tract along its length.
Follows the approach outlined in [Yeatman2012].
The statistic to sample with the streamlines.
for each to have the same length) with which we are resampling. See Note below about orienting the streamlines.
The mapping from voxel coordinates to streamline points. The voxel_to_rasmm matrix, typically from a NIFTI file.
The number of points to sample along the bundle. Default: 100.
A streamline to use as a standard to orient all of the streamlines in the bundle according to.
Weight each streamline (1D) or each node (2D) when calculating the tract-profiles. Must sum to 1 across streamlines (in each node if relevant). If callable, this is a function that calculates weights.
The statistic used to average the profile across streamlines. If weights is not None, this must take weights as a keyword argument. The default, np.average, is the same as np.mean but takes weights as a keyword argument.
Additional key-word arguments to pass to the weight-calculating function. Only to be used if weights is a callable.
bundle
Notes
Before providing a bundle as input to this function, you will need to make
sure that the streamlines in the bundle are all oriented in the same
orientation relative to the bundle (use
orient_by_streamline()).
References.
dipy.stats.analysis.
anatomical_measures(bundle, metric, dt, pname, bname, subject, group_id, ind, dir)
save it in hd5 file.
Name of bundle being analyzed
dti metric e.g. FA, MD
DataFrame to be populated
Name of the dti metric
Name of bundle being analyzed.
subject number as a string (e.g. 10001)
which group subject belongs to 1 for patient and 0 control
ind tells which disk number a point belong.
path of output directory
dipy.stats.analysis.
assignment_map(target_bundle, model_bundle, no_disks)
Calculates assignment maps of the target bundle with reference to model bundle centroids.
target bundle extracted from subject data in common space
atlas bundle used as reference
Number of disks used for dividing bundle into disks. (Default 100)
References)
dipy.stats.analysis.
gaussian_weights(bundle, n_points=100, return_mahalnobis=False, stat=<function mean>)
Calculate weights for each streamline/node in a bundle, based on a Mahalanobis distance from the core the bundle, at that node (mean, per default).
The streamlines to weight.
The number of points to resample to. If the `bundle` is an array, this input is ignored. Default: 100.
Weights for each node in each streamline, calculated as its relative inverse of the Mahalanobis distance, relative to the distribution of coordinates at that node position across streamlines.
dipy.stats.analysis.
mahalanobis(u, v, VI)
Compute the Mahalanobis distance between two 1-D arrays.
The Mahalanobis distance between 1-D arrays u and v, is defined as
where
V is the covariance matrix. Note that the argument VI
is the inverse of
V.
Input array.
Input array.
The inverse of the covariance matrix.
The Mahalanobis distance between vectors u and v.
Examples
>>> from scipy.spatial import distance >>> iv = [[1, 0.5, 0.5], [0.5, 1, 0.5], [0.5, 0.5, 1]] >>> distance.mahalanobis([1, 0, 0], [0, 1, 0], iv) 1.0 >>> distance.mahalanobis([0, 2, 0], [0, 1, 0], iv) 1.0 >>> distance.mahalanobis([2, 0, 0], [0, 1, 0], iv) 1.7320508075688772
dipy.stats.analysis.
map_coordinates(input, coordinates, output=None, order=3, mode='constant', cval=0.0, prefilter=True).
The input array.
The coordinates at which input is evaluated.
The array in which to place the output, or the dtype of the returned array. By default an array of the same dtype as input will be created.
The order of the spline interpolation, default is 3. The order has to be in the range 0-5.
The mode parameter determines how the input array is extended beyond its boundaries. Default is ‘constant’. Behavior for each valid value is as follows:
The input is extended by reflecting about the edge of the last pixel.
The input is extended by filling all values beyond the edge with the same constant value, defined by the cval parameter.
The input is extended by replicating the last pixel.
The input is extended by reflecting about the center of the last pixel.
The input is extended by wrapping around to the opposite edge.
Value to fill past edges of input if mode is ‘constant’. Default is 0.0.)
dipy.stats.analysis.
optional_package(name, trip_msg=None)
Return package-like thing and module setup for package name
package name
message to give when someone tries to use the return package, but we could not import it, and have returned a TripWire object instead. Default message if None.
TripWireinstance
If we can import the package, return it. Otherwise return an object raising an error when accessed
True if import for package was successful, false otherwise
callable usually set as
setup_module in calling namespace, to allow
skipping tests.
Examples
Typical use would be something like this at the top of a module using an optional package:
>>> from dipy.utils.optpkg import optional_package >>> pkg, have_pkg, setup_module = optional_package('not_a_package')
Of course in this case the package doesn’t exist, and so, in the module:
>>> have_pkg False
and
>>> pkg.some_function() Traceback (most recent call last): ... TripWireError: We need package not_a_package for these functions, but ``import not_a_package`` raised an ImportError
If the module does exist - we get the module
>>> pkg, _, _ = optional_package('os') >>> hasattr(pkg, 'path') True
Or a submodule if that’s what we asked for
>>> subpkg, _, _ = optional_package('os.path') >>> hasattr(subpkg, 'dirname') True
dipy.stats.analysis.
orient_by_streamline(streamlines, standard, n_points=12, in_place=False, as_generator=False)
Orient a bundle of streamlines to a standard streamline.
The input streamlines to orient.
This provides the standard orientation according to which the streamlines in the provided bundle should be reoriented.
The number of samples to apply to each of the streamlines.
Whether to make the change in-place in the original input (and return a reference), or to make a copy of the list and return this copy, with the relevant streamlines reoriented. Default: False.
Whether to return a generator as output. Default: False
possible to the standard.
dipy.stats.analysis.
peak_values(bundle, peaks, dt, pname, bname, subject, group_id, ind, dir)
and quantitative anisotropy (qa) values from peaks object (eg: csa) for every point on a streamline used while tracking and saves it in hd5 file.
Name of bundle being analyzed
contains peak directions and values
DataFrame to be populated
Name of the dti metric
Name of bundle being analyzed.
subject number as a string (e.g. 10001)
which group subject belongs to 1 patient and 0 for control
ind tells which disk number a point belong.
path of output directory
dipy.stats.analysis.
save_buan_profiles_hdf5(fname, dt)
Saves the given input dataframe to .h5 file
file name for saving the hdf5 file
DataFrame to be saved as .h5 file
dipy.stats.analysis.
set_number_of_points()
(either by downsampling or upsampling)
Change the number of points of streamlines in order to obtain nb_points-1 segments of equal length. Points of streamlines will be modified along the curve.
dipy.tracking.Streamlines
If ndarray, must have shape (N,3) where N is the number of points
of the streamline.
If list, each item must be ndarray shape (Ni,3) where Ni is the number
of points of streamline i.
If
dipy.tracking.Streamlines, its common_shape must be 3.
integer representing number of points wanted along the curve.
dipy.tracking.Streamlines
Results of the downsampling or upsampling process.
Examples
>>> from dipy.tracking.streamline import set_number_of_points >>> import numpy as np
One streamline, a semi-circle:
>>> theta = np.pi*np.linspace(0, 1, 100) >>> x = np.cos(theta) >>> y = np.sin(theta) >>> z = 0 * x >>> streamline = np.vstack((x, y, z)).T >>> modified_streamline = set_number_of_points(streamline, 3) >>> len(modified_streamline) 3
Multiple streamlines:
>>> streamlines = [streamline, streamline[::2]] >>> new_streamlines = set_number_of_points(streamlines, 10) >>> [len(s) for s in streamlines] [100, 50] >>> [len(s) for s in new_streamlines] [10, 10]
dipy.stats.analysis.
transform_streamlines(streamlines, mat, in_place=False)
Apply affine transformation to streamlines
Streamlines object
transformation matrix
If True then change data in place. Be careful changes input streamlines.
Sequence transformed 2D ndarrays of shape[-1]==3
dipy.stats.analysis.
values_from_volume(data, streamlines, affine)
Extract values of a scalar/vector along each streamline from a volume.
Scalar (for 3D) and vector (for 4D) values to be extracted. For 4D data, interpolation will be done on the 3 spatial dimensions in each volume.
If array, of shape (n_streamlines, n_nodes, 3) If list, len(n_streamlines) with (n_nodes, 3) array in each element of the list.
The mapping from voxel coordinates to streamline points. The voxel_to_rasmm matrix, typically from a NIFTI file.
coordinate along the length of each streamline.
Notes
Values are extracted from the image based on the 3D coordinates of the nodes that comprise the points in the streamline, without any interpolation into segments between the nodes. Using this function with streamlines that have been resampled into a very small number of nodes will result in very few values. | https://dipy.org/documentation/1.4.1./reference/dipy.stats/ | CC-MAIN-2021-25 | refinedweb | 3,468 | 59.7 |
In this problem, we are given an element N. We need to find the next palindrome prime.
Problem Description − We need to find the smallest prime number which is also a palindrome number, greater than N.
Palindrome Number is a number in which the numbers are the same in both directions.
Prime Number is a number if its only factors are 1 and itself.
Let’s take an example to understand the problem,
N = 12
101
The series of palindromes greater than 12 are 22, 33, 44, 55, 66, 77, 88, 99, 101… out of these the smallest palindrome is 101.
A simple solution to the problem is by finding all palindromes greater than N that are primes.
A more efficient solution is by finding the even digit palindrome which is multiple of 11.
Here is a proof of this solution,
11% 11 = 0 1111% 11 = 0
Using this we will find palindrome with even digits −
xyzzyx % 11 = 0, which makes all even number digits not palindrome.
Program to illustrate the working of our solution,
#include <iostream> #include <string> using namespace std; bool isPrime(int num) { if (num < 2 || num % 2 == 0) return num == 2; for (int i = 3; i * i <= num; i += 2) if (num % i == 0) return false; return true; } int primePalindrome(int N) { if (8 <= N && N <= 11) return 11; for (int x = 1; x < 100000; ++x) { string s = to_string(x), r(s.rbegin(), s.rend()); int y = stoi(s + r.substr(1)); if (y >= N && isPrime(y)) return y; } return -1; } int main() { int N = 432; cout<<"The next prime palindrome is "<<findNextPrimePallindrome(432); return 0; }
The next number with same set of digits is 92543 | https://www.tutorialspoint.com/find-next-palindrome-prime-in-cplusplus | CC-MAIN-2021-25 | refinedweb | 280 | 74.22 |
.
Components are loaded using the load_components() method within your DBIx::Class classes.
package My::Thing; use base qw( DBIx::Class::Core ); __PACKAGE__->load_components(qw/InflateColumn::DateTime TimeStamp/);
Generally you do not want to specify the full package name of a component, instead take off the DBIx::Class:: part of it and just include the rest. If you do want to load a component outside of the normal namespace you can do so by prepending the component name with a +.
__PACKAGE__->load_components(qw/ +My::Component /);
Once a component is loaded all of it's methods, or otherwise, that it provides will be available in your class.
The order in which is you load the components may be very important, depending on the component. If you are not sure, then read the docs for the components you are using and see if they mention anything about the order in which you should load them. DBIx::Class::Row and others. For example, you could override the insert and delete methods.
sub insert { my $self = shift; # Do stuff with $self, like set default values. return $self->next::method( @_ ); } sub delete { my $self = shift; # Do stuff with $self. return $self->next::method( @_ ); }
Now, the order that a component is loaded is very important. Components that are loaded first are the first ones in the inheritance stack. So, if you override insert() but the DBIx::Class::Row component is loaded first then your insert() will never be called, since the DBIx::Class::Row insert() will be called first. If you are unsure as to why a given method is not being called try printing out the Class::C3 inheritance stack.
print join ', ' => Class::C3::calculateMRO('YourClass::Name');
These components provide extra functionality beyond basic functionality that you can't live without.
DBIx::Class::Serialize::Storable - Hooks for Storable freeze/thaw.::UTF8Columns - Force UTF8 (Unicode) flag on columns.> | http://search.cpan.org/~frew/DBIx-Class-0.08123/lib/DBIx/Class/Manual/Component.pod | CC-MAIN-2013-48 | refinedweb | 313 | 54.83 |
" ); } } }
Do you happen to have an example that uses a TimePicker? I’m trying to implement a solution where the background color of the field is set to red if a start time is set through a picker that is later than the end time. We have a DateSelected public event for a DatePicker, but do we have a TimeSelected event for a TimePicker, of course not. So we have to implement it via the property changed event. I can’t seem to get the event handler to respond even though I use RaisePropertyChanged() on the property within the ViewModel.
Hi Jesse,
Thanks for your job, i have a question, how to use inotifyproperty change in an object
for exmaple:
I have a simple class,
public class Employe:INotifyPropertyChanged
{
public string Name {get; set;}
public string Surname {get; set}
}
And i have a viewmodel class
public class viewModel:InotifyPropertyChange
{
private Employe_employe;
public Employe Employe
{
get { return _employe; }
set
{
_employe= value;
RaisePropertyChanged();
}
}
private void RaisePropertyChanged(
[CallerMemberName] string caller = “” )
{
if (PropertyChanged != null)
{
PropertyChanged( this, new PropertyChangedEventArgs( caller ) );
}
}
}
And the xaml
¿I’m absolutely wrong or can be done? ¿how please?
Thank you very much!
Pingback: Organizing Business and Presentation entities | Asking
Appreciate this post. ʟet me trry it οut.
Wow, this paragraph iѕ pleasant, mу sister is analyzing tɦese things, tɦerefore Ι am going to
let know her.
This page hangs in Safari and Chrome!
It hangs in Firefox too with an error that the javascript times out and the option to wait, cancel or debug…
Pingback: Organizing Business and Presentation entities | DL-UAT
Your style is so unique in comparison to
other folkks I’ve rdad stuff from. Many thanks for
posting when you have tthe opportunity, Guess I will just book mark this page.
Feeel free too visit my webpage; offering; scatter.dpi.me, | http://jesseliberty.com/2012/06/28/c-5making-inotifypropertychanged-easier/ | CC-MAIN-2017-04 | refinedweb | 304 | 59.94 |
Peer Meshes
A mesh is a named collection (an interconnected graph) of peer nodes that can communicate among themselves and that are identified by a unique mesh ID. Each node is connected to multiple other nodes. In a well-connected mesh, there is a path between any two nodes, with relatively few hops between the nodes on the furthest edges of the mesh, and the mesh will remain connected even if some nodes or connections drop out. Active nodes in the mesh publish their endpoint information with a corresponding mesh ID so that other peers can find them.
A unique ID identifies each mesh. The name of the mesh (or mesh ID) is in the same format as a Domain Name System (DNS) host name. As such, this mesh ID must be unique for the intended client of the application within the scope of the resolver being used. A common name such as "MyFamilysPeers" or "KevinsPokerTable," may easily collide with other user names and may return unintended peer endpoint information, which could result in privacy issues or increase connection latency. One way to avoid these issues may be to add a unique ID as a postfix to the nickname for the mesh (for example, "KevinsPokerTable90210").
The mesh allows messages to be propagated from one or more senders to all other peer nodes in the same mesh. Messages flooded by peer nodes use headers specified in the namespace at.
A Peer Channel mesh automatically adjusts when nodes join and leave, ensuring that all nodes have good connectivity with little chance of creating partitions (groups of nodes isolated from each other). Connections in the mesh are also dynamically optimized based on current traffic patterns so that message latency from sender to receiver is as small as possible.
It is important to be aware of popular network features that Peer Channel does not provide. These features, which may all be built on top of Peer Channel, include the following:
Message ordering: Messages originating from a single source may not arrive at all other parties in the same order or in the order that the source sent. Applications that require messages be delivered in a certain order must build it into their applications (for example, by including a monotonically increasing ID with all messages).
Reliable messaging: Peer Channel does not include a mechanism to ensure message reception by all peers. To guarantee message delivery, you must write a reliability layer on top of Peer Channel. | https://msdn.microsoft.com/en-us/library/ms734692.aspx | CC-MAIN-2016-07 | refinedweb | 411 | 56.79 |
Key ideas: Smoothing, NHANES data
This notebook demonstrates the scatterplot smoothing capabilities of Statsmodels using data from the National Health and Nutrition Examination Study (NHANES).
The function that implements smoothing is called
lowess and is located in
statsmodels.nonparametric.smoothers_lowess. First we import lowess and some other modules that we will need. Note that the xport module is needed to load the SAS xport format files that we will be using (the NHANES data are distributed in this format). This is a nonstandard library so you may need to install it before continuing.
import xport import numpy as np import pandas as pd import StringIO import urllib2 from statsmodels.nonparametric.smoothers_lowess import lowess import matplotlib.pyplot as plt
The following function downloads an XPORT format data file from a URL and returns it as a Pandas data frame. The raw XPORT data is first stored as a list of dictionaries, with each dictionary mapping variable names to data values for one subject. The variable named "SEQN" is the unique subject id, so we pop that out and use it as the index in our data frame.
def read_xport_from_url(urlname): url = urllib2.urlopen(urlname) zdata = url.read() sio = StringIO.StringIO(zdata) with xport.XportReader(sio) as reader: Z = [row for row in reader] Ix = [z.pop("SEQN") for z in Z] data = pd.DataFrame(Z, index=Ix) return data
Next we use this function to obtain the demographic and body measurement data. These are (mostly) different variables measured on (mostly) the same subjects.
urlname = "" demo = read_xport_from_url(urlname) urlname = "" bmx = read_xport_from_url(urlname)
We want to merge these files, but there are some variable name clashes in the two data sets, so we augment each variable name with the file name.
demo.columns = ["DEMO:" + x for x in demo.columns] bmx.columns = ["BMX:" + x for x in bmx.columns]
Now we can do the merge:
data = pd.concat((demo, bmx), axis=1)
First we'll make a scatterplot showing BMI as a function of age, restricting to adults (since the BMI changes very rapidly for children). Note that this is a cross-sectional data set, so the changes with respect to age could be partially attributable to birth cohort effects.
ii = data["DEMO:RIDAGEYR"] >= 18 L = lowess(data.loc[ii, "BMX:BMXBMI"], data.loc[ii, "DEMO:RIDAGEYR"]) plt.plot(L[:,0], L[:,1], '-', lw=4, color='orange') plt.xlabel("Age", size=14) plt.ylabel("BMI", size=14) plt.xlim(15, 85) plt.gca().set_xticks(range(20, 81, 10))
[<matplotlib.axis.XTick at 0x51ec250>, <matplotlib.axis.XTick at 0x4e1aa10>, <matplotlib.axis.XTick at 0x4e221d0>, <matplotlib.axis.XTick at 0x4e2ff50>, <matplotlib.axis.XTick at 0x4e2fd50>, <matplotlib.axis.XTick at 0x51db450>, <matplotlib.axis.XTick at 0x51dbcd0>]
lowess has a parameter called "frac" that determines the smoothness of the fitted curve. It defaults to 0.66, but you can reduce it to get a less smooth curve (less bias, more variance), and you can increase it to get a smoother curve (more bias, less variance). Setting frac=0.1 is clearly too small:
ii = data["DEMO:RIDAGEYR"] >= 18 L = lowess(data["BMX:BMXBMI"][ii], data["DEMO:RIDAGEYR"][ii], frac=0.1) plt.plot(L[:,0], L[:,1], '-') plt.xlabel("Age") plt.ylabel("BMI")
<matplotlib.text.Text at 0x4193890>
It is also useful to know how much data are available in different parts of the domain. Note that the ages are truncated at 80, so if a person is over 80 years old, the age is reported as 80.
plt.clf() plt.hist(np.asarray(data["DEMO:RIDAGEYR"]), color='orange', alpha=0.7) plt.xlabel("Age", size=14) plt.ylabel("Frequency", size=14)
<matplotlib.text.Text at 0x541db90>
Next we do the smoothing analysis again, now startifying by gender.
i1 = (data["DEMO:RIDAGEYR"] >= 18) & (data["DEMO:RIAGENDR"] == 1) i2 = (data["DEMO:RIDAGEYR"] >= 18) & (data["DEMO:RIAGENDR"] == 2) L1 = lowess(data["BMX:BMXBMI"][i1], data["DEMO:RIDAGEYR"][i1]) L2 = lowess(data["BMX:BMXBMI"][i2], data["DEMO:RIDAGEYR"][i2]) plt.plot(L1[:,0], L1[:,1], '-', label="Male", lw=4, alpha=0.7, color='orange') plt.plot(L2[:,0], L2[:,1], '-', label="Female", lw=4, alpha=0.7, color='purple') leg = plt.legend(loc="upper left") leg.draw_frame(False) plt.xlabel("Age", size=14) plt.ylabel("BMI", size=14) plt.xlim(10, 90) plt.ylim(24, 30)
(24, 30) | http://nbviewer.jupyter.org/urls/umich.box.com/shared/static/uu936njshiti7ymdh0dp.ipynb | CC-MAIN-2018-05 | refinedweb | 718 | 62.04 |
C++ Program to Display Prime Numbers Between Two Intervals
Grammarly
In this post you will learn how to Display Prime Numbers Between Two Intervals
This lesson will teach you how to display Prime Numbers between two intervals, with a for loop, logical operator and decision making statement using the C++ Language. Let’s look at the below source code.
How to Display Prime Numbers Between Two Intervals?
Source Code
#include <iostream> using namespace std; int main() { int a, b, i, j, flag; cin >> a; cout << "Enter lower bound of the interval: "<<a; cin >> b; cout << "\nEnter upper bound of the interval: "<<b<<endl; cout << "\nPrime numbers between " << a << " and " << b << " are: "; for (i = a; i <= b; i++) { if (i == 1 || i == 0) continue; flag = 1; for (j = 2; j <= i / 2; ++j) { if (i % j == 0) { flag = 0; break; } } if (flag == 1) cout << i << " "; } return 0; }
Input
10 15
Output
Enter lower bound of the interval: 10 Enter upper bound of the interval: 15 Prime numbers between 10 and 15 are: 11 13
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 a, b, i, j, flag an integers and collect the initial and final number; the upeer bound and lower bound from the user and store it in the a and b respectively using function
cin>>and display the value using
cout<<and the Insertion Operators'<<‘ , ‘>>’.
- Create a for loop with the condition
(i = a; i <= b; i++), and then we create the loop statement.
- Using the decision making if else statements we declare the condition to be verified. In the condition the logical operator OR is used. When both or any one of the sides of the conditions is true then the if condition is true, or it is false.
- The continue statement is used to force the loop to continue, if the if condition is true, the next iteration is executed if not it moves to the next statement.
- Create a for loop with the condition
(j = 2; j <= i / 2; ++j), and then we create the loop statement which includes an if statement with a condition to be verified.
- When the condition is verified the body of the if statement is executed. Finally we add another if statement with a condition to be verified. | https://developerpublish.com/academy/courses/c-programming-examples-2/lessons/c-program-to-display-prime-numbers-between-two-intervals/ | CC-MAIN-2021-49 | refinedweb | 407 | 59.37 |
None
0 Points
Jun 26, 2017 11:09 PM|DanielRail|LINK
Hi,
I'm trying to develop a WebAPI that will be self-hosted using OWIN, that will be running within a Windows service. For those interested, we chose this deployment for easier installation at our customers sites. This is the first time I'm trying to implement a self-hosted solution.
I was getting the following type of error:
{"Message":"No HTTP resource was found that matches the request URI ''.","MessageDetail":"No type was found that matches the controller named 'HelloWorld'."}
So, I thought lets make a simpler project with a simple console application. But, I'm getting the same error.
I'm currently using Visual Studio 2017, .Net Framework 4.6.2, Microsoft.AspNet.WebApi.OwinSelfHost(and dependent NuGet packages).
Here's the code, that I'm using for testing:
using Microsoft.Owin.Hosting; using Owin; using System; using System.Web.Http; namespace FiloptoServer { class Program { public static void Main(string[] args) { WebApp.Start<StartOwin>(""); Console.ReadLine(); } public class StartOwin { public void Configuration(IAppBuilder appBuilder) { var config = new HttpConfiguration(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); appBuilder.UseWebApi(config); } } public class HelloWorldController : ApiController { public string Get() { return "Hello, World!"; } } } }
Any help would be appreciated.
Jun 27, 2017 05:52 AM|zxj|LINK
Hi DanielRail,
You can modify like this.
string baseAddress = ""; // Start OWIN host using (WebApp.Start<StartOwin>(url: baseAddress)) { // Create HttpCient and make a request to api/values HttpClient client = new HttpClient(); var response = client.GetAsync(baseAddress + "api/HelloWorld").Result; Console.WriteLine(response); Console.WriteLine(response.Content.ReadAsStringAsync().Result); Console.ReadLine(); }
Regards,
zxj
None
0 Points
Jun 27, 2017 07:29 PM|DanielRail|LINK
Thanks for the information.
I noticed what my error was. I had the ApiController class declared inside the program class. Once it was outside the program class, it worked as expected. It still didn't help me with the Windows Service project, which was still giving me that error and the ApiController class was defined in it's own .cs file. Anyway, I did find the TopShelf library that did permit me to transform the console application into a Windows Service application. So, now I have a self-hosted Owin Web API running inside a Windows service, which was what I wanted.
2 replies
Last post Jun 27, 2017 07:29 PM by DanielRail | https://forums.asp.net/t/2124105.aspx?WebAPI+OWIN+Self+Hosted+Problem | CC-MAIN-2019-18 | refinedweb | 398 | 50.84 |
iulio Vannini21,922 Points
I can't figure out why this Equals override doesn't work
I believe that this should be working. However it says that the Equals has no virtual/override in its class (which is really weird!) Any idea about what it could be wrong?
using System; namespace Treehouse.CodeChallenges { public class VocabularyWord { public string Word { get; private set; } public VocabularyWord(string word) { Word = word; } public override string ToString() { return Word; } public override bool Equals(System.Object w1, System.Object w2) { return this.Word == w2.Word; } } }
2 Answers
andren28,524 Points
There are multiple issues, first of all the error is technically correct, the method you are trying to override does not exists, you are creating an equals method that takes in two objects, the equals method you inherit from Object only takes one argument, which means they are technically not the same method.
Since the equals method compares the object itself against another object it does not need both of the objects passed in, and in fact you don't even use the w1 argument you created in your own code.
The second issue is that when the object gets passed in to the method it is just that, only an object, it has not been cast to VocabularyWord, which it needs to be in order to access any of the VocabularyWord properties like Word.
The third issue is the fact that you do not check to see if the object is in fact a VocabularyWord object, and not some other object entirely or just null for that matter.
Here is the corrected code with some comments added for clarity:
using System; namespace Treehouse.CodeChallenges { public class VocabularyWord { public string Word { get; private set; } public VocabularyWord(string word) { Word = word; } public override string ToString() { return Word; } public override bool Equals(System.Object obj) { // returns false if the passed in object is not a VocabularyWord if (!(obj is VocabularyWord)) { return false; } // Now that we know the object is a VocabularyWord // We can safely cast it as such VocabularyWord word2 = obj as VocabularyWord; // Then we can compare this objects Word with the passed in objects Word return this.Word == word2.Word; } } }
Alexander Davison65,454 Points
Instead of saying
return this.Word == w2.Word;
Try this instead:
return Word == w2.Word;
This isn't JavaScript! lol
Hope this helps! ~Alex
Giulio Vannini21,922 Points
Giulio Vannini21,922 Points
I still get: VocabularyWord.cs(18,30): error CS0506:
Treehouse.CodeChallenges.VocabularyWord.Equals(object, object)': cannot override inherited memberobject.Equals(object, object)' because it is not marked virtual, abstract or override /usr/lib/mono/4.5/mscorlib.dll (Location of the symbol related to previous error) Compilation failed: 1 error(s), 0 warnings | https://teamtreehouse.com/community/i-cant-figure-out-why-this-equals-override-doesnt-work | CC-MAIN-2022-40 | refinedweb | 452 | 54.12 |
A code-completion engine for Vim
python3 install.py --clangd-completer
:YcmDebugInfoshows "Server has Clang support compiled in: False" and "Clangd running", so I guess the C-family completer is correctly set to clangd-completer.
bearbut that probably won't work anymore
Sometimes, after some hour of coding, in which I've certainly mashed TAB, I find out some file containing
#include <bits/stdc++.h>, which means that some TAB-completion triggered that. Since I discover this after a long time coding, typically when qualifying the change, I don't know which completion trigger that. Any idea which could it be? Plus, shouldn't that header be avoided, in general?
I've created this: | https://gitter.im/Valloric/YouCompleteMe?at=601132b70eed905f1873856a | CC-MAIN-2022-05 | refinedweb | 114 | 58.69 |
.
Getting this working was really quite simple, and it's something that I can see being useful for SAAS projects - just take a look at the 37signals projects such as Basecamp and the way they handle per-company logins: each company has it's own subdomain.
The first thing that needs to be done is server configuration. Your domain name needs to have a wildcard entry setup (eg *.yourdomain.com), using Bind9 this is as easy as adding the following line to your domain name config. For other setups, speak to your web hosting provider.
* CNAME yourdomain.com.
Next, configure your web server software to answer requests for *.yourdomain.com the same way as. I'm assuming that already works, and that you're using Apache - again, YMMV so speak to your hosting provider. In Apache, just add the following line to your yourdomain.com virtual host configuration:
ServerAlias *.yourdomain.com
After restarting your DNS & web server software, you'll find that going to shows up the same result as. Perfect.
Lastly you need to configure Django to treat subdomains differently. In this case I'm making another assumption, that Django is handling requests for yourdomain.com, and that there is a view already in place (eg via urls.py) for handling requests for the root of the domain. I'm also assuming content for your "main page" (eg, anything that's not a subdomain) is handled by other views, and that your main page is under /mypage/.
My 'index' view therefore looks like this:
def index(request): django_site = Site.objects.get_current() if request.META['HTTP_HOST'] == django_site.domain: # The visitor has hit the main webpage, so redirect to /mypage/ return HttpResponseRedirect('/mypage/') # Split the domain into it's parts, remove the main part of the domain # from the requested host, and we're left with one variable: 'subdomain'. # We also strip out the 'www.' non web-savvy users often type 'www' in # front of every website they visit, so let's not show them an error message! domain_parts = django_site.domain.split(".") domain = ".".join(domain_parts[1:]) subdomain = request.META['HTTP_HOST'].replace(domain, '').replace('.', '').replace('www', '') # You can now access your data models using 'subdomain', eg: couple = Couple.objects.get(subdomain=subdomain)
You can see I'm referring to a model called Couple, with a field named 'Subdomain'. All you need to do is refer to your own model with a 'subdomain' key and you're in business - just remember to enforce unique subdomains at signup time! Lastly, ensure your current Django 'Site' entry (django.contrib.sites) is up to date with the domain set to ''.
From here you can customise what's shown to the visitor based off of the subdomain they've hit. Very easy to setup, and potentially very powerful - especially in environments where people need something as easy as possible to remember or as unique as possible.. | http://www.rossp.org/blog/2007/apr/28/using-subdomains-django/ | CC-MAIN-2014-15 | refinedweb | 479 | 56.35 |
This […]
The post Self-service messaging with Red Hat AMQ Online and GitOps appeared first on Red Hat Developer Blog.]]>.
GitOps is a way to do Continuous Delivery (CD) where the source code and all configuration of an application is stored in Git. Changes to a production environment involve creating a pull/change request to a Git repository. Once the pull request .
Managing an AMQ Online installation in Git can be as simple as unpacking the release bundle and committing the parts that is used for a particular installation. Additionally, the desired messaging configuration and available plans can be created. This configuration contains instances of the following resource types: control how much resources that are consumed by developer teams. Requirements such as “never spin up more than two brokers” and “allow max 1000 addresses” can be implemented using plans. Plans are offered at two levels, for the address spaces, and for the addresses..
The development teams can use the same workflow as the operations team, but they do not need to care about the underlying messaging infrastructure. All the underlying components, such as AMQ Interconnect and AMQ Broker, are all hidden behind the address space abstraction.); // Initiate the connection.
Once your application is written, some configuration for using the messaging resources available on
your cluster is needed.
An AMQ Online the amount of resources reserved for this address. An address can be defined like this:
apiVersion: enmasse.io/v1beta1 kind: Address metadata: name: app.orders namespace: team1 spec: address: orders type: queue plan: small-queue
To ensure that only trusted applications are able to send and receive messages to your addresses, a messaging user must be created. For applications running on-cluster, you can authenticate clients using an OpenShift three resources, you have the basics needed for an application to use the messaging service.: amq-online-infra.
We have seen how an operations team and a set of development teams can manage messaging as Red Hat OpenShift manifests. This allows your whole organization to follow the GitOps model when deploying your applications using messaging on OpenShift.
The post Self-service messaging with Red Hat AMQ Online and GitOps […]
The post Use the Kubernetes Python client from your running Red Hat OpenShift pods your fingertips.
The Kubernetes Python client is another great tool for interacting with an OpenShift cluster, allowing you to perform actions on Kubernetes resources with Python code. It also has applications within a cluster. We can configure a Python application running on OpenShift to consume the OpenShift API, and list and create resources. We could then create containerized batch jobs from the running application, or a custom service monitor, for example. It sounds a bit like “OpenShift inception,” using the OpenShift API from services created using the OpenShift API.
In this article, we’ll create a Flask application running on OpenShift. This application will use the Kubernetes Python client to interact with the OpenShift API, list other pods in the project, and display them back to the user.
You’ll need a couple of things to follow along:
Let’s get started!
I’ve created a template to alleviate a lot of the boilerplate, so let’s clone it down:
git clone cd openshift-client-demo
You can create a new app on your OpenShift cluster using the provided template and see the application running:
oc new-app openshift_deploy/ocd.yaml
If you do an
oc get routes, you’ll be able to see the route that’s been created. For now, if you select the Pods menu item you’ll just get some placeholder text. We’ll fix this shortly
Listing pods is trivial once we have our client configured, and, fortunately, we can use a little Kubernetes Python client magic to configure this easily with the correct service account token.
Usually, we’d configure a Kubernetes client using a kubeconfig file, which has the required token and hostname to create API requests. The Kubernetes Python client also provides a method
load_incluster_config(), which replaces the kubeconfig file in a running pod, instead using the available environment variables and mount points to find the service account token and build API URLs from the information available within the pod.
There’s another huge benefit to using
load_incluster_config()—our code is now portable. We can take this same application to any Kubernetes cluster, assume nothing about hostnames or network addresses, and easily construct API requests using this awesome little method.
Let’s configure our application to use the
load_incluster_config() method. First, we need to import the client and config objects, you can verify this in the
ocd.py file:
from kubernetes import client, config
We can now use that magic method to configure the client:
config.load_incluster_config() v1 = client.CoreV1Api()
That’s it! This is all of the code we need to be able to interact with the OpenShift API from running pods.
I’m going to introduce something new here, and yes, it’s another “OpenShift-inception” concept. We’re going to use the
list_namespaced_pod method to list pod details; you can find all of the methods available in the documentation. To use this method, we need to pass the current namespace (project) to the Kubernetes client object. But wait, how do we get the namespace for our pod, from inside the running pod?
This is where another awesome Kubernetes API comes into play. It’s called the Downward API and allows us to access metadata about our pod from inside the running pod. To expose information from the Downward API to our pod, we can use environment variables. If you look at the template, you’ll see the following in the ‘env’ section:
- name: POD_NAMESPACE valueFrom: fieldRef: apiVersion: v1 fieldPath: metadata.namespace
Now let’s get back to our
/pods route in the
ocd.py file. The last thing we need to do is to pass the namespace of the app to the Kubernetes client. We have our environment variable configured to use the downward API already, so let’s pass it in:
pods = v1.list_namespaced_pod(namespace=os.environ["POD_NAMESPACE"])
Ensure you’re in the top-level project directory (i.e., you can see the README) and start a build from the local directory:
oc start-build openshift-client-demo --from-dir=.
When you next visit the route and select the Pods menu, you’ll be able to see all of the pods for the current namespace:
I hope you’ve enjoyed this short introduction to the Kubernetes Python client. If you want to explore a little deeper, you can look at creating resources. There’s an example here that looks at creating containerized batch jobs from API POSTs.
The post Use the Kubernetes Python client from your running Red Hat OpenShift pods […]
The post Red Hat OpenShift 4, AWS, Windows, and a video to find out.
In late April, I published a somewhat popular article about creating a Red Hat OpenShift 4 cluster on AWS using Windows as your desktop operating system, despite that fact that the OpenShift installer (
openshift-install) runs on Linux or macOS, but not Windows.
For those who learn better by visual input—”visual learning” is the phrase—I’ve created a short video. It’s about four minutes and touches on the key points. Click here to watch the video and read the previous article.
Some things to note:
./openshift-install destroy cluster
Yes, by all means. If you’re, say, a .NET developer and want to learn about, play with, or start using Linux container technology, don’t count yourself out.
The move from .NET Framework to .NET Core is a small step—not a giant leap—and you can leverage your existing developer skills immediately. You do not need to learn a ton of Linux skills and commands and jargon; you can get started immediately.
Here’s to the future and your success.
The post Red Hat OpenShift 4, AWS, Windows, and a video. OpenShift Workshops Build your own Kubernetes Operator Tuesday, May 7, 9:00 a.m.-11:00 a.m. Jorge Morales, Michael […]
The post OpenShift workshops and breakout sessions at Red Hat Summit.
Thursday, May 9, 10:45 a.m.-12:45 p.m.
Jan Kleinert, Jorge Morales, Graham Dumpleton
Instructor-led lab.
Track: Cloud-native app dev
Topics: Application development, Application platforms, Containers
Products & services: Red Hat OpenShift Container Platform
Technical difficulty: Deep dive
The post OpenShift workshops and breakout sessions at Red Hat Summit […]
The post Announcing odo: Developer-focused CLI for Red Hat OpenShift. This article provides an overview of odo’s functionality.
We have created odo.
Red Hat OpenShift is an on-premise platform built around containers and on top of Kubernetes, providing developers with a user interface and command line to deploy their applications. OpenShift automates the build, deployment, and management of all applications so you can focus on what matters most: code.
When first developing applications on Red Hat OpenShift, developers typically accomplish their tasks in this order:
ocor OpenShift Console to deploy their application.
Odo automates the workflow by combining steps 2 through 6.
odo create.
odo push. This can either be source code or binary data.
odo watch.
The following is a demonstration on deploying an example Node.js application to a Red Hat OpenShift cluster:
Asciilink:
At Red Hat Summit, you can attend the “Put the dev back in DevOps: Cloud-native at local speed” breakout session, on Tuesday, May 7 at 3:45 p.m., where Jorge Morales will walk you through some of the drivers of odo, talk about other competing tools, and show it in action.
If you prefer a deep dive workshop, Jan Kleinert will lead “Developing applications on Red Hat OpenShift as mere mortals” on Thursday, May 9 at 10:45 a.m., a two-hour hands-on workshop introducing odo in more depth.
“Easing application development on OpenShift with odo” by Jorge Morales Pou
If you haven’t registered for Red Hat Summit yet, sign up now to attend. See you in Boston!
The post Announcing odo: Developer-focused CLI for Red Hat OpenShift, […]
The post Easing application development on Red Hat OpenShift with odo, but the key ones involve complexity and speed. In this article, I’ll explain further and provide an introduction to the odo command-line tool.
As a Java developer, one of the things that I’ve done for a long time has been to build using Maven. triggered a restart of my runtime or just a reload if the integration with the runtime allowed for such fanciness.
It took me a long time to get used to Maven, but once I knew (more or less) how to use it, it was pretty cool. I could share my source code, with a pom.xml file to any of my colleagues, and they could build and test the application-forward also needed to create containers rather than applications, as these are the new artifacts. This posed a new challenge has the desired runtime your application would use.
OpenShift s2i is one of these mechanisms. Heroku and Cloud Foundry Buildpacks is another approach. As a Java developer, I think that these approaches work much better than dealing with a Dockerfile yourself.
Now, the platform you use to run your application can also build your application, as long as it can access the source code for it. But the process is slower than what you’re used to. And although slower can work sometimes—typically when for a long time. We need a fast inner development loop, that is, code, build, deploy, test, code, build, deploy, test, again and again. We don’t want to push our code to a Git server for the platform to build it, as this is a longer process. And, we have to consider whether we should commit code to a Git server if we and that also have the runtime for the application included and already running. We then only need to push the application to such containers. were hosting.
Here is an example:
As you can see, the process we went through is recognizable to you, even if you’re not an OpenShift or Kubernetes expert. How is that possible?
We decided to make the tool as user (a.k.a. developer) friendly as possible. We are aware that many users don’t fully understand all the complex constructs a platform like OpenShift or Kubernetes provides, and we wanted to make the tool simple and immediately familiar. So, we decided the language the tool was going to provide should be natural to developers.
Another important observation we embodied in the tool is that developers usually work on a single component (part of an application) at a time. So, while developers can have a quite complex application (consisting of multiple deployed components or services), they are only going to work through the inner development loop of one of these components at a time. Thus, the developer experience in mind and should be straightforward to use for most developers, regardless of the programming language. Developers no longer need to know the specifics of the platform where their application will be deployed and running.
This is just an introduction to a project we’re developing. It’s currently under heavy development and only community supported. It’s already in a working state, but not yet!
The post Easing application development on Red Hat OpenShift with odo […]
The post Get started with Jenkins CI/CD in Red Hat OpenShift 4 Red Hat OpenShift 4. I will not dive into a lot of details—and there are a lot of details—but we’ll get a good overview. The details will be explained later in this series of blog posts.
Note: In this post, I’ll sometimes refer to OpenShift 4 as OpenShift Container Platform (OCP).
It’s not enough to start an OCP cluster. We need to get Jenkins up and running. Fortunately, OCP has templates, an ever-growing selection of environments that you can get up and running with a simple point and click (or at the command line). This catalog of templates, however, is not readily apparent in the OCP dashboard.
In the following screen capture, you’ll notice that nine options are available:
Nine items. You will also notice that Jenkins is not an option. But what if it is an option? The developer’s friend—the command line—is where the catalog really springs to life. We can run the following command to see all of the templates that are included when we launch our OCP 4 cluster but are not visible on the dashboard:
oc get templates -n openshift
You’ll see a list that’s too long to show here—about 91 templates. As it stands, we can use them at the command line, and we will. A Template Service Broker is used to make them appear on the dashboard, but that’s another article. For now, we’ll use the command line.
If you look through the list, you’ll find two templates for Jenkins:
Because we don’t have persistent storage configured (that’s yet another article), we’ll use the “Jenkins-ephemeral” template for this article. The fundamentals are the same, and the knowledge is transferable, but this way we spend our time in this article on Jenkins and CI/CD and not on creating and configuring and using persistent storage.
Let’s start with the easy part: Getting Jenkins up and running inside our OCP 4 cluster. It’s one command:
oc new-app jenkins-ephemeral
You can now run the following command to get the URL to your Jenkins installation:
oc get routes
Put that URL (
jenkins-default.apps.jenkins.rhdemos.com) into your browser and voilà … Jenkins:
By the way, if you want to see the template that did all this work, you can view it by using the following command:
oc get template/jenkins-ephemeral -o json -n openshift
Go ahead and log in with OpenShift, and select the Allow Selected Permissions option. You’ll then be presented with your Jenkins dashboard:
That was the easy part. Now the real work begins. We need to set up a pipeline to build our software, but we want to use the build that is built into OpenShift. The following command will create a build configuration (or “build config,” which is an object of type “BuildConfig”), which has the instructions we give to OpenShift to tell it how to build our application. In this particular case, we’re creating a pipeline that, in turn, has the build instructions:
oc create -f
Don’t sweat the details for now; we’ll cover that in the next blog post. For this article, we simply want to see what’s possible and get the creative gears turning.
Want to see the pipeline? Use the following command:
oc get buildconfig/nodejs-sample-pipeline -o yaml
Note: This build example is using Node.js, and I did all the work using a Windows PC running PowerShell. Open source and platform independent—that’s the beauty of all this. That is, the
oc command works everywhere. Also; this example relies heavily on the OpenShift examples GitHub page.
At this point in Red Hat OpenShift, we have a build config for a pipeline. That’s it. We haven’t actually built anything yet; we just have a configuration of a pipeline. We can see this—the fact that we haven’t built anything—in two ways: We can look at the Builds section of the OpenShift dashboard, and we can view the Jenkins dashboard. In both of them, we do not see our pipeline—again, because we haven’t built the pipeline.
No builds in the OpenShift dashboard.
No pipelines (except the default which we should ignore).
By the way, if you look in the BuildConfig section of the OpenShift dashboard, you’ll see our build config sitting there like a rocket that’s ready for liftoff.
Now the magic happens. At the command line, we can run a command to see the name of the BuildConfig we want to build:
oc get buildconfigs
There it is. Let’s get this show on the road.
We can start the build and then, for fun, switch over to the Jenkins dashboard to watch it run. Even better, while in Jenkins, select the “Open Blue Ocean” option on the menu (on the left side) to view things in a nice, modern interface instead of the, uh, “classic” Jenkins UI. You’ll see the pipeline appear, from which you can follow the build. It may take a few seconds before it’s available in Jenkins.
Use this command to kick off all the action:
oc start-build nodejs-sample-pipeline
It’s alive.
The pipeline was built and the build was started. If you look in OpenShift, under Builds, you’ll see the two separate builds:
Based on a combination of knowledge and a hunch, I bet there’s a route for that “nodejs-mongodb-example” service. Running
oc get routes will confirm:
If I put that URL into a browser I should get:
BAM. It worked.
Note: See that “Deploying code changes” section in the image? You might want to play around with that (hint, hint).
Well, OpenShift and Jenkins did it. But we now have Jenkins building and deploying our solution.
There’s a lot more we can do. Tests? Manual deployments? Deployments to other environments (e.g., dev, testing, staging, and production). Other programming languages? Additionally, this Jenkins environment doesn’t have persistent storage—something we’ll likely want in a real-world scenario. And, we need to dive even deeper to see what’s going on and get a real understanding so we can build our own solutions.
There’s a lot more to come; watch this space for future articles.
The post Get started with Jenkins CI/CD in Red Hat OpenShift 4 […]
The post Automated migration from JBoss AMQ 6 to Red Hat AMQ 7 on Red Hat OpenShift.
There is a Red Hat AMQ 7 migration guide with the most important topics; however, how to do this on Red Hat OpenShift is not completely covered. From my field experience with customers, we defined an automated process to do it on OpenShift including:
Red Hat JBoss AMQ 6 (AMQ 6) provides a drainer pod, only available for persistent templates, which is responsible for managing the migration of messages. When AMQ 6 is deployed using a multi-node configuration, it is possible for messages to be left in the KahaDB store directory when the AMQ 6 cluster is scaled down. To prevent messages from remaining, the drainer pod will recover them and move them to other AMQ 6 pod instance. Behind the scenes, a network of brokers is established between the drainer pod and other AMQ 6 pods.
Red Hat AMQ 7 provides the same protocols that previous version. The drainer pod uses OpenWire protocol to move messages, so we will use it to move messages to the new Red Hat AMQ 7 broker.
We need to change the service selectors of each AMQ 6 protocol service (openwire, amqp, stomp, mqtt) to identify the new Red Hat AMQ 7 pod instances. When an AMQ 6 broker is scaled down (replicas = 0), the drainer pod will move the persisted messages.
This feature defines a very straight forward migration process as:
The migration process described above includes steps and checks, which are very easy to execute manually. However, it could be more difficult if you need to do this for each AMQ 6 broker deployed in Red Hat OpenShift. Ansible playbooks and Ansible roles can help you automate it easily.
I developed a simple Ansible playbook to migrate brokers using command module and OpenShift CLI. Of course, there are other alternatives to implement other approaches, such as, oc module, openshift_raw module, openshift module, etc.
This Ansible playbook sample is available in this GitHub repository.
This article shows how easy it is to migrate Red Hat JBoss AMQ 6 brokers to Red Hat AMQ 7 brokers on Red Hat OpenShift. Do not miss the opportunity to get the best improvements of Red Hat AMQ 7 in your Red Hat OpenShift deployments.
The post Automated migration from JBoss AMQ 6 to Red Hat AMQ 7. […]
The post Red Hat OpenShift 4.0 Developer Preview on AWS: Up and running with Windows.
The key to success is to embrace the Windows Subsystem for Linux (WSL). With this tool in hand, you can download and install the necessary bits to start up your Red Hat OpenShift 4.0 cluster on AWS, then switch over to PowerShell on Windows to log in and do your development. In my case, my code is written in C# and, although the WSL Linux that I used (Fedora Remix) does have vi installed, I want to do my work in Visual Studio Code. Windows is my comfort zone; why should I be forced to leave it? Besides, I know how to exit VS Code (**grin**).
Here is the plan, the TL;DR:
I strongly recommend reading the aforementioned article, “OpenShift 4.0 Developer Preview on AWS is up and running”, for some details that are not repeated here. Don’t worry if you don’t understand all the Linux commands; the important part is to know what steps need to happen.
The PowerShell command is:
Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Windows-Subsystem-Linux
Go to the Microsoft Store on your Windows PC and install the Linux distro of your choosing. For this article, I spent the five bucks and opted for the “Fedora Remix” distro. If you install a different distro, the package-related commands will differ (e.g., “yum” for Fedora versus “apt-get” for Ubuntu). The rest will be the same, however.
Install the distro and open a terminal window.
For this, follow the instructions at steps one and two on the Red Hat OpenShift 4.0 on AWS installation page.
The instructions from the developer preview are browser-based. That is, you visit a web page and click on a button to download the bits. We’re not going to use that. We’re going to use
wget instead to download the bits from the command line.
Use your distro’s package management tool to make sure
wget is installed. On my Fedora Remix distro, I had to run
sudo yum install -y wget.
Open your Windows browser of choice and visit the openshift installer releases web page. Right mouse-click on the link for “openshift-install-linux-amd64” and select the option to copy the link to your local clipboard. Then switch over to your Linux terminal window so you can paste in the link and run the command:
wget <paste-the-link-in-here>
You’ll see a few super-long URLs scroll by before you see the bits downloading to your Linux distro in your WSL.
Rename the downloaded bits with this command:
mv openshift-install-linux-amd64 openshift-install
Now, make it executable with this command:
chmod +x openshift-install
Now you have the OpenShift installer available on your Linux distro. You can take the steps needed to start your Red Hat OpenShift 4.0 cluster on AWS. If you followed the “Configure AWS” steps above, you’ll have the Access ID and key needed.
You can copy the Pull Secret from the installation page mentioned earlier as well.
The magic starts to happen when you use the following command in your Linux terminal:
./openshift-install create cluster
Be patient. I’ve had it take up to 24 minutes for a cluster to install. Don’t worry; it’s worth the wait.
When the installation is finished, your cluster will be up and running. You won’t be able to log in until the time, but you can go ahead and make sure the OpenShift command-line tool,
oc, is installed on your Windows PC. At your PowerShell command line, run:
choco install -y openshift-cli
Again, if you don’t have Chocolatey installed on your Windows machine, stop everything and get it immediately. It’s that good.
Here’s the part where you make the transition from Linux to Windows, which will allow you to run everything from your PowerShell command line—and from inside VS Code too, if you wish.
After the installation is finished and the cluster is up and running, a configuration file will be written to your Linux distro’s filesystem. The file is
/home/<your-username>/auth/kubeconfig. We need to copy this file to a location where we can read it from Windows PowerShell.
To date (April 2019), the WSL filesystem maps to the Windows filesystem as follows:
/mnt/c (Linux) maps to C:\ (Windows)
Note: Future versions of Windows 10 will make it much easier to share data files between WSL and Windows. For now, just to be safe, we’ll copy the configuration file.
So, we can create a directory—I did it off the root of my C: drive to keep it simple—and then use the Linux
cp(copy) command to get the config file over to Windows.
In PowerShell:
mkdir C:\ocp4aws
In Linux:
sudo cp /home/<username>/auth/kubeconfig /mnt/c/ocp4aws
Switch back to your PowerShell terminal and move the directory
C:\ocp4aws. A listing of the directory contents will show the file
kubeconfig, which is now available to your PowerShell session.
There’s just one more step before logging in.
In PowerShell, set the environment variable “KUBECONFIG” that points to your config file:
$env:KUBECONFIG="C:\ocp4aws\kubeconfig"
Up to this point, it’s been a winding path with a lot of steps just to be able to log in to an OpenShift 4.0 cluster on AWS. Here’s the good news: After this, you just need to do two steps: Set the
$env:KUBECONFIG environment variable and run
oc login.... That means, when you return to your PC tomorrow, you run two steps and, boom, you’re connected to your cluster.
In other words:
$env:KUBECONFIG="C:\ocp4aws\kubeconfig"
oc login -u kubeadmin -p <password-generated-during-cluster-install>
Simply run the command as instructed in your Linux terminal session. It should look like the following—with a different password.
oc login -u kubeadmin -p KSiVQ-gww7K-HEaiv-HNnfG
Keep this information. You’ll need it to log into your cluster again.
To create or destroy a cluster, use the
openshift-install command within your Linux distro terminal.
After creating a new cluster, you’ll have a new login password. It’ll be displayed in your Linux distro terminal after the cluster is created. Copy that to your clipboard to paste into PowerShell to log in from Windows.
Before you log in from Windows, make sure the
$env:KUBECONFIG is set.
That’s it. You can now create, use and destroy your Red Hat OpenShift 4.0 cluster on AWS from your Windows PC.
The post Red Hat OpenShift 4.0 Developer Preview on AWS: Up and running with Windows appeared first on Red Hat Developer Blog.]]> | https://developers.redhat.com/blog/category/openshift-cloud/feed/atom/ | CC-MAIN-2019-22 | refinedweb | 4,867 | 62.88 |
Opened 11 years ago
Closed 11 years ago
Last modified 11 years ago
#1205 closed defect (invalid)
PasswordField for secret input is missing and not easily self-madeable.
Description
There doesnt seem to be a thing like a PasswordField, or?
I found a formfield.PasswordField, but when I try to derive from CharField like this:
class PasswordField(meta.CharField):
def get_manipulator_field_objs(self):
return [formfields.PasswordField]
and want to use the resulting class, manage.py throws:
File "/usr/lib/python2.3/site-packages/django/core/management.py", line 75, in get_sql_create
col_type = db.DATA_TYPES[data_type]
KeyError: 'PasswordField'
Change History (2)
comment:1 Changed 11 years ago by
comment:2 Changed 11 years ago by
Milestone Version 0.91 deleted
Add this to your
PasswordField: | https://code.djangoproject.com/ticket/1205 | CC-MAIN-2017-22 | refinedweb | 123 | 52.66 |
Don’t Reinvent The Wheel! Use White-Label Web Components
Creating and maintaining high quality web components is hard work. You not only implement the crucial functionality but — for UI components — you also have to make it look nice.
And while reusability is one core aspect of web components, it’s most often bound to the design language used: Simple input fields based on Material Design or Fluent UI work like the other, but look different. You don’t want to implement the component twice, so wouldn’t it be nice to separate functionality and design?
Enter Lion, a collection of white-label web components, created by ING (aka ING Diba). The components are open-sourced and available on GitHub. For now Lion concentrates on form and navigation controls, as well as overlays and localization. But apart from buttons and inputs you can also find dialogs and even a calendar. Clearly, the web component collection is a byproduct of the ING development team.
|We recommend you to read the announcement blog post and browse the live Storybook
Browsing the live storybook the first obvious thing is: the components have no default styles; or better: they use the browsers default styles. It is almost like when you forget to include your CSS into a website. But that’s the point! The web components are fully functional, for example form controls can be labelled, prefilled, disabled, and validated. But they are not opinionated regarding design. Make use of them and your only task is to make them blend in.
Lion Web Components are based on lit-html / lit-element. Each component resides in a separate npm repository and can be imported as ES module. To apply CSS directives to a component — or to add functionality — you have to subclass it. Because the components use Shadow DOM, global styles are not applied automatically.
The examples in the Lion docs are bare minimum — based on the assumption that you have a suitable development environment ready. We will get into more detail here.
We will do the following:
1. Setup a development environment and install our dependencies
2. Extend a Lion component to apply some styling.
3. Create a bundle to use the styled component elsewhere
Setup a development environment and install our dependencies
Our base component will be the basic input. Create a new folder named white-label-web-components for our projects, run
npm init
and install the component with
npm i --save @lion/input
As a result, the node_modules contain quite a lot packages, several of them in the @lion subfolder (most importantly the input subfolder), as well as lit-html and lit-element as base classes of the Lion components.
Furthermore bootstrap an index.html.
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>White-Label Web Components</title>
</head>
<body><form>
<lion-input</lion-input>
</form><script type="module" src="main.js"></script>
</body>
</html>
Additionally setup a one-liner main.js looking like this:
import '@lion/input/lion-input.js';
When you open the index file using a simple web server like Pythons SimpleHTTPServer, PHP builtin server, or NodeJS lite-server, then you will see *nothing*. The paths used to load the ES module and it’s recursive dependencies cannot be resolved. We will have to setup a special dev server. You might be familiar with the LitElement dev environment, which will work perfectly. Alternatively you can use the es-dev-server by open-wc. You might have noticed “@open-wc” as a dependency of the Lion components in the node_modules. That is no coincidence as Lion and open-wc are (at least partly) backed by the same people. We will go with the lightweight option for now and use es-dev-server:
npm i —-save-dev es-dev-server
This will inflate your node_modules folder quite a bit, but thats okay. All additions have nothing to do with the Lion components. Add a script to the package.json to start the server in watch mode. Every change in the source files (directly or indirectly referenced by index.html) will cause the browser window to reload. Notice the node-resolve option that will fix the paths of referenced files on the fly:
{
"scripts": {
...
"serve": "es-dev-server --app-index index.html --node-resolve --watch --open" } }
}
Running npm run serve will open up a new browser window showing with our desired unstyled input. If you are interested, open the Network tab of your Dev Tools and preview the file named “LionInput.js”. Note that the path of
import { LionField } from '../../form-core/index.js';
differs from what you can see in the source file in the IDE:
import { LionField } from '@lion/form-core';
That’s what the es-dev-server is for.
Extend a Lion component to apply some styling
Now that we see the lion-input in the browser, let’s create a brushed up version. First subclass LionInput, the base class of lion-input web components: Create a file pretty-input.js on the top level of your project, next to index.html and main.js.
import { css } from 'lit-element';
import { LionInput } from '@lion/input';export class PrettyInput extends LionInput {static get styles() {
return [
super.styles,
css`:host{
font-family:Segoe UI WestEuropean,Segoe UI,
-apple-system,BlinkMacSystemFont,Roboto,Helvetica Neue,
sans-serif;
-webkit-font-smoothing:antialiased;
display: inline-block;
min-width:300px
}
::slotted(input:focus) {
border: 1px solid #33C3F0;
outline: 0;
} ::slotted(label) {
display: block;
margin-bottom: .5rem;
} ::slotted([slot=help-text]){
font-style: italic
} ::slotted(input) {
height: 38px;
padding: 6px 10px;
background-color: #fff;
border: 1px solid #D1D1D1;
border-radius: 4px;
box-shadow: none;
box-sizing: border-box;
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
}`
];
}}customElements.define('pretty-input', PrettyInput);
Within the pretty-input.js we create a the class PrettyInput as subclass of LionInput. Therefore LionInput has to be imported. The PrettyInput class is also exported as we are creating a new ES module here and maybe someone needs subclass PrettyInput itself. The most part of our class is the styles getter, a benefit that LionInput inherited from LitElement. Using the css tag function we can inject our CSS directives as string. The css tag function has to be imported as well. The styles are originally taken from Skeleton, a tiny CSS library.
The :host() selector references the custom element itself and is used for general styling like applying a nice font-face for all major OSes. As most of the parts in the elements Shadow DOM are exposed as slots, the ::slotted() selector is used to reference all parts like the input or label.
At last we define a custom element named pretty-input based on the PrettyInput class.
The pretty input is ready to be used, so next we extend our main.js :
//main.js
import '@lion/input/lion-input.js';
import './pretty-input.js';
and index.html files
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset="UTF-8">
<meta name="viewport” content=”width=device-width, initial-scale=1.0">
<title>White-Label Web Components</title>
</head>
<body><form>
<lion-input</lion-input>
<pretty-input
<div slot="help-text">This looks much nicer</div>
</pretty-input>
</form><script type="module" src="main.js"></script>
</body>
</html>
You can find more about styling, e.g. about reuseable styles, in the LitElement docs.
Create a bundle to use the styled component elsewhere
Bundling is a topic for itself. Most of you will know Rollup, Webpack, Parcel, and other, but you might not have used them directly. When you start your LitElement projects using the Javascript / Typescript starter projects mentioned above, a bundler is already included.
For those of you not familiar to bundler: a bundler takes the sources of your web project, gathers all dependent scripts that are required, imported or referenced by script tags, deduplicates code, wrangels them all up and outputs a single Javascript file to be included in the production version of your code.
To show how bundling our PrettyInput component works, we install Rollup via npm:
npm install rollup
You can install Rollup globally to have it in your toolbox for upcoming projects:
npm install --global rollup
Rollup faces the same problems resolving the dependencies in node_modules but luckily there is a plugin ready. We add it to our project with:
npm install --save-dev rollup-plugin-node-resolve
At last we write a configuration script for rollup to point it to the right direction:
// rollup.config.js
import resolve from 'rollup-plugin-node-resolve';export default {
input: 'main.js',
output: {
file: 'bundle.js',
format: 'cjs'
},
plugins: [
resolve({
browser: true,
only: [ /^@lion\/.*$/ ]
})
]
}
Basically the configuration defines main.js as entry point for the bundling. The file bundle.js will be the output. The node-resolve plugin is imported like any ES module and should run in browser mode, meaning it respects potential browser fields in the package.json of the dependencies.
The only parameter of the resolve configuration is helpful when you want to only include some of the dependencies. All other dependencies will be marked as external and you have to take care of inlcuding them yourself. In our example we only include the @lion* parts, so LitElement will not end up in the bundle. When you aim at a single bundle file, remove the line strting with only.
Execute
rollup --config
on the command line and the bundle gets generated in the main directory white-label-web-components. That’s it! | https://onebitahead.medium.com/dont-reinvent-the-wheel-use-white-label-web-components-fa57fa54cc15?source=user_profile---------3---------------------------- | CC-MAIN-2021-39 | refinedweb | 1,587 | 56.66 |
Using jinja2 outside of the web.
I may be the last person out there to do that, but i hadn’t actually gotten to that yet.
So here is the thing, sometime you want to produce a text file, with some complex structure, and string.format is not really up to the task, so you scratch your head and wonder what could be useful to… template an output.
Then a nice lib like jinja2 totally makes sense.
For my use case, i want to generate java source code, using info parsed from other java source code (thanks to the awesome plyj lib), so it’s easy to give the general form of the output file, and to pass the content after that.
{% if package %}package {{ package }};{% endif %} import {{ module.package_declaration.name.value }}.*; {{ imports }}\ public class {{ cls.name }}{{ suffix }} extends {{ cls.name }} { public interface I{{ cls.name }} {\ {% for method in methods %} {{ method.return_type | get_type }} {{ method.name }}({{ method.parameters | render_params }});\ {% endfor %} } private I{{ cls.name }} implem = null; public void setImplem(I{{ cls.name }} implem) { this.implem = implem; } {% for method in methods %} {{ method.return_type | get_type }} {{ method.name }}({{ method.parameters | render_params }}) { if (this.implem) return this.implem.{{ method.name }}({{ method.parameters | render_params_values }}); }{% endfor %} }
One problem i had, though, was when it turned out it would be convenient to use custom filters inside my template, it took me some time to find the relevant documentation about how to register functions as filters in this situation (since people usually use jinja2 in a framework, they document how to do so using the environment used by this framework).
So the answer was not to use jinja2.Template directly, but to build an environment before.
env = jinja2.Environment()
then to setup my filters in this environment:
env.filters['render_params'] = render_params env.filters['render_params_values'] = render_params_values env.filters['get_type'] = get_type
and to use
env.template_from_string(template_string) to create a Template object from my
string. | http://blog.tshirtman.fr/page/2 | CC-MAIN-2014-15 | refinedweb | 314 | 52.46 |
matching database again July 21, 2010 at 7:34 PM
Dear experts,So happy I get through this ask a question page again. Thank God.I want to say "A BIG THANK YOU" for helping me about the matching codes.It is working now after fine tuning the SQL query :-) but I can't do it without you showing me the steps... View Questions/Answers
XML in database July 21, 2010 at 5:59 PM
Hi Deepak, i m again facing problem with single element multiple tag in xml.i m trying to read the tag values into my database but it gives nullpointerexception. pls guide me appropriatly.MyXML Structure is ,Test1.xml<test1> <Firsttab>... View Questions/Answers
java July 21, 2010 at 5:05 PM
HiPlease observe the following code:import mysql.DataAcc;// import package class for getting database connectionimport java.sql.*;import java.awt.*;import javax.swing.*;import java.awt.event.*;class D1 extends JFrame implements... View Questions/Answers
javascript for prompt July 21, 2010 at 4:39 PM
Dear Sir, I am using a prompt() for taking a reason for delete.I used your code,its working fine .but i am validating a prompt contains any special character or what.If contains a alert message has to come toremove a special character.I done but when an alert message come press ok then that ... View Questions/Answers
java July 21, 2010 at 4:26 PM
Hiiam using servlets ,in one program my requirement is if there is a image(if u like) in anywhere and we browse that image and it is store in u r account like orkut.my doubt is if the image is stored in database it is not the good idea. my requirement is the image is stored in... View Questions/Answers
tree view July 21, 2010 at 4:04 PM
I want to use tree view in my example code to display data in hierarchical form. how ??Thanks ... View Questions/Answers
java July 21, 2010 at 3:26 PM
Hiiam created a new registration form as a desktop application using swings.and this is the code: pls have a lookimport mysql.DataAcc;// import package class for getting database connectionimport java.sql.*;import java.awt.*;im... View Questions/Answers
Java with Grid July 21, 2010 at 12:18 PM
please check this URL on above link is made in dotnet. i want to make [b]same UI[/b] as in Java.which technologies should be used that can be easy to use with java.... View Questions/Answers
What's wrong with my form? July 21, 2010 at 11:55 AM
Dear expert,I'm having trouble with my enquiry form.Hope you can tell me where my mistake lies.Thanks.Here's my jsp code:<title>Enquiries</title><link rel="stylesheet" type="text/css" href="styl... View Questions/Answers
java July 21, 2010 at 11:27 AM
how to grab pixel from an image ... View Questions/Answers
give me a source code to add any wallpaer of my PC as a background image to jpanel on a jframe . ... View Questions/Answers
java to excel connectivity July 21, 2010 at 11:11 AM
give me source code to stored the value entered by user in a text field(such as name, age, sex, add. of the user etc.) that are on the jpanel to the database created in MSEXCEL 2007. actually i am making project on bank and i want to stored the information of customer to my database on the excel. ... View Questions/Answers
Read XML in java July 21, 2010 at 10:19 AM
Hi Deepak, I want to read a xml file which have only one element with multiple attributes with same tag name.here is my file<employee> <firstname>Tom</firstname> <lastname>Cruise</lastname> <firstname>joil</firstname> ... View Questions/Answers
java July 21, 2010 at 9:43 AM
hiiam created a desktop login form using swings , and it works properly and my doubt iswhen valid user is login , the user name ,server date and server time is automatically stored in database and how it is and how to check valid user or not.pls tell me ... View Questions/Answers
Java Problem July 20, 2010 at 9:47 PM
How to create a jar file of a program ... View Questions/Answers
Java Program July 20, 2010 at 9:42 PM
A program to create a simple game using swings. ... View Questions/Answers
java July 20, 2010 at 7:57 PM
Can you provide me the concepts of class hierarchy with a suitable diagram and concepts of polymorphism with dynamic binding with a programming example for each please... ... View Questions/Answers
Java Networking July 20, 2010 at 2:58 PM
I want to get all systems' (computer,printer,laptop) IP address on LAN using java code. I tried a lot but find only my system's IP. I want java code for dat. ... View Questions/Answers
dropdown July 20, 2010 at 1:01 PM
i have below code for dropdown . now i want to user that textbox value in query at same page... how to get it in a new variable???<html><script>function getValue(){var combo = document.getElementById("sel");var val = combo.options[combo.selec... View Questions/Answers
validation message July 20, 2010 at 12:41 PM
sir, i took help of that example but in that we change only color of the message i want to shift the place of the error message.means all messages are put together at top of the form. ... View Questions/Answers
struts validation problem July 20, 2010 at 11:40 AM
i used client side validation in struts 2 .but message will display only on the top of the component.i want to display it on the top of the page ya right side of the component.Que: how to configure parameter for the message tag or any other alternative solution? ... View Questions/Answers
servlets July 20, 2010 at 10:57 AM
Q: i write program to upload image into perticular folder.but i want to store that path into database but not image and display that image in page from the db.pls any one send me code for that in servlets asap.pls vary urgent.i will be thankful to youpls send me ... View Questions/Answers
drodown July 20, 2010 at 10:49 AM
how to display selected dropdown value in textbox without using form. also want to use that value in query... ... View Questions/Answers
jsp solution July 20, 2010 at 10:43 AM
how to display javascript value in current jsp page without refreshing page.. dont want alert... got value in 1 variable in javascript and want to print in current jsp page ... View Questions/Answers
core java July 20, 2010 at 9:28 AM
what is the difference b/w #include and import?? ... View Questions/Answers
Cybercafe July 19, 2010 at 11:19 PM
Hi, i'm a java beginner, i'm in project to create a cyber cafe manager, my machines are running linux (ubunutu). I am looking for a code to freeze the screen until a user name and a password is given. Thanks for helping me ... View Questions/Answers
javascript for prompt July 19, 2010 at 6:07 PM
Dear sir, I have used prompt() for taking a reason while deleting using java script its working fine but prompt was coming at the top left so i want that prompt should come at middle so how to do this ,please help me.Thanks.... ... View Questions/Answers
java July 19, 2010 at 5:05 PM
Q What is the real use for log4J? ... View Questions/Answers
Servlet July 19, 2010 at 5:02 PM
Q why javasoft has declared HttpServlet Class as an Abstract Class althoug there is no abstract method availiable in HttpServlet Class? ... View Questions/Answers
java July 19, 2010 at 4:58 PM
Q What is the disadvantage of Singleton design pattern? ... View Questions/Answers
grid view in java July 19, 2010 at 4:47 PM
Is it possible to create dynamic grid view to display data from database. if yes. how ?? ... View Questions/Answers
Java July 19, 2010 at 12:27 PM
I have write a program to capture images from camera and scanners,I got image in panel but how should i save this image through save dialogbox at any location ...plz help ... View Questions/Answers
ToolTip Code July 19, 2010 at 11:59 AM be used ... View Questions/Answers
Java logical error July 19, 2010 at 11:26 AM
Subject:Buttons not displaying over imageDear Sir/Madam,I am making a login page using java 1.6 Swings.I have want to apply picture in the backgoud of the frame and want to place buttons on it.But the buttons are not displaying properly.So,I request your kind help... View Questions/Answers
Hash value is not same July 19, 2010 at 9:29 AM
Hi, I've two Excel files with same data. One is in Excel 2003 (.xls) format and other one is in Excel 2007 (.xlsx) format. I've generated one way hash using SHA-1 algorithm. But the hash value of Excel 2003 files is not same as the hash value of Excel 2007 file. What might be... View Questions/Answers
JSP and AJAX very urgent July 18, 2010 at 10:01 PM
Hi Team, This is Ragavendran.R.. I have a very basic doubt in AJAX. While Using AJAX, of course, there will be <div> tag involved in JSP page. But in my current project, I am using too many <div> tags in my JSP page and as a result, I am getting only the last div t... View Questions/Answers
struts July 18, 2010 at 9:51 PM
when the action servlet is invoked in struts? ... View Questions/Answers
Java Code July 18, 2010 at 9:48 PM
why overiding method used in your project? ... View Questions/Answers
java July 17, 2010 at 6:24 PM
how to create a login page for desktop application haveing user interface page and after thatuser is valid then it will store name,mail,etc., and also automatic date and time(it is important) database.the uqestion is how to store automatic date and timepls help me ... View Questions/Answers
core java July 17, 2010 at 6:15 PM
how to create a login page using only corejava(not servlets,jsp,hibernate,springs,structs)and that created loginpage contains database(ms-access) the database contains data what ever u r enter and automatically date and time and alsoinserted in the database pls help me that is useful f... View Questions/Answers
audio files in jdbc connectivity with ms-access July 17, 2010 at 4:03 PM
i need to know how to retrieve audio files through jdbc connectivity with ms-access and how to play them through link in browser.... ... View Questions/Answers
Unable to get data from class July 16, 2010 at 10:10 PM
I get this code from the internet which read from comm port of the computer & modify is as below:-package COM;/** * * @author kwngeaw */import javax.comm.*;import java.io.*;import java.util.*;public class ComControl implemen... View Questions/Answers
servlet July 16, 2010 at 7:22 PM
problem: home.jsp contains 6 checkboxes 1.A 2.B 3.C 4.C1 5.C2 6.D conditions are (1)if user select only A (or) only B (or) only c(or) only D (or)both AB ,AD --print valid user(2)if user select only C(or) only C1 (or) only C2 --print valid user... View Questions/Answers
J2ME Sub Menu July 16, 2010 at 7:01 PM
I am creating a J2ME midlet in which I have created a menu by adding different commands in it. Now for example my command list is as follows1. A2. B3. C4. D5. ExitNow my question is I want to add the command in A (i.e. A -> 1. Hi), etc.Can you... View Questions/Answers
hibernate caching July 16, 2010 at 7:00 PM
what is caching ?how to work with caching in hibernate ?can u give brief explanitation ... View Questions/Answers
spring first example July 16, 2010 at 3:53 PM
I am trying my first example of spring from the link I am not getting the simple "Hi" message ,I have created simple one jsp page and /WEB_INF/web.xml it is showing status 404HTTP Status 404 - /springapp/--------... View Questions/Answers
java July 16, 2010 at 3:38 PM
write a package for college which has two classes teacher and subject .teacher has two methods accept() and display and student has two methods accepts() and display().display the information about teacher and subject of the college package ... View Questions/Answers
java July 16, 2010 at 3:37 PM
write a package for college which has two classes teacher and subject .teacher has two methods accept() and display and student has two methods accepts() and display().display the information about teacher and subject of the college package ... View Questions/Answers
java July 16, 2010 at 3:34 PM
create two packages ,package1 contains two classes manager and clerk.both classes having method to accept corresponding information.packages 2 contains class employee with method accept info.write a program to display all information. ... View Questions/Answers
core java July 16, 2010 at 11:53 AM
Is there any Compile time exceptions in java? ... View Questions/Answers
javascript for textbox or prompt using servlet July 16, 2010 at 10:26 AM
Dear sir, I am using a prompt(),when a delete is confirmed,its working fine ,but when a prompt is closed or cancel ,i have to remain in the same page but here it is going to next page .So please help me how to do..Thanks... ... View Questions/Answers
One way hash in Java July 16, 2010 at 9:46 AM
Hi, What is one way hashing. How to implement it in Java. I've to compare the contents of two files by generating their hash value in Java.Please give some examples.Thank You, ... View Questions/Answers
Java code July 16, 2010 at 7:35 AM
in GWT ,which classes would be required to implement a screen showing a Grid with its cells derived from a JDBC select to a database table, let's define the table simply, say: CREATE TABLE contact ( name TEXT, phone_number TEXT );So effectively you would be just displaying t... View Questions/Answers
java bean July 16, 2010 at 12:02 AM
what is the diffrence between javabean and propertyfile both can be used as storage if these are there than in which case we use file and database please clearify.one more question why there is ejb if all that work can be done by simple pojo as in mvc ,is only we want container help for transaction ... View Questions/Answers
code July 15, 2010 at 11:51 PM
hi,i have a condition like when a radio button is clicked than it should refresh that page and give a warning message like "you are unable to route this document as its INTERNAL" and that option should also be disabled after that,so if possible provide th code in java,post the ... View Questions/Answers
javascript July 15, 2010 at 11:45 PM
hi,i need to disable the link/hyperlink by clicking on a object by meeting the condition by using java script.if possible provide a code in a simple way,post the code to my id:vpbtech@gmail.com ... View Questions/Answers
MySql ClassNotFoundException July 15, 2010 at 6:40 PM
Dear sir,i am working in Linux platform with MySQL database , actually i finished all installation in MySQL but while i am executing java program i am getting ClassNotFoundException. Can i install in linux any software making connection between java and MySQL. Or how can i execute my pro... View Questions/Answers
web design July 15, 2010 at 3:45 PM
hello sir.my quesstion is same please guide me.please reply my question .because it very urgrent.I want make header like- this sitebut in this site header make in flash,I use java script or any other script.like that side clic... View Questions/Answers
website creation using java and mysql July 15, 2010 at 3:22 PM
i am going to create a website for some company using java and mySql... i dont know the procedure to create a website.can anybody give me the steps what i have to follow for these??? ... View Questions/Answers
struts2-db connection error July 15, 2010 at 3:07 PM
i m unable to connect to the database in one of my application using struts2???These concepts are pretty new to me..so i wanted to know where the problem would hav occured? ... View Questions/Answers
jsp July 15, 2010 at 1:14 PM
Write a program using JSP that accepts the enrollment number of a student as input 20and displays the name and address of study center to which the student is attached. ... View Questions/Answers
jsp July 15, 2010 at 1:12 PM
Write a program using JSP that displays a webpage consisting of Examination Form of 20any university. The form is filled by any student who intends to appear for examinations.Make necessary assumptions ... View Questions/Answers
code for this problem July 15, 2010 at 1:09 PM
i have buttom submit .It is working with single click.Suppose if i am At the same time clicking(parallel) twise second request will be stoped until process the proces first requst and terminate the process. ... View Questions/Answers
JSP Code July 15, 2010 at 12:31 PM
Hi frnds,This is reference to solution which u have provided for 'Limiting the Number of Record Display in a table'.With full respect to what the solution you have provided, its really appreciable but since i am using PostgreSQL, few of the function of SQL are not available i... View Questions/Answers
JSP Code July 15, 2010 at 12:22 PM
Hi Frnds,I am using a checkbox in my one of page & which is by default checked. Now if i have to use the status of this checkbox in another page then how can i use. Example: if it is checked in page1.jsp then it should also be checked in page2.jsp.How can i achieve ... View Questions/Answers
JSP Code July 15, 2010 at 12:16 PM
Dear Frnds,I m using a 'multiple selecttion in List box' & trying to get all the value selected in list box. Here is the line which i am using to retrieve the value....String a=request.getParameter("drpdwnAllRole");This is giving me only first ... View Questions/Answers
jsp July 15, 2010 at 12:07 PM
it is possible to fire a java page from a jsp page through <a href > tag ... View Questions/Answers
jsp July 15, 2010 at 11:53 AM
what are the thinks in el (jsp) nesseay to take care wel codeing ... View Questions/Answers
Java Problem July 15, 2010 at 11:51 AM
How to create executable file of a java program.That is steps to create a Jar File of a Java Program ... View Questions/Answers
Calling exe through Java program. July 15, 2010 at 11:19 AM
Hi,How to call a vb exe that takes one argument , using a Java program.Thank You,Umesh Kilkile ... View Questions/Answers
co July 15, 2010 at 12:52 AM
what is the difference b/w #include and import?? ... View Questions/Answers
core java July 15, 2010 at 12:50 AM
catch(Exception e) {System.out.println(e); }what is use of this?? ... View Questions/Answers
How to identify the remote system that gets connected to our July 14, 2010 at 6:53 PM
Hi,I am doing a project which works on providing security.In this my pblem is any user from anywhere and any location if they get registered into our site how can we provide security to them through my website in online from accessing unwanted sites.how can I provide that security... View Questions/Answers
javascript for textbox or prompt using servlet July 14, 2010 at 5:26 PM
Dear sir I am writing script in servlet,so prompt() is not working here so please help me...In my project when a vendors want to delete the uploaded file ,if they are confirmed to delete the i have to take a reason for deleting a textbox as to come if press ok then delete the file then i... View Questions/Answers
javascript for textbox July 14, 2010 at 4:08 PM
Dear Sir, In my project if i use a var reason=prompt(\"Reason for deleting:\",\"\") in a javascript after confirm the delete option ,its not invoking the prompt()...So please help me..Thanks... ... View Questions/Answers
about interview ques. July 14, 2010 at 3:18 PM
i give a interview for java..they ask me.what is System.out.println(); what is its write ans... ... View Questions/Answers
About desing patterns July 14, 2010 at 12:36 PM
How many Design Patterns are there supported by Java? and what is an Application Controller? what is the difference between Front Controller & Application Contorller? ... View Questions/Answers
java July 14, 2010 at 11:42 AM
Develop a multi-threaded GUI application of your choice. ... View Questions/Answers
java July 14, 2010 at 11:41 AM
Write a multi-threaded Java program to print all numbers below 100,000 that areboth prime and fibonacci number (some examples are 2, 3, 5, 13, etc.). Design athread that generates prime numbers below 100,000 and writes them into a pipe.Design another thread that generates fibonacci... View Questions/Answers
java July 14, 2010 at 11:39 AM
Design a thread-safe implementation of Queue class. Write a multi-threadedproducer-consumer application that uses this Queue class. ... View Questions/Answers
java July 14, 2010 at 11:38 AM
Develop a template for linked-list class along with its methods in Java. ... View Questions/Answers
java July 14, 2010 at 11:38 AM
Develop a scientific calculator using even-driven programming paradigm of Java. ... View Questions/Answers
java July 14, 2010 at 11:37 AM
Develop a simple paint-like program that can draw basic graphical primitives indifferent dimensions and colors. Use appropriate menu and buttons. ... View Questions/Answers
java July 14, 2010 at 11:37 AM sequ... View Questions/Answers
java July 14, 2010 at 11:36 AM
Design a Java interface for ADT Stack. Develop two different classes that implementthis interface, one using array and the other using linked-list. Provide necessaryexception handling in both the implementations. ... View Questions/Answers
java | http://www.roseindia.net/answers/questions/222 | CC-MAIN-2016-36 | refinedweb | 3,809 | 63.09 |
Rich Hickey on Protocols and Clojure 1.3
Recorded at:
Bio Rich is the inventor of Clojure. He serves as an advisor to the Clojure/core () team, bringing his technical expertise in matters of Clojure and programming in general to ensure the highest quality development and mentoring experience for our customers.. Clojure has released version 1.2, is going to 1.3. What have you learned since the release of Clojure 1.0? Are there some big lessons that you’ve learned, any things that you want to do differently?
I don’t think there are any big lessons; I think we’re just moving forward on adding things for completeness that we sort of knew about and then refining things that we already had. We’re always trying to improve performance and 1.2 of course had a big addition, which was a different polymorphism system with protocols. I think Clojure probably didn’t go out with that because wanted more time to think about it, but I think what we ended up with was pretty flexible.
2. You mentioned protocols which are I guess a new tool for polymorphism, that’s between functions and multi-methods. Is that correct?
Right. They are very similar, depending on your perspective, there are either similar to Common Lisp generic functions or maybe the dynamic flavor of type classes. But they have the advantage that both of those systems have in that you can add polymorphic behavior to things that already exist without changing them, so that is nothing that relies on type intrusive inheritance kind of a thing.
3. It’s essentially solving the expression problem.
If you know what that is, it’s a way to do that. The expression problem makes it harder for people to understand. People understand that it can be difficult to extend the systems that require you to change your types. So when you have something that allows you to write new extensions, new functions that behave differently depending on the types they're passed without touching those types - that’s something that allows for independent extension. You can have new functions, with old data, new data and make it work with old functions - that’s the point.
4. In a way it’s different than for instance Ruby’s open classes, where for an open class you modify the class. Protocols are different. Can you scope them in some way?
Yes. Protocols are functions and in Clojure all functions are in namespaces. So if you had some abstraction that needed the function foo and I had an independent abstraction where foo also made sense. They would be in different name spaces and they wouldn’t conflict with each other where when you try to use classes as name spaces, you have conflict when people choose the same names for different semantics.
5. Can you use protocols to put a new function on String for instance but only in your namespace?
It’s not like you are putting it on String. You are saying "There is a function whose behavior I’d like to be different when it’s passed Strings vs. when it’s passed collections or something like that." That kind of polymorphism isn’t in the classes any more, it’s in the functions. Once that’s the case and functions are in separate name spaces, you have an open system that allows for mutual independent extension.
6. One difference with protocols is that it's single dispatch vs. multi dispatch.
Right. That’s a compromise essentially so that: a) it can be really fast and b) there can be a relationship between it and what the hosts provide. Because generally Clojure is hosted on systems that provide single dispatch. By limiting it to single dispatch, which is the 99% case, you get that ability to have a mapping which is important for bridging, so you are able to say "I’ve defined a protocol, but if you are in Java and you need to extend it from there, you can use the inheritance mechanism you are used to, because there is a corresponding interface."
Nothing about having protocols precludes or denies the value of multi-methods which are still in Clojure and are still valuable for those situations where you have something more involved, you want to dispatch on something other than the type or use multi-dispatch.
7. You can also hook into the JVM’s invoke_virtual, the infrastructure that makes that fast.
That’s part of why the single dispatch is fast. Single dispatch is generally easier to make fast because it has less to do.
8. Just needs a lookup table, essentially or an inline cache.
Like you said, if the host has got a single dispatch mechanism and you can map to it, then you can just take a free ride on Hotspot.
9. You are talking generically about host. The CLR port, is that still around? Is that being developed?
It’s still around. The development is probably slowed a little bit, it’s tracking Clojure, but it does not yet have the protocol stuff.
10. I think I saw that one reason for adding protocols was the Clojure in Clojure project. Is that right? Is there a relationship to that?
It’s sort of a recognition that out of the gate, as I said, Clojure didn’t come with an abstraction mechanism like protocols. The reason was I didn’t want to invent a new object system. I wanted to think about what the right solution was. I also wanted to encourage people to program to generic data structures, which has happened in the Clojure ecosystem with tremendous benefits because library interoperability is really great in the ability to suck data in from anywhere and use the generic suite of library functions is there. But Clojure is heavily built on top of abstractions so when you look at how Clojure was built, and what Clojure the language was delivering, you realize that it wasn’t yet delivering everything it needed to be built.
As a thought exercise, if nothing else, saying it would be nice if the language had everything required to implement itself, it was missing this abstraction system which protocols now provide in a way that I’m satisfied with. Getting around to redoing Clojure in that system is something that will take some time. I think the most pressing thing right now is to get the compiler rewritten in Clojure, because it’s currently written in Java and it’s sort of a monolithic transformation and a lot of tooling would like to step in the middle of that or at least get some of the results from the analysis phase of compilation and that will probably happen sooner or rather later.
11. The ratio of Java to Clojure code in Clojure 1.2 is still the same as in 1.0; have you changed other [Clojure sub]systems to Clojure.
It’s mostly about newness, so usually there is not a tremendous benefit to redoing something that’s already working. For instance we did introduce some new collections of primitives, they're written with the new deftype stuff, not in Java. The things that were written in Java are still in Java and they get maintained there until they get transferred. But most of Clojure’s runtime library, other than the collection classes is written in Clojure already, so we continue to do that. I don't think we’re writing a lot of new Java that’s not maintenance or minor tweaks to the compiler.
12. You mentioned these new special collection classes that use primitives, are they written for performance or to use less space?
They can use less space right off the bat, connecting all of the pieces together for performance is something that’s still yet to come. Obviously they were written and delivered in 1.2 before the new primitive support, which is in 1.3, which is the second step of probably 3 or 4 required to eventually end up with a system where you can take a higher order function that knows how to manipulate primitives and run it over a collection of primitives and end up with the same thing you’ve gotten from writing a primitive loop in Java, except it’s over a collection not over arrays, which are the only things in Java proper that give you primitives.
13. Since Clojure 1.0 you mentioned you’ve been doing a lot of work on performance, and I guess scalability, for instance the introduction of transients. I think transients are a performance feature. Transients were introduced in 1.1 and they are essentially a way to manipulate persistent data structures, is that right?
You can never manipulate a persistent data structure, but there is a constant time way to go from a persistent data structure to a transient data structure. Then if you use a transient data structure linearly essentially, not presuming that it’s modified in place, you can change it more efficiently than you could a persistent [data structure]. Then, when you’re done with that, you can get a persistent data structure out of it, again in constant time.
14. Essentially you’re making it transient between the ticks, changing it and then at the next tick it’s a value again.
Yes. Except that the notion of transient is important because to talk about changing it means that there is an "it" before and after the change, but you have to use the transient linearly, which means you can never refer to the value prior to any changing function. You can only just consume the results of the functions you call on it, you can’t keep around, so it sits in between "change in place" and "you can't change at all"; and functional transformation. When you use it, it feels much more like functional transformation. It just happens to be a more efficient than creating new values every time.
16. This was added in 1.1, but you now have new ideas for expanding transient and using the transient concepts more generically.
Transients do two things right now: they do the data structure part of the job, which is the constant time conversion to and from persistent data structures and the efficient transient changing functions, if you will, because I don’t think we have the right vocabulary for that yet. And they implement policy, so because you have this requirement that you use them linearly, currently transients self-enforce that they are used in a single thread. What I wanted to do is actually separate the policy part out from the data structure part. When you separate the policy part out, you look for a good place to put it and you end up with another reference type, like the existing reference types that will manage a transient internally. Right now I’m calling them Pods.
17. Clojure Pods are an abstractions of transients or reference types?
No. Clojure Pods are just another flavor of the time model, the reference types, is just another one of those, but they’ll automate the process of, you put a value in a pod, when it’s needed it will turn into a transient. The kinds of functions you send into a pod are functions of transients and when you look at the value of a pod, they’ll also automate that conversion from transient back to value. In that way, they get the user of transients to actually don’t touch transients any more. They are an implementation detail of the pods; they can enforce linearity now with different policies.
There might be pods with single-threaded policy, but there will also be pods that have multi-threaded policies where they can support multiple threads trying to produce the next value cooperatively and they’ll internally use locks to make sure that works correctly.
18. An interesting example you gave me at the talk was the pods enforce the order of locking. Is that the right? I mean if you have multiple locks.
Right. You don’t want to think about the locks, but the idea is, like STM, pods will let you have a single unit of work that impacts more than one reference. And because they use locks under the hood, obviously they have to take care of lock acquisition order, which they will, but you don’t have to think about that as a user.
19. But as someone who implements a pod? Or do you implement the pod?
No, I’ll implement the pods.
20. That’s always good. We prefer for Rich to provide the abstraction. Another thing you are working on currently for the stream that’s going to become 1.3 is the numerical work, the work on fixing BigIntegers - what’s that about?
There is a bunch of things in 1.3 around primitives and better support for primitives. There is a few pieces to it; the first is that right now Clojure only supports objects as arguments and return values from functions and that’s to give a uniform system and it supports fast primitive operations inside the scope of a function. You can write a loop and have that be fast. But when that grows to a certain size, let’s say "This piece of code is getting too large; I want to take some part of this numerically intensive code and break it out, now you are suffering boxing overhead because you are using a function."
What is added to 1.3 is the ability to write functions that take and return longs and doubles in addition to objects. That removes the penalty from breaking something out into a function. That’s the first thing. The second thing is a unification of the semantics of arithmetic between boxed numbers and primitives and that basically is a move away from auto-promotion to checked primitive arithmetic. It’s the native primitive operation on the hardware, plus an overflow check which throws an exception and that’s very fast.
21. We’re looking forward to Clojure getting faster and seeing Clojure in Clojure at some point. Finally, you recently joined a company to do commercial backing, commercial development for Clojure? Is that right? Or what is that about?
Right. We formed Clojure/Core, it’s a joint endeavor between myself and Relevance and it acts as a consulting arm of Relevance and we’re providing support and mostly, right now, mentorship, training and consulting services to companies that are trying to adopt Clojure. You can come to us and get help, we can come to you and give you some advice, either looking at existing projects or helping projects get started.
22. So you could hire Rich Hickey to come to my company?
No, actually you can’t hire Rich Hickey to go anywhere. But you can hire Clojure/Core and I work with the team who will show up and I’m behind their efforts.
23. You are there improving Clojure.
I’m also there as the expert advice. You can get questions answered through the team which eventually may hit me because I’m the only one who can answer them.
24. Thank you very much, Rich Hickey.
Thanks.
Hello stranger!You need to Register an InfoQ account or Login to post comments. But there's so much more behind being registered.
Get the most out of the InfoQ experience.
Tell us what you think | http://www.infoq.com/interviews/hickey-clojure-protocols | CC-MAIN-2014-15 | refinedweb | 2,610 | 69.92 |
Details
Description
put the BIRT run environment to the ofbiz, make the BIRT as the ofbiz component, and let the user can develop the BI more easily and efficiently
Activity
- All
- Work Log
- History
- Activity
- Transitions
Hi All,
I need some report function for a project, so I try to integrate ofbiz with
the birt, here is some ideas and want to share with you, and if there is any
problems, please let me know.
1. BIRT is the open source project and the license is the Eclipse Public
License that is compatible with Apache;
2. It's a report designer based on Eclipse, and a runtime component that you
can add to your app server. BIRT also offers a charting engine that lets you
add charts to your own application, that's what I need.
3. I want to Ofbiz deal the *.rptdesign as convenient as the jsp;
4.. I want to use the birt servlet to display the rptdesign file as it have
provider full display function, and I can update this code with the birt
easily.
So I create the rpt view handler, this handler doesn't really display the
rpt file but get the display info from the control.xml and pass the
parameters to the birt servlet, and I take the "info" parameter in view-map
as the permission, here is the example:
<handler name="birt" type="view" class="
org.ofbiz.webapp.view.BirtViewHandler" />
<request-map
<security https="false" auth="false"/>
<response name="success" type="view" value="testbirt"/>
</request-map>
<view-map
here is the render code:
///////////////////BirtViewHandler //////////////////////////////////////
public class BirtViewHandler implements ViewHandler {
public static final String module = BirtViewHandler.class.getName();
protected ServletContext context;
public void init(ServletContext context) throws ViewHandlerException{ this.context = context; // context.. }
public void render(String name, String page, String info, String
contentType, String encoding, HttpServletRequest request,
HttpServletResponse response) throws ViewHandlerException {
// some containers call filters on EVERY request, even forwarded
ones,
// so let it know that it came from the control servlet
if (request == null)
if (page == null || page.length() == 0){ throw new ViewHandlerException("Null or empty source"); }
String baseURL = request.getScheme( ) + "://"
+ request.getServerName( ) + ":"
+ request.getServerPort( );
String path=context.getRealPath(page);
BirtViewHelper.PATH = path;
BirtViewHelper.PERMISSION = info;
try
catch( Exception e){}
}
}
///////////////////END BirtViewHandler
//////////////////////////////////////
///////////////////BirtViewHelper//////////////////////////////////////
package org.ofbiz.webapp.view;
public class BirtViewHelper{
public static String PATH = new String();
public static String PERMISSION = new String();
}
///////////////////END BirtViewHelper//////////////////////////////////////
here is the permission check in birt servlet :
///////////////////AuthenticateHelper //////////////////////////////////////
package org.eclipse.birt.report.servlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletContext;
import org.ofbiz.security.Security;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.webapp.control.LoginWorker;
import org.ofbiz.webapp.view.BirtViewHelper;
public class AuthenticateHelper {
public static boolean hasPemission(HttpServletRequest request,
HttpServletResponse response, ServletContext context)
{
LoginWorker.checkExternalLoginKey(request, response) ;
GenericValue userLogin =
(GenericValue)request.getSession().getAttribute("userLogin");
Security security = (Security)request.getAttribute("security");
if (security == null)
return security.hasPermission(BirtViewHelper.PERMISSION, userLogin);
}
}
///////////////////END AuthenticateHelper
//////////////////////////////////////
you can download the BIRT code , place
those code in the framework folder add add this module to the
ofbiz-component.xml, and add the BirtViewHandler.java ,BirtViewHelper.java in
the ofbiz\framework\webapp\src\org\ofbiz\webapp\view.
Birt has a bug when export as word document, it will be fixed later.
Jack,
thanks for your work. Could you please send the source code as a patch or (the complete java file if it is new), instead of a Jira comment?
Thanks!!!
About EPL licence,please have a look at. Seems fine with some light constraints
I just checked there are currently no use of EPL licences. Be sure to check the link above about the constraints before any huge work for OFBiz integration.
unzip birt.zip to the "framework" folder and upzip plugins1.zip, plugins2.zip and plugins3.zip to the "ofbiz\framework\birt\webapp\birt\WEB-INF\platform\plugins" folder. place the BirtViewHandler.java and BirtViewHelper.java in the "ofbiz\framework\webapp\src\org\ofbiz\webapp\view" folder. rebuild the component, then you can run the BIRT with ofbiz!
this is just the first step to integret BIRT with ofbiz, more work need to be done to make more perfect, please let me know if there is any problem or advise.
This is an interesting first step.
My main concern is: do we really need +20MB plugins to run the reports?
If the answer is yes, then we could think of including in the trunk the 3 source files and leave out the birt component (and just provide a link to download it): I've noticed that your new classes don't require any external jar to compile (and this is good).
Jack, would you be brave enough to provide an example of a report based on the following view definition:
SalesInvoiceItemStarSchema
?
I'd love to see how the birt reports integrate with the existing ofbiz applications, and your example could be compared with the existing simple 'report' over the same view entity (in the Business Intelligence component).
Thanks
As the first step, the BIRT cann't work with the Ofbiz view definition, it just the let the BIRT web viewer run with the OFBIZ, and can use the BIRT designer to design the report, the data sources come from the db maintenancing by BIRT . here is the data sources configuration code:
<data-sources>
<oda-data-source
<text-property</text-property>
<property name="odaDriverClass">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
<property name="odaURL">jdbc:sqlserver://localhost
SQLEXPRESS:1433;DatabaseName=jins</property>
<property name="odaUser">sa</property>
<encrypted-propertyMTIzNCFAIyRxd2Vy</encrypted-property>
</oda-data-source>
</data-sources>
of course it's no the good way as the BI component to ofbiz. I also want to let the BIRT can work with the Ofbiz view/entity
So, the next step what I need to do is:
1. Make the BIRT web viewer can work with Ofbiz view/Entity .(high PRI)
2. Fix the bug and improve the permission mechanism..(mid PRI)
3. Make the BIRT designer can work with Ofbiz view/entity (low PRI)
this is class get the data from the Ofbiz and return the list, placed it in the framework\birt\src\org\ofbiz\birt
update AuthenticateHelper.java
take the OrderItemPriceInfo entity for example
how to design BIRT with Ofbiz
Hhi Jacopo,
There is not any data in SalesInvoiceItemStarSchema in my evironment, so I take the OrderItemPriceInfo as the example, it can work with the Ofbiz entity now by BIRT scripted data source, BIRT can support many kind of data sources,
With the BIRT designer, it's easy to design the report now.
please let me know if there is any problems, thanks.
Hi Jack.
To successfully run the example report that have a link in webapp/birt/index.jsp. I have to make a comment on line number 1644-1647 in org.eclipse.birt.report.utility.ParameterAccessor.
So, Is These line come from the origin code? or It 's customized by you.
Thanks.
That exmaple is the origin code, the OfbizScripted.rptdesign is customized , you can try run this according the quickStart.doc
Hi Jack.
I think there is a problem with your BirtHelper.java and BirtViewHandler design.
You should not use a static field to held a (temporary) session data because it will cause a problem when concurrent thread request a report at the same time.
Here the problem code which i had make the comment down below.
public class BirtViewHandler implements ViewHandler {
public void render(String name, String page, String info, String contentType, String encoding, HttpServletRequest request, HttpServletResponse response) throws ViewHandlerException {
...
String baseURL = request.getScheme( ) + "://"
+ request.getServerName( ) + ":"
+ request.getServerPort( );
String path=context.getRealPath(page);
//===== THESE TWO LINE WILL CAUSE A PROBLEM WHEN ACCESS FROM CONCURRENT THREAD ===//
BirtViewHelper.PATH = path;
BirtViewHelper.PERMISSION = info;
try{ response.sendRedirect(baseURL+"/birt/control/frameset?"+LoginWorker.EXTERNAL_LOGIN_KEY_ATTR+"="+request.getSession().getAttribute(LoginWorker.EXTERNAL_LOGIN_KEY_ATTR)); }
catch( Exception e){}
}
}
Yes, you are right, there is need to be improved, I will try to fix this . any idea are welcome... Thanks
I have fixed the thread problem, but I don't want to upload the last code until I have finished the document and some other function/problem we need, if you want this code ,please let me know, and I will send it to you.
Work with BIRT2.3.1 Note, it fixed some error..
1. Download birt-runtime-2_3_1;
2. Extract the file and copy the sub files in the WebViewerExample folder to the webapp folder of the ofbiz component;
3. Merge the web.xml, remember ofbiz using the web-app_2_3.xsd and BIRT needs web-app_2_4.xsd, update to 2.4 and change some order of the elements in web.xml.
After those you can use the BIRT now.
And more:
4. If you want to use the pojo datasource just download CreateDataSource.java, it can work as the pojo datasource;
I think using the birt viewer tag is the best well to work with the Ofbiz, you can see how it work in OfbizScripted.rptdesign and testBirt.jsp
When I will get a chance, I will make a FAQ for that (I have to test it before though...)
OK, I had already done that FAQ for Birt, I will not do more...
Thanks for your work Jack !
Hi i have been trying to integrate BIRT with Ofbiz i have followed the initial steps but i have not found birt.zip file mentioned here.
hi i have downloaded the BIRT RCP designer and have used it to generate the report...............
but once i make the database connection with my ofbiz database and when i fire query it does not displays all the tables of my databse it is just showing some particular no of tables.
i m using mysql as database............and there are around 700-800 tables but in BIRT after making the database connection it is only showing 100 tables.................
And also when i m trying to display my .rptdesign file through ofbiz................i m getting an exception...........cannot get instance of handler.............
current in the branch:
and sometimes perhaps in the trunk......
This implementation is not supported anymore.
AFAIK, BIRT uses EPL (the Eclipse Public Licence) and I thought we needed to have everything under Apache License. I doubt we can get everyone in the BIRT project to agree to relicense under ASF terms.
I'm guessing this will be closed in a matter of minutes...
Which is sad, because it would be nice to have a hundreds of quickly edited reports in the system. | https://issues.apache.org/jira/browse/OFBIZ-1348?attachmentOrder=desc | CC-MAIN-2017-17 | refinedweb | 1,741 | 57.98 |
Help framework guide
Abstract
Various services are available for software developed on the maemo platform. One of them is the Help Framework, a context-based help system, which can be easily used in any application. This document focuses on the explanation of the various steps necessary to enable this feature in your application. The current version of this document was updated specifically for maemo SDK version 2.1, and is subject to changes, as new versions of the SDK become available.
The examples discussed in this document can be downloaded from help-framework.
Creating the help file
The help file is an XML document, with various pre-defined tags, used to aid the creation of help topics. The example below shows the format this file must conform to:
<).
This
is the
osso_example_help context UID that is used in the application.
Below is a list of available tags with a short description:
- folder
Contains help topics, one or more
- title
Title text for the folder to be displayed in the Help application's Contents list, usually the name of the application
- topic
Single help content to be displyed for the user. Every topic can be referred via its unique contextUID.
- topictitle
Title text for the topic to be shown under the main title in the folder list
- heading
Can be used on long help pages to separate different subsections. Note that headings are not needed for all topics because the topic title is used as a topic's main heading. Headings are formatted with a different colour and are bigger and in bolder font.
- display_text
Used for presenting text that appears on the device display, like button labels and so on. Display text is formatted with a different colour in the Help application.
- graphic
Used to show in-line images in the text. You have to define either the absolute path (with
- para_context
A context paragraph (see also
tip,
note,
important,
exampleand
warning)
- tip
Shows a "Tip:" prefix (see
para_context)
- note
Shows a "Note:" prefix (see
para_context)
- important
Shows an "Important:" prefix (see
para_context)
- example
Shows an "Example:" prefix (see
para_context)
- ref
Used to create a cross-reference, the 'refid' parameter defines referred topic's contextUID and the 'refdoc' parameter is the name of the reference
- emphasis
Used to emphasise the text
- ossohelpsource
Main XML tag for the help files
- change_history
Change history of the help content. Used only by help content authors (see
change).
- change
Entry for
change_history
- synonyms
Synonyms are only used by Global search and are not displayed for the users. Synonyms are extra keywords for search.
You can download an example xml file here>.
Adding help context support to the application
This section demonstrates how to create an application with an online help system. This application uses the XML file described in the previous section.
To use the online help system on the maemo platform, you must include the following header files with your application:
#include <libosso.h> #include <osso-helplib.h>
The header file
libosso.h provides the environment
initialisation to the user.
Now
you must the application, carry out these two steps:
- Initialise the GTK+ library by calling the function
gtk_init().
- Initialise the application context using
osso_initialize().
In the following example shows you in detail how this initialisation must be carried out:; }
The maemo help system is now fully functional. To show one
of the topics from our help file, you only need to call the function
ossohelp_show(),
as in the example below.
In the event that the topic is not available,
the
ossohelp_show() function returns to the main function to create a button to activate help:
/* add a Help button */ help_button = gtk_button_new_with_label("Help"); g_signal_connect(G_OBJECT(help_button), "clicked", G_CALLBACK(help_activated), OSSO_HELP_TOPIC_EXAMPLE);
The next step is to add a help button to the
dialog box. The process is simple: enable the button in the dialog box with
the
ossohelp_dialog_help_enable() function. The example below
shows how this you only need to compile the example:
gcc `pkg-config --cflags --libs hildon-libs libosso libossohelp` \ -o example_help_framework example_help_framework.c
Starting from the SDK 2.1 it is also possible to test the help system in the scratchbox. You can download the following help-framework example, help-framework desktop, and help-framework service files.
Distributing the example application
To quickly test your help content, manually
copy the XML file to a correct path (for example,
/usr/share/osso-help/en_GB/)
where it can be found by the help library. Replace the
en_GB path
by the correct language definition if your help is written for some other
language. When you start your newly created application (or Help application)
you are now able to show your help content. The easiest way to distribute
help file and application is to create
an Application Manager package.
Improve this page | http://maemo.org/development/documentation/manuals/2-x/help_framework/ | CC-MAIN-2017-04 | refinedweb | 795 | 53.41 |
Chinese Branded Ready Made Garments Manufacturers Exported Clothes to Israel
US $1.56-2.56 / Piece
1000 Pieces (Min. Order)
Factory Supply High Quality 100% Cotton Soft kids clothing wholesale ready made garments manufacturers
US $0.99-4.99 / Piece
1000 Pieces (Min. Order)
ready made garments manufacturers
US $0.33-0.69 / Meter
1 Meter (Min. Order)
Factory Supply High Quality 100% Cotton Soft kids clothing wholesale ready made garments manufacturers
US $0.69-2.2 / Meter
1000 Meters (Min. Order)
Glo-story ready made knitted garments manufacturers buyer
US $3.4-3.76 / Piece
1000 Pieces (Min. Order)
stocklot garments black and white polo shirt t shirt
US $1.5-4.8 / Piece
100 Pieces (Min. Order)
Plain dyed Stocklot with a Low Price Ladies Fashion t shirt Ready made Garments Wholesale Market
US $3-3.01 / Piece
450 Pieces (Min. Order)
Micro Wax Fabric Printing for Garment
US $0.4-0.45 / Meter
2000 Meters (Min. Order)
Plain Fitted Color T-Shirts Wholesale By Ready Made Garment
US $1-6.5 / Piece
500 Pieces (Min. Order)
MS69477C summer mink color fashion kids tshirts ready made garments
US $2.55-7.96 / Piece
12 Pieces (Min. Order)
High Quality Men T-Shirt Wholesaler Branded Ready Made Garments
US $2-5 / Piece
180 Pieces (Min. Order)
2015 Ready goods 100%rayon voile good stock lots fabric air jet loom for Garment
US $0.7-1.3 / Meter
100 Meters (Min. Order)
Women's branded ready made garments
500 Pieces (Min. Order)
garment for shirts
0 Pieces (Min. Order)
(A4082) 2-6Y Ready made cotton boy stripe woven shirt nova branded garment
US $4.13-5.16 / Piece
25 Pieces (Min. Order)
factory direct offer import of ready made garment
US $7-10 / Piece
100 Pieces (Min. Order)
Korea styles export surplus branded garments fashion branded garmentsboys ready made garments
US $4.2-4.2 / Piece | Buy Now
6 Pieces (Min. Order)
branded ready made garments
US $3-5 / Piece
100 Pieces (Min. Order)
ready made high quality 100 polyester lining fabric dobby lining for garment
US $0.61-0.7 / Meter
100 Meters (Min. Order)
Super quality printing T/C kids ready made garment
US $1.8-3.5 / Piece
100 Pieces (Min. Order)
classic boys V collar pringting boys ready made garments
US $2.18-2.89 / Piece
500 Pieces (Min. Order)
190T/210T/230T taffeta printed/branded ready made or garments
US $0.25-0.48 / Meter
1000 Meters (Min. Order)
import ready made garment
US $1.5-5 / Piece
500 Pieces (Min. Order)
Dark red polyester chiffon glitter table cloth fabric with flock for costume garments
US $1.4-1.8 / Yard | Buy Now
3 Yards (Min. Order)
ready made garments natural soie spandex satin wholesale
US $1-10 / Meter
200 Meters (Min. Order)
gold velvet cloth italian velvet fabric/korean velvet for garments/upholstery
US $3.5-4 / Kilogram
1000 Kilograms (Min. Order)
Ready made fabric supplier Heat transfer Soft digital printed fabric for garment
US $1.03-2.13 / Yard
200 Yards (Min. Order)
Onway Textile 100% polyester cheap jacquard fabric for ready made garment/dress textile
US $0.1-10 / Meter
1000 Meters (Min. Order)
Net yarn long sleeve round collar render unlined upper garment
US $4-15 / Piece
2 Pieces (Min. Order)
Ready Made Garments for women
US $0.80-2.00 / Piece
3000 Pieces (Min. Order)
environmental ready made garment /free sample t-shirts
US $0.7-1.5 / Piece
1000 Pieces (Min. Order)
ready made garments with free sample
US $3.65-5.95 / Piece
1200 Pieces (Min. Order)
2015 wholesale 100% cotton men's polo shirt ,custom fred perries polo shirt made in china
US $2-30 / Piece
20 Pieces (Min. Order)
Ready made children summer clothing short sleeve print sport kids blouse top boys t shirt
US $6.35-7.8 / Piece | Buy Now
10 Pieces (Min. Order)
Best luxury ready made curtains design for living room
US $2-5 / Meter
60 Meters (Min. Order)
Buying Request Hub
Haven't found the right supplier yet ? Let matching verified suppliers find you. Get Quotation NowFREE
Do you want to show ready made garments manufacturers or other products of your own company? Display your Products FREE now!
Related Category
Product Features
Supplier Features
Supplier Types
Recommendation for you
related suppliers
related Guide | http://www.alibaba.com/countrysearch/CN/ready-made-garments-manufacturers.html | CC-MAIN-2017-04 | refinedweb | 722 | 70.29 |
# -*- coding: utf-8 -*-
#!/usr/bin/python3
import socket
# nao tem servidor UDP no google -> vamos usar netcat como servidor UDP!
#Programa de chat: so fala um de cada vez
#implementar falando ao mesmo tempo
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
"""
pacotes_recebidos = client.recvfrom(1024) devolve uma tupla:
(' llallalaaaa\n', ('192.168.1.4', 667))
msg recebida + (IP,porta)
"""
try:
while 1: #while True
client.sendto(input("Voce: ") +"\n", ("192.168.1.4", 668)) # endereço do servidor UDP do kali linux usando netcat
msg, friend = client.recvfrom(1024)
print(str(friend) + ": " + msg)
#se quiser apenas o ip: use friend[0]
# convertemos str(friend) porque recebemos o erro:
# (TypeError(can only concatenate tuple (not str) to tuple,))
client.close()
except Exception as erro:
print("Conexao falhou ")
print("O erro foi: ", erro)
client.close()
('O erro foi: ', NameError("name 'hi' is not defined",))
Here is an example of a 'multithreaded' UDP python client in python3 that allows messages to be sent and received simultaneously.
I personally like to make a Wrapper for the
socket class that has all the threading and functions built in, so we'll start with the wrapper.
import socket import threading class socketwrapper: def __init__(self, host, port): self.server = (host, port) self.client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.client.settimeout(5) # Time is in seconds self.connected = False def startrecvdata(self): recvThread = threading.Thread(target=self.recvdata) recvThread.daemon = True recvThread.start() self.connected = True def recvdata(self): while self.connected: try: data, friend = self.client.recvfrom(1024) if data: print(str(friend) + ": " + data.decode('utf-8')) except socket.timeout: else: print("No Message Received before timeout.") continue except: self.connected = False self.stop() def sendmessage(self, data): data += "\n" self.client.sendto(data.encode('utf-8'), self.server) def stop(self): self.client.shutdown(socket.SHUT_RDWR) self.client.close()
So as you can see we have a couple functions in this, the two you should notice are
startrecvdata(self) and
recvdata(self). We will call the
startrecvdata(self) from our main function, which will start the
recvdata(self) thread. That function will print any received data to the console.
Additionally, notice that we have
settimeout(5) in the
__init__ function of the wrapper, which sets a 5 second timeout on the socket connection. This way, we can close the entire program cleanly, shutting down and closing the socket with the
stop() function.
Now for the main loop. Since we setup all of our functions in the wrapper class, we can have a super simple and clean loop:
def main(): server = socketwrapper('192.168.1.1', 30000) server.startrecvdata() while not server.connected: continue print("Connected to server! Type 'exit' to quit.") while server.connected: message = input("Voce: ") if message == "exit": server.connected = False break server.sendmessage(message) server.stop()
In this loop, we create a an instance of our
socketwrapper which initializes everything for us. Then we call
server.startrecvdata() which, as we said above, starts the function to receive and print data from the UDP connection. The
while not server.connected blocks the program until the thread has started.
Lastly, we have our
while server.connected loop, which waits for user input in the console. We check if the user wants to exit, and if they do, we set
server.connected = False and
break our while loop.
If the user does not want to exit, we send the message to the UDP server.
After the loop ends, we call
server.stop to ensure that the socket is closed before exiting the application. | https://codedump.io/share/hgjQFmEg352j/1/creating-a-chat-client-program-how-can-i-add-simultaneous-conversation | CC-MAIN-2017-51 | refinedweb | 589 | 61.63 |
One program that some new users of Unix-like systems are introduced to when learning the command-line is fortune. The purpose of the program is simple: to display a random message from a database of quotations.
Note: fortune is available on the Mac OS X using MacPorts (
port install fortune), Ubuntu (
apt-get install fortune-mod), and Fedora (
yum install fortune-mod).
A demonstration of running it:
$ fortune The human race has one really effective weapon, and that is laughter. -- Mark Twain
I thought it would be fun to get this to work in Factor. We're going to do it two different ways. The first way is to use the io.launcher vocabulary for launching processes and printing the output directly to the listener.
( scratchpad ) "/opt/local/bin/fortune" utf8 [ contents print ] with-process-reader It'll be just like Beggars Canyon back home. -- Luke Skywalker
Another way is to parse the fortune files directly, and then choose a random quotation to print (i.e., implementing the fortune logic inside of Factor). First, we will need to list the vocabularies we will be using and define a "fortune" namespace:
USING: io io.encodings.ascii io.files kernel make memoize random sequences splitting strings ; IN: fortune
The fortune program uses data files which are stored in a "cookie-jar format". From faqs.org:
It is appropriate for records that are just bags of unstructured text. It simply uses newline followed by %% (or sometimes newline followed by %) as a record separator.
Parsing a fortune data file (given a string containing the contents in cookie-jar format) is pretty straightforward. We are using slices which allow us to keep pointers to sections of text within the data file.
: parse-fortune ( str -- seq ) [ [ "%\n" split1-slice dup ] [ swap , ] while drop , ] { } make ; : load-fortunes ( path -- seq ) ascii file-contents parse-fortune ;
The fortune data files are installed in different locations on different systems, so we can define a search path which includes some of the locations that are often used. We can then use this list to load the fortunes from the first data file that exists (and memoize the results for performance):
CONSTANT: FORTUNES { "/usr/games/fortune/fortunes" "/usr/share/games/fortune/fortunes" "/usr/local/share/games/fortune/fortunes" "/opt/local/share/games/fortune/fortunes" } MEMO: default-fortunes ( -- seq ) FORTUNES [ exists? ] find nip load-fortunes ;
Getting a fortune is then just a matter of choosing a random quotation and printing it out:
: fortune ( -- ) default-fortunes random >string print ;
If you want, you could define a MAIN: entry point and use the deploy tool to make this into a deployed binary.
The source code for this is available on my Github.
Update: Doug Coleman suggested a one-liner that can produce the same result:
"/opt/local/share/games/fortune/fortunes" ascii file-lines { "%" } split random [ print ] each | http://re-factor.blogspot.com/2010_09_01_archive.html | CC-MAIN-2013-20 | refinedweb | 474 | 51.99 |
Lopy and Node-Red communication
Hi,
I’ve got a Lopy with Pytrack extension board and have been playing around with GPS coordinates.
Now I’d like to connect to Node-Red, which I installed on my PC (Windows 10). What is the easiest way to send data between Lopy and Node-Red for testing purposes?
I’ve tried this via the serial port but did not succeed. I’ve to admit I’m bit of a beginner at this and hoping that someone can point me in the right direction.
I installed the serial nodes in Node-Red and set this to COM3 (9600 baud rate). This shows the Lopy as connected.
Then I created a simple loop to print every 5 seconds from the Lopy. I can see this in the REPL console but not in the debug window in Node-Red. I figured instead of print, I should use uart.write and added the following bits to my code:
from machine import UART uart = UART(0, 9600) while True: time.sleep(5) uart.write("Test")
However still no output in Node-Red. Also tried 115200 baud rate and UART1.
Where am I going wrong? Or is there perhaps a better way to communicate between Lopy and Node-Red, other than the serial port?
Also a little sub-question: how can I send l76.coordinates of the Lopy to Node-Red? I know uart.write expects bytes object or string, not tuple. Is there an easy way to convert or an alternative to uart.write that works with tuple?
Many thanks in advance!
Brilliant @Matthew-Felgate-0 the example is working for me and I was able to integrate this into my project. Thanks!
But now you also got me interested in MQTT :)
I followed some of the examples from here and here.
However I always run into the same error leading back to the mqtt library:
Traceback (most recent call last): File "main.py", line 19, in <module> File "/flash/lib/mqtt.py", line 65, in connect OSError: Network card not available
This is line 65 in the connect function:
self.sock = socket.socket()
I tried various MQTT brokers, e.g. HiveMQ ,test.mosquitto.org, as well running mosquito locally.
But I just can’t get past the above error.
Any idea?
- Matthew Felgate 0 Global Moderator last edited by Matthew Felgate 0
I have got node-red Serial node working. In Node Red I have
/dev/tty.usbmodemPy91b3c81. Your board will have a similar name. note: make sure there is no empty space at the end of the name and baud rate set to
115200.
Node Red debug output:
04/03/2021, 15:08:12node: 7cae131c.d729ec msg.payload : string[6] "hello↵" 04/03/2021, 15:08:12node: 7cae131c.d729ec msg.payload : string[13] "print hello↵" 04/03/2021, 15:08:12node: 7cae131c.d729ec msg.payload : string[2] "↵"
I think your serial connection in terminal or Visual Studio will need to be closed else you won't get the data into Node-Red. (I think serial data can only be read at one place at a time)
Here is my code for reference:
from machine import UART import os uart = UART(0, 115200) os.dupterm(uart)
import time print('Hello World!') while True: uart.write('hello\n') print('print hello\n') time.sleep(5) print('The End.')
Let me know if that works for you?
Thanks @Matthew-Felgate-0, that's a good suggestion. Will give MQTT a try.
Still curious though where I went wrong on the serial port. If someone sees an obvious error, please let me know.
- Matthew Felgate 0 Global Moderator last edited by
Hi
Maybe using MQTT on Lopy to send messages into Node-Red (via a MQTT broker) may be a way to do it? | https://forum.pycom.io/topic/6874/lopy-and-node-red-communication/2 | CC-MAIN-2021-17 | refinedweb | 635 | 76.82 |
The Material View is probably among the most unknown Sales Order Enhancements in SD.
Let’s change that – your sales reps will love it!
Let’s change that – your sales reps will love it!
The Material View improves the sales order entry experience significantly as it helps sales reps to reduce their navigation effort back and forth down to a few clicks when answering customer’s and their own questions.
And the best is: The Material View is configured and activated in just 30min!
Did I make you curious? Good!
Let’s first start with the business problem:
I’m sure you heard common customer questions like these a million times:
- “I need more items than you have in stock in your store. Could you please check if more are available in other stores?”
- “Why is the product so expensive? Last time I paid 50 dollars, and now it’s 58. Has there been a price change recently,
or is there a scale price I could benefit from when I increase my order quantity?“
- “I urgently need 100 pieces in two days delivered. If you haven’t so many in stock, could you please call your supplier to make sure I get’em in time?“
- “Are there any alternative or upselling/downselling/cross selling products?”
Lots of navigation is required you might think.
NO, it’s not – it’s one click when you have the Material View activated in va01!
NO, it’s not – it’s one click when you have the Material View activated in va01!
Just mark the corresponding sales item(s) in your ERP sales order and click on a new button “Material View” in the lower toolbar (see red circle below):
A consolidated page appears, the Material View, from which you’ll get all the information you need to answer all those types of questions:
(The picture is taken from an IS Retail system, that’s why it says “Article” instead of “Material” and some other terms. However, this ERP core feature works with all ERP 6.0 EhP2+ systems, regardless of whether it is an industry solution or ERP standard.)
So with one click in the ERP Sales Order the Material View gives you a consolidated 1-page view with the most important material and sales data,
like the most important material basic data, dimensions, alternative/up/down/cross selling materials, basic and sales texts, regular vendor information, ATP stock availability, list prices and customer sales prices incl. scales, plus an overview of the last sales orders of the customer for the selected material.
like the most important material basic data, dimensions, alternative/up/down/cross selling materials, basic and sales texts, regular vendor information, ATP stock availability, list prices and customer sales prices incl. scales, plus an overview of the last sales orders of the customer for the selected material.
Where does all this information come from?
The information is pulled out of the corresponding standard tables in ERP in the moment you call the Material View for a selected sales order item..
Will the Material View potentially mess up my Sales Order?
No. The Material View is called via RFC from the Sales Order. It is a pure display functionality, without affecting the Sales Order in any way. In fact the Material View uses information provided by the Sales Order, like Org Data, conditions, etc, but does not transfer any information back to the Sales Order. So your Sales Order configuration and behavior remains untouched – promised!
All my questions answered with one click, alright. So where’s the hitch? Trust me, there is none!
- All you need is a SAP ERP 6.0 system with Enhancement Package 2 or higher. No BW, no CRM, no search engine, no services, no NetWeaver, no limitation to specific industry solutions, no nothing! It’s a generic ERP core function!
- No extra costs or licenses. It’s a continuous ERP improvement.
- No performance decrease – on the contrary! Your sales reps get the required information faster, without a further need to navigate.
- Simple installation, done in 30 min max.
OK, I want it. How do I get it?
Here you find everything you need:
- Material View Info Kit
A presentation, solution briefs, a config guide and an offline demo about the Material View is available here:
- Business Function
First you need to make sure the required Business Function of the ERP Enhancement Package is activated. The Material View is part of SAP ERP Core 6.0 EhP2, contained in component SAP_APPL 602 in Business Function SD_01. The business function can be activated with transaction SFW5.
In EhP5 you need to activate business function LOG_SD_CI_02.
- SAP Online Help Documentation
- How to add customer specific tabs in Material View?
You can add one customer specific tab per frame which already contains tabs. Therefore you have to enhance the existing coding using the enhancement spots. For EhP2 and 3 please read SAP note 1096359. For EhP4 and 5 please read SAP note 1470088.
- How can I use alternative materials and cross-/up-/down-sessling proposals in ERP. Isn’t this a SAP CRM functionality?
This functionality has been implemented as BAdIs to be used in the Material View. You can find these BAdIs in Customizing IMG > Sales and Distribution > Basic Functions > Additional Functions for Material > Enhancements using Business Add-Ins > Business Add-Ins for Material View.
In our demo system we have I implemented all relations in a single Z-table.
Any questions are welcome!
Enjoy and post your experiences with the Material View!
Best regards,
Dr. Ingo Woesner
Product Manager
Suite Development – Multi Channel
SAP AG
Product Manager
Suite Development – Multi Channel
SAP AG
P.S. All my blogs about Sales Order Enhancements are collected here:
Sales Order Enhancement Series: Overview
Sales Order Enhancement Series: Overview
Regards,
Joan Swan
Graybar
no, there is no need to configure anything. Please raise an OSSticket on component LO-GEN-EMF.
Best regards,
Ingo
But there are two things you can do to avoid a core modification:
Option 1)
use the BAdI “Enhancement of Material View with Additional Screens” to add a new tab in the top frame. Within this tab you can display whatever you want.
– disadvantage: you have to create a whole tab content from scratch
Option 2)
Copy the Material View package to Z-namespace. Within the copy you can extend the code without having a modification. Use the BAdI “BAdI: Customer-Specific Material View” to call the copy when calling the Material View.
– disadvantage: The Material View was slightly extended in Enhancement Pack 5. You would have to make these changes manually.
Thank you for your quick response. Could you please tell me if the Enhancement Pack 5 extension changes will affect the ability to change the tab in any way?
Currently the request from our business community is for us to build a list of alternate materials containing Material number, catalog number, Description, Product Hierarchy, Vendor name, and Customer Material number. They do not want to see the pricing info etc. We do have Guixt at our facility so that might give us some additional flexibility.
Thanks for your input
Ellie
Thank you for your quick response to my first question. Your input is very helpful. Followup question. Will the “slightly extended in Enhancement Pack 5” affect the ability to change the tab?
My requirement is that I provide an output list of alternate material numbers with catalog numbers, description, product Heirarchy, Vendor name, and customer material number. My business anaylysts do not want the current info offered such as price, etc.
Ellie
Your original response was very helpful. We had a followup question. Will the “slightly extended in Enhancement Pack 5” affect the ability to change the tab. I appreciate your input.
Ellie
the (minor) changes in EhP5 do not affect the tabs in the upper part of the screen.
Changes comprise:
– in vendor tab all vendors can now be seen (incl. the info which one is the regular vendor), plus button to call the corresponding purchasing info record
– in Availability tab a new button was introduced to call the stock overview transaction
– in tab “Last Sales Orders” new fields are displayed (Status, billing block, created by). double clicking on the sales order numbers calls the va03 of this sales order.
Enjoy,
Ingo
Calculation of Contribution Margin
The calculation of the margin is often company specific. Therefore a BAdI is provided to implement a customer specific algorithm, to show the calculated margin in the Material View.
You can find the BAdI in IMG > Sales &Distribution > Basic Functions > Additional Functions for Material > Enhancements using Business Add-Ins > Business Add-Ins for Material View > BAdI: Calculation of Contribution Margin.
Enjoy,
Ingo
Hi Ingo,
We are implementing the Article View and I have a quick question regarding the List Price Overview section. Do you know if there is a way to configure the validity period included in the list? i.e. at the moment it seems to include all past, present and future changes in the list price. We would like to restrict it for example so that it doesn’t include all past changes (as the list could get quite long over time).
I know there is a configuration option for the Last Sales Orders to limit the period it looks at – is there something similar for the list prices?
Thanks,
Alex
Hi Alex,
unfortunately there is no customizing option to influence the validity period of prices. All past and future prices are shown.
The only you can do is to modify it, I’m sorry.
The Material View is quite matured and most likely there won’t be any future updates. So your modification should be without any effect to future compatibility.
Best regards,
Ingo
Hi Ingo,
We have activated Business function LOG_SD_CI_02 for Material view. but we are not able to get data in ‘List price overview and Scale prices’ under Sales Prices Tab. We have done the required configuration. Could you please help me what could be the reason. Thanks in Advance.
Note: We have upgraded to EHP6 FOR SAP ERP 6.0
Regards,
Reddy | https://blogs.sap.com/2009/07/31/sales-order-enhancement-series-the-material-view/ | CC-MAIN-2018-30 | refinedweb | 1,688 | 56.45 |
Hello everybody,
Storing char or String in EEPROM
Thanks
Hello everybody,
Storing char or String in EEPROM
Thanks
The docs are your friend. EEPROM can be unintuitive, give 'em a read!
If you are storing a single int value, it should be something like
#include <EEPROM.h> int addr = 0; // EEPROM address (location where int is stored void setup() { ... } void loop() { ... int val = 58; // get your integer value EEPROM.write(addr, val); // write the integer value to EEPROM address }
That's preety easy. But, the problem is that I need to store a string value to the EEPROM
Read the docs. It can be done.
My friend If I can did it alone, I wouldn't ask here from the first place. I have read it before even writing this problem and tried it so many times without any result. So please if you don't want to help just be silent and let other help.
Nice response when I just tried to help you.
Your OP specifically asked to store an INT.
My friend, I know how to store an integer before writing this problem, my problem is that I want to store a string inside the EEPROM and I don't know hot to do that.
I need to store a string value like "130 207 95 100" to the EEPROM
It's not clear if you have a String object (capital 'S') or c-string (small letter 's' null terminated character array).
You can not store the String object, but you can store the underlying character array with eeprom.put().
To extract the underlying character array if you have a String object, you can use the .toCharArray() String function.
It is capital String, I found a way to convert it to a unsigned long but couldn't also save it to the EEPROM.
Any help with that?
Please post some simple code which shows what you are doing.
It should be straightforward to use EEPROM.put() and EEPROM.get() with an unsigned long.
Store it character-by-character?
void store(int address, String s) { int len = s.length(); for (int i=0; i<len; i++) EEPROM[address+i] = s[i]; EEPROM[address+len] = '\0'; // Add a null terminator }
Thank you so much, I have solved the problem appreciate your attention to help
Thanks, I have selected your reply as a solution
I apologize for any negative behavior or miss communication. I was upset that night.
Spoken like a man. Apology accepted.
I see you have a solution.
Best of luck! | https://forum.arduino.cc/t/storing-in-eeprom-memory/922176 | CC-MAIN-2021-49 | refinedweb | 423 | 75.3 |
Collaborating with the BizTalk 2006 R2 SharePoint Adapter
Of the options above, "Yes" and "Optional" require support from the "Templates Document Library" and the "Templates Namespace Column" to associate the file with the appropriate template. Refer to the additional information section for more details.
Further down the properties dialog is the "Windows SharePoint Services Integration" section. The dialog appears below:
In this section, you assign the property values in the Document Library. The "Column 0N" contains the name of the property as it appears in the SharePoint Document Library property label and the "..Value" column contains the value to place in the column.
You may have noticed that the column values and in the filename property contain "%XPATH...". For example, the full filename property value appears below:
%XPATH=//ns0:BizTalkContext[1]/ns0:MessageSource% %XPATH=//ns0:FailedMessageDocID%.xml
Macro values such as %XPATH allow you to extract information from the file you are storing or from the BizTalk context. In the XPATH example above, the Adapter is programmed to use the value of the MessageSource element and the FailedMessageDocID element to name the file. Writing XPATH statements is beyond the scope of this article, but you'll find a helpful article here. When using XPATH, you also need to fill in the Namespace Alias if you're using namespace aliases in the XPath statement. Finally, all macros must be enclosed in the "%" sign.
There are some other useful insights to keep in mind. I wanted to highlight them because they should be foremost in your mind as you apply what you've learned.
It is worth noting that work for the project this article is based on was done using InfoPath 2003. I was, however, using SharePoint 2007 and BizTalk 2006 R2, so behavior may vary with other product versions. Although I could not get Document Library properties created by a published InfoPath Template file to work properly, your properties can be created from within the SharePoint Document library. You should also note that versioning, approvals, and check-in/out are not supported by the Adapter.
I mentioned earlier that you could use the Adapter to update Lists and Wikis. Updating these other repositories is covered in the BizTalk documentation. Also, there is a great four-part Webcast on the SharePoint BizTalk adapter ().
Conclusion
SharePoint has become a major collaboration platform. Microsoft has made it part of many of their major products. In BizTalk, the SharePoint Adapter and an accompanying Web Service perform all the SharePoint integration duties. The Adapter mostly works with Document and Form Libraries. It is especially adept with XML and InfoPath.
Download the Code
You can download the source code for this article here.
Acknowledgements
Special thanks to Jeff Hunter and Corné van Dyk, my company's SharePoint experts, for their expertise and assistance<< | http://www.developer.com/net/article.php/10916_3703961_3/Collaborating-with-the-BizTalk-2006-R2-SharePoint-Adapter.htm | CC-MAIN-2016-26 | refinedweb | 467 | 55.64 |
Migrate4j - Database Migration Tool for Java
Migrate4j is a migration tool for java, similar to Ruby's db:migrate task. Unlike other Java based migration tools, database schema changes are defined in Java, not SQL. This means your migrations can be applied to different database engines without worrying about whether your DDL statements will still work.
Schema changes are defined in Migration classes, which define "up" and "down" methods - "up" is called when a Migration is being applied, while "down" is called when it is being rolled back. A simple Migration, which simply adds a table to a database, is written as:
package db.migrations;
import static com.eroi.migrate.Define.*;
import static com.eroi.migrate.Define.DataTypes.*;
import static com.eroi.migrate.Execute.*;
import com.eroi.migrate.Migration;
public class Migration_1 implements Migration
{
public void up()
{
createTable(
table("simple_table",
column("id", INTEGER, primaryKey(), notnull()),
column("desc", VARCHAR, length(50), defaultValue("NA"))));
}
public void down()
{
dropTable("simple_table");
}
} adds improved usability (simplified syntax), additional schema changes and support for more database products. While migrate4j does not yet have support for all database products, we are actively seeking developers interested in helping fix this situation.
Visit for more information on how migrate4j can simplify synchronizing your databases. To obtain migrate4j, go to and download the latest release. For questions or to help with future development of migrate4j, email us at migrate4j-users AT lists.sourceforge.net (replacing the AT with the "at symbol").
- Login or register to post comments
- 5966 reads
- Printer-friendly version
(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)
Jon Chase replied on Mon, 2008/04/28 - 1:17pm
Looks nice, but does this offer anything over and above what Liquibase () does (other than sql defined in Java instead of XML)?
I've been using Liquibase for automatic database upgrades during app deployments and it's been great - it's so nice not to have to run those scripts manually anymore!
I'm glad to see another serious project in this market - it shows that there is definitely interest, and this is something that the agile Java community has needed for a long time.
-------------------
Jon Chase
SendAlong.com - Securely email large files to anyone
todd replied on Mon, 2008/04/28 - 1:47pm
Jon,
From a feature standpoint, migrate4j is intended to be very similar to Liquibase. However, our main focus is to provide a tool that uses Java to define schema changes.
If you're already using Liquibase, db:migrate, or some other migration tool, you'll probably want to stick with that. However, for Java projects that are not using a migration tool, migrate4j is an option to consider.
Jon Chase replied on Mon, 2008/04/28 - 1:53pm
Todd,
Thanks for the clarification - I think Migrage4j is a good option for teams that want to stick to Java and stay out of XML.
Jon
Stefan replied on Mon, 2008/04/28 - 11:22pm
The sourceforge project page indicates that migrate4j is licenced under GPL. This means many open source projects that are using a more liberal license (e.g. Apache) as well as closed source projects won't be able to use it.
Is that by intention?
todd replied on Tue, 2008/04/29 - 9:14am
in response to: srt
Stefan,
The reason for going GPL right now is to make sure improvements get shared. As much as we'd love migrate4j to be adopted by other projects, we want all work being done to be donated back. Once our codebase is more complete, offering other licensing options is certainly a possibility.
Stefan replied on Tue, 2008/04/29 - 10:18am
in response to: toddrun
I guess you could also achieve this with LGPL which would still make sure enhancements to the library are passed back while allowing more liberal usage of the library in other projects.
LGPL is also used by LiquidBase - probably your strongest "competitor" ;)
=Stefan | http://java.dzone.com/announcements/migrate4j-database-migration-t | crawl-002 | refinedweb | 666 | 61.16 |
I need some suggestions from some of you people.
What would be a good first game using graphics?
I just figured out how to use graphics.h and I need some info on a project that would be simple for a first!
I need some suggestions from some of you people.
What would be a good first game using graphics?
I just figured out how to use graphics.h and I need some info on a project that would be simple for a first!
I just thought of a new game, it could be two player, or one against the AI. There is a runner and a catcher. Both players control circle, the runner circle is smaller that the catcher. If you are the runner, you are suppose to avoid the catcher for a certain time. If you are the catcher you are suppose to catch the runner. By catch, it means touch them. It looks better in my head than it sounds :).
If you want to get some graphics experience without worrying about having to conquer anything too new, I'd say take a game you've already written in console and make a graphical version of it. Like say a graphical tic-tac-toe or hangman.
If you want something totally fresh, then maybe make a side-scrolling shooter or top-down shooter. And of course there's always everyone's (? maybe) first graphical game, Pong.
Chokes and spits out drink when sees pong...
PONG!?!?!
No thank you.. no bounce and angles and crap :D
I have a problem though... how do I use graphics with arrays?
Is there any good examples of programs
I'm not familiar with the graphics.h file you mentioned but here's a generic example of using arrays with graphics:
Not sure if that's what you're looking for or not. If you could post a generic blit routine that you might you use, I can offer more specific help.Not sure if that's what you're looking for or not. If you could post a generic blit routine that you might you use, I can offer more specific help.Code:
CEnemy cdBadGuys[3];
CHero chYou;
int i;
MainDrawingLoop()
{
for(i=0;i<3;i++)
{
if(cdBadGuys[i].IsAlive())
{
cdBadGuys[i].DrawBaddy(cdBadGuys[i].MapX(),cdBadGuys[i].MapY);
}
}
chYou.DrawHero(chYou.MapX,chYou.MapY);
}
Jason
I really just want to know how to draw.. say a circle and move the circle across the screen.
And is it dificult to use images?
Im not sure how I would make a ship in a shooter?
What compiler are you using? Did graphics.h come with it or is it something you downloaded from somewhere else? This is the first I've heard of it so I'm not sure if it's a stand-alone library or a wrapper for another. If I can find out what API/library it's using then I can look into it and give you a better answer.
Borland C++ 5.02
Its BGI graphics.
cant get any farther... :(cant get any farther... :(Code:
#include <iostream.h>
#include <graphics.h>
int GraphicsDriver;
int GraphicsMode;
int gridx [50];
int gridy [50];
int main()
{
initgraph ( &GraphicsDriver, &GraphicsMode, "c:\\bc5\\bgi" );
setcolor (RED);
outtext ("So sue me.. ");
setcolor (YELLOW);
setfillstyle ( SOLID_FILL, YELLOW );
pieslice ( 100, 100, 30, 330, 15 );
setcolor (WHITE);
setfillstyle ( SOLID_FILL, WHITE );
pieslice ( 140, 100, 1, 360, 2 );
pieslice ( 160, 100, 1, 360, 2 );
pieslice ( 180, 100, 1, 360, 5 );
cin.get();
closegraph();
return 0;
}
You finally figured that thing out huh? That's some funky old DOS library J :) Why don't you give tetris a try Vicious? You'd get to learn basic collision among cool stuff.
I would but all I know how to do is put out the graphics...
I cant make it move or get key input and move the pieces or whatever.
:rolleyes:
oh and if anybody knows this...
How do you make a tetris block?
:confused:
Whoa... I think you're going to need to learn how to get keyboard input if you're going to make a game there buddy :)
Tetris blocks? Think about it... every block is made up of four smaller blocks.
You could either code some rectangles, or use bitmaps.
I'm about to start working on a tetris game myself. I've put it off way too long. I just can't decide which library to use. No, I don't think I'll use BGI :rolleyes:
Thanx again Lamb. :DThanx again Lamb. :DCode:
#include <iostream.h>
#include <graphics.h>
#include <conio.h>
int GraphicsDriver;
int GraphicsMode;
int x = 25;
int y = 25;
int quit = 0;
int mve;
int main()
{
initgraph ( &GraphicsDriver, &GraphicsMode, "c:\\bc5\\bgi" );
while ( !quit )
{
gotoxy(1,1);
cout << "X: " << x << " Y: " << y;
mve = getch();
switch ( mve )
{
case 'w': y--; break;
case 's': y++; break;
case 'd': x++; break;
case 'a': x--; break;
case 'q': quit=1; break;
}
cleardevice();
circle ( x, y, 10 );
}
closegraph();
return 0;
}
OOOPS!
Forgot to post my question.
How can I make it move faster?? | https://cboard.cprogramming.com/game-programming/18754-new-game-printable-thread.html | CC-MAIN-2017-13 | refinedweb | 846 | 85.49 |
Socket having to close and reopen
Hello,
I have a Raspberry pie connected to 4 Lopy's over wifi, and a java tcp server program running on the rpi with sockets (with different port) for each lopy.
My problem is that I have to close the connection after sending a bytearray, and the repon it again when I need to send the next bytearray. The time it takes for it to reconnect to the socket is not really feasible for the system.
Is it supposed to work like this with sockets, or am I doing something wrong?
The server code is here:
And the lopy code is here:
from network import Bluetooth from network import WLAN import socket #from network import socket import pycom import time import machine import binascii from machine import Timer pycom.heartbeat(False) pycom.rgbled(0x000000) # turn off led lopyID = 4 # set this unique to each lopy print('started! lopy id: ', lopyID) #for breaking out of while(True) loops. Removed when program is finished chrono = Timer.Chrono() # chrono.start() wlan = WLAN(mode=WLAN.STA) nets = wlan.scan()0000) # red #time.sleep(0.5) #pycom.rgbled(0x000000) # turn off led #time.sleep(1) pycom.rgbled(0x7f0000) for net in nets: # connect to rpi wifi if net.ssid == 'cooppifi': print('rpi found!') wlan.connect(net.ssid, auth=(net.sec, 'cooppifi2017'), timeout=4000) for _ in range(20): time.sleep(1) if wlan.isconnected(): print("connected to rpi") break print('.', end='') else: print("could not connect to wifi, resetting lopy...") machine.reset() bluetooth = Bluetooth() bluetooth.start_scan(-1) adv = None # bluetooth advertisementa time.sleep(2) def sendToSocket(beaconID, rssi): RSSIpositive = rssi * -1 #newData = beaconID + lopyID + RSSIpositive #newData = 255 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(socket.getaddrinfo('10.42.0.1', 6792)[0][-1]) pycom.rgbled(0x007f00) time.sleep(0.5) pycom.rgbled(0x000000) # turn off led time.sleep(0.5) print('.') data = bytearray() #data.append(newData) data.append(lopyID) data.append(beaconID) data.append(RSSIpositive) print("sending to socket, binary: ", data, data[0]) #conv = binascii.hexlify(data) #print(conv, encoding='utf8') s.send(data) s.close() # b'f3bc0b6feb4c' # raw: b'\xf3\xbc\x0bo\xebL' # b'edbed48d0b87' # raw: b'\xed\xbe\xd4\x8d\x0b\x87 # b'c7c383eeaaa4' # raw? # b'cd87e6a38dc2' # raw? pycom.rgbled(0x007f00) # green while True: adv = bluetooth.get_adv() if adv != None: #print('!') #print('!!') macRaw = adv[0] # binary mac address macReal = binascii.hexlify(macRaw) # convert to hexadecimal if macReal == b'f3bc0b6feb4c': print('beacon A rssi: ', adv[3]) # adv[3] is rssi sendToSocket(beaconID = 1, rssi = adv[3]) elif macReal == b'edbed48d0b87': print('beacon B rssi: ', adv[3]) sendToSocket(beaconID = 2, rssi = adv[3]) elif macReal == b'c7c383eeaaa4': print('beacon C rssi: ', adv[3]) sendToSocket(beaconID = 3, rssi = adv[3]) elif macReal == b'cd87e6a38dc2': print('beacon D rssi: ', adv[3]) sendToSocket(beaconID = 4, rssi = adv[3]) # adv[3] #time.sleep(1) #lap = chrono.read() # for breaking out of loop (remove this part when program is finished) #if lap > 30: # print("breaking") # bluetooth.stop_scan() # break ```
@soren said in Socket having to close and reopen:
You close socket on server side then you must close it also on client side(it is closed already but..)
Question is what problem do you have with the code?
Is it working, if yes, do you ask if there is some better way? | https://forum.pycom.io/topic/2093/socket-having-to-close-and-reopen/2 | CC-MAIN-2020-29 | refinedweb | 549 | 59.7 |
Công Nghệ Thông Tin
Cơ sở dữ liệu
Tải bản đầy đủ
Chapter 2. Downloading Spark and Getting Started
Chapter 2. Downloading Spark and Getting Started
Tải bản đầy đủ
You don’t need to have Hadoop, but if you have an existing Hadoop cluster or HDFS
installation, download the matching version. You can do so from http://
spark.apache.org/downloads.html by selecting a different package type, but they will
have slightly different filenames. Building from source is also possible; you can find
the latest source code on GitHub or select the package type of “Source Code” when
downloading.
Most Unix and Linux variants, including Mac OS X, come with a
command-line tool called tar that can be used to unpack TAR
files. If your operating system does not have the tar command
installed, try searching the Internet for a free TAR extractor—for
example, on Windows, you may wish to try 7-Zip.
Now that we have downloaded Spark, let’s unpack it and take a look at what comes
with the default Spark distribution. To do that, open a terminal, change to the direc‐
tory where you downloaded Spark, and untar the file. This will create a new directory
with the same name but without the final .tgz suffix. Change into that directory and
see what’s inside. You can use the following commands to accomplish all of that:
cd ~
tar -xf spark-1.2.0-bin-hadoop2.4.tgz
cd spark-1.2.0-bin-hadoop2.4
ls
In the line containing the tar command, the x flag tells tar we are extracting files,
and the f flag specifies the name of the tarball. The ls command lists the contents of
the Spark directory. Let’s briefly consider the names and purposes of some of the
more important files and directories you see here that come with Spark:
README.md
Contains short instructions for getting started with Spark.
bin
Contains executable files that can be used to interact with Spark in various ways
(e.g., the Spark shell, which we will cover later in this chapter).
core, streaming, python, …
Contains the source code of major components of the Spark project.
examples
Contains some helpful Spark standalone jobs that you can look at and run to
Don’t worry about the large number of directories and files the Spark project comes
with; we will cover most of these in the rest of this book. For now, let’s dive right in
and try out Spark’s Python and Scala shells. We will start by running some of the
10
|
Chapter 2: Downloading Spark and Getting Started
examples that come with Spark. Then we will write, compile, and run a simple Spark
job of our own.
All of the work we will do in this chapter will be with Spark running in local mode;
that is, nondistributed mode, which uses only a single machine. Spark can run in a
variety of different modes, or environments. Beyond local mode, Spark can also be
run on Mesos, YARN, or the Standalone Scheduler included in the Spark distribu‐
tion. We will cover the various deployment modes in detail in Chapter 7.
Introduction to Spark’s Python and Scala Shells
Spark comes with interactive shells that enable ad hoc data analysis. Spark’s shells will
feel familiar if you have used other shells such as those in R, Python, and Scala, or
operating system shells like Bash or the Windows command prompt.
Unlike most other shells, however, which let you manipulate data using the disk and
memory on a single machine, Spark’s shells allow you to interact with data that is dis‐
tributed on disk or in memory across many machines, and Spark takes care of auto‐
matically distributing this processing.
Because Spark can load data into memory on the worker nodes, many distributed
computations, even ones that process terabytes of data across dozens of machines,
can run in a few seconds. This makes the sort of iterative, ad hoc, and exploratory
analysis commonly done in shells a good fit for Spark. Spark provides both Python
and Scala shells that have been augmented to support connecting to a cluster.
Most of this book includes code in all of Spark’s languages, but
interactive shells are available only in Python and Scala. Because a
shell is very useful for learning the API, we recommend using one
of these languages for these examples even if you are a Java devel‐
oper. The API is similar in every language.
The easiest way to demonstrate the power of Spark’s shells is to start using one of
them for some simple data analysis. Let’s walk through the example from the Quick
Start Guide in the official Spark documentation.
The first step is to open up one of Spark’s shells. To open the Python version of the
Spark shell, which we also refer to as the PySpark Shell, go into your Spark directory
and type:
bin/pyspark
(Or bin\pyspark in Windows.) To open the Scala version of the shell, type:
bin/spark-shell
Introduction to Spark’s Python and Scala Shells
|
11
The shell prompt should appear within a few seconds. When the shell starts, you will
notice a lot of log messages. You may need to press Enter once to clear the log output
and get to a shell prompt. Figure 2-1 shows what the PySpark shell looks like when
you open it.
Figure 2-1. The PySpark shell with default logging output
You may find the logging statements that get printed in the shell distracting. You can
control the verbosity of the logging. To do this, you can create a file in the conf direc‐
tory called log4j.properties. The Spark developers already include a template for this
file called log4j.properties.template. To make the logging less verbose, make a copy of
conf/log4j.properties.template called conf/log4j.properties and find the following line:
log4j.rootCategory=INFO, console
Then lower the log level so that we show only the WARN messages, and above by
changing it to the following:
log4j.rootCategory=WARN, console
When you reopen the shell, you should see less output (Figure 2-2).
12
|
Chapter 2: Downloading Spark and Getting Started
Figure 2-2. The PySpark shell with less logging output
Using IPython
IPython is an enhanced Python shell that many Python users pre‐
fer, offering features such as tab completion. You can find instruc‐
tions for installing it at. You can use IPython
with Spark by setting the IPYTHON environment variable to 1:
IPYTHON=1 ./bin/pyspark
To use the IPython Notebook, which is a web-browser-based ver‐
sion of IPython, use:
IPYTHON_OPTS="notebook" ./bin/pyspark
On Windows, set the variable and run the shell as follows:
set IPYTHON=1
bin\pyspark
In Spark, we express our computation through operations on distributed collections
that are automatically parallelized across the cluster. These collections are called resil‐
ient distributed datasets, or RDDs. RDDs are Spark’s fundamental abstraction for dis‐
tributed data and computation.
Before we say more about RDDs, let’s create one in the shell from a local text file and
do some very simple ad hoc analysis by following Example 2-1 for Python or
Example 2-2 for Scala.
Introduction to Spark’s Python and Scala Shells
|
13
Example 2-1. Python line count
>>> lines = sc.textFile("README.md") # Create an RDD called lines
>>> lines.count() # Count the number of items in this RDD
127
>>> lines.first() # First item in this RDD, i.e. first line of README.md
u'# Apache Spark'
Example 2-2. Scala line count
To exit either shell, press Ctrl-D.
We will discuss it more in Chapter 7, but one of the messages you
may have noticed is INFO SparkUI: Started SparkUI at
http://[ipaddress]:4040. You can access the Spark UI there and
see all sorts of information about your tasks and cluster.
In Examples 2-1 and 2-2, the variable called lines is an RDD, created here from a
text file on our local machine. We can run various parallel operations on the RDD,
such as counting the number of elements in the dataset (here, lines of text in the file)
or printing the first one. We will discuss RDDs in great depth in later chapters, but
before we go any further, let’s take a moment now to introduce basic Spark concepts.
Introduction to Core Spark Concepts
Now that you have run your first Spark code using the shell, it’s time to learn about
programming in it in more detail.
At a high level, every Spark application consists of a driver program that launches
various parallel operations on a cluster. The driver program contains your applica‐
tion’s main function and defines distributed datasets on the cluster, then applies oper‐
ations to them. In the preceding examples, the driver program was the Spark shell
itself, and you could just type in the operations you wanted to run.
Driver programs access Spark through a SparkContext object, which represents a
connection to a computing cluster. In the shell, a SparkContext is automatically
14
|
Chapter 2: Downloading Spark and Getting Started
created for you as the variable called sc. Try printing out sc to see its type, as shown
in Example 2-3.
Example 2-3. Examining the sc variable
>>> sc
Once you have a SparkContext, you can use it to build RDDs. In Examples 2-1 and
2-2, we called sc.textFile() to create an RDD representing the lines of text in a file.
We can then run various operations on these lines, such as count().
To run these operations, driver programs typically manage a number of nodes called
executors. For example, if we were running the count() operation on a cluster, differ‐
ent machines might count lines in different ranges of the file. Because we just ran the
Spark shell locally, it executed all its work on a single machine—but you can connect
the same shell to a cluster to analyze data in parallel. Figure 2-3 shows how Spark
executes on a cluster.
Figure 2-3. Components for distributed execution in Spark
Finally, a lot of Spark’s API revolves around passing functions to its operators to run
them on the cluster. For example, we could extend our README example by filtering
the lines in the file that contain a word, such as Python, as shown in Example 2-4 (for
Python) and Example 2-5 (for Scala).
Example 2-4. Python filtering example
>>> lines = sc.textFile("README.md")
>>> pythonLines = lines.filter(lambda line: "Python" in line)
Introduction to Core Spark Concepts
|
15
>>> pythonLines.first()
u'## Interactive Python Shell'
Example 2-5. Scala filtering example
scala> val lines = sc.textFile("README.md") // Create an RDD called lines
lines: spark.RDD[String] = MappedRDD[...]
scala> val pythonLines = lines.filter(line => line.contains("Python"))
pythonLines: spark.RDD[String] = FilteredRDD[...]
scala> pythonLines.first()
res0: String = ## Interactive Python Shell
Passing Functions to Spark
If you are unfamiliar with the lambda or => syntax in Examples 2-4 and 2-5, it is a
shorthand way to define functions inline in Python and Scala. When using Spark in
these languages, you can also define a function separately and then pass its name to
Spark. For example, in Python:
def hasPython(line):
return "Python" in line
pythonLines = lines.filter(hasPython)
Passing functions to Spark is also possible in Java, but in this case they are defined as
classes, implementing an interface called Function. For example:
JavaRDD
pythonLines = lines.filter(
new Function
() {
Boolean call(String line) { return line.contains("Python"); }
}
);
Java 8 introduces shorthand syntax called lambdas that looks similar to Python and
Scala. Here is how the code would look with this syntax:
JavaRDD
pythonLines = lines.filter(line -> line.contains("Python"));
We discuss passing functions further in “Passing Functions to Spark” on page 30.
While we will cover the Spark API in more detail later, a lot of its magic is that
function-based operations like filter also parallelize across the cluster. That is,
Spark automatically takes your function (e.g., line.contains("Python")) and ships
it to executor nodes. Thus, you can write code in a single driver program and auto‐
matically have parts of it run on multiple nodes. Chapter 3 covers the RDD API in
detail.
16
|
Chapter 2: Downloading Spark and Getting Started
Standalone Applications
The final piece missing in this quick tour of Spark is how to use it in standalone pro‐
grams. Apart from running interactively, Spark can be linked into standalone appli‐
cations in either Java, Scala, or Python. The main difference from using it in the shell
is that you need to initialize your own SparkContext. After that, the API is the same.
The process of linking to Spark varies by language. In Java and Scala, you give your
application a Maven dependency on the spark-core artifact. As of the time of writ‐
ing, the latest Spark version is 1.2.0, and the Maven coordinates for that are:
groupId = org.apache.spark
artifactId = spark-core_2.10
version = 1.2.0
Maven is a popular package management tool for Java-based languages that lets you
link to libraries in public repositories. You can use Maven itself to build your project,
or use other tools that can talk to the Maven repositories, including Scala’s sbt tool or
Gradle. Popular integrated development environments like Eclipse also allow you to
directly add a Maven dependency to a project.
In Python, you simply write applications as Python scripts, but you must run them
using the bin/spark-submit script included in Spark. The spark-submit script
includes the Spark dependencies for us in Python. This script sets up the environ‐
ment for Spark’s Python API to function. Simply run your script with the line given
in Example 2-6.
Example 2-6. Running a Python script
bin/spark-submit my_script.py
(Note that you will have to use backslashes instead of forward slashes on Windows.)
Initializing a SparkContext
Once you have linked an application to Spark, you need to import the Spark packages
in your program and create a SparkContext. You do so by first creating a SparkConf
object to configure your application, and then building a SparkContext for it. Exam‐
ples 2-7 through 2-9 demonstrate this in each supported language.
Example 2-7. Initializing Spark in Python
from pyspark import SparkConf, SparkContext
conf = SparkConf().setMaster("local").setAppName("My App")
sc = SparkContext(conf = conf)
Standalone Applications
|
17
Example 2-8. Initializing Spark in Scala
import org.apache.spark.SparkConf
import org.apache.spark.SparkContext
import org.apache.spark.SparkContext._
val conf = new SparkConf().setMaster("local").setAppName("My App")
val sc = new SparkContext(conf)
Example 2);
These examples show the minimal way to initialize a SparkContext, where you pass
two parameters:
• A cluster URL, namely local in these examples, which tells Spark how to connect
to a cluster. local is a special value that runs Spark on one thread on the local
machine, without connecting to a cluster.
• An application name, namely My App in these examples. This will identify your
application on the cluster manager’s UI if you connect to a cluster.
Additional parameters exist for configuring how your application executes or adding
code to be shipped to the cluster, but we will cover these in later chapters of the book.
After you have initialized a SparkContext, you can use all the methods we showed
before to create RDDs (e.g., from a text file) and manipulate them.
Finally, to shut down Spark, you can either call the stop() method on your Spark‐
Context, or simply exit the application (e.g., with System.exit(0) or sys.exit()).
This quick overview should be enough to let you run a standalone Spark application
on your laptop. For more advanced configuration, Chapter 7 will cover how to con‐
nect your application to a cluster, including packaging your application so that its
code is automatically shipped to worker nodes. For now, please refer to the Quick
Start Guide in the official Spark documentation.
Building Standalone Applications
This wouldn’t be a complete introductory chapter of a Big Data book if we didn’t
have a word count example. On a single machine, implementing word count is sim‐
ple, but in distributed frameworks it is a common example because it involves read‐
ing and combining data from many worker nodes. We will look at building and
18
|
Chapter 2: Downloading Spark and Getting Started
packaging a simple word count example with both sbt and Maven. All of our exam‐
ples can be built together, but to illustrate a stripped-down build with minimal
dependencies we have a separate smaller project underneath the learning-sparkexamples/mini-complete-example directory, as you can see in Examples 2-10 (Java)
and 2-11 (Scala).
Example 2-10. Word count Java application—don’t worry about the details yet
// Create a Java Spark Context
SparkConf conf = new SparkConf().setAppName("wordCount");
JavaSparkContext sc = new JavaSparkContext(conf);
// Load our input data.
JavaRDD
input = sc.textFile(inputFile);
// Split up into words.
JavaRDD
words = input.flatMap(
new FlatMapFunction
() {
public Iterable
call(String x) {
return Arrays.asList(x.split(" "));
}});
// Transform into pairs and count.
JavaPairRDD
counts = words.mapToPair(
new PairFunction
(){
public Tuple2
call(String x){
return new Tuple2(x, 1);
}}).reduceByKey(new Function2
(){
public Integer call(Integer x, Integer y){ return x + y;}});
// Save the word count back out to a text file, causing evaluation.
counts.saveAsTextFile(outputFile);
Example 2-11. Word count Scala application—don’t worry about the details yet
// Create a Scala Spark Context.
val conf = new SparkConf().setAppName("wordCount")
val sc = new SparkContext(conf)
// Load our input data.
val input = sc.textFile(inputFile)
// Split it up into words.
val words = input.flatMap(line => line.split(" "))
// Transform into pairs and count.
val counts = words.map(word => (word, 1)).reduceByKey{case (x, y) => x + y}
// Save the word count back out to a text file, causing evaluation.
counts.saveAsTextFile(outputFile)
We can build these applications using very simple build files with both sbt
(Example 2-12) and Maven (Example 2-13). We’ve marked the Spark Core depend‐
ency as provided so that, later on, when we use an assembly JAR we don’t include the
spark-core JAR, which is already on the classpath of the workers.
Standalone Applications
|
19
Example 2-12. sbt build file
name := "learning-spark-mini-example"
version := "0.0.1"
scalaVersion := "2.10.4"
// additional libraries
libraryDependencies ++= Seq(
"org.apache.spark" %% "spark-core" % "1.2.0" % "provided"
)
Example 2-13. Maven build file
com.oreilly.learningsparkexamples.mini
learning-spark-mini-example
4.0.0
example
jar
0.0.1
org.apache.spark
spark-core_2.10
1.2.0
provided
1.6
org.apache.maven.plugins
maven-compiler-plugin
3.1
${java.version}
${java.version}
20
|
Chapter 2: Downloading Spark and Getting Started
Tài liệu liên quan
OReilly learning spark lightning fast big data analysis
Chapter 1. Introduction to Data Analysis with Spark
Chapter 4. Working with Key/Value Pairs
Chapter 5. Loading and Saving Your Data
Chapter 7. Running on a Cluster
Chapter 8. Tuning and Debugging Spark
Chapter 11. Machine Learning with MLl | https://toc.123doc.org/document/972694-chapter-2-downloading-spark-and-getting-started.htm | CC-MAIN-2017-43 | refinedweb | 3,215 | 65.12 |
#include <sys/neti.h> netid_t net_zoneidtonetid(const zoneid_t zone);
Solaris DDI specific (Solaris DDI).
valid zoneid_t structure that refers to a running zone.
The net_zoneidtonetid() function maps the given zoneid_t structure (used to represent a zone that is currently running) into a netid_t structure that is associated with the IP instance supporting network functions for that zone.
The net_zoneidtonetid() function returns -1 if no mapping took place. Otherwise, it returns the netid_t structure currently used by the zoneid_t structure. For zones that are using a shared IP instance, the netid_t structure for the instance owned by the global zone is returned.
The net_zoneidtonetid() function may be called from user, kernel, or interrupt context.
See attributes(5) for descriptions of the following attributes:
net_netidtozonid(9F), attributes(5) | http://docs.oracle.com/cd/E36784_01/html/E36886/net-zoneidtonetid-9f.html | CC-MAIN-2014-42 | refinedweb | 126 | 56.25 |
Handling Recursion Limit in Python
In this tutorial, we will learn to handle recursion limit in Python.
Programming languages such as C or C++ perform tail recursion optimization. Python interpreter does not have any such property. Because of this, Python sets a very small number as the recursion limit which is generally of order 10^4. Therefore, if we have a recursive function in Python, it will throw an error for large input to avoid any stack overflow.
Have a look at the given code and the output below.
def rec_fun(n): if n == 0: return 0 return rec_fun(n-1) + n n = 1000 print(rec_fun(n))
Output:
Traceback (most recent call last): File "err.py", line 8, in <module> print(rec_fun(n)) File "err.py", line 5, in rec_fun return rec_fun(n-1) + n File "err.py", line 5, in rec_fun return rec_fun(n-1) + n File "err.py", line 5, in rec_fun return rec_fun(n-1) + n [Previous line repeated 994 more times] File "err.py", line 2, in rec_fun if n == 0: RecursionError: maximum recursion depth exceeded in comparison
The rec_fun in the above program is a recursive function that returns the sum of all natural numbers from 1 to n. As you can see, when we set the value of n to 1000, an error is thrown because the recursion limit is reached.
How to change the recursion limit
Python has a setrecursionlimit() method that helps us manipulate the recursion limit for a recursive function. This method is present in sys module in Python. It takes one parameter as the new recursion limit. The below program demonstrates the working of this method. See the code.
import sys def rec_fun(n): if n == 0: return 0 return rec_fun(n-1) + n sys.setrecursionlimit(10**6) n = 1000 print(rec_fun(n))
Output:
500500
As you can see, the program now works for the input given in the first example program as we have increased the recursion limit.
Thank you.
Also read: Finding the power of a number using recursion in Python | https://www.codespeedy.com/handling-recursion-limit-in-python/ | CC-MAIN-2020-50 | refinedweb | 343 | 64.71 |
Below is the code I have implemented. My doubt here is: when I am trying to print the first biggest and second Biggest values in the string, the output I get is in the order of
[second biggest, first biggest]
The output of the map is: real--6
The output of the map is: to--2
The output of the map is: world--1
The output of the map is: hello--0
The list after insertion is: [to, real]
The list inserted as [biggest,secondBiggest] after calling main is: [to, real]
......
The list after insertion to be: [real, to]
public class ReadString {
static String input = "This is a real project with real code to do real things to solve real problems in real world real";
public static void main(String[] args) {
List<String> lst = ReadString.RepeatedString("This is a real project with real "
+ "code to do real things to solve real " + "problems in real world real");
System.out.println("The list inserted as [biggest,secondBiggest] after calling main is: " + lst);
}
public static List<String> RepeatedString(String s) {
String[] s2 = input.split(" ");
String[] key = { "real", "to", "world", "hello" };
int count = 0;
Integer biggest = 0;
Integer secondBiggest = 1;
Map<String, Integer> map = new HashMap<String, Integer>();
for (int j = 0; j < key.length; j++) {
count = 0;
for (int i = 0; i < s2.length; i++) {
if (s2[i].equals(key[j])) {
count++;
}
}
map.put(key[j], count);
System.out.println("The output of the map is: " +key[j] + "--" + count);
}
/*
* To find the top two most repeated values.
*/
List<Integer> values = new ArrayList<Integer>(map.values());
Collections.sort(values);
for (int n : map.values()) {
if (biggest < n) {
secondBiggest = biggest;
biggest = n;
} else if (secondBiggest < n)
secondBiggest = n;
}
/* To get the top most repeated strings. */
List<String> list = new ArrayList<String>();
for (String s1 : map.keySet()) {
if (map.get(s1).equals(biggest))
list.add(s1);
else if (map.get(s1).equals(secondBiggest))
list.add(s1);
}
System.out.println("The list after insertion is: " +list);
return list;
}
}
The problem appears to be when you are adding items to the list. As you are iterating through the map.keySet(), there is no guarantee that you will get the biggest item first. The smallest change I would make would be to add the biggest item first in the list.
This way, if secondBiggest is added first, biggest will be at the top of the list.This way, if secondBiggest is added first, biggest will be at the top of the list.
for (String s1 : map.keySet()) { if (map.get(s1).equals(biggest)) list.add(0, s1); else if (map.get(s1).equals(secondBiggest)) list.add(s1); } | https://codedump.io/share/4icrb2bfn7a/1/to-print-the-first-biggest-and-second-biggest-elements-in-a-string | CC-MAIN-2017-09 | refinedweb | 438 | 65.62 |
Mmh, today I got bitten by this again. It took me a while to figure out what was going on while trying to construct a pedagogical example manipulating numpy poly1d objects, and after searching for 'poly1d multiplication float' in my gmail inbox, the *only* post I found was this old one of mine, so I guess I'll just resuscitate it:
On Tue, Jul 31, 2007 at 2:54 PM, Fernando Perez fperez.net@gmail.com wrote:
Hi all,
consider this little script:
from numpy import poly1d, float, float32 p=poly1d([1.,2.]) three=float(3) three32=float32(3)
print 'three*p:',three*p print 'three32*p:',three32*p print 'p*three32:',p*three32
which produces when run:
In [3]: run pol1d.py three*p: 3 x + 6 three32*p: [ 3. 6.] p*three32: 3 x + 6
The fact that multiplication between poly1d objects and numbers is:
- non-commutative when the numbers are numpy scalars
- different for the same number if it is a python float vs a numpy scalar
is rather unpleasant, and I can see this causing hard to find bugs, depending on whether your code gets a parameter that came as a python float or a numpy one.
This was found today by a colleague on numpy 1.0.4.dev3937. It feels like a bug to me, do others agree? Or is it consistent with a part of the zen of numpy I've missed thus far?
Tim H. mentioned how it might be tricky to fix. I'm wondering if there are any new ideas since on this front, because it's really awkward to explain to new students that poly1d objects have this kind of odd behavior regarding operations with scalars.
The same underlying problem happens for addition, but in this case the answer (depending on the order of operations) changes even more:
In [560]: p Out[560]: poly1d([ 1., 2.])
In [561]: print(p)
1 x + 2
In [562]: p+3 Out[562]: poly1d([ 1., 5.])
In [563]: p+three32 Out[563]: poly1d([ 1., 5.])
In [564]: three32+p Out[564]: array([ 4., 5.]) # !!!
I'm ok with teaching students that in floating point, basic algebraic operations may not be exactly associative and that ignoring this fact can lead to nasty surprises. But explaining that a+b and b+a give completely different *types* of answer is kind of defeating my 'python is the simple language you want to learn' :)
Is this really unfixable, or does one of our resident gurus have some ideas on how to approach the problem?
Thanks!
f | https://mail.python.org/archives/list/numpy-discussion@python.org/message/LJD5KZIFSVM5LJZFZDG2TX7AEIWSBIKG/ | CC-MAIN-2022-21 | refinedweb | 429 | 65.35 |
Clara Stancu761 Points
Don't understand the "bummer"
In the statement it says: "to return true if the tile is in the tiles field, and false if it isn't." I did exactly that: return true ... return false. But the bummer says he wants the result if the expression; and if instead of "return true" i put "return isTile", the "bummer" says exactly the same thing. To what expression does it refer ?
public class ScrabblePlayer { // A String representing all of the tiles that this player has private String tiles; public ScrabblePlayer() { tiles = ""; } public String getTiles() { return tiles; } public void addTile(char tile) { // TODO: Add the tile to tiles tiles += tile; } public boolean hasTile(char tile) { // TODO: Determine if user has the tile passed in boolean isTile = tiles.indexOf(tiles) != -1; if (isTile) return true ; return false; } }
1 Answer
Jonathan GrieveTreehouse Moderator 84,410 Points
The code is challenging you to work out a way of passing without using an if statement but instead returning the result of the expression in
hasTile()
public boolean hasTile(char tile) { // TODO: Determine if user has the tile passed in return tiles.indexOf(tile) >= 0; }
This works because you're passing an expression to the return keyword, which only ever evaluates to true or false. Sionce the expression checks for greater than zero it will be a "truthy" value so returns true. In every ever instance (i.e. a retuen of less than zero the return value will be false.
Hope this helps! :) | https://teamtreehouse.com/community/dont-understand-the-bummer | CC-MAIN-2020-10 | refinedweb | 248 | 66.57 |
In this tutorial you will learn about enumerated type controls in LabView. If you are familiar with any other text based programming language, you must have used enumerated types before. The explanatory discussion on enumerated data type is, however, given in the introduction section. After that the use and functionality of enumerated data types in LabView is explained with the help of a VI. At the end of the tutorial you are provided with an exercise to do it by yourself, and in the next tutorials I will assume that you have done those exercises and I will not explain the concept regarding them.
Introduction to Enumerated data type in labview
An enumeration can be declared using the keyword “enum”, an enumerator list is a distinct type that consists of a set of named constants. To define it directly within a namespace is the best way to define an enumerator so that all classes in the namespace can access it with equal convenience.
An enumerated data type is a type consisting of a set of named valued called as enumerals, members or elements (same as we define for a set in mathematics) or an enumerator of the type, in computer programming. Identifiers, that acts as normal constants are enumerator names or elements in a programming language. A degenerate tagged union of unit type can also be defined as an enumerated data type. All elements of an enumerator set are distinguishable i.e. no two elements of the same data set can be similar in an enumeration. All the elements of a single enumerator are different from each other and therefore can be compared and assigned but are not specified, however, compilers and interpreters can represent them arbitrarily.
Enumerated type control provides the user with a list of ite from which the data is selected for further processing. Information about the numeric values and the string labels in the control, however, is included in the data type of an enumerated type control. Numeric data type is by default assigned to the ring control.
In LabView, the user is not allowed to enter the undefined values in enumerated type controls, and the items in enumerated type controls cannot be assigned specific numeric values, as you will see the in explanation using VI section. Enumerated type control can also be used to select the cases of a case structure in LabView.
Examples of Enumerated data type in labview
- Let’s explain the working of enumerated data types using a VI. I have tried my best to explain the working and functionality of enumerated controls individually and there use with case structures also.
- Create a VI as we have discussed in tutorial 1 and save it as we have done in all previous tutorials. On the front panel right click and from the control palette select Ring & enum and then select enum as shown in the figure below,
Figure 1: Placement of enum control
- We are looking for an enumerated control here to understand its working, below is shown the front panel block of an enum block.
Figure 2: Enum block
- Currently, this block has no variables stored in it. If you want to edit the variables of the enumerated block i.e. the elements or enumerals of the data type right click on the block a dropdown will appear, select edit items from the drop down as shown in the figure below,
Figure 3: Edit Items
Figure 4: Edit window
- This window will let you edit the elements of the enum. As the picture shows you can insert delete or move up an element in this window. If you want to insert an element in the enum simply click on the insert button it will let you right a name of the variable you want to be the element of you enum as shown in the figure below,
Figure 5: Insertion
- You can write the desired name of your element and not the value because in enumerated data type the numeric value assigned to the elements are not editable. You can however change the sequence of the enumerals but not there value. See the figure below,
Figure 6: Inserting variables
- From the block available at the front panel you can select which variable to be accessed from the enum. You can only access one of all the elements of the enum at a time. By clicking on the front panels’ block on enum you can select which of the element to be accessed. See the figure below,
Figure 7: Variable selection
- Now if you want to place an indicator to see the output of the enum, there is no need to look for it in the control palette. Simply right click on the block diagram windows’ block of the enum and select create and then select indicator as shown in the figure below,
Figure 8: Indicator creation
Figure 9: Enum indicator
Figure 10: Front panel blocks
Figure 11: Changing the variables
- Now if you run the VI the indicator will display the name of the variable you assigned to the enum control.
Figure 12: Running the VI
- The question here may arise that how to access the integer values assigned to the elements of the enum control?? It is not a difficult task. From the function palette select numeric then conversion and then select to long integer. This will covert you value from enumerated type to integer type.
Figure 13: Conversion block placement
- Connect the input side of this block to the output of enum control and at the output of the conversion block create an indicator as we have been doing in all previous tutorials. The resulting figure will look like the one shown below,
Figure 14: Block diagram
- This indicator block on the front panel will display the integer value of the particular selected enum element after running the VI. The figure below shows the results of the VI after running it
Figure 15: Integer values
- From the edit item window you can also change the place of the variables and hence the integer number assigned to them. By clicking on the move up button after selecting a particular element we can move its integer values as shown in the figure below,
Figure 16: Moving an element up
- Now if I run the VI the output at the integer indicator will not be the same as shown in the figure below,
Figure 17: Changed value of same variable
After you move an element up or down, your VI might give you an error. This error could be removed by deleting the enum indicator block from the block diagram and creating a new indicator because on indicator can not be used for different sequences of elements
Exercise:
- Use enum variable we just created as a case selector of a case structure and perform three different operations i.e. add, subtract and multiply
(Hint: You may need to add a case for third element as we have done in case structure tutorial)
<<Previous tutorial Next tutorial>>
1 thought on “Enumerated data types in labview : tutorial 16”
Very useful notes | https://microcontrollerslab.com/enumerated-data-types-labview/ | CC-MAIN-2021-39 | refinedweb | 1,186 | 52.02 |
Unicode variable names
You are encouraged to solve this task according to the task description, using any language you may know.
- Describe, and give a pointer to documentation on your languages use of characters beyond those of the ASCII character set in the naming of variables.
- Show how to:
- Set a variable with a name including the 'Δ', (delta character), to 1
- Increment it
- Print its value.
- Cf.
-
[edit] ACL2
Variables in ACL2 cannot be modified in place.
(let ((Δ 1))
(1+ Δ))
[edit] Ada
As of Ada 2005, all source code can be made of up to 32bit characters. Unless you have made it a default, GNAT would require the -gnatW8 flag to understand you are using UTF8 for the code below, other encodings are possible.
with Ada.Text_IO;
procedure main is
Δ : Integer;
begin
Δ := 41;
Δ := Δ + 1;
Ada.Text_IO.Put_Line (Δ'Img);
end main;
- Output:
42
[edit] AutoHotkey
The earlier version of AutoHotkey (AutoHotkey Basic) will produce an error since it doesn't support Unicode. It is perfectly working in AutoHotkey_L Unicode (Lexikos Custom Build). Documentation:
Δ = 1
Δ++
MsgBox, % Δ
[edit] Bracmat
Bracmat allows any sequence of non-zero bytes as symbol and therefore, as variable name. Even the empty string is a variable, though a special one. If a symbol/variable name contains characters that have special meaning (operators, prefixes, parentheses, braces and the semicolon) it may be necessary to enclose it in quotes. Other special characters must be escaped C-style. See bracmat.html in the git-repo. The example below requires a terminal that supports UTF-8 encoded characters.
( (Δ=1)
& 1+!Δ:?Δ
& out$("Δ:" !Δ)
);
Output:
Δ: 2
[edit] C
C has limited support for Unicode in variable names, see Annex D of the C standard.
[edit] C#
Section 2.4.2 of the C# Language Specification gives rules for identifiers. They correspond exactly to those recommended by the Unicode Standard Annex 31, except that underscore is allowed as an initial character (as is traditional in the C programming language), Unicode escape sequences are permitted in identifiers, and the "@" character is allowed as a prefix to enable keywords to be used as identifiers.
class Program
{
static void Main()
{
var Δ = 1;
Δ++;
System.Console.WriteLine(Δ);
}
}
- Output:
2
[edit] Clojure
According to the current documentation, one should stick to naming with alphanumeric characters and *, +, !, -, _, and ? to avoid possible problems if future versions of Clojure decide to apply special meaning to a character.
That being said, it is not currently enforced, so while you probably shouldn't, you technically can.
(let [Δ 1]
(inc Δ))
- Output:
2
[edit] Common Lisp
(let ((Δ 1))
(incf Δ))
- Output:
2
[edit] D
D source files support four character encodings: ASCII, UTF-8, UTF-16 and UTF-32.
import std.stdio;
void main() {
auto Δ = 1;
Δ++;
writeln(Δ);
}
- Output:
2
You can use any of the following:
Letters, digits, underscore (_), code points >= \u00A0 and < \uD800, code points > \uDFFF.
However, the following cannot be used:
\u0024 ($), \u0040 (@) and \u0060 (`).
See:
[edit] Delphi
For more information about naming identifiers (including variables) visit: Identifiers in Delphi
(* Compiled with Delphi XE *)
program UnicodeVariableName;
{$APPTYPE CONSOLE}
uses
SysUtils;
var
Δ: Integer;
begin
Δ:= 1;
Inc(Δ);
Writeln(Δ);
Readln;
end.
[edit] Déjà Vu
set :Δ 1
set :Δ ++ Δ
!. Δ
[edit] DWScript
var Δ : Integer;
Δ := 1;
Inc(Δ);
PrintLn(Δ);
[edit] F#
As with C# the F# Language Specification refers to Unicode Standard Annex #31 for identifier syntax, allowing Unicode letter characters.
let mutable Δ = 1
Δ <- Δ + 1
printfn "%d" Δ
[edit] Forth
Historically, Forth has worked only in ASCII (going so far as to reserve the eighth bit for symbol smudging), but some more modern implementations have extended character set support such as UTF-8.0.7.0
variable ∆
5 ∆ !
∆ @ .
[edit] Go
Go source encoding is specified to be UTF-8. Allowable variable names are specified in the sections identifiers and Exported identifiers.
package main
import "fmt"
func main() {
Δ := 1
Δ++
fmt.Println(Δ)
}
- Output:
2
[edit] Haskell
Haskell variables must start with a lower case character, however Δ is an upper case delta. As such, lower case delta (δ) was used as the first character instead, followed by an upper case delta as the second character in the variable name.
Also, Haskell does not allow mutable variables, so incrementing delta isn't possible. Instead lower case psi was used to store the incremented value of delta since tridents are cool.
main = print ψ
where δΔ = 1
ψ = δΔ + 1
[edit] J
Variable names must be comprised of ASCII characters.
From the Dictionary page Alphabet and Words:
- "The alphabet is standard ASCII, comprising digits, letters (of the English alphabet), the underline (used in names and numbers), ..."
- "Names ... begin with a letter and may continue with letters, underlines, and digits."
[edit] Java
int Δ = 1;
double π = 3.141592;
String 你好 = "hello";
Δ++;
System.out.println(Δ);
- Output:
2
[edit] Julia
The official documentation is there
julia> Δ = 1 ; Δ += 1 ; Δ
2
julia> int('Δ'), char(916), '\u394', "\u394"
(916,'Δ','Δ',"Δ")
[edit] LOLCODE
The spec mandates that identifiers be alphanumeric. However, the fact that YARNs are Unicode-aware permits the use of the SRS operator introduced in 1.3 to utilize variables of arbitrary name.
I HAS A SRS "Δ" ITZ 1
SRS "Δ" R SUM OF SRS ":(394)" AN 1
VISIBLE SRS ":[GREEK CAPITAL LETTER DELTA]"
- Output:
2
[edit] Lua
local unicode = {}
unicode["Für"] = "for"
print(unicode["Für"])
unicode["garçon"] = "boy"
print(unicode["garçon"])
unicode["∆"]=1
print(unicode["∆"])
[edit] Mathematica
Δ = 1;
Δ++;
Print[Δ]
[edit] Nemerle
From the Nemerle Reference Manual: "Programs are written using the Unicode character set, using the UTF-8 encoding."
using System.Console;
module UnicodeVar
{
Main() : void
{
mutable Δ = 1;
Δ++;
WriteLine($"Δ = $Δ");
}
}
[edit] NetRexx
The NetRexx Language Definition section of the NetRexx documentation (netrexx.org/files/nrl3.pdf) describes the character set support within the language.
/* NetRexx */
options replace format comments java crossref symbols nobinary
upperΔ = 1
Δupper = upperΔ
lowerδ = 2
δlower = lowerδ
say upperΔ '+' Δupper '= \-'
upperΔ = upperΔ + Δupper
say upperΔ
say lowerδ '+' δlower '= \-'
lowerδ = lowerδ + δlower
say lowerδ
say
-- Unicode works with the NetRexx built-in functions
Υππερ = '\u0391'.sequence('\u03a1') || '\u03a3'.sequence('\u03a9') -- ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ
Λοωερ = '\u03b1'.sequence('\u03c1') || '\u03c3'.sequence('\u03c9') -- αβγδεζηθικλμνξοπρστυφχψω
say Υππερ'.Lower =' Υππερ.lower()
say Λοωερ'.Upper =' Λοωερ.upper()
say
-- Note: Even with unicode characters NetRexx variables are case-insensitive
numeric digits 12
δ = 20.0
π = Math.PI
θ = Π * Δ
σ = Θ ** 2 / (Π * 4) -- == Π * (Δ / 2) ** 2
say 'Π =' π', diameter =' δ', circumference =' Θ', area =' Σ
return
Output:
1 + 1 = 2 2 + 2 = 4 ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ.Lower =τυφχψω.Upper = ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ Π = 3.141592653589793, diameter = 20.0, circumference = 62.8318530718, area = 314.159265359
[edit] Nimrod
From the spec:
var Δ = 1
Δ.inc()
echo(Δ)
[edit] Objeck
As of 3.2, Objeck supports UTF-8 encoded I/O and stores characters in the runtime's native Unicode format.
class Test {
function : Main(args : String[]) ~ Nil {
Δ := 1;
π := 3.141592;
你好 := "hello";
Δ += 1;
Δ->PrintLine();
}
}
[edit] PARI/GP
GP accepts only ASCII in strings and variable names.
PARI supports Unicode variable names only insofar as C does.
[edit] Perl
Requires Perl 5.8.1 at the minimum. See
use utf8;
my $Δ = 1;
$Δ++;
print $Δ;.
[edit] Perl 6
Perl 6 is written in Unicode so, with narrow restrictions, nearly any Unicode letter can be used in identifiers.
See Perl 6 Synopsis 02. -
my $Δ = 1;
$Δ++;
say $Δ;
Function and subroutine names can also use Unicode characters: (as can methods, classes, packages, whatever...)
my @ᐁ = (0, 45, 60, 90);
sub π { pi };
sub postfix:<°>($degrees) { $degrees * π / 180 };
for @ᐁ -> $ಠ_ಠ { say sin $ಠ_ಠ° };
[edit] PicoLisp
Variables are usually Internal Symbols, and their names may contain any UTF-8 character except null-bytes. White space, and 11 special characters (see the reference) must be escaped with a backslash. Transient Symbols are often used as variables too, they follow the syntax of strings in other languages.
: (setq Δ 1)
-> 1
: Δ
-> 1
: (inc 'Δ)
-> 2
: Δ
-> 2
[edit] PHP
PHP is not made to support Unicode. UTF-16 (UCS-2) will not work because it adds null bytes before or after ASCII characters (depending on endianness of UTF-16). As every code has to start with
<?php (ASCII) exactly, the parser doesn't find the match and just prints
<?php mark.
UTF-8 uses ASCII values for bytes which can be represented as ASCII and as result it's possible to insert
<?php mark at beginning. PHP sees your document as some 8-bit encoding (like ISO-8859-1), but it doesn't matter because UTF-8 doesn't use ASCII ranges for its values and calls to the variable are consistent.
Documentation: mbstring.php4.req, language.variables.basics
<?php
$Δ = 1;
++$Δ;
echo $Δ;
[edit] Prolog
% Unicode in predicate names:
是. % be: means, approximately, "True".
不是 :- \+ 是. % not be: means, approximately, "False". Defined as not 是.
% Unicode in variable names:
test(Garçon, Δ) :-
Garçon = boy,
Δ = delta.
% Call test2(1, Result) to have 2 assigned to Result.
test2(Δ, R) :- R is Δ + 1.
Putting this into use:
?- 是.
true.
?- 不是.
false.
?- test(X,Y).
X = boy,
Y = delta.
?- test2(1,Result).
Result = 2.
[edit] Protium
1. (working on it)
2.
<@ LETVARLIT>Δ|1</@>
<@ ACTICRVAR>Δ</@>
<@ SAYVAR>Δ</@>
Using what Google Translate says is the Traditional Chinese for 'delta'
<@ LETVARLIT>三角洲|1</@>
<@ ACTICRVAR>三角洲</@>
<@ SAYVAR>三角洲</@>
[edit] Python.
>>> Δx = 1
>>> Δx += 1
>>> print(Δx)
2
>>>
[edit] R
See
?assign for details.
f <- function(`∆`=1) `∆`+1
f(1)
- Output:
[1] 2
[edit] Racket
Racket has virtually no restrictions on valid characters for identifiers. In particular, Unicode identifiers are supported.
#lang racket
;; Racket can use Unicode in identifier names
(define √ sqrt)
(√ 256) ; -> 16
;; and in fact the standard language makes use of some of these
(λ(x) x) ; -> an identity function
;; The required binding:
(define Δ 1)
(set! Δ (add1 Δ))
(printf "Δ = ~s\n" Δ) ; prints "Δ = 2"
[edit] Retro
This has been tested on Retro 11.0 running under OS X.
variable Δ
1 !Δ
@Δ putn
1 +Δ
@Δ putn
Function and variable names are stored as strings, and UTF-8 is usable, as long as the host system allows it.
[edit] Ruby
This task requires Ruby 1.9. Multilingualization, or m17n, is a major new feature of Ruby 1.9. With m17n, the identifiers can use the non-ASCII characters. Ruby is a Code Set Independent (CSI) language, so there are many different character encodings.
- Any non-ASCII characters require a magic comment to select the encoding.
- Ruby source code must be ASCII compatible. For example, SJIS and UTF-8 are ASCII compatible, but ISO-2022-JP and UTF-16LE are not compatible. So one can write the source file in UTF-8, but not in UTF-16LE.
A more complete reference is The design and implementation of Ruby M17N.
The next example uses a magic comment to select the Big5 encoding. Then it creates a local variable named Δ.
# -*- coding: big5 -*-
Δ = 1
Δ += 1
puts Δ
00000000 23 20 2d 2a 2d 20 63 6f 64 69 6e 67 3a 20 62 69 |# -*- coding: bi| 00000010 67 35 20 2d 2a 2d 0a a3 47 20 3d 20 31 0a a3 47 |g5 -*-.Δ = 1.Δ| 00000020 20 2b 3d 20 31 0a 70 75 74 73 20 a3 47 0a | += 1.puts Δ.| 0000002e
The output is
2.
One can also use the non-ASCII characters in a method name. The next example selects the EUC-JP encoding, and creates a method named ≦, with a parameter named ♯♭♪. Because ≦ is an ordinary method, not an operator, so the program must use a dot to call the method.
# -*- coding: euc-jp -*-
class Numeric
def ≦(♯♭♪)
self <= ♯♭♪
end
end
∞ = Float::INFINITY
±5 = [-5, 5]
p [(±5.first.≦ ∞),
(±5.last.≦ ∞),
(∞.≦ ∞)]
00000000 23 20 2d 2a 2d 20 63 6f 64 69 6e 67 3a 20 65 75 |# -*- coding: eu| 00000010 63 2d 6a 70 20 2d 2a 2d 0a 0a 63 6c 61 73 73 20 |c-jp -*-..class | 00000020 4e 75 6d 65 72 69 63 0a 20 20 64 65 66 20 a1 e5 |Numeric. def ≦| 00000030 28 a2 f4 a2 f5 a2 f6 29 0a 20 20 20 20 73 65 6c |(♯♭♪). sel| 00000040 66 20 3c 3d 20 a2 f4 a2 f5 a2 f6 0a 20 20 65 6e |f <= ♯♭♪. en| 00000050 64 0a 65 6e 64 0a 0a a1 e7 20 3d 20 46 6c 6f 61 |d.end..∞ = Floa| 00000060 74 3a 3a 49 4e 46 49 4e 49 54 59 0a a1 de 35 20 |t::INFINITY.±5 | 00000070 3d 20 5b 2d 35 2c 20 35 5d 0a 70 20 5b 28 a1 de |= [-5, 5].p [(±| 00000080 35 2e 66 69 72 73 74 2e a1 e5 20 a1 e7 29 2c 0a |5.first.≦ ∞),.| 00000090 20 20 20 28 a1 de 35 2e 6c 61 73 74 2e a1 e5 20 | (±5.last.≦ | 000000a0 a1 e7 29 2c 0a 20 20 20 28 a1 e7 2e a1 e5 20 a1 |∞),. (∞.≦ | 000000b0 e7 29 5d 0a |)].| 000000b4
The output is
[true, true, true] because the numbers -5, 5 and infinity are all less than or equal to infinity.
[edit] Rust
Rust source encoding is specified to be UTF-8. Variable names must begin with a character that has Unicode XID_start property and remaining characters must have the XID_Continue property. (Note that flipping tables is not permitted under current specification)
Non-ASCII identifiers are feature gated since version 0.9
// rustc 0.9 (7613b15 2014-01-08 18:04:43 -0800)
#[feature(non_ascii_idents)];
fn main() {
let mut Δ:int = 1;
Δ += 1;
println!("{}", Δ);
}
[edit] Scala
var Δ = 1
val π = 3.141592
val 你好 = "hello"
Δ += 1
println(Δ)
[edit] Swift
var Δ = 1
let π = 3.141592
let 你好 = "hello"
Δ++
println(Δ)
- Output:
2
[edit] Tcl
Tcl variable names can include any character (the
$var syntax can't, but that's just a shorthand for the operationally-equivalent
[set var]). Thus, this script is entirely legal:
set Δx 1
incr Δx
puts [set Δx]
However, this script only works smoothly if the “Δ” character is in the system's default encoding (thankfully more common than it used to be, as more and more systems use UTF-8 or UTF-16 as their default encodings) so normal Tcl practice is to stick to ASCII for identifier names.
It is also possible to encode characters using a \uXXXX substitution (each X is a hexadecimal digit), thus the
Δx could be replaced throughout above by
\u0394x; the result is a variable with exactly the same name as before. Doing this allows a script to be written with just ASCII characters, which tends to maximize portability across platforms.
- Programming Tasks
- Unicode
- BBC BASIC/Omit
- ACL2
- Ada
- AutoHotkey
- Bracmat
- C
- C sharp
- Clojure
- Common Lisp
- D
- Delphi
- Déjà Vu
- DWScript
- F Sharp
- Forth
- Go
- Haskell
- J
- Java
- Julia
- LOLCODE
- Lua
- Mathematica
- Nemerle
- NetRexx
- Nimrod
- Objeck
- PARI/GP
- Perl
- Perl 6
- PicoLisp
- PHP
- Prolog
- Protium
- Protium examples needing attention
- Examples needing attention
- Python
- R
- Racket
- Retro
- Ruby
- Rust
- Scala
- Swift
- Tcl
- AWK/Omit
- BASIC/Omit
- Bc/Omit
- BLAST/Omit
- C/Omit
- Dc/Omit
- Erlang/Omit
- GUISS/Omit
- Icon/Omit
- Locomotive Basic/Omit
- Lotus 123 Macro Scripting/Omit
- Sed/Omit
- TUSCRIPT/Omit
- Unicon/Omit
- UNIX Shell/Omit
- Zkl/Omit
- ZX Spectrum Basic/Omit | http://rosettacode.org/wiki/Unicode_variable_names | CC-MAIN-2014-35 | refinedweb | 2,583 | 63.29 |
StandardS
Your hibernet tutorial is not working - Hibernate
Your hibernet tutorial is not working Hi,
I am learning hibernate from your tutorial.
when i execute the 1st hibernate example at following location it working
x-axis and y-axis
x-axis and y-axis hi,, i want to to write a program that display a graph of x-axis and y-xais when i entered the parameters of the function... can use
the windows default editor "notepad"
if working on windows environment
hi - Hibernate
hi hi,
what is object life cycle in hibernate.
Update not working in hibernate.
Update not working in hibernate. Update not working in hibernate
Hi - Hibernate Interview Questions
Hi please send me hibernate interview questions
Dynamic-update not working in Hibernate.
Dynamic-update not working in Hibernate. Why is dynamic update not working in hibernate?
Dynamic-update is not working. It means when you are running your update, new data is added in your table in place
UIView frame x,y width and height
UIView frame x,y width and height HI,
How to print the x,y width and height of UIView?
Thanks
Hi,
Following code can be used:
CGRect...(@"width = %f", myFrame.size.width);
NSLog(@"x = %f", myFrame.origin.x);
NSLog(@"y
Y No Multiple Inheriatance in Java - Java Beginners
Y No Multiple Inheriatance in Java
Hi Friends,
Why java doesn't support multiple inheritance. Hi
Multiple Inheritance
The mechanism of inheriting the features of more than one base class
Hibernate Basic Example not working
Hibernate Basic Example not working I have implemented basic hibernate example from your site .
In console i got output but database is not affected.
hbm.xml
<id name="id" type="long" column="id">
<generator
Y servlet as a controller - Servlet Interview Questions
Y servlet as a controller Hi Friends, Can anyone tell me why servlet used as controller not jsp.
What are the advantages. Hi Friend,
Servlet and JSP, both are server side components which can respond
Hi... - Struts
of this installation Hi friend,
Hibernate is Object-Oriented mapping tool...Hi... Hi,
If i am using hibernet with struts then require... more information,tutorials and examples on Struts with Hibernate visit
Hibernate delete HQL - Hibernate
Hibernate delete HQL Hi
I am trying hibernate tutorial. But delete HQL tutorial not working properly. It gives null pointer exception.
Query class has method executeUpate() & not executeUpdate
Hi.. - Struts
Hi..
Hi Friends,
I am new in hibernate please tell me... me Hi Soniya,
I am sending you a link. I hope that, this link.../struts/struts-hibernate/struts-hibernate-plugin.shtml
myJSF,Hibernate and Spring integration code is not working. - Hibernate
myJSF,Hibernate and Spring integration code is not working. the code given in this url :
i have tried but it does not work.
when i - XML
Thanks
Rajanikant Hi friend,
It is a format to share data... working of Rss Feed
1. Those Web pages we want to be show by other
UIWebView zoom not working
UIWebView zoom not working Hi,
I don't know why UIWebView zoom not working? Tell the solution.
Thanks
Hi,
Open the .xib file and set scalesPageToFit to YES.
Thanks
hi - Java Beginners
; Hi anjali,
class ploy {
public void ployTest(int x){
System.out.println("value of x: "+ x);
}
public void ployTest(int x, int y){
System.out.println("Value of x and y: " + x + " and " + y);
}
}
public class
Working of POS Terminal
Working of POS Terminal Hi there, thanks for this post. Just curious how actual POS terminal will interact with PHP. PHP doesn't provide hardware interaction.
Thanks for reply.
Regards
hi - IDE Questions
hi hi,
we have 2
IDE controller
u r first one is not boot r not show
so,second HD is working r... of the shape of the button.then Draw these on some x and y co-ordinated in j2me
Persist a List Object in Hibernate - Hibernate
Persist a List Object in Hibernate
Hi All,
I have a query on hibernate.
How to persist a List object in Hibernate ?
Can you give me a working Code /Example for the same ?
Help provided will be highly appreciated
Why is this code working
struct _point{
int x;
int y;
} point;
int main (void)
{
point *ptr;
point obj...\n", ptr->x, ptr->y);
return 0;
}
Why is it running correctly when I
Working with Eclipse IDE - Struts
Working with Eclipse IDE hello, i am beginner to eclipse .
i want to run my first struts program in eclipse 3.2.
what are the steps for running... with struts.
Thanks in advance. Hi friend,
Read for more
hibernate
;Hi Friend,
Please visit the following link: Hi
Good Morning
Will u please send me the some of the tutorials of hibernate.Because ,i have to learn the hibernate.i am new to this its
Hibernate - Hibernate
Hibernate application development help Hi, Can anyone help me in developing my first Java and Hibernate application
Hi... - Java Beginners
but this not working
Upload Record
please tell me Hi Friend,
Please clarify your question.
Thanks Hi frnd,
Your asking...Hi... Hi friends,
I hv two jsp page one is aa.jsp & bb.jsp
window.open() not working - Ajax
is that the pop up window is not at all working.. Once I click the button, the page...;Hi Friend,
Change your function name as it contradicts with the predefined
hi roseindia - Java Beginners
hi roseindia what is class? Hi Deepthi,
Whatever we can see in this world all the things are a object. And all the objects... is used for the working on the particular properties of the class or its group
hibernate - Hibernate
hibernate is there any tutorial using hibernate and netbeans to do a web application add,update,delete,select
Hi friend,
For hibernate tutorial visit to :
JTextfields working with JTextArea
JTextfields working with JTextArea I have 2 database tables one is history the other is patient,
How can I get which every patient is being... on a Jtextarea
hi friend,
try the following code below :
import java.sql.
ClassPathResource class is not working - Spring
ClassPathResource class is not working Hi, Below is a sample code... ClassPathResource("hello.xml");BeanFactory factory = new XmlBeanFactory(res); Hello... parsing XML document from class path resource [classpath:hello.xml
Autocomplete demo not working
Autocomplete demo not working Hi Team,
I am so happy with our examples on Autocomplete ,
I have copied the source files to my local machine and renamed
Duplicates - Hibernate
Duplicates Hi,
Im running a query where it fetches the records from the view and displaying 25 records in the page. Everything is working fine and but when displaying the contents in the jsp, each record is repeated. So
hibernate - Hibernate
hibernate hi friends i had one doubt how to do struts with hibernate in myeclipse ide
its urgent
Hi,
Hi, Hi,what is the purpose of hash table
Login form using Jsp in hibernate - Hibernate
Hibernate - Hibernate
Hibernate how to call the stored procedure in mysql database server using hibernate..?? Hi Friend,
Please visit the following link:
Thanks
onClick not working - Java Beginners
the
Hi Friend
hibernate - Hibernate
hibernate how to write join quaries using hql Hi satish...:
Thanks
Working Example for Spring AOP - Spring
Working Example for Spring AOP Hi All,
I need a complete working Java example /Code/Logic for Spring -Aspect Oriented Programming.
Code provided will be highly appreciated.
--
Deepak L this is really good example to beginners who is learning struts2.0
thanks | http://roseindia.net/tutorialhelp/comment/708 | CC-MAIN-2014-15 | refinedweb | 1,238 | 55.95 |
Flex Mobile: Problems with MultiDPI SplashScreenFrancesco_C Jul 23, 2011 3:17 AM
Hi guys,
The property applicationDPI in my application is 160, and I created three bitmaps to 160, 240 and 320 DPI to be used in the SplashScreen.
I created this class . see : rticlecontentAdobe_numberedheader_5
package preloaders
{
import mx.core.DPIClassification;
import mx.core.mx_internal;
use namespace mx_internal;
public class MultiDPISplashScreen extends CustomSplash
{
[Embed(source="assets/mobile160/splash_160.png")]
private var SplashImage160:Class;
[Embed(source="assets/mobile240/splash_240.png")]
private var SplashImage240:Class;
[Embed(source="assets/mobile320/splash_320;
}
}
}
Ih the main app:
<s:TabbedViewNavigatorApplication xmlns:fx=""
xmlns:
The problem is that Flex does not take the correct bitmap if i run my app at 240DPI or at 320DPI (as does the class MultiDPIBitmapSource)and my splash screen is scaled and grainy! :-(
Can anyone help me?
Thnks a lot!
Francesco
1. Re: Flex Mobile: Problems with MultiDPI SplashScreenkokorito Jul 23, 2011 3:46 AM (in response to Francesco_C)
I dont know, but should you be hard coding the dpi with applicationDPI="160"
wouldnt that mean you are always using the 160 image and scaling it up, hence the loss of quality.
dont know, just a guess
2. Re: Flex Mobile: Problems with MultiDPI SplashScreenFrancesco_C Jul 23, 2011 4:13 AM (in response to kokorito)
Hi kokorito
the application DPI is 160 in TabbedViewNavigatorApplication tag, but the framework should take the correct bitmap when my app run at 240 or 360 DPI and don't scaling up!
Should do the same thing that MultiDPIBitmapSource class does... :-(
3. Re: Flex Mobile: Problems with MultiDPI SplashScreenkokorito Jul 23, 2011 4:29 AM (in response to Francesco_C)
just had a look at the link you pasted and they dont set the applicationDPI in the application tag
/me shrugs
4. Re: Flex Mobile: Problems with MultiDPI SplashScreenEvtim Georgiev (Adobe)
Jul 25, 2011 11:08 AM (in response to Francesco_C)
Hi Francesco,
Setting the application dpi shouldn't affect the splash screen (you can verify by testing when you don't set the app dpi or by debugging the function). The dpi that gets passed in to the imageClass should always be the runtime dpi.
I see that in your MultiDPISplashScreen class extends CustomSplash instead of the SplashScreen. Maybe that could be the issues, where does CustomSplash come from?
Edit:
The issue seems to be that in the SplashScreen class we don't undo the automatic dpi scale factor when the scaleMode="none" (the default). When this is combined with different images per dpi, this will cause the observed behavior. Setting scaleMode to any other value should fix the issue.
If you need to have the image centered and not scaled, then you may follow the work-around posted by Uggers at the end of the thread (bottom of the page) at umberedheader_5
Thanks,
-Evtim
5. Re: Flex Mobile: Problems with MultiDPI SplashScreenFrancesco_C Jul 26, 2011 12:53 AM (in response to Evtim Georgiev (Adobe))
Hi Evtim,
thanks for your reply!
Great!!! The work-around posted by Uggers does works!!!and I had not read the last post!
Many many thanks!!
Francesco | https://forums.adobe.com/thread/881065 | CC-MAIN-2017-51 | refinedweb | 515 | 61.36 |
This makes it clear ELF/**/*.cpp files define things in the lld::elf
namespace and simplifies elf::foo to foo.
Details
This makes it clear ELF/**/*.cpp files define things in the lld::elf
Diff Detail
Event Timeline
I think that somewhere in the Coding Style Guideline, it is recommended to keep namespace {} as narrow as possible. This is why I chose this style in the first place. Has that changed?
I don't know the history but gives an example that does this:
namespace llvm { namespace knowledge { ...
Yeah, I'm fine with quoting the entire file with the namespaces, but I'm not entirely happy about adding endian:: to read32. Looks like the problem is that we use the same name for two functions. Can you just rename one to avoid the name collision? Does that make the code look simpler?
Adding endian:: is due to the rule of unqualified name lookup. Renaming either family of functions below will cause the change of hundreds of call sites changes.
llvm::support::endian::write32 and its friends lld::elf::write32 and its friends
llvm::support::endian::* is used in very few files. And as this patch suggests, only Mips.cpp needs endian::*. I think this change clarifies things without making code more complex.
lld::elf::* are more commonly used in lld. This will end up with a lot of qualified write32 read16 calls. I think we should reduce the number of using namespace llvm::support::endian;.
I mean we can replace all occurrences of endian::write32<E>() with write32(). It looks like lld still compiles after I run the following command to replace them.
sed -i 's/write32<.>/write32/g' lld/ELF/Arch/Mips.cpp
This will make the generated code slightly worse because the implementation tests config->endianness. llvm::support::endian::write16(p, v, config->endianness);
Personally I prefer keeping the templated version, though I don't mind changing it if you are strong about this or @atanasyan is fine with lld::elf::* functions.
I originally preferred the template version of write32 for the exact same reason, but I now prefer non-template write32 because it doesn't seem slow at all, perhaps because the branch is highly predictable. Every time it actually branches to the same direction. So maybe the template version is just making the code too verbose? | https://reviews.llvm.org/D68323?id=222767 | CC-MAIN-2020-10 | refinedweb | 390 | 67.15 |
Last post I wrote on WCF Web HTTP Service: why and how. This post was for beginners in which I discussed how to get it started and write your fist WCF WEB HTTP Service. In this post we will go one step further and learn to work with streams or to be precisely images. Service will return image based on the input from client. We are going to create an image server. Image server will do following task
- Read requested image from file system on server
- Convert that to stream
- Return stream to clients
We are going to create WCF WEB HTTP Service which will act as image server. So to start with let us create Service Contract.
using System.IO; using System.ServiceModel; using System.ServiceModel.Web; namespace Demo1 { [ServiceContract] public interface IService1 { [OperationContract] [WebGet] Stream FetchImage(string imageName); } }
In above Service, there is one Operation Contract which returns a stream. Operation Contract can be accessed using baseurl/FetchImage?imageName={imagename with extension}. Client will pass image name in query parameter to fetch a particular image. If image is not present on image then null would be returned from service.
Service implementation is very simple. You need to do following steps to fetch image and return it as stream.
Step 1: First check for existence of the image. If it exists got to step 2 else go to step 4
Step 2: Read image as FileStream
Step 3: Set Outgoing Request Content Type as image/jpeg
Step 4: convert string Image does not exist as stream and return
Service is implemented as below,
public class Service1 : IService1 { public Stream FetchImage(string imageName) { string filePath = @"c:\\" + imageName; if (File.Exists(filePath)) { FileStream fs = File.OpenRead(filePath); WebOperationContext.Current.OutgoingRequest.ContentType = "image/jpeg"; return fs; } else { byte[] byteArray = Encoding.UTF8.GetBytes(" Requested Image does not exist :("); MemoryStream strm = new MemoryStream(byteArray); return strm; } } }
Service implementation is very simple but one line of code in which we are explicitly saying that outgoing response content type is image/jpeg
Already we have covered this in previous post about EndPoint configuration but for quick reference open markup of .svc file and add use Factory method System.ServiceModel.Activation.WebServiceHostFactory to create WEB HTTP Service.
This is what all you need to do to create an Image Server as WCF WEB HTTP Service. You can test server from IE browser.
And if requested image is not present then error message will be rendered as below,
Now you can go ahead and consume and work with this image server in any kind of client able to perform HTTP GET operation. In further post we will get into details of consuming this service from various kind of clients. I hope this post will help you. | http://debugmode.net/category/rest-services/ | CC-MAIN-2015-18 | refinedweb | 458 | 55.74 |
Collect distributed graph. More...
#include <vtkCollectGraph.h>
Collect distributed graph.
This filter has code to collect a graph from across processes onto vertex 0. Collection can be turned on or off using the "PassThrough" flag.
Definition at line 36 of file vtkCollectGraph.h.
Definition at line 40 of file vtkCollectGraph.h.
Definition at line 71 of file vtkCollectGraph.
By default this filter uses the global controller, but this method can be used to set another instead.
When this filter is being used in client-server mode, this is the controller used to communicate between client and server.
Client should not set the other controller.
To collect or just copy input to output.
Off (collect) by default.
Directedness flag, used to signal whether the output graph is directed or undirected.
DIRECTED_OUTPUT expects that this filter is generating a directed graph. UNDIRECTED_OUTPUT expects that this filter is generating an undirected graph. DIRECTED_OUTPUT and UNDIRECTED_OUTPUT flags should only be set on the client filter. Server filters should be set to USE_INPUT_TYPE since they have valid input and the directedness is determined from the input type.
This is called by the superclass.
This is the method you should override.
Reimplemented from vtkGraphAlgorithm.
This is called by the superclass.
This is the method you should override.
Reimplemented from vtkGraphAlgorithm.
Definition at line 95 of file vtkCollectGraph.h.
Definition at line 96 of file vtkCollectGraph.h.
Definition at line 103 of file vtkCollectGraph.h.
Definition at line 104 of file vtkCollectGraph.h. | https://vtk.org/doc/nightly/html/classvtkCollectGraph.html | CC-MAIN-2021-17 | refinedweb | 246 | 62.54 |
Introduction: ESP32 LORA: Gas Sensor, Humidity, and Temperature by SMS
Sensors, with an ESP32 LORA, can be easily designed for safety purposes involving gas, temperature, and humidity. Today, I’m). Both will be read by the first ESP32 LORA, which will function as the Sender, and will send an alert to the second ESP32 Lora, which will be a Receiver. This provides safety for a situation such as a gas leak, for example.
Using a gas leak simulation, as in our demonstration (image above), the Sender will send a signal to the Receiver, which will turn on the Buzzer and the red LED. As the SPI port of this Receiver will already be busy, it will send the data via UART to the Arduino Nano. Through the SPI, it will then communicate with the Ethernet interface. The software on this Receiver will then send an SMS to your cell phone notifying a potential gas leak hazard.
The ESP32 will read the analog value and indicate the quantity of gas involved, and the risk of explosion in the analyzed location. This information will be directed to the SMS.
In our assembly, I placed an Ethernet cable interface on the Receiver. Why is this performed? Because we need reliability in this project, where there is guaranteed access even during WiFi failure. This ensures the sending of SMS, which can be replaced by email or connection, according to your preference and gateway availability.
Step 1: Operation (Data Transmission)
Here is a diagram of how the assembly works.
Step 2: Resources Used
2 ESP32 LORA OLED Display
1 Arduino Nano ATmega328
1 Ethernet Module ENC28J60 for Arduino
1 Gas sensor module MQ2
1 Humidity and Temperature Sensor DHT22 (AM2302)
2 330 ohm resistors
1 4k7 ohm resistor
1 Buzzer 5V
1 green LED
1 red LED
Jumpers
Step 3: Features - Sender
1 ESP32 LORA Display
1 Gas sensor module MQ2
1 Humidity and Temperature Sensor DHT22 (AM2302)
1 4k7 ohm resistor
Jumpers
Step 4: Features Used - Receiver
1 ESP32 LORA OLED Display
1 Arduino Nano ATmega328
1 Ethernet Module ENC28J60 for Arduino
2 330 ohm resistors
1 Buzzer 5V
1 green LED
1 red LED
Jumpers
Step 5: MQ-2 Gas Sensor Sensitivity
The resistance (Rs / Ro) of the sensor is higher or lower according to the existing gas concentration (ppm). This concentration can be visualized by the output of pin A0.
The MQ-2 gas sensor has high sensitivity to gases:
• LPG (liquefied petroleum gas);
• Propane (C3H8);
• Hydrogen (H2);
• Methane (CH4);
• Fuel gases, such as Propane, CO, Alcohol, and Butane (used in lighters).
Step 6: Sender Mount --- Pinout ESP32 LORA OLED
Step 7: Sender Circuit
Step 8: Sender Mounting
Step 9: Mounting Receiver --- Pinout Arduino Nano ATmega328
Step 10: Receiver Circuit
Step 11: Receiver Mounting
Green LED indicates that the Arduino is connected to the Ethernet client.
Red LED indicates that SMS has been sent.
When sending the SMS, the Arduino is disconnected so that no more messages are sent.
Step 12: DHT Library Installation
1. Go to Sketch->Include Library->Library Manager.
2. Search for SimpleDHT and click Install.
Step 13: Sender - Organization of the Code
Setup
Loop
- readDhtSensor: Function responsible for reading the sensor and obtaining values of temperature and humidity.
- gasDetected: Function responsible for reading the sensor and verifying that the gas has been detected.
- sendPacket: Function responsible for sending the package via LORA to the Receiver.
- showDisplay: Function responsible for displaying the messages and values obtained on the display.
Step 14: Sender Code [Includes and Defines]
First, we will include the libraries to make the definition of the pins.
#include <SPI.h> //serial peripheral interface (SPI) library #include <LoRa.h> //wifi lora library #include <Wire.h> //communication i2c library #include "SSD1306.h" //display communication library #include <SimpleDHT.h> //dht communication library //Descomment the line below which dht sensor type are you using //#define DHTTYPE DHT11 // DHT 11 //#define DHTTYPE DHT21 // DHT 21 (AM2301) #define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321</p><p>// MQ_analog 12 //analog gas sensor pin #define MQ_dig 13 //digital gas sensor pin #define BAND 433E6 //Radio frequency, we can still use: 433E6, 868E6, 915E6
We will deal with the sensor of the variables used to receive the analog and digital signal, in addition to defining the minimum trigger value of the gas sensor.
// DHT Sensor<br>const int DHTPin = 23; int analog_value; //variable used to receive the analog signal from sensor (from 100 to 10000) int dig_value; //variable used to receive the digital signal from sensor int gas_limit = 0; //used to indicates the minimum value to active the gas sensor (that value changes as the sensor screw is adjusted) //h = humidity; c = Celsius temperature float h, c; String packSize; //variable used to receive the size of package converted in string String packet = "OK"; //part of packet, that informs the status of sensor. That variable will be concatenate with the string "values" String values = "|-|-"; //humidity and temperature values, separated by pipe //parameters: address,SDA,SCL SSD1306 display(0x3c, 4, 15); //display object SimpleDHT22 dht22;
Step 15: Sender Code [Setup]
In the Setup, we will first configure the pins and the display.
void setup() { //set the humidity and temperature values with zero h = c = 0; //initialize the Serial with 9600b per second Serial.begin(9600); //configures analog pin as input pinMode(MQ_analog, INPUT); //configures digital pin as input pinMode(MQ_dig, INPUT); //configures oled pins as output pinMode(16,OUTPUT); //reset oled digitalWrite(16, LOW); //wait 50ms delay(50); //while the oled is on, GPIO16 must be HIGH digitalWrite(16, HIGH); //initializes the display display.init(); //flip vertically the display display.flipScreenVertically();
Next, we will define the print characteristics on the display, and start the serial communication with LORA. We then will proceed to its configuration.
//set display font display.setFont(ArialMT_Plain_10); //wait 1500ms delay(1500); / (true); } }
Step 16: Sender Code [Loop]
In the Loop, we also work with the characteristics of the display, and indicate the procedures of reading the sensors, as well as gas detection and the sending of alerts by the LORA.
<p>void loop()<br>{ //clear the display display.clear(); //set the text alignment to left display.setTextAlignment(TEXT_ALIGN_LEFT); //sets the text font display.setFont(ArialMT_Plain_16); //draw in the position 0,0 the message in between quotation marks display.drawString(0, 0, "Running..."); //reads temperature sensor values readDhtSensor(); //it concatenates on string the humidity and temperature values separated by pipe values="|"+String(h)+"|"+String(c); //if the digital signal of sensor is lower, it means gas detected (inverse logic) if(gasDetected()) { //sets the value of the packet string to "ALARM" packet = "ALARM"; //it concatenates the packet with the values packet+=values; //sends package by LoRa sendPacket(); //shows display, true = gas detected showDisplay(true); }
We define the information that will be sent by SMS.
else { //sets the value of the packet string to "OK" packet = "OK"; //it concatenates the packet with the values packet+=values; //sends package by LoRa sendPacket(); //shows display, false = no gas detected showDisplay(false); } //waits 250ms delay(250); }
Step 17: Sender Code [showDisplay]
Again, we deal with the display of data on the LORA’s display.
void showDisplay(bool gasDetected) { //clear the display display.clear(); //set the text alignment to left display.setTextAlignment(TEXT_ALIGN_LEFT); //sets the text font display.setFont(ArialMT_Plain_16); //draw in the position 0,0 the message in between quotation marks display.drawString(0, 0, "Running...");</p><p> //if flag = true if(gasDetected) { //draw in the position 0,20 the message in between quotation marks display.drawString(0, 20, "Status: ALARM"); //draw in the position 0,40 the message in between quotation marks display.drawString(0, 40, "Gas detected!"); //turns on the LCD display display.display(); } else { //draw in the position 0,20 the message in between quotation marks display.drawString(0, 20, "Status: OK"); //draw in the position 0,40 the message in between quotation marks display.drawString(0, 40, "H: "+String(h)+" T: "+String(c)+"°"); //turns on the LCD display display.display(); } }
Step 18: Sender Code [gasDetected]
Here, we have the function responsible for triggering a message if the sensor detects some type of gas leakage.
bool gasDetected() { //reads the analog value of the sensor analog_value = analogRead(MQ_analog); //reads the digital value of the sensor dig_value = digitalRead(MQ_dig); //obs: the serial views in this code do not influence the operation of the prototype //shows value to the serial Serial.print(analog_value); //shows tab "||" to the serial Serial.print(" || "); //inverse logic if(dig_value == 0) { //sets the minimum analog value if(gas_limit == 0 || gas_limit > analog_value) gas_limit = analog_value; //shows 'gas detected' to the serial Serial.println("GAS DETECTED !!!"); //shows the minimum gas limit to the serial Serial.println("Gas limit: "+String(gas_limit)); //gas detected return true; } else { //shows 'no gas detected' to the serial Serial.println("No gas detected..."); //if first time, shows 'X' to the serial if(gas_limit == 0) Serial.println("Gas limit: X"); else //shows gas limit to the serial Serial.println("Gas limit: "+String(gas_limit)); //no gas detected return false; } }
Step 19: Sender Code [readDhtSensor]
void readDhtSensor() { // declaration of variables that will receive the new temperature and humidity float novoC, novoH; //waits 250ms delay(250); //set dht22 sensor values tovariables &novoC and &novoH int err = dht22.read2(DHTPin, &novoC, &novoH, NULL); //checks for an error if (err != SimpleDHTErrSuccess) { //shows error in the serial Serial.print("Read DHT22 failed, err="); Serial.println(err); return; } //if no error //sets the variable values c = novoC; h = novoH; //shows values in the serial Serial.print((float)c); Serial.println(" *C "); Serial.print((float)h); Serial.println(" H"); //waits 250ms delay(250); }
Step 20: Sender Code [sendPacket]
Finally, we opened a package to add the data for SMS sending.
void sendPacket() { //starts a connection to write UDP data LoRa.beginPacket(); //send packet LoRa.print(packet); //returns an int: 1 if the packet was sent successfully, 0 if there was an error LoRa.endPacket(); }
Be the First to Share
Recommendations
2 Comments
1 year ago
Thank you for a very useful case.
How would you do, if you want to add more than one sender module? Let's say you have 5 rooms, with a gas detector in each, and still only use one receiver unit.
Best, Mikael
2 years ago on Step 20
Hi there
i am just going through your project and have question about coding.
Is this all one program or different program files as i am new to Arduino programming.
please help me in this regards
Amrit | https://www.instructables.com/ESP32-LORA-Gas-Sensor-Moisture-and-Temperature-by-/ | CC-MAIN-2021-25 | refinedweb | 1,737 | 52.39 |
Number Guess
For this challenge we get a binary (guessPublic64) and the source it was compiled from (guessPublic.c).
Outline
The program basically does the following:
- Ask the user to enter the sum (guess) of two secret random numbers in the range from 0 to 1000000
- Calculate the random numbers, using
c.time()as seed
- If the guess equals the sum of the two random numbers, the flag gets printed
Here’s the source code:
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> char *flag = "REDACTED"; char buf[50]; int main(int argc, char **argv) { puts("Welcome to the number guessing game!"); puts("Before we begin, please enter your name (40 chars max): "); fflush(stdout); fgets(buf, 40, stdin); buf[strlen(buf)-1] = '\0'; strcat(buf, "'s guess: "); puts("I'm thinking of two random numbers (0 to 1000000), can you tell me their sum?"); srand(time(NULL)); int rand1 = rand() % 1000000; int rand2 = rand() % 1000000; printf(buf); fflush(stdout); int guess; char num[8]; fgets(num,8,stdin); sscanf(num,"%d",&guess); if (guess == rand1+rand2){ printf("Congrats, here's a flag: %s\n", flag); } else { printf("Sorry, the answer was %d. Try again :(\n", rand1+rand2); } fflush(stdout); return 0; }
From a quick look at the source code we learn that there is no buffer overflow vulnerability due to the use of ‘'’fgets()’’’ which restricts the length of the input to be read. However, when we enter e.g.
%d as name, our name suddenly becomes something like
1339265028. Obviously we’re dealing with a format string vulnerability here. This allows us to read the stack and subsequently find out the secret random numbers!
We can outline the approximate steps from here to the flag:
- Using GDB, find out, where on the stack the random numbers are stored (this always the same)
- Craft a format string payload suited to the scenario (and buffer)
- Use this payload on the shell server
Debugging
We load the binary in GDB and via
disas main obtain the assembly instructions of the main function. For us the two parts where the random numbers are pushed on the stack are of most interest. For this, we just need to find the function calls to the rand() function:
Call for first number:
0x0000000000400930 <+202>: callq 0x400750 <rand@plt>
Call for second numb:
0x000000000040095f <+249>: callq 0x400750 <rand@plt>
From these positions we go down a few steps to find those instructions where the random and modulo operations are finished. In case you are as much of an assembly pro like I am, this might involve a few iterations of trial and error :) . We basically set breakpoints somewhere after the first and second
rand() calls find out the random numbers via
info reg.
Below we can see the result of this investigation:
First number moved to %ecx:
0x000000000040095a <+244>: mov %ecx,%eax
Second number moved to %ecx:
0x0000000000400989 <+291>: mov %ecx,%eax
Now we know what our random numbers. Next up is finding out their location on the stack. For this we set another breakpoint after the second breakpoint, prefarrably here:
0x0000000000400993 <+301>: mov $0x0,%eax
At this breakpoint we display the content of some stackframes via
x/24d $rsp (in this case 24 frames and in decimal representation). Et voilà, there are our two random numbers (see screenshot below).
In order to display both of them, we exactly need to read exactly 9 stack frames, which is achieved with
%d %d %d %d %d %d %d %d %d as name.
Below you can see an exemplary (debug) run of the binary:
And finally, we apply our knowledge on the CTF server. Works like a charm!
| http://admin-admin.at/angstromctf2018-numberGuess | CC-MAIN-2018-47 | refinedweb | 614 | 66.27 |
Exploring Spark DataSource V2 - Part 6 : Anatomy of V2 Write sixth blog in the series where we discuss about different interfaces to write data in V2 API.You can read all the post in the series here.
Write API with Transactions
One of the shortcoming of the data source V1 API was bare bone write API. It was not built to support complex down stream systems like databases. Also the interface has not exposed any transactional support. So it was all left to user to do all the complex handling of failures and cleanup.
Datasource V2 API addresses this shortcoming. It has transactional support in API level. This makes building more powerful connectors much easier.
Write API Interfaces
Write API interfaces mimics the read interfaces which we saw in last few posts. The below are the different interfaces.
DataSourceV2
DataSourceV2 is a marker interface. It doesn’t have any methods to override. Extending this interface we indicate that we are implementing support for V2 datasource.
WriterSupport
WriterSupport is interface which indicates that data source supports write.
It has single method with below signature
def createWriter(jobId: String, schema: StructType, mode: SaveMode, options: DataSourceOptions): Optional[DataSourceWriter]
From the above signature it’s clear that,it’s an entry point method for data source. The below are different options
jobId - Id of the job in which this write is happening.
schema - Schema of DataFrame/Dataset that need to be written
SaveMode - Different modes of write like overwrite, update etc. This is same as earlier API
options - Map containing all the options passed to connect to the underneath source.
The method returns an optional DataSourceWriter. Optional type is a Java 8 equivalent of scala Option. The return type is optional here, because data source can decide not to do anything depending upon the SaveMode.
DataSourceWriter
DataSourceWriter is the primary interface for actually responsible for writing. It exposes below methods
DataWriterFactory
def createWriterFactory:DataWriterFactory[Row]
DataWriterFactory is a factory class to create actual data writers. For each partition of data it is created and sent to executors.
It’s little bit different compared to read path. In read, data source returned a list of factory objects. The reason for that is, the list indicated how many partitions needs to be created. But in case of write, spark already knows number of partitions. So no need to of list here.
Commit
def commit(messages: Array[WriterCommitMessage]): Unit
As we discussed before, the above method is part of transaction support in the writer. When all the writing is done, this method is called to commit. This is overall commit. Individual partition commit will be there in DataWriter interface which we will discuss below.
WriterCommitMessage is a message interface, that should be used by data source to define their own messages to indicate the status of each partition write.
Abort
def abort(messages: Array[WriterCommitMessage]): Unit
It’s a mirror interface to commit. This is called whenever there is complete failure of job. This is used to cleanup the partially written data.
DataWriterFactory
It’s a factory class to create actual data writer. This code executes in each executor.
def createDataWriter(partitionId:Int, attemptNumber:Int): DataWriter[T]
As the name suggest, it creates data writers. The parameters are
partitionId - Id of partition. This helps writer to understand which partition it’s writing
attemptNumber - In case of writing, there can be multiple attempts. These attempts can be due to speculative run or because of failures
Method returns DataWriter. As of now, T can be Row only.
DataWriter
Finally we have the interface which actually writes data. The below are methods
def write(record: T): Unit def commit(): WriterCommitMessage def abort(): Unit
write method is the one which responsible for actual write. Other two methods are same as DataSourceWriter but now they work at the level of partition. These methods are responsible committing or handling write failures at partition level.
The WriterCommitMessage sent by commit method in this interface are the one which are sent to DataSourceWriter. This helps data source to understand status of each partition.
Conclusion
Datasource V2 brings transaction support to data source writes. This makes API more powerful and flexible. | http://blog.madhukaraphatak.com/spark-datasource-v2-part-6/ | CC-MAIN-2018-34 | refinedweb | 695 | 58.58 |
You will hear a lot about namespaces, symbol tables and lexical scoping in Perl discussions, but little of it will make any sense without a few key facts:
Symbols, Symbol Tables and Packages; Typeglobs‘ minimise.
Lexical Variables and Symbols or a hash. timewhich. 🙂
my()creates a lexically-limited non-package-based scalar, array, or hash — when the scope of definition is exited at compile-time, the variable ceases to be accessible. Any references to such a variable at runtime turn into unique anonymous variables on each scope exit.
The @INC array
.
The %INC hash
‘print ‘use ‘use test; print map {"$_ => $INC{$_}n"} keys %INC’
test.pm => test.pm
Since the file was found relative to
. (the current directory), the
relative path is inserted as the value. If we alter
@INC, by adding /tmp to the end:
% cd /tmp % perl -e ‘BEGIN ‘BEGIN ‘BEGIN.
For the sake of completeness, I’ll present this{‘test.pm’}n";
In the above example
$FindBin::Bin is equal to /tmp. If we move
the script somewhere else… e.g. /tmp/x in the code above
$FindBin::Bin equals /home/x.
% /tmp/load.pl
test.pm => /tmp/test.pm
This is just like
use lib except that no hard coded path is
required.
You can use this workaround to make it work under mod_perl.
do ‘FindBin.pm’; unshift @INC, "$FindBin::Bin"; require test; #maybe test::import( … ) here if need to import stuff
This has a slight overhead because it will load from disk and
recompile the
FindBin module on each request. So it may not be
worth it.
Modules, Libraries and Program Files
Before we proceed, let’s define what we mean by module, library and program file.
- Librariesrnrn"; } 1;
web.pl ———— package web ; # Call like this: web::print_with_class(‘loud’,"Don’t shout!"); sub print_with_class{ my( $class, $text ) = @_ ; print qq{<span class="$class">$text</span>}; } 1;
- Modulesn"} 1;
- Program Filesor
.plx.
The program file will normally
require()any libraries and
use()any modules it requires for execution.
It will contain Perl code but won’t usually have any package names.
Its last statement may return anything or nothing.
require()HellHell()
use(), just like require(), loads and compiles files containing Perl
code, but it works with modules().
do().
- An article by Mark-Jason Dominus about how Perl handles variables and namespaces, and the difference between
use vars()and
my()– .
- For an indepth explanation of Perl data types see the the Chapters 10, 11 and 21.
- The Exporter, perlvar, perlmod and perlmodlib man pages. | http://www.devshed.com/c/a/perl/introduction-to-mod_perl-part-6-even-more-perl-basics/ | CC-MAIN-2019-09 | refinedweb | 419 | 66.23 |
IqRdf - RDF Renderering for Ruby and Rails
IqRdf is a RDF renderer for Ruby and Rails. You can use it in any Ruby environment to render Trurtle-, N-Triple- (not implemented yet) or XML-RDF.
IqRdf underlays a Builder-like approach to specify the RDF-Data by using a internal Ruby DSL. The basic Idea for specifing a triple (subject, predicate, object) is that the predicate is a method call on the subject with the object as parameters:
IqRdf::some_subject.some_predicate(IqRdf::some_object)
The IqRdf namespaces are needed not to mess up the rest of your project due to
the heavy use of method_missing in the IqRdf-Library. See the IqRdf::use method
for Ruby 1.9 to omit the
IqRdf:: prefix.
Ruby example
You can use IqRdf in pure Ruby to produce Strings in a certain RDF Syntax like Turtle or XML:
require 'IqRdf' document = IqRdf::Document.new('') document.namespaces :skos => '', :foaf => '' # A :rdf namespace is added automatically document << IqRdf::john_doe.myCustomNote("This is an example", :lang => :en) # Turtle: :john_doe :myCustomNote "This is an example"@en. document << IqRdf::john_doe(IqRdf::Foaf::build_uri("Person")).Foaf::name("John Doe") # Turtle: :john_doe a foaf:Person; foaf:name "John Doe". document << IqRdf::john_doe.Foaf::knows(IqRdf::jane_doe) # Turtle: :john_doe foaf:knows :jane_doe. document.to_turtle # => "@prefix : <>. ..."
Rails example
Include IqRdf to your Ruby on Rails project by adding the following line to your Gemfile (or with Rails 2.x in your config/environment.rb):
gem "iq_rdf"
Add the mime types you want to support to your config/initializers/mime_types.rb file:
Mime::Type.register "application/rdf+xml", :rdf Mime::Type.register "text/turtle", :ttl Mime::Type.register "application/n-triples", :nt
Now you can define views in you application. Use the extension .iqrdf for the view files. You can use the extensions .ttl or .rdf in the URL of your request, to force the output to be in Turtle or XML/RDF.
Views
In your views IqRdf gives you a document object you can add your triples
to. But first you will have to define your namespaces and the global language if
you want to label all String literals in a certain language (as long as there is
no other language or
:none given).
document.namespaces :default => '', :foaf => '' document.lang = :en document << IqRdf::test_subject.test_predicate("test") # Turtle: :test_subject :test_predicate "test"@en. document << IqRdf::test_subject.test_predicate("test", :lang => :de) # Turtle: :test_subject :test_predicate "test"@de. document << IqRdf::test_subject.test_predicate("test", :lang => :none) # Turtle: :test_subject :test_predicate "test". # ...
Use the namespace token
:default to mark the default namespace. This has the
same effect as specifing the default namespace in
IqRdf::Document.new.
Complex RDF definitions
TODO
Copyright (c) 2011 innoQ Deutschland GmbH, released under the Apache License 2.0 | http://www.rubydoc.info/gems/iq_rdf/frames | CC-MAIN-2016-40 | refinedweb | 451 | 51.24 |
How to save a Safe Array into SQL CE
- 02 Agustus 2012 20:50
Hello:
I'm now facing a problem saving an image which is contained in a safe array into "image" datatype field in SQL CE 3.5.
Previously, this MFC program is dealing with SQL express using ADO
#import "c:\Program Files\Common Files\system\ado\msadox.dll"
#import "c:\Program Files\Common Files\system\ado\msado15.dll" no_namespace rename("EOF", "EndOfFile")
The code was like: appendchunk(safearray), and then use update() method. But I found out that ADOX doesn't support update() method, so the previous code failed.
I tried to find a way to work around it: save the content in safe array into a char *, and then save it to a CString, and then use query "update table set image=convert(varbinary, '"+CString+"') where **", since char* contains 0 in it and CString considers it as terminator, so I added "1" to char * before save it into CString. So basically, storing problem is solved. However, when I need to retrieve image from "image" field, it's the contaminated data. after image decode, I couldn't get my original image.
Therefore, I'm looking for a solution that can store a safe array in SQL CE 3.5.
Anyone has any idea? Thank you
Semua Balasan
- 06 Agustus 2012 10:00Moderator
- 06 Agustus 2012 14:56
Thank you for your reply Chen.
The image in my application is from the scanner, it is coded into JPEG, and stored in a safe array. Elements in this safe array are numbers from 0-255.
- 11 Agustus 2012 19:13
I worked out the problem, here is the solution:
In my situation, ADO failed so I went back to basic SQL query, now problem becomes how to convert safe array (with content 0-255 representing image) to CString.
1. pass safe array content to unsigned char * using "SafeArrayGetElement()"
2. pass each element in unsigned char* to integer
3. append all integers together and store in a CString
4. "UPDATE table SET column=convert(ntext,'"+CString+"' WHERE ***". Yes, I use ntext datatype to store image.
To retrieve information from this column, reverse all the above steps.
I guess this is really a case-to-case problem, I did find some information helping me decide why update() method doesn't work, but to solve the problem, it took me almost two weeks.
Hope this helps.
- Ditandai sebagai Jawaban oleh JensKitchen 11 Agustus 2012 19:14
- | http://social.msdn.microsoft.com/Forums/id-ID/sqlce/thread/a63cca51-1e04-4d45-981e-5a31e9f38e88 | CC-MAIN-2013-20 | refinedweb | 414 | 63.9 |
A Dozen Ways to Get the Testing Bug in the New Year
Test-driven development received a lot of attention in 2003, and the interest will grow in 2004. For good reason: everyone agrees testing is important, but now many respected programmers are claiming that by writing tests first, they see better designs emerge. These same programmers quickly point out that test-driven development makes them feel more productive and less stressed. At the end of a shorter programming day they've built a suite of passing tests and code with better designs. Sound too good to be true? Well, there's nothing to lose in giving it a whirl. In fact, there's much to be gained.
This article gives you 12 practical ways to start writing tests, and keep
writing tests, regardless of your development process. The first two
techniques play off of things you're probably already doing, so you don't have to move too far out of your comfort zone. The next two challenge you to wade deeper into the pool to realize the benefits of test-driven development. The remaining techniques round out the regimen to keep you testing effectively all year. You'll be well on your way to fulfilling your new year's resolutions. Caution: contents have been known to be infectious!
1. Let Your Computer Do the Boring Stuff
The easiest way to start writing tests is to identify situations where you visually inspect results, then replace that human checking process with automated checking. Color me lazy, but I want to put this thing called a computer to work for me. It's much more reliable than I am at keeping my expectations in check. Some results are difficult to check without a human in the loop; don't start there. Instead, go after low-hanging fruit to get a few small victories under your belt. I've found the pervasive
main() test driver to be easy pickings for automating. I'm not referring to the entry point that bootstraps your application, but rather the
main() method that acts like a test driver by printing results to the console.
For example, imagine that you're writing a Java class that performs the functions of a simple spreadsheet. A spreadsheet cell -- indexed by a column and row combination such as "A1" -- can store a number or a formula that may include numbers and cell references. Here's an example
main() test driver for the
Spreadsheet class:
public static void main(String args[]) {
Spreadsheet sheet = new Spreadsheet();
System.out.println("Cell reference:");
sheet.put("A1", "5");
sheet.put("A2", "=A1");
System.out.println("A2 = " + sheet.get("A2"));
System.out.println("\nCell change propagates:");
sheet.put("A1", "10");
System.out.println("A2 = " + sheet.get("A2"));
System.out.println("\nFormula calculation:");
sheet.put("A1", "5");
sheet.put("A2", "2");
sheet.put("B1", "=A1*(A1-A2)+A2/3");
System.out.println("B1 = " + sheet.get("B1"));
}
You may recognize this testing style or may have even written similar test drivers yourself, if only to give you some confidence that the code produced the results you expected. The
main() method was my testing harness of choice for many years, and I still get the urge to use it from time to time because it's easy. But just as I'm about to take the bait, I remember how a
main() test driver sucks the life out of me. See, every time I change code that affects the
Spreadsheet class, I want to run the test to see if my change broke anything. I'm confident in my changes if I run the test afterward and see the following console output:
Cell reference:
A2 = 5
Cell change propagates:
A2 = 10
Formula calculation:
B1 = 15
This testing approach has at least one problem: it requires that I visually inspect the output every time I run the test. Worse yet, as the number of results output by the test driver increases, my workload also increases. I'll quickly grow weary of doing work best suited for a computer and stop running the test altogether. Inspecting the output also implies that between test runs I have to remember how the expected output should look. Is the correct result of the formula calculation 10 or 15? Hmm, I can't remember. And if I can't remember, there's little hope of sharing the test with other folks.
JUnit is a computer's taskmaster when it comes to checking expectations. If you've never used JUnit, the JUnit FAQ will get you up and running in less time than it takes to type a
main() method signature. Using JUnit, a
main() test driver requiring human checking can be easily replaced by automated tests that check their own results. Here's the equivalent
Spreadsheet test, expressed in a JUnit test:
import junit.framework.TestCase;
public class SpreadsheetTest extends TestCase {
public void testCellReference() {
Spreadsheet sheet = new Spreadsheet();
sheet.put("A1", "5");
sheet.put("A2", "=A1");
assertEquals("5", sheet.get("A2"));
}
public void testCellChangePropagates() {
Spreadsheet sheet = new Spreadsheet();
sheet.put("A1", "5");
sheet.put("A2", "=A1");
sheet.put("A1", "10");
assertEquals("10", sheet.get("A2"));
}
public void testFormulaCalculation() {
Spreadsheet sheet = new Spreadsheet();
sheet.put("A1", "5");
sheet.put("A2", "2");
sheet.put("B1", "=A1*(A1-A2)+A2/3");
assertEquals("15", sheet.get("B1"));
}
}
Notice that the result checking is now codified in the use of
assertEquals() methods that automatically check whether the expected value (the first parameter) matches the actual value (the second parameter). There's no need for you to remember what the correct results should be.
JUnit is distributed with two test runners -- textual and graphical -- that both produce simple and unambiguous output. Using the textual runner, an "OK" on the console signifies that all of your expectations were met:
> java junit.textui.TestRunner SpreadsheetTest
...
Time: 0.04
OK (3 tests)
Using the graphical runner (
junit.swingui.TestRunner), you're looking for a comforting green bar. Most Java IDEs have an integrated graphical runner just waiting to stroke your ego, such as this runner in Eclipse:
Figure 1. Green is good
If your expectations aren't met, JUnit is quick to let you know. Depending on the test runner used, if a test fails, you'll either see an eye-popping failure message on the console or a flaming red bar, along with details of the failed test.
Automation isn't necessarily testing, you say? I couldn't agree more. So now that you have an automated test harness that takes the pain out of manual testing, feel free to write more comprehensive tests. The book Pragmatic Unit Testing will help you strengthen your testing skills and write better tests. As you write more tests, it doesn't cost you anything to keep them running. Indeed, automated tests increase in value over time as ongoing regression tests, so that you have more time to write good tests.
2. Stop Debugger Testing
There was a time when I followed the conventional wisdom of running my code through a debugger to check that the code worked as I expected. That approach worked well, if only I never had to change the code again. But then when the code needed to be changed, I resisted the change because I dreaded firing up the debugger and walking through the code. In other words, using the debugger as a regression testing tool had the same drawbacks as using the
main() method as a test driver. It just didn't scale. Consequently, I tended not to touch working code for fear of unknowingly breaking something. The result was code rot.
If you're like me, you use a debugger to validate mental assertions as follows:
- Set a breakpoint right before a section of code you have questions about.
- Set watches on interesting variables within that code section.
- Run the program up to the breakpoint.
- Single-step through each line, examining the variables along the way.
- Optionally, manipulate variables on the fly to force certain code paths to be exercised.
The entire time I'm doing this, in my head I have expectations about the values of variables and the results of method calls. The debugger merely gives me answers that I then match against my expectations. That is, when I use a debugger, I'm really settling for human checking that's prone to error and boredom.
Look for opportunities to replace the human checking you do via debugger with an automated test that checks its own results. It's not always easy to initialize the environment required by a section of code you'd like to test. After all, it's running the program up to the breakpoint that builds that context around the code, though usually at a significant start-up cost. But if the code is likely to undergo change that might break it, then it's worth finding a way to write an automated test. In doing so, you might just discover that the code being tested can be decoupled from some of its dependencies.
3. Assert Your Expectations
A lot has been written about test-driven development, summed up in this simple recipe:
- Write new code only after an automated test has failed.
- Refactor to keep the code clean.
The notion of writing a failing test before writing the code that makes it pass may seem awkward, but think about how you write code. Before you write a method, you generally have some idea what the method should do. If you don't, one might argue you're not yet ready to write the method. Writing the test first is typically easier and quicker than writing the corresponding code. The test then keeps you from wandering down rabbit holes and lets you know when you're done coding. So, before writing that next method, stop to consider what expectations you already have in mind. Assume you've already written the method, then simply write an automated test that asserts that the method works correctly.
Say, for example, you're staring at a blank editor screen, ready to begin writing a
ShoppingCart class. The first thing you want it to do is manage a collection of items. If the same item is added twice, each time with a specified quantity, the shopping cart should contain the sum of both quantities. Now turn that mental assertion -- the success criteria for the code you wish you had -- into an automated test. The following is an example JUnit test:
import junit.framework.TestCase;
public class ShoppingCartTest extends TestCase {
public void testAddItems() {
ShoppingCart cart = new ShoppingCart();
cart.addItems("Snowboard", 1);
cart.addItems("Lift Ticket", 2);
cart.addItems("Snowboard", 1);
assertEquals(4, cart.itemCount());
}
}
Serious question: how much more effort would it take to write that test after you'd already expended brain cycles deciding what the shopping cart should do? Think of test-driven development as a way of structuring and refining that thought process.
Now that you have a test, write just enough code to make it pass. No more, no less. Just let the test guide you rather than speculating about what you might need in the future or worrying about the next test. When the test passes, refactor the code as necessary to keep it clean and as simple as possible. Then re-run the test to make sure refactoring didn't break anything. Repeat by asserting your expectations for what the code should do next. Before long you'll fall into your own test-code-refactor rhythm. Stick with it; it will serve you well.
4. Think of It as Design
Writing tests first is a design activity because it forces you to think through how the code should work from the outside before diving into an implementation. In good time and with practice, you'll notice test-driven development is more of a design technique than a testing technique. But if you go looking for stunning design insights with your first tests, you'll be disappointed. For now, just listen to what the tests are trying to tell you about your design by paying careful attention to difficulties writing the tests. Tests are just another client of your code, and writing the tests first gives you a client's perspective. If the code is difficult to test, it follows that it will be difficult for a client to use.
Here's an example design scenario: you're writing a shopping cart application. Client code should be able to add named items to a shopping cart and retrieve detailed information for the items currently in the cart. Without worrying about the infrastructure necessary to support the shopping cart, start by writing a JUnit test similar to the following:
public void testGetItem() {
ShoppingCart cart = new ShoppingCart();());
}
This test documents how you'd want the ideal
ShoppingCart class to look and behave from the outside. The test won't pass; nay, it won't even compile. But how much code do you need to write to make the test pass? Remember, somehow you need to swizzle a named item ("ISBN123") into its corresponding
Product instance. Sounds like a good job for a database, eh? Ugh! Setting up a database and writing JDBC code at this point will only delay the feedback loop. A passing test sooner rather than later would do wonders for your confidence. Do you really need a database to make the test pass? No, you just need a data structure that associates keys with
Product instances. You could certainly take a small step for now just to get the test to pass by hard-coding the iterator to return the expected product. In a subsequent step, you could encapsulate the mapping layer behind a simple interface:
public interface Catalog {
public void addProduct(String key, Product p);
public Product getProduct(String key);
}
Now you can avoid setting up a database by writing an in-memory implementation of the
Catalog interface that uses something like a
HashMap. The decision to put off writing a persistent catalog implementation isn't triggered by laziness. Rather, by choosing a natural and simple implementation first, the
Catalog interface is naturally clean. Indeed, the test helps you separate interface design from implementation design so that implementation details don't creep into the interface. The
Catalog interface can now be used to decouple the shopping cart from any particular catalog implementation. Simply construct a
ShoppingCart with any implementation of the
Catalog interface. Here's the same test refactored to do just that:
public void testGetItem() {
Catalog catalog = new InMemoryCatalog();
catalog.addProduct("ISBN123", new Product("Confessions of an OO Hired Gun", 9.95));
ShoppingCart cart = new ShoppingCart(catalog);());
}
Getting this test to pass is markedly easier now that a database isn't in the picture. Yes, you'll probably need a real database at some point. And you'll want to test that the shopping cart behaves the same with a real database plugged in. Until then, the in-memory catalog helped you focus on designing the shopping cart before speculating on infrastructure. Writing the test first revealed an insight for a design with low coupling and high cohesion: the
ShoppingCart class is decoupled from any particular catalog implementation, and the
Catalog interface encapsulates details of how named items are mapped to products.
You don't have to be an OO hired gun to craft good designs. You just have to listen to what the test says you need, and then write the simplest code that will make it pass. Remember to refactor between tests to keep the code clean.
5. Build Safety Nets
You wouldn't sign up to compete in a triathlon as your first goal toward exercising more in the new year; you'll experience the same pain and frustration if you attempt to test legacy code as your first testing exercise. Nothing kills a resolution quicker than going overboard. That being said, unless you're on a new project, legacy code -- code already written, but without tests -- is a fact of life. And without tests, legacy code is a liability. You can't change the code for fear of breaking something, and you usually can't write tests without having to change the code. Rock meets hard place.
When faced with changing legacy code, reduce the risk of breakage by building safety nets. I don't mean you should halt forward progress to write comprehensive tests for the entire legacy code base. That is the road to discouragement and lost opportunity cost. Instead, be pragmatic by writing focused tests that create a safety net around the code you intend to change. Then change the code and run the tests to ensure that nothing unexpected happened. If you can't write focused tests without first refactoring, use any other safety nets at your disposal to gain confidence, including existing functional tests or a buddy looking over your shoulder.
Refactoring helps prevent code rot. Safety nets make refactoring safe. If you're writing new code test-first, you're building safety nets along the way. If you're attempting to refactor legacy code, it's dangerous without safety nets. Building them isn't always easy, but it's usually well worth it.
6. Learn by Checked Example
Learning how to use third-party APIs can be frustrating. If you're lucky, the API might include a comprehensive JavaDoc. If you're really lucky, the API might even behave as the JavaDoc claims. Regardless of the documentation (or lack thereof), I learn best by doing. To truly understand how an API works, I need to write code that pokes and prods the API to get feedback about my assumptions. But exploring an API by first attempting to use it in my production code doesn't give me a warm fuzzy feeling. I hear dear Mom reminding me to "Put my play clothes on." I'd rather learn in a forgiving environment where I can explore an API with impunity. Checked examples provide a safe context for learning.
A checked example is a test, though perhaps not in the traditional sense of the word. Think of it as a learning test that validates your assumptions about how an API behaves, but doesn't necessarily attempt to uncover errors in the API. For example, say you're writing an application that will use Lucene -- a search engine technology with a Java API. How do you begin writing code that uses Lucene to search for indexed documents? Start by writing a learning test similar to the following that checks its own results and teaches you what you want to learn:
<imports omitted for brevity>
public class LuceneLearningTest extends TestCase {
public void testIndexedSearch() throws Exception {
//
// Prepare a writer to store documents in an in-memory index.
//
Directory indexDirectory = new RAMDirectory();
IndexWriter writer =
new IndexWriter(indexDirectory, new StandardAnalyzer(), true);
//
// Create a document to be searched and add it to the index.
//
Document document = new Document();
document.add(Field.Text("contents", "Learning tests build confidence!"));
writer.addDocument(document);
writer.close();
//
// Search for all indexed documents that contain a search term.
//
IndexSearcher searcher = new IndexSearcher(indexDirectory);
Query query = new TermQuery(new Term("contents", "confidence"));
Hits hits = searcher.search(query);
assertEquals(1, hits.length());
}
}
The
LuceneLearningTest is a standard JUnit test that invokes the Lucene API to index an example document in an in-memory directory (
RAMDirectory), then asserts that a search for the word "confidence" in the document's contents yields a hit. With this test under your belt, you can continue to grow the learning test suite one test at a time. For each new thing you need to learn, write a test method and refactor any common test code into the
setUp() method. The following refactored version of the
LuceneLearningTest includes checked examples for two additional query types:
<imports omitted for brevity>
public class LuceneLearningTest extends TestCase {
private IndexSearcher searcher;
public void setUp() throws Exception {
Directory indexDirectory = new RAMDirectory();
IndexWriter writer =
new IndexWriter(indexDirectory, new StandardAnalyzer(), true);
Document document = new Document();
document.add(Field.Text("contents", "Learning tests build confidence!"));
writer.addDocument(document);
writer.close();
searcher = new IndexSearcher(indexDirectory);
}
public void testSingleTermQuery() throws Exception {
Query query = new TermQuery(new Term("contents", "confidence"));
Hits hits = searcher.search(query);
assertEquals(1, hits.length());
}
public void testBooleanQuery() throws Exception {
Query query =
QueryParser.parse("tests AND confidence", "contents", new StandardAnalyzer());
Hits hits = searcher.search(query);
assertEquals(1, hits.length());
}
public void testWildcardQuery() throws Exception {
Query query =
QueryParser.parse("test*", "contents", new StandardAnalyzer());
Hits hits = searcher.search(query);
assertEquals(1, hits.length());
}
}
Notice that the indexing step has been refactored into the
setUp() method, which is called prior to every test method. In this case, the use of the
setUp() method has four functions:
- Removes code duplication from the test methods.
- Ensures that the test methods don't affect or rely on each other.
- Helps readers of the test understand the purpose of this particular set of tests: indexing and searching.
- Serves as a reminder that your application using Lucene will generally index documents less frequently than it will search documents.
Writing learning tests in isolation helps you focus on one thing at a time. You first focus on writing a learning test that confirms your understanding of an API. Then you write a test for the production code that relies on the underlying API. When that test passes, you've successfully integrated the API into your application. In other words, build confidence layer by layer. If the behavior of the API ever changes, your learning tests will pinpoint the change with greater accuracy than your integration test.
What happens when a new version of the API is available? Well, your learning tests also serve as an automated regression test suite that you can use to detect changes. Before upgrading to a new version of an API, run your learning tests to ensure that your assumptions about the API are still valid.
One more thing, while you have your play clothes on: you can also use this technique to learn new programming languages. For example, I learned Ruby (and you should too!) by writing a learning test every time I discovered something new in the language. The following is an example learning test that documents and validates two features of Ruby arrays:
require 'test/unit'
class RubyArrayTest < Test::Unit::TestCase
def testPushPopShift
a = Array.new
a.push("A")
a.push("B")
a.push("C")
assert_equal(["A", "B", "C"], a)
assert_equal("A", a.shift)
assert_equal("C", a.pop)
assert_equal("B", a.pop)
assert_equal(nil, a.pop)
end
def testCollect
a = ["H", "A", "L"]
collected = a.collect { |element| element.succ }
assert_equal(["I", "B", "M"], collected)
end
end
Any time I need to remember how to use an API or Ruby language feature, I refer back to my suite of learning tests. They document working examples that I can continually run and modify until I'm confident enough to move forward. And if I can't find what I'm looking for, I expand my knowledge base by writing a new test.
7. Corner Bugs
Even when we've written solid tests, once in a while someone using our code (a paying customer, a persnickety cubemate) discovers a bug. Don't let that stop you from continuing to write tests that catch the majority of bugs. Instead, use it as an opportunity to improve your testing skills. In the meantime, a bug has been reported and it needs to be fixed. Thankfully, you're able to quickly identify the suspect lines of code because you happen to have vast knowledge of the code base. So you fire up your favorite editor with fingers poised on the keyboard, ready to make the necessary repairs. But before you do that, don't let a golden opportunity to forever corner that bug pass you by.
How will you know when your code changes have squashed the bug? After all, if you're moments away from making a change, then you must have expectations about how the code will work after you've made the change. Writing code is a means to an end. Now is the time to turn your expectations into an automated test that will signify the end. The bug has been fixed when the test passes. Moreover, once the test passes, you have an automated way to keep the bug cornered for life.
8. Expand Your Toolbox
Often, we'd like to test something, but we just don't have the right tool for the job. We're short on time as it is, and spending precious time crafting a test harness is yet another reason not to test. Thanks to the work of others, there's no excuse for skimping on testing for lack of sufficient tools. The open source world is currently teeming with handy testing tools. It pays to be creatively lazy by looking around before reinventing yet another test harness.
Say, for example, you're writing a servlet that provides a shopping cart service. The intent of the servlet is to add the item and quantity specified in the request parameters to the shopping cart. You'd like to test that the servlet works, but the method you want to test requires an
HttpServletRequest instance. You can't create one of those very easily. And if you have to crank up a J2EE server to put the servlet in a known state every time you want to run the test, you won't run the test very often. It's time to expand your toolbox to include the Mock Objects framework. The following JUnit test uses the Mock Objects framework to test the servlet outside of a J2EE server:
import junit.framework.TestCase;
import com.mockobjects.servlet.*;
public class ShoppingServletTest extends TestCase {
public void testAddRequestedItem() throws Exception {
ShoppingServlet servlet = new ShoppingServlet();
MockHttpServletRequest request = new MockHttpServletRequest();
request.setupAddParameter("item", "Snowboard");
request.setupAddParameter("quantity", "1");
ShoppingCart cart = new ShoppingCart();
servlet.addRequestedItem(request, cart);
assertEquals(1, cart.itemCount());
}
}
Notice that the test presets the request parameters on a
MockHttpServletRequest instance. That instance is then passed in to the servlet's
addRequestedItem() method. When you run the test, your servlet is fooled into thinking that it's running in a servlet container. Later on, your integration tests will cast a wider net by validating that the servlet works in its native environment. But when you're writing the servlet code, using mock objects makes running the tests quick and painless.
So, before attempting to write a test harness from scratch or giving up on testing altogether, survey the tools others have crafted in their times of need. JUnit is a framework, not an application. By all means, if the standard JUnit assertion methods aren't enough, then write custom assertion methods. It's also relatively easy to write applications that build upon JUnit. JUnit.org maintains a list of existing JUnit applications and extensions. Don't stop with JUnit and its Java ilk. Many xUnit testing framework implementations for other languages and technologies are already there for the taking (visit XProgramming.com). If you can't seem to find what you're looking for, let Google be your guide. And if you do end up building a test harness, please share it so that others can expand their toolbox.
9. Make It Part of Your Build Process
A test is a valuable radiator of information. It documents -- in an executable format -- how code works. You don't have to trust that the documentation is correct; just run the test for yourself. If it fails, the output tells you straight up that the code doesn't work as the test promises. So once you've written a passing test, treat it with the respect it deserves by checking it in to your version control system. Then capitalize on the investment by running the test as part of your team's build process.
While you're grooving in the test-code rhythm, it's convenient to use the JUnit test runner integrated into your favorite IDE. But you also need to externalize the build process so that anybody on your team, regardless of their IDE loyalties, can build and test the code on their machine. In the Java world, Ant is the king of the hill when it comes to making your build and test process portable. The following snippet of an Ant build.xml file uses the built-in
<junit> and
<batchtest> tasks to run all JUnit tests conforming to the
*Test naming convention:
<path id="build.classpath">
<pathelement location="${classes.dir}" />
<pathelement location="${lib.dir}/junit.jar" />
</path>
<target name="test" depends="compile" description="Runs all the *Test tests">
<junit haltonfailure="true" printsummary="true">
<batchtest>
<fileset dir="${classes.dir}" includes="**/*Test.class" />
</batchtest>
<formatter type="brief" usefile="false" />
<classpath refid="build.classpath" />
</junit>
</target>
First notice the use of the
<path> element to explicitly declare a classpath for the build rather than relying on the
CLASSPATH environment variable being set correctly. This makes the classpath portable across machines. Second, notice that the
test target is dependent on the
compile target. So, to compile and test the code in one fell swoop, anybody on your team can check out the project from the version control system and type:
ant test
Finally, notice that the
<junit> task is configured with
haltonfailure="true". This means that the build process will fail if any test fails. After all, the build contains tainted goods if all the tests don't pass.
Why stop there? Now that you have an Ant target that compiles and tests the project, schedule the
test target to be automatically run by a computer at a periodic interval. For example, using
CruiseControl or Anthill (both free) you can put an idle machine to good use running any Ant target as often as you'd like. Using a separate build-and-test machine implies that everything needed to build and test your project is under version control. You are using version control, aren't you? You'll be surprised how often a separate machine flushes out build problems. And if the build fails, those schedulers will even send you an email so that you can take appropriate action to get back on solid ground.
So, no matter how many tests you have, realize their value to your team early and often by making testing part of your process. Add each passing test you write to your version control system and run all the tests continuously to radiate confidence.
10. Buddy Up
When learning anything new, I've found it helpful to buddy up with another newbie. Besides being a lot more fun than trudging up the learning curve alone, together, you and your buddy can cover more ground. You can also keep each other accountable to the goals you share and challenge each other to become better. As you practice the techniques described in this article, openly discuss with your buddy your triumphs and struggles. Critique each other's tests and share design insights gained from code driven by tests. And when you feel pressure to slip back into old coding habits, a good buddy will bring you back from the brink.
So how do you find a buddy? It's been my experience that many folks secretly want to try test-driven development, but they don't want to be the only person on the team doing it. So start by expressing your desire to learn and practice test-driven development. By making this proclamation, you'll invite social support that can be a powerful motivator to help you follow through. Moreover, once you step into the spotlight you'll likely draw others out of the shadows.
11. Travel With a Guide
Sometimes buddying up just isn't enough. If you and your buddy are learning at the same time, you may both stumble into the same pitfalls. Traveling with an experienced guide will help you avoid getting bogged down. Don't feel that seeking outside help is a way of copping out. You'll be more productive if you don't have to blaze your own trails.
Consider arranging for training in unit testing or test-driven development to quickly put these techniques into practice. For this kind of training to be truly effective, it needs to be customized for you. For example, students I've taught have found short and focused sessions -- tailored and applied to the software they're building and the technologies they're using -- to be most beneficial. So look for training that covers the basic trails, but then lets you chose advanced paths of interest.
As you continue to practice test-driven development, you'll undoubtedly hit a few snags. Don't spend too much time fighting through them. A few minutes of one-on-one discussion with a mentor who's been there and done that will keep you on pace.
12. Practice, Practice, Practice
Writing tests first is a programming technique that takes practice, and lots of it. Accept the fact that you won't see miraculous results overnight. Experts say it takes a minimum of 21 days to build a positive habit and six months for it to become part of your personality. So when you feel yourself backsliding, don't despair. Just keep pressing on and pay careful attention to mental assertions you're making that could be codified in tests. Your brain will love you for it!
As with anything new, the more you practice, the better you get. Start simple by promising yourself to write just one good automated test a day. If you write more, it's bonus points. Tomorrow morning, you'll at least have one passing test. In a week, you'll have at least five. Run all your tests every time you change code, even if you don't think your change could possibly break anything. This will get you in the habit of running the tests often and build your confidence in the tests. Before long, you'll have a suite full of tests and you won't be able to confidently touch the code without running the suite afterward. Green bars are your reward for progress.
Summary
Getting started writing tests doesn't have to be difficult or time-consuming. Just wade in gradually by spotting practical opportunities to let your computer automatically check what you're already checking manually. Before writing new code, assert your expectations about what it should do. Along the way, listen to the tests for design insights. Make testing an integral part of your development process by writing tests first and making it easy for anyone on your team to run all the tests at any time. Finally, don't go it alone.
I hope these techniques help you get the testing bug this year. It's a resolution that's sure to improve your design and testing skills. Don't forget to relax by reminding yourself that every day you're just getting started. You'll quickly find that indeed you do have time to test, and then some.
Resources
-
JUnit FAQ
Answers to the world's most frequently asked JUnit questions.
Pragmatic Unit Testing
Andy Hunt and Dave Thomas, The Pragmatic Programmers, LLC, 2003.
A must-have, easy-to-read book that will help you quickly start writing good JUnit tests.
"Lucene Intro"
by Erik Hatcher
The first of a two-part series of great Lucene articles. I buddied up with Erik to write the Lucene learning tests.
- Login or register to post comments
- Printer-friendly version
- 16173 reads | https://today.java.net/node/219457/atom/feed | CC-MAIN-2015-27 | refinedweb | 5,928 | 64.3 |
mtl-compat
Backported Control.Monad.Except module from mtl
See all snapshots
mtl-compat appears in
Module documentation for 0.2.1.3
There are no documented modules for this package.
mtl-compat
This package backports the
Control.Monad.Except module from
mtl (if using
mtl-2.2.0.1 or earlier), which reexports the
ExceptT monad transformer and the
MonadError class.
This package should only be used if there is a need to use the
Control.Monad.Except module specifically. If you just want
mtl class instances for
ExceptT, use
transformers-compat instead, since
mtl-compat does nothing but reexport the instances from that package.
Note that unlike how
mtl-2.2 or later works, the
Control.Monad.Except module defined in this package exports all of
ExceptT’s monad class instances. Therefore, you may have to declare
import Control.Monad.Except () at the top of your file to get all of the
ExceptT instances in scope.
Changes | https://www.stackage.org/nightly-2019-01-10/package/mtl-compat-0.2.1.3 | CC-MAIN-2019-04 | refinedweb | 159 | 61.73 |
First solution in Clear category for The Hidden Word by GreenhornPro
from itertools import zip_longest
def checkio(text, word):
arry = list(map(lambda i:i.replace(' ', '').lower(), text.split('\n')))
arry_t = [''.join(i) for i in zip_longest(*arry, fillvalue=' ')]
row = 0
for i in arry:
row += 1
if word in i:
return [row, i.find(word)+1, row, i.find(word)+len(word)]
col = 0
for i in arry_t:
col += 1
if word in i:
return [i.find(word)+1, col, i.find(word)+len(word), col]
]
May 8, 2020
Forum
Price
Global Activity
ClassRoom Manager
Leaderboard
Coding games
Python programming for beginners | https://py.checkio.org/mission/hidden-word/publications/GreenhornPro/python-3/first/share/39a9710fa93892edc1f16be271336ca2/ | CC-MAIN-2021-31 | refinedweb | 103 | 57.98 |
A lot of people try to avoid refactoring, whether it's because they are scared of breaking their code, because they don't see immediate benefit, or they just pretend that there's no time for it. In reality though, refactoring can be extremely beneficial both short-term and long-term and there's a lot of reasons to spend some time on it. The most commonly mentioned ones would probably be finding bugs, making software easier to understand or improving its design.
The real reasons in my opinion, though, that should push you to mess with your (or maybe legacy) terrible code should be that refactoring helps us lose fear from our own code and the helps us avoid the feeling of shame when we have to show our code to somebody else.
So, in this article we will go over some easy ways to refactor and considerably improve your code without risking breaking everything at the same time, so that you don't have to be scared of your own code or be ashamed to show it to your colleagues.
The Easiest Improvements
To ease you into the refactoring of the feared codebase we will start with simple, yet very significant improvements that literary cannot break anything - first one being reformatting of code.
There are couple of ways how to approach fixing code formatting. You can either fix things like wrong indentation or missing
{} around code-blocks as you go or you can take little more systematic approach. The more systematic approach would constitute creating a style-guide and then applying it (and ideally enforcing it).
I said that we should create a style-guide, but for most programming languages there already is a set of standard conventions such as PEP8 for Python or Google Java Style Guide for Java, which you can adopt and use tools or IDE plugins to help you find and fix all formatting issues.
Regardless of which approach you choose, it's important to (carefully) choose one style and stick to it and also make sure everybody in the team follows same guide to keep things consistent.
Another safe area for refactoring is comments. It's good to have them as long as they're relevant, up-to-date and useful. Most of the time though, you will find a lot of comments that should be removed. Those can be redundant comments or docs that describe something self-explanatory, commented-out code or obsolete comments that should be updated (or removed if not relevant anymore). Of these three I really want to highlight the commented-out code, because a lot of people will say: "But I might need it later!" - no you won't, stop lying to yourself, just delete it now and if you will actually need it in the future, then you'll be able to find it in
git history.
When it comes to comments, just remember that comments do not make up for bad code.
Last thing for this section is dead code. It creates clutter and the longer you leave it in the codebase the harder it becomes to remove because no one knows what it does or whether it's needed or not. Nowadays, any decent IDE will tell you about unreachable dead code so you don't need to be scared about removing it, so just get rid of it, there's no reason to keep it in there.
Low Hanging Fruit
Oftentimes it's easy to find things to refactor, like with the simple improvements shown above. If you however need a few examples of crappy code to look for, then here's a list:
Spending a lot of time looking for good variable, class or function name is in my opinion a time very well spent. It's also easy thing to refactor that can greatly improve readability of code, without risking any damage to fragile code. So, how to choose good names? In general, use nouns for classes - preferably non-generic (no,
Datais not a good name for class); verbs (or whole phrase) for a function and for variables?
Well, there's not really a single rule for naming variables, but generally, anything descriptive and unambiguous should work. To be more specific and technical - you should always avoid using single character names like
xor
a. For boolean variable names use a "question", e.g.
isReadyor
hasName. Oftentimes people don't like to use long variable names, but it's better to use long name, rather then using meaningless name (but concise names are obviously better). One last general recommendation would be to stick to single letter case - whether
camelCase,
snake_caseor anything else, choose one and stick to it (and preferably use convention and nomenclature of specific programming language).
Similarly to variables, also constants can help your code to become more readable. Therefore, try to replace any magical numbers/values with sensible named constants and use
CAPITALIZED_WITH_UNDERSCORESletter case.
Another thing ripe for refactoring are negated conditionals which are confusing, hard to read and error-prone. They're easy to remove though, as it's usually enough to reverse the bodies of
if/
elseblock. As I mentioned a few times already, your IDE might be able to spot negated conditionals for you and suggest a fix.
We already spoke about proper code-block formatting, but I want to mention here one thing I really hate to see and that is when people omit braces/body of conditionals and loops, for example:
if (checkStuff(value)) doStuff(otherValue); // Terrible if (checkStuff(value)) doStuff(otherValue); // Better, but still bad if (checkStuff(value)) { // Can put breakpoint on this line doStuff(otherValue); // and also on this line }
If you omit braces like this you might save one line of code, but really you're just setting yourself up for some nasty, long debugging. On top of that, if you need to set breakpoint in such one-liners, you will find out that you can't really put the breakpoints in properly because you can only set them on whole line and not just the part in a conditional or loop.
- Last but not least is vertical separation - or in other words - big distance between definition of variables and their usage. Variables, but also functions and methods should be defined as close as possible to the place where they are used to make it easier to read the code. Big vertical distance in definition of local variables and its usage might be a sign of function that is too big and should broken up into smaller ones.
The most basic rule: Make only tiny changes and retest.
Digging Deeper
Now that you went through some of the code and have little more confidence modifying it, you might want to dig deeper and look for more specific flaws in the code. One of the flaws you will definitely find will be duplicate code. Simple rule of thumb with code duplication is that if you repeat same piece of code 3 times, it's time extract it to separate function or variable.
Another common flaw might be excessive use of boolean parameters. Passing boolean parameters to a function might indicate that this function is doing more than one thing and therefore should be split into (at least) two smaller ones.
Speaking of function parameters - you might sometime encounter a bad practice of modifying input parameters. Arguments are function input and that's it - use them as input and don't change their value. If you see this flaw in a code it's best to copy the value into new variable and avoid modifying the parameter.
Last issue related to parameters that you might want to look out for are functions with too many parameters. Up to 3 parameters are usually fine, but seeing any more than that should raise a suspicion. You should inspect such function and make decision whether it's OK to use so many arguments or whether it's better to break up and/or simplify the function.
Moving on to variables, there are 2 basic issues that you might encounter, first being redundant temporary variables. This would look something like this:
def greet(person): first_name = person.name last_name = person.surname return f"Hello {first_name} {last_name}!"
Using this kind of variable is not useful in any way. It makes the code longer and doesn't explain or improve readability in any way so we should remove it and inline it like so:
def greet(person): return f"Hello {person.name} {person.surname}!"
The other common issue would be opposite of the above - that is - code lacking variables, for example:
function isLeapYear(year) { return ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0); }
This piece of code - unlike the previous issue - would benefit from a few extra variables that would help to explain what the code does. It would also simplify debugging, as it would be easier to set breakpoints and watch for each variable. Refactored version can look for example like this:
function isLeapYear(year) { var isFourthYear = ( year % 4) == 0 var isHundrethYear = (year % 100) == 0 var isFourHundredthYear = (year % 400) == 0 return ((isFourthYear && !isHundrethYear) || isFourHundradthYear); }
Last candidate for refactoring in this section is very easy to spot - it is complex/composite conditional. We've all seen those huge multi-line conditionals with a few
&& and
|| grouped together. They're ugly, hard to parse, hard to debug and hard to modify. The simplest way to get rid of it - or rather abstract it - is to extract it into separate checking function. Example of that looks like so:
if (checkValidity(card) || checkCredit(user, card) && isActive(user)) { // Bad doStuff(user, value); } else { doOtherStuff(user); } if (isEligibility(user)) { // Better doStuff(user, value); } else { doOtherStuff(user); }
Legacy Code
To be able to effectively refactor our code we need to have a decent test coverage, otherwise we're risking breaking the existing functionality. In previous sections I kinda assumed that we have tests and therefore can modify code and run tests suite to verify that everything is OK.
But how do we refactor code that doesn't have proper test coverage - or in other words how do we refactor Legacy Code? In cases where we can't rely on tests, I recommend only messing with what has to be changed, which would be code that has bugs that need fixing or part of codebase where we're adding new feature. In these areas start by writing tests for existing legacy code and only then proceed with any code modifications. I would personally start with first refactoring the old code to familiarize myself with it and to make it more "welcoming" to the necessary changes.
From this point you can proceed as with any other code that needs refactoring - take it one step at the time, start with small simple changes and retest frequently.
Leverage Tooling
Refactoring and in general taking good care of your code can be time-consuming, which can be problem on projects with tight schedule or when deadlines are approaching. These are the times when people throw all the good practices out of the window and try to "just ship it" as soon as possible.
To alleviate this pressure and make it easier to keep refactoring and improving the code even when there seems to be no time for it, try to use tools that can do some of the work for you. These can be linters like
pylint, code checkers like Checkstyle or code coverage tools like Sonarqube.
Speaking about code coverage and tests - also make sure your test suite is fast, otherwise you will end up dropping the slow tests or not running the suite at all.
In ideal world, all the above should be automated using some kind of CI/CD pipeline, which would run code checks with mandatory quality gates, report any code style inconsistencies, any possible bugs or issues before it even gets build and deployed.
Conclusion
This article is not an exhaustive list of "all things refactoring". For more extensive list and examples you should definitely check out books like Clean Code (especially chapter Smells and Heuristics) by uncle Bob or book called Refactoring by Martin Fowler.
Regardless of which guides or books on this topic you decide to follow, it eventually all boils down to a few simple rules. Always try to leave the code little cleaner then before - this way you can slowly but surely refactor and improve overall quality without too much effort and time spend. At the same time don't put off refactoring because doing it later usually mean never, which ends up producing terrible mess of a legacy code.
Discussion (1)
I'd say that one of the first steps to do is to introduce tests. General ones at first, more specific later as you advance in refactoring.
If a part of the code is not easily testable, it's a good candidate for refactoring. | https://practicaldev-herokuapp-com.global.ssl.fastly.net/martinheinz/the-simple-ways-to-refactor-terrible-code-115e | CC-MAIN-2021-17 | refinedweb | 2,154 | 64.54 |
I write the folowing code which is taking RAM and Hard disk capacity from user by using structures and than saving it to a new file after the user complete entring data it is displaying data entered by the user by opening that file. Problm is that i want to ask the user to choose an option (y/n): If user enter y then your program again get the next record of computer specification i.e RAM capacity and hard disk capacity and store the information in file. And when the user enter n it will stop getting information and display the data of the file. For this i use do while construct but it is not working properly it is getting data but displays only last entry. plz tell me wat should i do.
the code is:
#include <conio.h> #include <iostream.h> #include <fstream.h> struct computerspec { int ram; int hdisk; }compuspec; void main() { char ch; do { //prompt the user to enter RAM capacity cout<<"Enter the RAM capacity"<<endl; cin>>compuspec.ram; cout<<endl; //prompt the user to enter Hard Disk capacity cout<<"Enter the Hard Disk capacity"<<endl; cin>>compuspec.hdisk; cout<<endl; cout<<"Press 'y' if u wanna continue"<<endl; ch=getch(); cout<<endl; } while(ch=='y'||ch=='Y'); ofstream file; file.open("computerspec.txt"); file<<"ComputerSpec attributes/Data members\n"; file<<"RAM"<<"\t"<<"Hard disk"<<endl; file<<compuspec.ram<<"\t"<<compuspec.hdisk<<endl; file.close(); { char ch; ifstream file; file.open("computerspec.txt",ios::nocreate); while(file) { file.get(ch); cout<<ch; } getch(); end: file.close(); } getch(); }
Code reformatted and tags added. -Narue | https://www.daniweb.com/programming/software-development/threads/22987/hlp-me-in-dis-code | CC-MAIN-2018-43 | refinedweb | 269 | 58.38 |
A member of the platform recently stumbled upon a bug in his python code. Once we got to the bottom of it, we were surprised to find that the bug in question had been caused by a peculiar behavior of Python.
Let’s take the following code as example :
def foo(bar=[]): bar.append('a') return bar
Intuitively, this piece of code might seem like it ought to return the list
['a']whenever it is run. In practice, it is not quite so.
>>>foo()
['a']
>>>foo()
['a','a']
>>>foo()
['a','a','a']
As we can see, the list is not reset at each iteration but rather keeps its previously appended values. This behavior is due to the fact that python functions are also objects themselves. The function, along with its arguments, is therefore evaluated once when it is defined, and not at every call.
This is not only the case only for list arguments. Any mutable type arguments such as dicts, sets, lists, byte arrays and even functions themselves will follow the same behavior.
I was somewhat shocked that I had never stumbled upon this myself as this is hailed as a common stumbling block for newcomers to Python. Perhaps an unconscious habit of setting empty default arguments to
Noneand handling them later on in the function had prevented me from falling into a similar situation. | http://bioinfo.iric.ca/mutable-default-arguments-in-python/ | CC-MAIN-2017-17 | refinedweb | 226 | 69.92 |
vread_tsc checks whether rdtsc returns something less thancycle_last, which is an extremely predictable branch. GCC likesto generate a cmov anyway, which is several cycles slower thana predicted branch. This saves a couple of nanoseconds.Signed-off-by: Andy Lutomirski <luto@mit.edu>--- arch/x86/kernel/tsc.c | 15 +++++++++++---- 1 files changed, 11 insertions(+), 4 deletions(-)diff --git a/arch/x86/kernel/tsc.c b/arch/x86/kernel/tsc.cindex 80e6017..a159fba 100644--- a/arch/x86/kernel/tsc.c+++ b/arch/x86/kernel/tsc.c@@ -791,14 +791,21 @@ static cycle_t __vsyscall_fn vread_tsc(void) * ensures that rdtsc is ordered wrt all later loads. */ - /* ("");+ return last; } #endif -- 1.7.4 | https://lkml.org/lkml/2011/3/28/222 | CC-MAIN-2017-30 | refinedweb | 108 | 53.88 |
This is the fifth part of my Monad series. See the introduction for a list of all the posts.
You can find the code for this post on GitHub here.
In part 3 we created our first Monad, Identity<T>. It was worth starting with the simplest possible thing, so that we could focus on the Monad pattern without being distracted by detail. But working with a useless Monad might well have left you scratching your head, still wondering what the point was. So let’s create our first useful Monad, the Maybe Monad.
We’re used to the idea of nullability in C#. Technically null is a value that any reference type variable can have when it’s not pointing to an actual instance of that type. Nulls are problematic, in fact some people thing they are a mistake. They can be both a bug when we’ve forgotten to initialise a variable, and intentional when we use them to represent some state. Nulls are often used as one of the possible return values from a method when, for some reason, an instance can not be returned.
If I have methods that might return null, I should check the return value for null and execute some alternative branch. If we’ve got a whole chain of methods, any of which might return null, our intention can soon be obfuscated by all the null checks. It would be nice if we could factor these out.
So we want to do two things; first, make the fact that our method might return ‘null’ explicit, and second, factor out the null checks. The Maybe Monad lets us do both. C# has a type Nullable<T>, but it can only be used with value types, so it’s not really what we’re after. Here’s a type called ‘Maybe’, that can or cannot have a value, and its two subtypes, Nothing, which has no value, and Just, which has a value:
public interface Maybe<T>{}
public class Nothing<T> : Maybe<T>
{
public override string ToString()
{
return "Nothing";
}
}
public class Just<T> : Maybe<T>
{
public T Value { get; private set; }
public Just(T value)
{
Value = value;
}
public override string ToString()
{
return Value.ToString();
}
}
The ToString overrides are not required, they’re just to make the output I write later a little easier. You can just as well write Maybe as a single type with a ‘HasValue’ boolean property, but I quite like this style, it feels closer to the Haskell Maybe.
To make Maybe<T> into a Monad we have to write ToMaybe and Bind methods for it. ToMaybe is simple, we just create a new ‘Just’ from our value:
public static Maybe<T> ToMaybe<T>(this T value)
{
return new Just<T>(value);
}
Bind is more interesting. Remember, Bind is where we put our Monad’s behaviour. We want to factor null checks out of our code, so we need to write Bind so that if the initial value, a, is Nothing, we simply return a Nothing, and only if it has a value do we evaluate the second function:
public static Maybe<B> Bind<A, B>(this Maybe<A> a, Func<A, Maybe<B>> func)
{
var justa = a as Just<A>;
return justa == null ?
new Nothing<B>() :
func(justa.Value);
}
So the Maybe Bind acts a short circuit. In any chain of operations, if any one of them returns Nothing, the evaluation will cease and Nothing will be returned from the entire chain.
Lastly let’s implement SelectMany so that we can use linq syntax to help us out. This time we’ll implement SelectMany in terms of Bind:
public static Maybe<C> SelectMany<A, B, C>(this Maybe<A> a, Func<A, Maybe<B>> func, Func<A, B, C> select)
{
return a.Bind( aval =>
func(aval).Bind( bval =>
select(aval, bval).ToMaybe()));
}
Remember this, we can the same pattern for the SelectMany of any Monad once we have a Bind implementation.
Now let’s do some sums. Here’s a safe division method, its signature explicitly tells us that it might not return an int:
public static Maybe<int> Div(this int numerator, int denominator)
{
return denominator == 0
? (Maybe<int>)new Nothing<int>()
: new Just<int>(numerator/denominator);
}
Now lets chain some division operations together:
public Maybe<int> DoSomeDivision(int denominator)
{
return from a in 12.Div(denominator)
from b in a.Div(2)
select b;
}
var result = from a in "Hello World!".ToMaybe()
from b in DoSomeDivision(2)
from c in (new DateTime(2010, 1, 14)).ToMaybe()
select a + " " + b.ToString() + " " + c.ToShortDateString();
Console.WriteLine(result);
Still no null checks and we’re mixing ints, strings and DateTimes. If I run this, it will output:
Hello World! 3 14/01/2010
var result = from a in "Hello World!".ToMaybe()
from b in DoSomeDivision(0)
from c in (new DateTime(2010, 1, 14)).ToMaybe()
select a + " " + b.ToString() + " " + c.ToShortDateString();
Console.WriteLine(result);
Nothing
19 comments:
Thanks for explaining Monads and im looking forward to more great content.
In your Div definition, is there a reason you cast the Nothing to a Maybe? I would have thought this would be automatic (since a Nothing is a Maybe).
I just want to make sure I'm not missing something important :)
For completeness sake, you could also implement Select:
public static Maybe<B> Select<A, B>(this Maybe<A> a, Func<A, Maybe<B>> select)
{
return a.Bind(aval => select(aval));
}
This would simplify the syntax in some scenarios. For example:
from c in GetCustomer(1) from n in c.Name.ToMaybe() select n
becomes:
from c in GetCustomer(1) select c.Name.ToMaybe()
What's your opinion on naming. Should the names "Bind" and "ToMaybe" be changed to better fit the specific usage? While playing with your code, I called them "IfNotNull" and "Maybe", which seemed to read better.
And finally, would you consider it bad practice to put a null check in ToMaybe, as in:
return obj == null ? (Maybe<T>)new Nothing<T>() : new Just<T>(obj);
@Redbeard, The cast to Maybe is simply to keep the compiler happy (or at least intellisense). Both branches of the conditional operator (?:) have to return the same type and VS wan't able in infer that the type should be Maybe without at least one cast.
@Michael, Is that the signature for Select? It's exactly the same as Bind, so you could just rename Bind. I'm not sure I like the fact that you have to call ToMaybe again in the select clause, the nice thing about linq syntax is that it executes all the Monad extension methods for you.
But yes, it would make an interesting exercise to implement more of the linq extension methods. As for what to call them, I like Bind, because it's explicitly saying, 'this is a Monad', but really it's a personal choice.
Should ToMaybe return Nothing if the argument is null? Hmm, I'd much rather explicitly create a new Nothing, rather than call mynullval.ToMaybe(). Are you considering a scenario where you are transitioning from dealing with null values into a section of code where you are using Maybe?
This is a better implementation of Select that does not require the extra ToMaybe():
public static Maybe<B> Select<A, B>(this Maybe<A> a, Func<A, B> select)
{
return a.Bind(aval => select(aval).ToMaybe());
}
This no longer matches the Bind signature, but I'm not sure that you necessarily want it to.
Now you can call it like this:
Maybe<string> name = from c in GetCustomer(1) select c.Name;
Very clean.
And, yes, my question about detecting null in ToMaybe is to bridge the gap between null-aware code and Maybe-aware code. So if GetCustomer wasn't enlightened, it could still be called like this:
Maybe<string> name = from c in GetCustomer(1).ToMaybe() select c.Name;
Still, there's something smelly about a null appearing on the left-hand side of a dot.
var result = from a in "Hello World!".ToMaybe()
from b in DoSomeDivision(2)
from c in (new DateTime(2010, 1, 14)).ToMaybe()
select b;
In the statement above I am just selecting b which means var is of type Maybe. How would I get to the int value inside that maybe container cleanly. Would I need to cast to Just and then access the value?
Hi nabils,
Yes, you need to cast result to Just first:
var just = result as Just<T>
if(just != null)
{
var actualResult = just.Value;
}
Because you are left with a result that might not have a value, you have to check for that first. If you don't like the cast, you could easily implement Maybe as a single class.
Don't you have to use "if" statement in your implementation of ToMaybe to check if value is null and return Nothing then?
Tx.
/Boris
You say: "We want to factor null checks out of our code, so we need to write Bind so that if the initial value, a, is Nothing, we simply return a Nothing, and only if it has a value do we evaluate the second function"
and in the code that follows, you check justa against null.
I'm having a hard time understanding this since if i try:
String foo = null;
var result = foo.ToMaybe().Bind(...)
it will not shortcircuit since ToMaybe() creates a new Just with Value null.
Am i missing something?
Hi Omar, 'justa' in the Bind function is of type Maybe<A>, the 'as' operator is effectively a 'try cast' operator, if it can cast the Maybe<A> to Just<A> then justa has a value, if it can't cast it, justa will be null. So I'm not checking if a is null, but if it can be cast as Just<A>.
I hope this makes sense.
Your code should start new Nothing<string>().Bind(...)
Good info, nice post.
I wanted implicit conversion to Maybe (mostly method returns) for convenience. Can't do that with the 'interface' implementation.
What do you think of changing maybe to an abstract base class and defining the implicit conversion there? Appears to be working for me ;)
Hi John, There are many different ways of implementing Maybe in C#. I've seen several that just have a single Maybe class that decides if it's Just or Nothing based on internal state. I don't see why you shouldn't use an ABC.
Hi Mike,
Thanks. Based on your post (and Dyer's) I've also added comprehension syntax to the lokad maybe monad.
Good stuff.
/jhd
Particularly Maybe can be implemented nicely using a struct.
Consider the base case of the _isSome field if using the implicit public empty constructor.
public struct Maybe where T : class
{
private readonly T _value;
private readonly bool _isSome;
private Maybe(T value)
{
_isSome = value != null;
_value = value;
}
public static Maybe None()
{
return new Maybe();
}
public static Maybe Some(T val)
{
return new Maybe(val);
}
public bool TryGet(out T t)
{
if (_isSome)
{
t = _value;
return true;
}
t = null;
return false;
}
}
That would have been a pain to write imperatively.
Well the painfull imperatively code will look something like this:
try {
var a = "Hello World!";
var b = DoSomeDivision(0);
var c = new DateTime(2010, 1, 14);
var result = a + " " + b.ToString() + " " + c.ToShortDateString();
Console.WriteLine(result);
}
catch {
Console.WriteLine("Nothing!");
}
public static int DoSomeDivision(int denominator) {
return 12 / denominator;
}
Misspelling: "in fact some people thinG they are a mistake".
@Sid Burn
Allot of developers consider error handling as part of program flow a code smell. | http://mikehadlow.blogspot.com/2011/01/monads-in-c-5-maybe.html?showComment=1474847120366 | CC-MAIN-2017-09 | refinedweb | 1,937 | 72.26 |
How to build a server in Java: Part 4 - A user interface
The beautiful UI
User Interface!
Okay, so we have a server running, it can accept connections from multiple clients, and we can connect to it from anywhere on the internet. However, this server doesn't look very nice. In this tutorial we are going to add a (very simple) user interface to our program using the "swing" GUI (Graphical User Interface) toolkit. Okay, let's jump right in.
Swing
Swing is part of the javax package and it is THE way to create a user interface in java. You don't have to download swing or anything, it is already included when you download java. To get swing you just need to import it by doing this:
import javax.swing.*;
To create our user interface (UI) we are going to be using JFrames, JTextAreas, and JTextFields. These are all just UI elements that we can add to our program. Now, this tutorial is not about how to create user interfaces, it is about how to add some UI to our server and our client. I will not be going into detail about how to use Swing. Hopefully you already know some Swing and can follow along!
The Code
Okay, so here is the code for the new, update server with the UI:
import java.net.*; import java.util.*; import java.io.*; import javax.swing.*; import java.awt.*; public class Server extends JFrame { //A JTextArea to hold the information received from clients JTextArea chatBox = new JTextArea(); public static void main(String[] args) { new Server(); } public Server() { //We need to set up a layout for our window setLayout(new BorderLayout()); //Only display text, do not allow editing chatBox.setEditable(false); //Add our chatbox in the center with scrolling abilities add(new JScrollPane(chatBox), BorderLayout.CENTER); setTitle("Chat Server"); setSize(550,400); //If the user closes then exit out setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Show the frame setVisible(true); //We need a try-catch because lots of errors can be thrown try { ServerSocket sSocket = new ServerSocket(5000); chatBox.append("Server started at: " + new Date()); //Loop that runs server functions while(true) { //Wait for a client to connect Socket socket = sSocket.accept(); //Create a new custom thread to handle the connection ClientThread cT = new ClientThread(socket); //Start the thread! new Thread(cT).start(); } } catch(IOException exception) { System.out.println("Error: " + exception); } } //Here we create the ClientThread inner class and have it implement Runnable //This means that it can be used as a thread class ClientThread implements Runnable { Socket threadSocket; //This constructor will be passed the socket public ClientThread(Socket socket) { //Here we set the socket to a local variable so we can use it later threadSocket = socket; } public void run() { //All this should look familiar try { //Create the streams PrintWriter output = new PrintWriter(threadSocket.getOutputStream(), true); BufferedReader input = new BufferedReader(new InputStreamReader(threadSocket.getInputStream())); //Tell the client that he/she has connected output.println("You have connected at: " + new Date()); chatBox.append("Client connected\n"); while (true) { //This will wait until a line of text has been sent String chatInput = input.readLine(); //Add the chat to the text box chatBox.append(chatInput+"\n"); System.out.println(chatInput); } } catch(IOException exception) { System.out.println("Error: " + exception); } } } }
The main changes that we have made are that we added the user interface and now, instead of doing System.out.println(), we just append the information we have to the JTextArea. The comments in the code are probably the best way to understand what is going on. Leave a comment if you have no clue what I did.
Now, try running the code and see what happens!
Client UI
Now we also need our client to get a user-interface. Again here is the code and make sure to read through the comments to see what is going on.
import java.io.*; import java.net.*; //We no longer need a scanner to get input! import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Client extends JFrame { JTextField inputField = new JTextField(); JTextArea chatBox = new JTextArea(); PrintWriter output; BufferedReader input; public static void main(String[] args) { new Client(); } public Client() { //Create a panel with the UI for getting input from user JPanel p = new JPanel(); p.setLayout(new BorderLayout()); p.add(new JLabel("Type here:"), BorderLayout.WEST); p.add(inputField, BorderLayout.CENTER); setLayout(new BorderLayout()); //Add the chatBox and the panel for getting user input add(new JScrollPane(chatBox), BorderLayout.CENTER); add(p, BorderLayout.SOUTH); //Add an action listener on the text field //so we can get what the user is typing inputField.addActionListener(new TextFieldListener()); //Housekeeping stuff setTitle("Chat Client"); setSize(550,550); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); try { Socket socket = new Socket("localhost",5000); output = new PrintWriter(socket.getOutputStream(), true); input = new BufferedReader(new InputStreamReader(socket.getInputStream())); //This will wait for the server to send the string to the client saying a connection //has been made. String inputString = input.readLine(); chatBox.append(inputString+"\n"); } catch (IOException exception) { System.out.println("Error: " + exception); } } //This class handles the text field class TextFieldListener implements ActionListener { //This method will be called when the user hits enter public void actionPerformed(ActionEvent e) { try { String userInput = inputField.getText(); output.println(userInput); chatBox.append(userInput+"\n"); inputField.setText(""); } catch (Exception ex) { System.out.println(ex); } } } }
Done!
And there you go! There is a server and a client with some update UI. Unfortunately though, the clients only get back the information they send to the server. If two clients connect and they are both talking to the server they do not get the information back from each other. So they can't really chat. This is a problem but I'm sure you guys can figure it out! If you can't then maybe I'll make another tutorial about how to do that.
Thanks so much for reading, I hope that this makes sense. Please leave a comment to let me know that I can do to improve this or my other hubs regarding building a java server!
Comments... A video I made showing off how to make a simple lan server easily using similar concepts
Really helpful, please make further parts of the tutorial.
Love the way you explains things and use nice examples to work through something so many people make difficult. Real talk. VERY GOOD
Can you make a tutorial of how to make is so that when Client 1 talks to the server Client 2 receives the information as well?
Straight forward tutorial. The code works great. Will expand it to build a monitoring system for all the programs running on several computer. Eventually will add some alarms.
This tutorial is really awesome and easy to follow. I just keep getting an "Address in use" error. Any reason why that is happening?
Where is the rest of the tutorial?
With the client tchat ?
Gooood Tutorial
I will preface this comment by saying that I have not yet tried out the code, I just read through it all to try to understand and learn from it.
I noticed one part that puzzles me:
while(true) {
}
Should there be something in that while loop? Otherwise why is there an empty while loop there?
I'm disappointed that this code doesn't really allow two or more people to chat. Since I'm very new to Java I doubt I'll be able to figure it out on my own. :(
I would guess that you would need an array to store each user in and broadcast each chat message to everyone except the one who said it otherwise they would end up seeing their own message twice. How to do this if this is the proper solution?
This is a nice hub Drenguin, i'll look forward to read more of your programming hubs. Thanks for sharing.
12 | https://hubpages.com/technology/How-to-build-a-server-in-Java-Part-4-A-user-interface | CC-MAIN-2018-30 | refinedweb | 1,307 | 56.45 |
Table of contents
Reading C++ standard may lead to cardiac arrest
Use of the BLSR instruction
Saturated arithmetic for the rescue
It might be 10 times slower than strstr
Fill a SIMD register starting from k-th bit
A spin off from base64 decoding research. Pretty straightforward use of pshufb.
SSE code could by more than 2 times faster than lookup-based scalar code.
SSE code could by more than 2 times faster than lookup-based scalar code.
SWAR swap case could be 3 times faster than scala version for English texts
Up to 15 times faster than sprintf
This could be done slightly faster
A picture from a bugs party
The conference for C++ programmers, Wrocław, Poland. I was there
Think out of the box and... use the most obvious solution
Our brains are not good at type inference
A tale about unnoticed warning and unhappy consequences
SSE procedure can convert 16- and 32-digits inputs producing 8- and 16-bytes results.
SSE procedure is able to convert two 8-digit numbers. The main instruction used in converting to numeric value is PMADDWD.
SWAR techniques to multiply digits in parallel
Not obvious use of the new instruction from BMI2
Nice example of use of the new instruction from BMI2
How to implement (x != 0) ? -1 : 0
Another use of a bit-trick
There are some places where a low-level programmer can beat a compiler. Consider this simple code:
#include <stdint.h> uint32_t bsr(uint32_t x) { // xor, because this builtin returns 31 - bsr(x) return __builtin_clz(x) ^ 31; } uint32_t min1(uint32_t x) { if (x != 0) { return bsr(x) + 1; } else { return 1; } }
Function min1 is compiled to (GCC 4.8 with flag -O3):
min1: movl 4(%esp), %edx movl $1, %eax testl %edx, %edx je .L3 bsrl %edx, %eax addl $1, %eax .L3: rep ret
There is a condtional jump, not very good. When we rewrite the function:
uint32_t min2(uint32_t x) { return bsr(x | 1) + 1; }
Result is this nice branchless code:
min2: movl 4(%esp), %eax orl $1, %eax bsrl %eax, %eax addl $1, %eax ret
Conculsion: it's worth to check a compiler output. Sometimes.
I've observed that some patterns issued to strstr cause significant slowdown.
Sample program kill-strstr.c executes strstr(data, pattern), where data is a large string (16MB) filled with the character '?'. Patterns are read from the command line.
On my machine following times were recorded:
1. searching string 'johndoe'... time: 0.032 2. searching string '??????????????????a'... time: 0.050 3. searching string '??????????????????????????????a'... time: 0.049 4. searching string '???????????????????????????????a'... time: 0.274 5. searching string '??????????????????????????????a?'... time: 0.356 6. searching string '??????????????????????????????a??????????????????????????????'... time: 0.396
SIMD version of a bit-trick
Starting from GCC 4.5 the asm statement has new form: asm goto. A programmer can use any label from a C/C++ program, however a output from this block is not allowed.
Using an asm block in an old form requires more instructions and an additional storage:
uint32_t bit_set; asm ( "bt %2, %%eax \n" "setc %%al \n" "movzx %%al, %%eax \n" : "=a" (bit_set) : "a" (number), "r" (bit) : "cc" ); if (bit_set) goto has_bit;
Above code is compiled to:
80483f6: 0f a3 d8 bt %ebx,%eax 80483f9: 0f 92 c0 setb %al 80483fc: 0f b6 c0 movzbl %al,%eax 80483ff: 85 c0 test %eax,%eax 8048401: 74 16 je 8048419
With asm goto the same task could be writting shorter and easier:
asm goto ( "bt %1, %0 \n" "jc %l[has_bit] \n" : /* no output */ : "r" (number), "r" (bit) : "cc" : has_bit // name of label );
Complete demo is available. See also GCC documentation about Extended Asm.
First we read:
21.4.1 basic_string general requirements [string.require]
[...]
3 No erase() or pop_back() member function shall throw any exceptions.
... few pages later:
21.4.6.5 basic_string::erase [string::erase]
basic_string<charT,traits, Allocator>& erase(size_type pos = 0, size_type n = npos);
[...]
2 Throws: out_of_range if pos > size().
Very interesting idea: Asymmetric numeral systems: entropy coding combining speed of Huffman coding with compression rate of arithmetic coding.
Recently I needed to synchronize my local repository with a remote machine, just for full backup. It's really simple if you have standard Linux tools (Cygwin works too, of course).
in a working directory run:
$ pwd /home/foo/project # ^^^^^^^ $ git update-server-info
in the parent directory start HTTP server:
$ cd .. $ pwd /home/foo $ python -m SimpleHTTPServer Serving HTTP on 0.0.0.0 port 8000 ...
on a remote machine clone/pull/whatever:
$ git clone ^^^^^^^
Step 1 have to be executed manually when the local repository has changed.
Yes, definitely. Lets see this simple example:
$ cat test.cpp int test(int x) { if (x = 1) return 42; else return 0; } $ g++ -c test.cpp $ g++ -c -Wall test.cpp int test(int x) { if (x = 1) return 42; else return 0; }
Only when we turn on the warnings, a compiler tell us about a possible error. Making the parameter const shows us error:
$ cat test2.cpp int test(int x) { if (x = 1) return 42; else return 0; } $ g++ -c test.cpp test2.cpp: In function ‘int test(int)’: test2.cpp:2:8: error: assignment of read-only parameter ‘x’ if (x = 1) ^
All input parameters should be const, all write-once variables serving as a parameters for some computations should be also const.
If your application slows down significantly it might be an SSE issue
Few years ago I counted instructions from many Linux binaries — 2014 is:
Lets look at top 15 rows from detailed results, i.e. instruction with frequency grater than 1%:
Very interesting observation is that conditions are mostly based on je/jne, i.e. jump if zero/jump if not zero.
The first FPU instruction appears at 28-th position. The first integer SSE appears at 167-th position. And the first SSE instruction operating on packed floats appear at 315-th position.
I needed to iterate through all values of 32-bit unsigned integer, so I wrote:
#include <stdint.h> for (uint32_t i=0; i <= UINT32_MAX; i++) { // whatever }
Is it ok? No, because the value of uint32_t will never exceed UINT32_MAX = 0xffffffff. Of course we can use larger types, like uint64_t, but on 32-bit machines this requires some additional instructions. For example gcc 4.7 compiled following code:
void loop1(void (*fun)()) { for (uint64_t i=0; i <= UINT32_MAX; i++) { fun(); } }
to:
00000000 : 0: 57 push %edi 1: bf 01 00 00 00 mov $0x1,%edi 6: 56 push %esi 7: 31 f6 xor %esi,%esi 9: 53 push %ebx a: 8b 5c 24 10 mov 0x10(%esp),%ebx e: 66 90 xchg %ax,%ax 10: ff d3 call *%ebx 12: 83 c6 ff add $0xffffffff,%esi 15: 83 d7 ff adc $0xffffffff,%edi 18: 89 f8 mov %edi,%eax 1a: 09 f0 or %esi,%eax 1c: 75 f2 jne 10 1e: 5b pop %ebx 1f: 5e pop %esi 20: 5f pop %edi 21: c3 ret
TBH, I have no idea why such a weird sequence has been generated (add, adc, or, jnz). The simplest and portable solution is to detect a wrap-around of 32-bit value after increment:
uint32_t i=0; while (1) { // loop body i += 1; if (i == 0) // wrap-around break; }
In an assembly code it's even simpler, because a CPU sets the carry flag:
xor %eax, %eax loop: ; loop body add $1, %eax jnc loop
It's not clear how function fopen applied to a directory should behave, manual pages don't say anything about this. So, our common sense fail — at least when use a standard library shipped with GCC, beacuse fopen returns a valid handle.
Discussion on stackoverflow pointed that fseek or ftell` would fail. But on my system it's not true, ftell(f, 0, SEEK_END) returns the size of an opened directory.
Only when we trying to read data using fread or fgetc the errno variable is set to EISDIR error code.
Here is output from simple test program:
$ ./a.out ~ testing '/home/wojtek'... fopen: Success [errno=0] fseek: Success [errno=0] fseek result: 0 ftell: Success [errno=0] ftell result: 24576 feof: Success [errno=0] feof result: 0 (EOF=no) fgetc: Is a directory [errno=21] fgetc result: -1 (EOF=yes) fread: Is a directory [errno=21] fread result: 0
Intel announced new extension to SSE: instructions accelerating calculating hashes SHA-1 and SHA256. As everything else added recently to the x86 ISA, these new instructions address special cases of "something". The number of instructions, encoding modes, etc. is increasing, but do not help in general.
Let see what sha1msg1 xmm1, xmm2 does (type of arguments is packed dword):
result[0] := xmm1[0] xor xmm1[2] result[1] := xmm1[1] xor xmm1[3] result[2] := xmm1[2] xor xmm2[0] result[3] := xmm1[3] xor xmm2[1]
Such generic instruction would be saved as generic_op xmm1, xmm2, imm_1, imm_2, imm_3 and execute following algorithm:
for i := 0 to 3 do arg1_indice := imm_1[2*i:2*i + 1] arg2_indice := imm_2[2*i:2*i + 1] if imm_3[2*i] = 1 then arg1 := xmm1 else arg1 := xmm2 end if if imm_3[2*i + 1] = 1 then arg2 := xmm2 else arg2 := xmm1 end if result[i] := arg1[arg1_indice] op arg2[arg2_indice] end for
Then sha1msg1 is just a special case:
generic_xor xmm1, xmm2, 0b11100100, 0b01001110, 0b01010000
Maybe this example is "too generic", too complex, and would be hard to express in hardware. I just wanted to show that we will get shine new instructions useful in few cases. Compilers can vectorize loops and make use of SSE, but SHA is used in drivers, OS and is encapsulated in libraries — sha1msg1 and friends will never appear in ordinary programs.
As documentation says FBSTP "Store BCD Integer and Pop".
FBSTP saves integer part of floating point value as BCD number. Instruction expects an 11-bytes buffer, the first byte is reserved for a sign, rest are BCD digits.
Disadvantages of this instruction:
Sources are available at github.
Program fbst_tests.c converts a number to a string, remove leading zeros, and detects errors:
$ ./test 0 12 5671245 -143433 334535 4543985349054 999999999999999999999 printf => 0.000000 FBSTP => 0 printf => 12.000000 FBSTP => 12 printf => 5671245.000000 FBSTP => 5671245 printf => -143433.000000 FBSTP => -143433 printf => 334535.000000 FBSTP => 334535 printf => 4543985349054.000000 FBSTP => 4543985349054 printf => 10000000000000000000000.000000 FBSTP => NaN/overflow
Program fbst_speed.c compares instruction FBSTP with simple implementation of itoa. There are no formatting, BCD to ASCII conversion, etc. Numbers from 1 to 10,000,000 are converted.
Results from quite old Pentium M:
FBSTP... ... 2.285 s simple itoa... ... 0.589 s
and recent Core i7:
FBSTP... ... 2.165 s simple itoa... ... 0.419 s
There is no difference! FBSTP is just 5% faster on Core i7.
The size of an integer in PHP depends on machine, it has 32 bits on 32-bit architectures, and 64 on 64-bit architectures.
On 32-bit machines PDO for PostgreSQL always convert bigint numbers returned by a server to string. Never casts to integer even if value of bigint would fit in 32-bit signed integer.
Type bigint is returned for example by COUNT and SUM functions.
On 64-bit machines there is no such problem because PHP integer is the same as bigint.
Here is a simple PostgreSQL type:
CREATE TYPE foo_t AS ( id integer, total bigint );
and a simple query wrapped in a stored procedure:
CREATE FUNCTION group_foo() RETURNS SETOF foo_t LANGUAGE "SQL" AS $$ SELECT id, SUM(some_column) FROM some_table GROUP BY id; $$;
Now, we want to sum everything:
CREATE FUNCTION total_foo() RETURNS bigint -- same as foo_t.total LANGUAGE "SQL" AS $$ SELECT SUM(total) FROM group_foo(); $$;
And we have an error about types inconsistency!
This is caused by SUM function — in PostgreSQL there are many variants of this function, as the db engine supports function name overriding (sounds familiar for C++ guys). There are following variants in PostgreSQL 9.1:
$ \df sum List of functions Schema | Name | Result data type | Argument data types | Type ------------+------+------------------+---------------------+------ pg_catalog | sum | numeric | bigint | agg pg_catalog | sum | double precision | double precision | agg pg_catalog | sum | bigint | integer | agg pg_catalog | sum | interval | interval | agg pg_catalog | sum | money | money | agg pg_catalog | sum | numeric | numeric | agg pg_catalog | sum | real | real | agg pg_catalog | sum | bigint | smallint | agg
Smaller types are promoted: from integer we get bigint, from bigint we get numeric, and so on.
PostgreSQL wiki has entry about sprintf — is is quite simple approach (and isn't marked as immutable). The main drawback is iterating over all chars of a format string. Here is a version that use strpos to locate % in the format string, and it's faster around 2 times:
CREATE OR REPLACE FUNCTION printf2(fmt text, variadic args anyarray) RETURNS text LANGUAGE plpgsql IMMUTABLE AS $$ DECLARE argcnt int := 1; head text := ”; -- result tail text := fmt; -- unprocessed part k int; BEGIN LOOP k := strpos(tail, '%'); IF k = 0 THEN -- no more '%' head := head || tail; EXIT; ELSE IF substring(tail, k+1, 1) = '%' THEN -- escape sequence '%%' head := head || substring(tail, 1, k); tail := substring(tail, k+2); ELSE -- insert argument head := head || substring(tail, 1, k-1) || COALESCE(args[argcnt]::text, ”); tail := substring(tail, k+1); argcnt := argcnt + 1; END IF; END IF; END LOOP; RETURN head; END; $$;
PHP is very funny language. Here we are a simple class, without a constructor:
class Foo { } $foo = new Foo($random, $names, $are, $not, $detected); echo "ok!\n";
One can assume that interpreter will detect undeclared variables, but as their names state this doesn't happen (PHP versions 5.3..5.5):
$ php foo1.php ok!
When the class Foo have the constructor:
class Foo { public function __construct() { } } $foo = new Foo($random, $names, $are, $not, $detected);
everything works as expected:
$ php foo2.php PHP Notice: Undefined variable: random in /home/wojtek/foo2.php on line 10 PHP Notice: Undefined variable: names in /home/wojtek/foo2.php on line 10 PHP Notice: Undefined variable: are in /home/wojtek/foo2.php on line 10 PHP Notice: Undefined variable: not in /home/wojtek/foo2.php on line 10 PHP Notice: Undefined variable: detected in /home/wojtek/foo2.php on line 10
The)
# Calcualate averge of two unsigned numbers # without access to carry from MSB # # Wojciech Mula # wojciech_mula@poczta.onet.pl # 2012-07-02()
Have you ever heard about "regular expression derivatives"? No? Me too. This is very interseting idea, that have pratical usage in pattern matching.
Matthew Might wrote a sample program using the idea: A regular expression matcher in Scheme using derivatives. There is also a detailed paper on this topic: Regular-expression derivatives re-examined by Owens, Reppy and Turon.
If a DAG has got one component, then the simplest traversing method is depth-first-search, which could be easily implemented recursively (using an implicit stack).
struct DAGNode { // user data bool visited; // after construction = 0 } void DFS_aux(DAGNode* node, const bool val) { if (node->visited != val) { // visit node node->visited = val; for (n in node.connected) DFS_aux(n, val) } } void DFS(DAGNode node) { static val = true; DFS_aux(node, val); val = not val; }
On every call of DFS() the variable val is switched, and visited member is marked alternately with true or false.
There is just one problem — what if a traversing method stop execution before visiting all nodes? Of course in such situation we have to visit the DAG twice: on first pass reset (possibly many times) visited member to false, and then visit once each node.
But usually bool have at least 8 bits, so numbers could be used instead of boolean values 0 or 1. On each call of DFS() a reference number is incremented, thanks to that even if previous call stopped in the middle, the procedure will work correctly.
The only moment when visited markers have to be cleared is wrapping a reference numbers to zero. This happen every 256 calls if 8-bit values used; for wider counters (16, 32 bits) max value is greater.
void DFS(DAGNode node) { static unsigned int val = 1; if (val == 0) { // set visited member of all nodes to 0 val += 1; } DFS_aux(node, val); val += 1; }
If you read Wikipedia entry about DAWG, then you find following sentence:
Because the terminal nodes of a DAWG can be reached by multiple paths, a DAWG is not suitable for storing auxiliary information relating to each path, e.g. a word's frequency in the English language. A trie would be more useful in such a case.
This isn't true!
There is a quite simple algorithm, that allow to perform two-way minimal perfect hashing (MPH), i.e. convert any path representing a word to a unique number, or back — a number to a path (word). Values lie in the range 1 .. n, where n is the number of distinct words saved in a DAWG.
The algorithm is described in Applications of Finite Automata Representing Large Vocabularies, by Claudio Lucchiesi and Tomasz Kowaltowski (preprint is freely available somewhere online).
The main part of the algorithm is assigning to each node the number of reachable words from a node; this can be easily done in one pass. Then these numbers are used to perform perfect hashing. Hashing algorithm is fast and simple, translation from pseudocode presented in the paper is straightforward.
Algorithm requires additional memory for numbers in each node and a table of size n to implement dictionary lookups.
I've updated pyDAWG to support MPH.
If a class has to support standard len() function or operator in, then must be a sequence-like. This requires a variable of type PySequenceMethods, that store addresses of proper functions. Finally the address of this structure have to be assigned to tp_as_sequence member of the main PyTypeObject variable.
Here is a sample code:
static PySequenceMethods class_seq; static PyTypeObject class_type_dsc = { ... }; ssize_t classmeth_len(PyObject* self) { if (not error) return sequence_size; else return -1; } int classmeth_contains(PyObject* self, PyObject* value) { if (not error) { if (value in self) return 1; else return 0; } else return -1; } PyMODINIT_FUNC PyInit_module() { class_seq.sq_length = classmeth_len; class_seq.sq_contains = classmeth_contains; class_type_dsc.tp_as_sequence = &class_seq; ... }
def isiterable(obj) try: iter(obj) return True except TypeError: return False
Suppose)
Method:
Suppose we have to exchange (or just move) two registers A and B:
If C is 0, then A and B left unchanged, else A and B are swapped. If only a conditional move from B to A is needed, then step 4th have to be skipped.
Here is a sample x86 code, where condition is value of CF:
sbb edx, edx ; part of step 2. - edx = 0xffffff if CF=1, 0x000000 otherwise mov ecx, eax xor ecx, ebx ; step 1 and ecx, edx ; completed step 2. - now C is 0 or (A xor B) xor eax, ecx ; step 3 xor ebx, ecx ; step 4
Branchless moves are possible in Pentium Pro and higher with instructions cmovcc.
See also XOR linked list.
The.
Problem: calculate value of sign(x):
My solution do not involve any hardware specific things like ALU flags nor special instructions — just plain AND, OR, shifts.
; input: eax = X movl %eax, %ebx sarl $31, %eax // eax = -1 if X less then zero, 0 otherwise andl $0x7fffffff, %ebx addl $0x7fffffff, %ebx // MSB is set if any lower bits were set shrl $31, $ebx // eax = +1 if X greater then zero, 0 otherwise orl %ebx, %eax // eax = result
C99 implementation:
int32_t sign(int32_t x) { int32_t y; y = (x & 0x7fffffff) + 0x7fffffff; return (x >> 31) | ((uint32_t)y >> 31); }
This is continuation of the subproblem from the previous post: we have a word (byte, dword, whatever) and want to fill it with the selected bit.
uint32_t fill1(uint32_t a, int bit) { uint32_t b; b = a = a & (1 << bit); a <<= 31 - bit; b >>= bit; return (a - b) | a; }
uint32_t fill2(uint32_t a, int bit) { a <<= 31 - bit; return (int32_t)(a) >> 31; }
On processors 386+ we can clone the carry flag (CF) with sbb reg, reg and with bt reg, reg copy the selected bit from a reg to CF.
uint32_t fill386(uint32_t a, int bit) { uint32_t result; __asm__ __volatile__ ( "bt %1, %0\n" "sbb %0, %0\n" : "=r" (result) : "r" (bit), "0" (a) ); return result; }
Method presented here allows to get any bit permutation, transposition is just one of possible operations. Lookup-based approach would be faster, but algorithm is worth to (re)show.
Algorithm outline for 8-byte vector (with SSE instruction it is possible to get 2 operations in parallel):.
Suppose that a database stores some kind of a dictionary and an user picks some items, but wants to keep the order. For example the dictionary has entries with id=0..10, and the user picked 9, 2, 4 and 0. This simple query does the job (query splitted):
foo = SELECT (ARRAY[9,2,4,0])[i] AS index, i AS ord FROM generate_series(1, 4) AS i SELECT * FROM dictionary INNER JOIN (foo) ON dictionary.id=foo.index ORDER BY foo.ord
With simple program following times were measured:
Function defined in scched.h returns the number of a CPU that runs calling thread or process.
There is no such instruction — CVTDQ2PS converts signed 32-bit ints. Solution: first zero the MSB, such number is never negative in U2, so mentioned instruction could be used. Then add 232 if the MSB was set.
float CONST[4] SIMD_ALIGN = packed_float((float)((uint32_t)(1 << 31))); /* 2^31 */ uint32_t MASK_0_30[4] SIMD_ALIGN = packed_dword(0x7fffffff); uint32_t MASK_31[4] SIMD_ALIGN = packed_dword(0x80000000); void convert_uint32_float(uint32_t in[4], float out[4]) { __asm__ volatile ( "movdqu (%%eax), %%xmm0 \n" "movdqa %%xmm0, %%xmm1 \n" "pand MASK_0_30, %%xmm0 \n" // xmm0 - mask MSB bit - never less then zero in U2 "cvtdq2ps %%xmm0, %%xmm0 \n" // convert this value to float "psrad $32, %%xmm1 \n" // populate MSB in higher word (enough to mask CONST) "pand CONST, %%xmm1 \n" // xmm1 = MSB set ? float(2^31) : float(0) "addps %%xmm1, %%xmm0 \n" // add 2^31 if MSB set "movdqu %%xmm0, (%%ebx) \n" : /* no output */ : "a" (in), "b" (out) ); }
See a sample implementation.
Branch-less x86 code:
movl %eax, %ebx sarl $32, %ebx ; fill ebx with sign bit xorl %ebx, %eax ; negate eax (if negative) subl %ebx, %eax ; increment eax by 1 (if negative)
SSE2:
pshufd $0b11110101, %xmm0, %xmm1 ; populate dwords 3 and 1 psrad $32, %xmm1 ; fill quad words with sign bit pxor %xmm1, %xmm0 ; negate (if negative) psubq %xmm1, %xmm0 ; increment (if negative)
RDTSC is incremented with bus-clock cycles, and then multiplied by core-clock/bus-clock ratio. From programmer view, RDTSC counter is incremented by value greater then 1, for example on C2D E8200 it is 8.
Latency of RDTSC in Pentium4 is about 60-120 cycles, on AMD CPU around 6 cycles.
asm( "..." : "+a" (var) );
This won't work, GCC complains:
asm( "..." : /* no output */ : "a" (var) : "eax" );
We can declare a temporary variable, and treat it as read-write:
int tmp_var = var; asm( "..." : "+a" (tmp_var) );
If there are more registers, or var shouldn't be changed, then we can declare a common dummy variable:
int dummy __attribute__((unused)); asm( "..." : "=a" (dummy), "=b" (dummy), "=c" (dummy) : "a" (var_or_value1), "b" (var_or_value2), "c" (var_or_value2) );
Found on Wikipedia:
gcc -dM -E - < /dev/null | http://0x80.pl/notesen.html | CC-MAIN-2018-13 | refinedweb | 3,843 | 60.65 |
I implement the kmeans algorithm in python, the code as following. I test the code use some simple data. just as following, which store in a file called data.txt
2 5
3 7
-1 -2
-3 -3
5 4
4 -4
3 -7
3.5 -9
my problem is that during the iteration, some cluster seem become empty, that is the (number of cluster) < k, and after my analysis, this seem will occure, but after search the web, I found no body deal this in the kmeans algorithm.
So I do not know where is the fault? is that because my test data is so simple
import sys
import numpy as np
from math import sqrt
"""
useage: python mykmeans.py mydata.txt k
"""
GAP = 2
MIN_VAL = 1000000
def get_distance(point1, point2):
dis = sqrt(pow(point1[0] - point2[0], 2) + pow(point1[1] - point2[1], 2))
return dis
def cluster_dis(centroid, cluster):
dis = 0.0
for point in cluster:
dis += get_distance(centroid, point)
return dis
def update_centroids(centroids, cluster_id, cluster):
x, y = 0.0, 0.0
length = len(cluster)
if length == 0: # TODO: this is my question? do we need to examine this?
return
for item in cluster:
x += item[0]
y += item[1]
centroids[cluster_id] = (x / length, y / length)
def kmeans(data, k):
assert k <= len(data)
seed_ids = np.random.randint(0, len(data), k)
centroids = [data[idx] for idx in seed_ids]
clusters = [[] for _ in xrange(k)]
cluster_idx = [-1] * len(data)
pre_dis = 0
while True:
for point_id, point in enumerate(data):
min_distance, tmp_id = MIN_VAL, -1
for seed_id, seed in enumerate(centroids):
distance = get_distance(seed, point)
if distance < min_distance:
min_distance = distance
tmp_id = seed_id
if cluster_idx[point_id] != -1:
dex = clusters[cluster_idx[point_id]].index(point)
del clusters[cluster_idx[point_id]][dex]
clusters[tmp_id].append(point)
cluster_idx[point_id] = tmp_id
now_dis = 0.0
for cluster_id, cluster in enumerate(clusters):
now_dis += cluster_dis(centroids[cluster_id], cluster)
update_centroids(centroids, cluster_id, cluster)
delta_dis = now_dis - pre_dis
pre_dis = now_dis
if delta_dis < GAP:
break
print(centroids)
print(clusters)
return centroids, clusters
def get_data(file_name):
try:
fr = open(file_name)
lines = fr.read().splitlines()
except IOError, e:
pass
finally:
fr.close()
data = []
for line in lines:
tmp = line.split()
x, y = float(tmp[0]), float(tmp[1])
data.append([x, y])
return data
def main():
args = sys.argv[1:]
assert len(args) > 1
file_name, k = args[0], int(args[1])
data = get_data(file_name)
kmeans(data, k)
if __name__ == '__main__':
main()
It is possible that k-means induces an empty cluster. Here is one example shown in figures. I also copied the figures below in case the link may expire some day.
The first figure below shows the distribution of the 7 points. Initially 3, 5, and 6 are selected as the cluster centers.
The '+' below shows the cluster centers changes after 1st iteration, and the same color indicates the corresponding points are in the same clusters.
From the figure below, you can see after 2 iterations, the blue cluster becomes empty, and there are indeed 2 clusters instead of the initialization value 3.
So the empty cluster probably due to the initialization and 'incorrect' cluster number. You may try different
k in your code and run the program several times to observe the clustering result, making it more robust. | https://codedump.io/share/e92SPKd0DvZv/1/assertionerror-when-running-the-main-function | CC-MAIN-2016-50 | refinedweb | 536 | 55.84 |
"
Package management systems have come into use in almost every distribution
out there. They are a clear step up from what came before, but, as Eric
pointed out, significant problems have been building for years. These
include:
Conary was developed as a way of addressing the above limitations and to
make it possible for users to create their own, customized distributions in
an easy manner. In the simplest sense, one can think of Conary as a
package management system with a more consistent view of objects from the
repository level down to individual files, combined with a version
management scheme.
Conary treats files as "first class objects," which are managed by the
framework as a whole. Files have a unique ID and a version history; they
also have a set of attributes. One of those attributes is the file's
location in the filesystem; moving a file is a simple matter of changing
that attribute.
A "trove" is a container holding one or more files and other troves. Files
are contained by reference. A "component" is a collection of files, by
reference. Example components listed by Eric for the bzip2 package might
be bzip2:runtime (binary files to run the program),
bzip2:lib, bzip2:doc, and, of course,
bzip2:source. Components can be aggregated
together into packages. Both components and packages are considered to be
"troves," for what it's worth.
Version strings are hung onto everything; Specifix has added some
complexity to the versioning system, though. Each version string includes
the repository name, a namespace (think of it as a distribution name), a
branch name (for the creation of trees in the version space), the upstream
package version, and a two-part local revision number. Needless to say,
the version strings get long, but the system hides the full string most of
the time. Creating versions in this way allows the system to easily
determine which version of a package is the newest, which version of which
distribution is built for, and so on.
Branching is done by adding a branch name to the version string. Branching
allows the tracking of versions of packages which were shipped with a
specific distribution, along with updates to those packages. There is also
a special type of branch called a "shadow" which tracks changes to the
trunk it was branched from. Essentially, the shadow is automatically
merged with each new version of the trunk it is following. This feature
would be useful for somebody maintaining a derivative distribution; they
want to keep up with what the source distribution is doing without losing
track of their own changes. The only problem with shadows is that, like a
number of other Conary features, they are not actually implemented yet.
"Flavors" are another Conary feature; they seem to be patterned after
Gentoo's "USE flags." A flavor is a set of configuration options
describing how all packages are to be built. This feature is used for
multiple architecture support, or for building versions of distributions
with different feature sets (e.g. creating a distribution without PAM
support). Multiple flavors of a package can be installed on a system if
they don't conflict with each other; this allows, for example, the
installation of 32-bit libraries on x86-64 systems.
Then, there is the concept of "changesets." A changeset is a collection of
modifications to files (including attribute changes) and the troves which
contain them. A changeset is, essentially, a patch to a package or a
distribution. Changesets, which track only changes, can be much smaller
than the packages they describe, and can thus be an efficient way of
distributing updates. Changesets describe changes to configuration files
in diff format, which often allows them to be merged automatically
with local changes. A system administrator can also create a changeset
describing his or her local changes to the system; that changeset can then
be used for merging with updates, or replicating the system elsewhere.
Local changesets can also be used for version control and the tracking of
system changes.
"Tags" are Conary's answer to the package script problem (and, also, to the
complex set of interactions represented by the RPM "trigger" mechanism). A
tag is a file attribute describing the type of the file, be it "shared
library," "info file," or any of a long list of alternatives. Most files
can be tagged automatically by Conary. Tags have scripts associated with
them; there is, for example, a script which handles the installation of an
info file and updating the relevant directory. These scripts are
distributed separately; there is only one copy of them on the system. The
scripts are thus easily fixed when bugs turn up, and they can be customized
by the local administrator if need be. Separating out the management
scripts in this way should also make it easier to install packages from
other distributions.
A "fileset" is an arbitrary collection of files built from components in
the repository. Filesets seem to be intended to help in the creation of
small system images for embedded systems; they allow an easy picking and
choosing of an exact set of desired files. "Groups" are, instead, the
analog of the Debian "task" or Anaconda "component." They allow the
management of several packages as a unit, but they come with their own
local changesets so that local changes to the group are tracked properly.
The paper
from the OLS proceedings (PDF format) is worthwhile reading for anybody
wanting more details on how Conary works.
Interested parties can download an early Conary release from the Specifix web site.
Be warned, however, that a few features are still missing; they include
shadows, dependencies (an important issue that they "think" they know how
to implement), flavors, package signatures, and more. "Release early" is an
important part of the free software development process, however, and the
Specifix founders understand that process well. Conary's vaporware
features will, beyond doubt, be filled in soon. As that happens, expect
interest in this tool to increase; it truly does have the potential to
change the way we set up and manage our projects, distributions, and
systems.
Expertise Needed
Posted Jul 28, 2004 11:13 UTC (Wed) by ccyoung (subscriber, #16340)
[Link]
In the exhausting list of attributes, why not "Intelligent Questions", letting a trove instantiate as many question/answer sets as it chooses, perhaps mapping to flavors or whatever - but something that allows others' expertise to effectively filter to MM's like myself. Nobody has time to be good at everything.
Intelligent Questions?
Posted Jul 28, 2004 20:16 UTC (Wed) by hazelsct (subscriber, #3659)
[Link]
Is it gonna be a bitkeeper?
Posted Jul 28, 2004 12:09 UTC (Wed) by rknop (guest, #66)
[Link]
Any talk about the licence this thing will be released under? Obviously, if it's not an open source licence, it's not going to be adopted by many distributions no matter how technically nice it is. It's a lot easier to convince just Linus than it is to convince (say) the Debian voters to use a proprietary pacakge....
-Rob
Posted Jul 28, 2004 12:26 UTC (Wed) by corbet (editor, #1)
[Link]
And yes, Conary is free software, no worries there.
no; it's free software.
Posted Jul 28, 2004 12:48 UTC (Wed) by mattdm (subscriber, #18)
[Link]
Posted Jul 29, 2004 2:04 UTC (Thu) by angdraug (subscriber, #7487)
[Link]
CPL is yet another GPL-incompatible license.
When will you people understand? There are only 3 free software licenses to choose from: X/MIT, GPL, and LGPL. Anything else is harmful to the free software movement: any marginal gains are completely overshadowed by license incompatibilities, user confusion, and legal risks.
Posted Jul 29, 2004 2:35 UTC (Thu) by ekj (subscriber, #1524)
[Link]
I agree with you that being "different" in itself is a huge minus for a license, even when the terms by themselves are acceptable, there's always the issues of user confusion and incompatibilities between different licenses.
Posted Jul 29, 2004 4:32 UTC (Thu) by angdraug (subscriber, #7487)
[Link]
Please, check the link to the licensing discussion. I've put it in my post for a reason.
BTW, I forgot to add fragmentation (as opposed to diversity) to the list of harms license incompatibility brings.
on overlooked links
Posted Jul 30, 2004 15:28 UTC (Fri) by giraffedata (subscriber, #1954)
[Link]
It would be good if that reason were evident from the post itself. In this case, you just hyperlinked the wrong text. The text X/MIT, GPL, and LGPL does not say "licensing discussion." It suggests a link or links to descriptions of three licenses.
In this case, the text There are only 3 free software licenses would have been better text to hyperlink, and "as discussed here" would be even better.
I don't know about you, but I virtually never click on every hyperlink in a document. I have to have some clue it's something I want to read.
Posted Aug 3, 2004 8:56 UTC (Tue) by angdraug (subscriber, #7487)
[Link]
You're right, my links could have been more obvious.
I don't know about you, but I virtually never click on every hyperlink in a document. I have to have some clue it's something I want to read.
When I'm interested in the subject, I usually dig deep enough to understand the point. When I'm not interested, I don't bother to read comments at all.
Posted Jul 29, 2004 7:16 UTC (Thu) by mattdm (subscriber, #18)
[Link]
When will you people understand? [emphasis added]
Who are the "you people" you are talking about? It's an OSI-approved license, for goodness sakes.
I would really appreciate it if people would keep these ideological discussions off of the LWN comments. It's good that these discussions exist, but this isn't a useful place for them. Write a guest editorial if you want, but otherwise, post to slashdot or kuro5hin or somewhere. (Or perhaps better in this case, contact the OSI/Debian and try to convince them.) Let's keep the comments here to points of fact. (Is that an official rule? No. It'd just be nice.)
Posted Jul 29, 2004 10:12 UTC (Thu) by angdraug (subscriber, #7487)
[Link]
Who are the "you people" you are talking about?
You in particular, and other people who shrug off license incompatibility as a non-issue.
It's an OSI-approved license, for goodness sakes.
OSI isn't God, they aren't even omniscient.
Even worse, it is their practice of blindly approving problematic licenses that created this problem in the first place. It all started when they let Netscape get away with MPL instead of convincing them to use GPL. Isn't it ironic that Mozilla project was eventually dual-licensed under GPL anyway?
I would really appreciate it if people would keep these ideological discussions off of the LWN comments.
It is not merely ideological as long as it has far-reaching practical consequences. I apologize for inflammatory tone of my comment, but I still think that usefulness of a license chosen by a new free software project is relevant to the discussion of this project.
Posted Aug 6, 2004 6:52 UTC (Fri) by dash2 (guest, #11869)
[Link]
Posted Aug 8, 2004 23:33 UTC (Sun) by mbp (guest, #2737)
[Link]
Nobody knows what will happen in the future: maybe it will stay free; maybe it will go proprietary; maybe they'll drop it altogether. Their intentions sounds good, and if the worst happens then the licence permits forking.
Remember bitkeeper started out with a free-ish licence originally, and then they changed.
OLS: An introduction to Conary
Posted Jul 28, 2004 13:07 UTC (Wed) by boudewijn (subscriber, #14185)
[Link]
Posted Jul 28, 2004 16:10 UTC (Wed) by jre (guest, #2807)
[Link]
Had me going there
Posted Jul 28, 2004 21:20 UTC (Wed) by ncm (subscriber, #165)
[Link]
Strawman problems or poorly done homework?
Posted Jul 29, 2004 2:28 UTC (Thu) by angdraug (subscriber, #7487)
[Link]
Repositories are an afterthought.
Debian pools are definitely not an afterthought. It is elegant, effective, and extensible solution. What's wrong with it?
The version scheme used by most package managers follows a straight line model; there is no provision for branches.
I don't see any advantage in cramping all the versioning, branching, and tagging information into a package version, as opposed to managing this separately. I like Monotone's idea of using SHA1 for a version: if the file is the same, its version should be the same no matter in how many branches it is available.
Packages contain scripts which handle parts of the installation and removal process which go beyond the simple management of files.
At a certain level of complexity, some things are better done as scripts, as opposed to declarative programming. Either you try to provide a better scripting environment to solve these tasks, or you go the route of XSLT.
Posted Jul 29, 2004 6:48 UTC (Thu) by angdraug (subscriber, #7487)
[Link]
Posted Jul 29, 2004 9:54 UTC (Thu) by vmole (subscriber, #111)
[Link]
Debian pools are definitely not an afterthought.
Debian pools are absolutely an afterthought. The fact that they
are a really good solution to the problem doesn't change that. We lived
for years with seperate trees for each release.
The entire Conary article reads like someone is trying to solve the random RPM problem, where "repositories" are simply piles-of-files, and has
never seen the Debian solution. I know that's not true, so my guess
is it's a way of making Specifix look like they've solved more problems
than they have. This is unfortunate, because based on the article, they
are solving problems that the Debian system doesn't.
I do agree with the previous that leaving the dependency problem for "later" is likely to be a really bad idea. But the RPM developers have never given the problem the respect it deserves, much to the pain of their users.
Triggers in dpkg/APT?
Posted Jul 29, 2004 19:15 UTC (Thu) by AnswerGuy (subscriber, #1256)
[Link]
Triggers don't seem to be widely used (packager ignorance?) but they seem like a neat idea. With some carefully designed standards among packagesthey could make your package management system almost "object-oriented."
(Consider: you install a mail user agent (MUA) which registers a trigger on the virtual package MTA. When any MTA is installed, the trigger runs a script which invokes the MTA's own MUA registration script. Now all MUAs can have some setting adjusted when an MTA is replaced. All of the MUAs "know" whether the system is using mbox, maildir, or MMDF system mailboxes --- for example).
(Sorry if the example is silly --- better examples might relate to registration of menu items and icons in window managers or something).
JimD
Posted Jul 30, 2004 7:08 UTC (Fri) by frodonl (subscriber, #16826)
[Link]
While I don't know about any triggers functionality in the Debian packaging system - I never needed them, so I never really searched for it, Debian does define a standard way to create menu items, called the Debian Menu System.
It works by postinstall and postrm scripts calling one central command (update-menus) that will call the menu-update scripts for the various packages that use "menu managers".
Grtz,
Frodo
Posted Aug 3, 2004 10:43 UTC (Tue) by angdraug (subscriber, #7487)
[Link]
This looks like the next evolution of package management
Posted Jul 30, 2004 12:35 UTC (Fri) by X-Nc (guest, #1661)
[Link]
Ports is great with the exception of one thing; it's source based only. Linux distros like Gentoo,
Lunar Linux and the Sourcerer based ones bring the Ports idea to Linux but still are based on
source code only.
The other side of the coin is the RPM/DEB packages with apt and yum manageing them. They
work nicely but don't provide for multiple versioning of packages and easy integration of
custome packages built outside of the apt/yum repositories.
Conary has some definite potential. I'd like to see what it looks like when it's finished. It could
be the next big step for Linux and open source in general.
Linux is a registered trademark of Linus Torvalds | http://lwn.net/Articles/95469/ | crawl-002 | refinedweb | 2,739 | 61.06 |
import "k8s.io/client-go/tools/pager"
ListPageFunc returns a list object for the given list options.
func SimplePageFunc(fn func(opts metav1.ListOptions) (runtime.Object, error)) ListPageFunc
SimplePageFunc adapts a context-less list function into one that accepts a context.
type ListPager struct { PageSize int64 PageFn ListPageFunc FullListIfExpired bool }
ListPager assists client code in breaking large list queries into multiple smaller chunks of PageSize or smaller. PageFn is expected to accept a metav1.ListOptions that supports paging and return a list. The pager does not alter the field or label selectors on the initial options list.
func New(fn ListPageFunc) *ListPager
New creates a new pager from the provided pager function using the default options. It will fall back to a full list if an expiration error is encountered as a last resort.
List returns a single list object, but attempts to retrieve smaller chunks from the server to reduce the impact on the server. If the chunk attempt fails, it will load the full list instead. The Limit field on options, if unset, will default to the page size.
Package pager imports 7 packages (graph) and is imported by 2 packages. Updated 2018-04-08. Refresh now. Tools for package owners. | https://godoc.org/k8s.io/client-go/tools/pager | CC-MAIN-2018-34 | refinedweb | 203 | 57.77 |
This action might not be possible to undo. Are you sure you want to continue?
org
M O B I L E
T R A I N I N G
Beginning Your Android Programming Journey
An Introductory Chapter from EDUmobile.ORG Android Development Training Program
EDUmobile .org
M O B I L E
T R A I N I N G
NOTICE: You Do NOT Have the Right to Reprint or Resell This eBook!
You Also MAY NOT Give Away, Sell or Share the Content Herein
ALL RIGHTS RESERVED. No part of this ebook in prohibited.
software and network carriers its market share is growing worldwide in leaps and bounds. As per the NPD group the unit sales Android phones is the largest among Smart Phones.EDUmobile .0 3D graphics API.org All Rights Reserved . Some of the popular Android Phones: Motorola Droid HTC Evo Nexus One Copyright © EDUmobile. SSL. WebKit layout engine. SGL graphics engine. Because it is widely supported by large number of hardware. powerful and elegant platforms coming out of Google in recent years. Android is an open source platform and it is released under open source license. It was initially developed by Android Inc later purchased by Google and positioned in the Open Handset Alliance. OpenGL ES 2. The Android operating system software stack consists of Java applications running on a Java based object oriented application framework on top of Java core libraries running on a Dalvik virtual machine featuring JIT compilation. OpenCore media framework. and Bionic libc.org M O B I L E T R A I N I N G 1. Being an open system based on modified Linux kernel it has been widely accepted by the developer community and presents a golden opportunity to create products and services for this amazing platform. SQLite relational database management system. Welcome to Android Application Development Android is one of the most versatile. Libraries written in C include the surface manager.
Android 2.EDUmobile . However.1 M O B I L E T R A I N I N G The SmartPhone Landscape Nokia started the SmartPhone revolution earlier this decade.org All Rights Reserved . Android and iPhone are now are the biggest players in the industry.2. AKA Froyo will also soon gain rapid market adoption. since then the SmartPhones market has grown from strength to strength.Blackberry.org 1.1 has finally reached a point where it is ready for the mass market. Copyright © EDUmobile. Android being open source and a wide hardware support is quickly gaining ground for smart phones as well as netbooks and recently. Nexus One with the next release 2. with Nokia’s Symbian OS quickly loosing market share . tablet PCs Generic pattern of SmatPhone penetration Google’s Android operating system has proven itself to be a growing force to be reckoned with as adoption rates among manufactures and consumers continue growing at considerable rates.
ORG is here to help new developers and content enthusiasts to benefit from this great opportunity. Copyright © EDUmobile. We will finally conclude with way forward for developers to cash in on this opportunity with intuitive and sellable products and services. that will be side-loaded into a real device. This eBook consists of a brief introduction to Android as a platform. We will go through the installation process of the SDK and we will create some simple programs.EDUmobile .org All Rights Reserved .com clearly indicates that Smarthone market is one of the rapidly emerging platform. We start by looking at the Android system and the development tools available.org M O B I L E T R A I N I N G The above data reproduced from Neilsen. EDUmobile.
6 2.EDUmobile .org M O B I L E T R A I N I N G The SDKs distribution currently in the market.5 1. Android Android Android Android Android Android 1.0 1.2 Screen Size Summary Copyright © EDUmobile.1 2.1 1.org All Rights Reserved . Google has released the Android platform under following versions.
The Android platform provides a framework API that applications can use to interact with the underlying Android system.2 Android 2. The framework API consists of: • • • • • A core set of packages and classes A set of XML elements and attributes for declaring a manifest file A set of XML elements and attributes for declaring and accessing resources A set of Intents A set of permissions that applications can request. So now that we have defined the scope of our discussions we must outline what is the minimum requirement for you to learn the application programming for Android.org M O B I L E T R A I N I N G 1. Application level – It involves creating software products and services which sits on top of the Android software stack and interacts with the hardware through the underlying Android platform. Copyright © EDUmobile.6 Android 1. The Android programming is done on two levels System Level – It involves modifying the Android system code and adapting it to various hardware platforms.1 Android 2. We will limit our discussion in this book only for Application level programming for Android and Android Marketplace. as well as permission enforcements included in the system Platform Version Android 2.0 API Level 8 7 6 5 4 3 2 1 The above data will give you a peek into the marketplace for which you will create products.0 Android 1. you should perhaps start with C and Linux kernel programming.0. It also involves creating additional services and features in the android system itself.1 Android 1.1 Android 2.org All Rights Reserved .2 Android API level API Level is an integer value that uniquely identifies the framework API revision offered by a version of the Android platform.5 Android 1.EDUmobile . The System level programming is out of the scope of this free ebook and if you want to jump right into it.
The first one is the JDK which you can download from Copyright © EDUmobile. To summarize. AWT or Swing are not supported).asp Eclipse – If you have worked in any IDE for Java you should be ok with eclipse.html Object fundamentals– You will be able to create elegant and efficient programs if you know the basics of OOPs. The Java byte code executes on a efficient and modified virtual machine known as Dalvik Virtual Machine.oracle. Look at the following links for these concepts Link . you are expected to know Core Java – Standard Java programming is necessary to program applications for Android. loops and should have a basic idea of classes and objects.EDUmobile . Instead it uses its own library built on a subset of the Apache Harmony Java implementation. Polymorphism.org All Rights Reserved . However to follow this book you need to have a basic understanding of Java. Features like Inheritance. You should understand operators. Link . Preparing your development machine Your development system should first download some software before you can program for it.com/javase/tutorial/java/concepts/ 2.de/articles/Eclipse/article.vogella. Encapsulation and Overloading help us create efficient and organized software systems and it is expected that you as ajava programmer must know them. Java ME classes. XML.. Link .. You can read more about it here.. Please follow the steps mentioned below to install Android SDK and eclipse IDE to get started with application development.w3schools.org M O B I L E T R A I N I N G Android applications are built using Java. You can refer here to brush up your java skills Link .com/xml/default. So you need to know basic core java but it alone is not sufficient to leverage this great platform for creating great applications.oracle. Dalvik does not align to Java SE nor Java ME Class Library profiles (e. 1. XML – You should know what the XML standard is all about and how it is used in software applications.. Eclipse and object oriented programming principles. Android SDK Installation and Usage.
org M O B I L E T R A I N I N G but you should always use the latest version.org/downloads/ You can use any eclipse IDE above 3.eclipse. You can download eclipse from here. Copyright © EDUmobile.com/technetwork/java/javase/downloads/in dex.html As this book is targeted towards beginners we suggest using Eclipse and ADT plug-in to develop for android.org All Rights Reserved . You can switch to different tool chain once you are familiar with the Android APIs.oracle.EDUmobile .
Eclipse JDT plugin (included in most Eclipse IDE packages) If you need to install or update Eclipse.eclipse. Supported Development Environments Eclipse IDE Eclipse 3.5. Please stay on 3.6.5 until further notice. Copyright © EDUmobile.org/downloads/.5 (Galileo) Caution: There are known issues with the ADT plugin running with Eclipse 3.EDUmobile .or 64-bit) Mac OS X 10. you can download it from. For information about how to add support for 32-bit applications.8 or later (x86 only) Linux (tested on Linux Ubuntu Hardy Heron) • 64-bit distributions must be capable of running 32-bit applications.org All Rights Reserved .4 (Ganymede) or 3.org M O B I L E T R A I N I N G Note: Make sure you first install the JDK before installing the Eclipse. see the Ubuntu Linux installation notes. Vista (32. Google Recommends Operating Systems Windows XP (32-bit). or Windows 7 (32.or 64-bit).
5. Optional. note that some Linux distributions may include JDK 1.EDUmobile . Optional.7 or later for Windows Not compatible with Gnu Compiler for Java (gcj) Note: If JDK is already installed on your development computer. both of which are not supported for Android development. For Windows only. For developing Android applications. The table below provides a rough idea of the disk-space requirements to expect. At least one platform is required. Optional. 1. Component type Approximate size SDK Tools 50 MB Android platform 150 MB (each) SDK Add-on (each) 100 MB USB Driver for 10 MB Windows Samples (per 10M platform) Offline documentation 250 MB Comments Required.6. please take a moment to make sure that it meets the version requirements listed above. Hardware requirements The Android SDK requires disk storage for all of the components that you choose to install. Note that the disk-space requirements above are in addition to those of the Eclipse IDE. Optional.4 or Gnu Compiler for Java.5 or later for Linux and Mac.org All Rights Reserved . Copyright © EDUmobile.1 and higher) JDK 5 or JDK 6 (JRE alone is not sufficient) Android Development Tools plugin (optional) Not compatible with Gnu Compiler for Java (gcj) Other development environments or IDEs JDK 5 or JDK 6 (JRE alone is not sufficient) Apache Ant 1. In particular. JDK. we recommend that you install one of these packages: Eclipse IDE for Java EE Developers Eclipse IDE for Java Developers Eclipse for RCP/Plug-in Developers Eclipse Classic (versions 3. or other prerequisite tools that you may need to install on your development computer. based on the components that you plan to use.org M O B I L E T R A I N I N G Several types of Eclipse packages are available for each platform.
org All Rights Reserved . It helps us quickly integrate java code with Android API and create applications with it.org 2. and select Properties.. 3. unpack the Android SDK archive to a safe location on your machine. In the Add Site dialog that appears. On Windows. Make a note of the name and location of the unpacked SDK directory on your system — you will need to refer to the SDK directory later. double-click on Path (under System Variables).com/sdk/index. Start Eclipse.html After downloading.. and in the dialog that comes up. You can get the latest version of the SDK starter package from the Link . enter this URL: Copyright © EDUmobile. 2.EDUmobile . right-click on My Computer. Under the Advanced tab. continue with the ADT installation as described in the steps below. click Add.. then select Help > Install New Software. To simplify ADT setup. "Android Plugin") in the "Name" field. When your Eclipse and Android SDK environments are ready. Add the full path to the tools/ directory to the path. compiling and signing and transferring to an android device. we recommend installing the Android SDK prior to installing ADT.. Installing the ADT plug-in ADT has been created for Android to ease the development of applications using an integrated system for development. 1. which you can use to download the rest of the SDK components. enter a name for the remote site (for example. 3. hit the Environment Variables button. M O B I L E T R A I N I N G Downloading Android Starter package Once you have your system ready you need to download the Android Starter package. In the Available Software dialog.android. In the "Location" field. The starter package is not a full development environment — it includes only the core SDK Tools. when setting up the ADT plugin or when using the SDK tools.
instead of "https" (https is preferred for security reasons. Launching from Eclipse/ADT If you are developing in Eclipse and have already installed the ADT Plugin. follow these steps to access the Android SDK and AVD Manager tool: 1.org All Rights Reserved . For the SDK Location in the main panel. Adding Android platform The last step is to use AVD manager to install various components into you development environment. 3. click Browse.. the Android DDMS and Android Development Tools features are listed.org M O B I L E T R A I N I N G. 5. Select the checkbox next to Developer Tools. 4.. Back in the Available Software view. then click Finish. Click Next to read and accept the license agreement and install any dependencies. Select Available Packages in the left panel. you can try using "http" in the URL. 4.google. Select Window > Android SDK and AVD Manager. Open Eclipse 2. Click Next. Click OK. Select Android from the left panel. then OK. Click Apply.. Configuring the ADT Plugin Once you've downloaded ADT the next step is to modify your ADT preferences in Eclipse to point to the Android SDK directory: 1. to open the Preferences panel (Mac OS X: Eclipse > Preferences).EDUmobile . you should now see "Developer Tools" added to the list.com/android/eclipse/ If you have trouble acquiring the plugin.. In the resulting Install Details dialog. Copyright © EDUmobile. Select Window > Preferences. This will reveal all of the components that are currently available for download from the SDK repository. and locate your downloaded SDK directory. 3. 5. 4. which will automatically select the nested tools Android DDMS and Android Development Tools. 6. Restart Eclipse. 2.
The components will now be installed into your existing Android SDK directories.org All Rights Reserved . Verify and accept the components you want and click Install Accepted.org M O B I L E T R A I N I N G 4. Start your eclipse and create a work directory if not already created. new add-ons are saved in the <sdk>/add-ons/ directory. samples are saved in the <sdk>/samples/android-<level>/. Select the component(s) you'd like to install and click Install Selected. Creating a Hello World App for Android Now our system is ready for work.EDUmobile . New platforms are automatically saved into the <sdk>/platforms/ directory of your SDK. 5. 3. and new documentation is saved in the existing <sdk>/docs/ directory (old docs are replaced). Copyright © EDUmobile.
org M O B I L E T R A I N I N G You will see the eclipse ID as shown in the figure below.org All Rights Reserved .EDUmobile . The left side of the UI shows the projects created by you. The lower end of it shows the console and logger which is very useful while debugging. Steps to create Hello World Example 1. The central UI will show the code written by you and the right end of the figure shows the task lists. Open the eclipse IDE in a work space and click File > New > Other > Android Project and click Next Copyright © EDUmobile.
You will see the following files created automatically by the SDK. Under contents Select “Create new Project in Workspace” and tick “Use Default Location”. 2.HelloAndroid Create Activity – HelloAndroid Click “Finish” to create the project in your workspace.hello. Select build target as the latest SDK available.EDUmobile . Copyright © EDUmobile.org All Rights Reserved .org M O B I L E T R A I N I N G 2. 3. Fill in the properties as follows Application Name – Hello Android Package Name – org. Fill the details with project name as “Hello Android”.
} } Let us spend some time understanding the code that got auto generated.Bundle.java”.EDUmobile .HelloAndroid.HelloAndroid.hello.onCreate(savedInstanceState). res and Android SDK files. The Master folder is same as Application name it is Hello Android in our case.hello. In our src folder it currently contains the package or. setContentView(R. package org. */ @Override public void onCreate(Bundle savedInstanceState) { super. If you have programmed in java before you can make out most of the code Copyright © EDUmobile.main).layout. src – It contains the source packages and java source files. public class HelloAndroid extends Activity { /** Called when the activity is first created. Let us look into the file structure. gen.org All Rights Reserved .org M O B I L E T R A I N I N G A new activity java file gets created as shown above contains the onCreate() method which is the first method to be called when the Application starts.Activity. import android. import android. The package further contains the jave file “HelloAndroid. It contains four subfolders including src.os.app.
sound files and java source files. Inside the class we define a method onCreate() which is called when the activity is starting. If you make changes in source code the code in this folder will get modified automatically. drawable – Copyright © EDUmobile. The setContentView() inflates the activity’s UI and in our example it is calling the main xml discussed below to draw the user Interface. drawable –ldpi. let me clarify few things for you.org M O B I L E T R A I N I N G above. As these files you should make any changes in them. However if you are new to java and programming.HelloAndroid”. Import is the key word which is used to access the standard and no standard packages inside a java file. A package is a namespace that organizes a set of related classes and interfaces.EDUmobile . res – It is one of the other important content folders. It contains three subfolders for images namely drawable –hdpi. We then create our class HelloAndroid which inherits the Activity class. So all the folders for this project will be contained in this package and they will contain different elements like images. The next two lines are importing standard packages for the Android specific java code. The first line declares the package “org. gen – It contains the auto generated java files.hello. The class further has a method called as onCreate() which initializes and paints the UI from a main file. Activity is a standard class of Android which we will discuss in detail a bit later. So now that it makes sense lets move ahead. Android – It contains the particular SDK libraries being used for the current project.org All Rights Reserved . To sum up this class imports standard definitions and create a class which is a subclass(inherited) of an Activity. This is where most initialization happens.
The orientation.xml”.com/apk/r es/android" android: <TextView android: </LinearLayout> It starts with the LinearLayout tag which implies that we want to put some components on the screen in a linear fashion.0" encoding="utf-8"?> <LinearLayout xmlns:Hello Android</string> </resources> Copyright © EDUmobile. We follow it with a “TextView” component which is used to display texts on the screen. If you are familiar with c or java programming you know the function main which is called when ever the programs first starts and in a similar way the main.xml contained in the values folder is used to define strings to be used within the applications.org All Rights Reserved .xml draws its content as soon as the application starts. The strings.0" encoding="utf-8"?> <resources> <string name="hello">Hello World. width and height describe how the layout should look. The layout contains the main. Let us look into these two important XML files in detail.org M O B I L E T R A I N I N G mdpi.EDUmobile . strings.android. There are many other layouts also defined in Android which you will learn later.xml which is called when the application is started.xml <?xml version="1. In this example it is taking the text from the “hello” string defined in the “strings.xml <?xml version="1.
You can define specific permissions for the application like Network access and SMS inbox access. Copyright © EDUmobile.com/apk/r es/android" package="org.0" encoding="utf-8"?> <manifest xmlns: </intent-filter> </activity> </application> </manifest> This file outlines the main xml and the activity (type of process) which should start after loading the application.EDUmobile . These four components are Manifest. Application.intent. Permission and Instrumentation.org All Rights Reserved .0"> <application android: <activity android: <intent-filter> <action android: <category android:name="android.action. The package name.org M O B I L E T R A I N I N G From the above content you can easily make out that the hello string corresponds to the actual string “Hello World.xml <?xml version="1. It is the android manifest file. Let us now look into another important xml file created by the SDK for us.intent. It primarily consists of four important parts which come together as a XML file.
org All Rights Reserved . Copyright © EDUmobile. Like if we are to add permission we will go to the permission tab and add the permission as shown below.EDUmobile . It is easy to compile the code and run the device simulator associated with the SDK. Compiling and executing our Hello World.org M O B I L E T R A I N I N G You will be making changes in the four components and the XML will get modified automatically.
Select the Android Application from it. Copyright © EDUmobile. A selection window appears as shown below.org All Rights Reserved . Once you press ok your code will start compiling and your simulator will start.org M O B I L E T R A I N I N G Click on the “Run As” as shown in the figure above.EDUmobile .
Open the strings. Let us in the meantime try and modify this program of ours and put some other text in the output screen.org All Rights Reserved .EDUmobile .xml of your project and make the following changes Copyright © EDUmobile. This example of ours was very basic but it still is a complete Android Application and you can take some time to grasp the structure and basic aspects of an Android Application.org M O B I L E T R A I N I N G Click on the “menu” key on the simulator and you can see the result of the application.
org M O B I L E T R A I N I N G <?xml version="1. You should now see the following Go through all the java and xml files for the project before you move ahead. we’re gonna have company!</string> <string name="app_name">Hello Android</string> </resources> Save your project and run your project once again. Copyright © EDUmobile. Luke.EDUmobile .0" encoding="utf-8"?> <resources> <string name="hello">Boring conversation anyway.org All Rights Reserved .
A Bit Of Theory Let us now go through some important features of Android and see how they are linked and provides application developers powerful environment to work in. Telephony components – These include other GSM and CDMA telephony components along with other phone features. Structurally Android can be broken down into four major parts Applications – The actual application that the user interacts with resides in this layer. content providers and notification manager helping the application use underlying standard libraries. Integrated Browser – Webkit based internet browser. middleware and key applications which can be summarized as follows Application framework – The application framework is a component driven system where old components are replaced and new components are added thereby keeping the environment dynamic. Media support – It has codecs for common video and audio support. Linux Kernel – Android uses linux kernel for hardware management and providing hardware abstraction to the rest of the software stack.org M O B I L E T R A I N I N G 4. It include things like Views. Resource manager. It primarily consists of a stack of operating system. Copyright © EDUmobile. These are provided to the developer through Application framework. Dalvik Virtual machine – it is an optimized java virtual machine. SQLite – A relational data base for applications. Application Framework – The application framework provides usable components for the application developers on top of which new applications can be built. All your third party applications you create will belong to this part of the system. Libraries – It is the C/C++ libraries used by Android system.EDUmobile .org All Rights Reserved .
You can have many activities based on the user interfaces used by your application but each one of them is a subclass of the Copyright © EDUmobile.1 Application Development Basics Android application development is done in java programming language. Hence there is no single entry point for Android application like main but rather there are components which can start as the need arises.EDUmobile .org All Rights Reserved . Activity – An activity is use to present visual interface to the user. If your application draws a view similar to what we did in our hello world application where we created a Textview is an example of an activity. The Android application can be considered as a series of processes and the control moves from one process to another creating an application for the user to interact with.org M O B I L E T R A I N I N G 4. These components can be classified into four parts: 1. The compiled code is bundled into an Android package which can be signed and installed on the mobile phone.
They must inherit BroadcastReceivers base class. Copyright © EDUmobile. So what should be your next steps? I suggest the following Master Core Java – You should know basic objective oriented programming and should know how to use java to leverage the power of object oriented programming. It runs in the main thread and for resource intensive tasks it can branch out a new thread. You can further expand into Opengl-ES based on your needs.2 The Road Ahead So. Services – A services does not have a visual component but runs in the background and carries out some background process while the other visual component s are running in the foreground. Content providers – This provides specific set of data from one application to other applications. 4.EDUmobile . You further need to decide if you will be using a back ground process as a service or not and if you want to handle Broadcast messages. These basic decisions will carve out the basic design of your application which can then be designed at a much lower level. You need to decide what your visual entities are and what resultant activities are there. Activity class. 4. Start with basic Android APIs like activity and intents to create simple programs using layouts. A service will inherit Service base class. Broadcast receivers – This component are responsible for receiving and reacting to broadcasted messages.org M O B I L E T R A I N I N G 2. Broadcast can be system generated like the “Low battery” but it can be from other applications running in the background. this was our introductory lesson on Android application development and the revolutionary it presents to the developers as a platform.org All Rights Reserved . Next inline is persistence and SQLite. These are used in conjunction with Content resolver which provide methods for inter process communication. The content providers extend ContentProvider base class. To summarize before developing an application you need to decide the structure of your application in terms of these fundamental entities. Move next to 2d graphics and multimedia and networking. Each activity has a separate window to draw the visual component but if required it can use more than one window also. 3.
You will also get access to our private forum where you can meet other fellow Android developers. If you are interested in mastering NAdroid Development.org All Rights Reserved . The course is delivered over a period of 12 weeks via Online Video that you may download and view at your convenience. along with material and Weekly Worksheets. What Next ? This was a small step in our journey towards getting started with Android development. whom you may consult any time with questions and problems you face.org M O B I L E T R A I N I N G So. so there is no risk at all.EDUmobile . Click Here To Learn More About The Android Course and To Enroll Affiliates Join Our High Paying Affiliate Program and Make Tons Of Money! Interested in promoting our Courses and making money? Get instant $25 bonus for signing up! Click Here to sign up for our Affiliate Program Copyright © EDUmobile. we suggest you sign up for our complete 12 Week Android Programming Course at the link below. It comes with a full money back guarantee. You will be assigned your own personal one-on-one tutor. | https://www.scribd.com/doc/92966730/Beginning-Android-Programming | CC-MAIN-2017-09 | refinedweb | 5,033 | 58.48 |
00001 /*@HEADER 00002 ************************************************************************ 00003 00004 Epetra: Linear Algebra Services Package 00005 Copyright (2001) Sandia Corporation 00006 00007 Under terms of Contract DE-AC04-94AL85000, there is a non-exclusive 00008 license for use of this work by or on behalf of the U.S. Government. 00009 00010 This library is free software; you can redistribute it and/or modify 00011 it under the terms of the GNU Lesser General Public License as 00012 published by the Free Software Foundation; either version 2.1 of the 00013 License, or (at your option) any later version. 00014 00015 This library is distributed in the hope that it will be useful, but 00016 00023 USA 00024 Questions? Contact Michael A. Heroux (maherou@sandia.gov) 00025 00026 ************************************************************************ 00027 */ 00028 //@HEADER 00029 00030 /* The purpose of this file is to allow for 00031 informative error reporting that will not abort a test program after a single 00032 error the way that an assert command does. */ 00033 00034 /* The macro takes two arguments. The first is the error code to be examined. The second is an int that can be viewed either as an error count, or as a bool that simply indicates if any errors have occurred as of the time that the macro was run (zero -> no prior errors, non-zero -> prior errors). If the error code is > 0, it is interpreted as a warning, and the code is printed, but an error is not tallied. If it is < 0, it is interpreted as an error.*/ 00035 00036 #ifndef EPETRA_TEST_ERR_H 00037 #define EPETRA_TEST_ERR_H 00038 #include "Epetra_ConfigDefs.h" 00039 using namespace std; 00040 // This function is to be used when first identifying an error. 00041 #define EPETRA_TEST_ERR(a,b) { { int epetra_testing_err = a; \ 00042 if (epetra_testing_err != 0) {\ 00043 cerr << "Non zero error code " << epetra_testing_err << \ 00044 ", file: " << __FILE__ << ", line: " << __LINE__ << endl;\ 00045 if (epetra_testing_err < 0) {\ 00046 b+=1;\ 00047 }\ 00048 }\ 00049 }\ 00050 } 00051 00052 #endif /* EPETRA_TEST_ERR_H */ | http://trilinos.sandia.gov/packages/docs/r7.0/packages/epetra/browser/doc/html/epetra__test__err_8h-source.html | CC-MAIN-2013-48 | refinedweb | 319 | 67.69 |
Wuffs is an imperative, C-like language and much of it should look familiar to somebody versed in any one of C, C++, D, Go, Java, JavaScript, Objective-C, Rust, Swift, etc. Accordingly, this section is not an exhaustive specification, merely a rough guide of where Wuffs differs.
Like Go, semi-colons can be omitted, and
wuffsfmt will remove them. Similarly, the body of an
if or
while must be enclosed by curly
{}s. There is no ‘dangling else’ ambiguity.
7 keywords introduce top-level concepts:
const
error
func
packageid
struct
suspension
use
2 keywords distinguish between public and private API:
pri
pub
8 keywords deal with control flow within a function:
break
continue
else
if
iterate
return
while
yield
5 keywords deal with assertions:
assert
inv
pre
via
2 keywords deal with types:
nptr
ptr
1 keyword deals with local variables:
var
TODO: categorize try, io_bind. Also: and, or, not, as, ref, deref, false, true, in, out, this, u8, u16, etc.
There is no operator precedence.
a * b + c is an invalid expression. You must explicitly write either
(a * b) + c or
a * (b + c).
Some binary operators (
+,
*,
&,
|,
^,
and,
or) are also associative:
(a + b) + c and
a + (b + c) are equivalent, and can be written as
a + b + c.
The logical operators,
&& and
|| and
! in C, are written as
and and
or and
not in Wuffs.
TODO: ignore-overflow ops, equivalent to Swift's
&+.
Converting an expression
x to the type
T is written as
x as T.
Types read from left to right:
ptr array [100] u32 is a pointer to a 100-element array of unsigned 32-bit integers.
ptr here means a non-null pointer. Use
nptr for a nullable pointer type.
Integer types can also be refined:
var x u32[10..20] defines a variable x that is stored as 4 bytes (32 bits) and can be combined arithmetically (e.g. added, compared) with other
u32s, but whose value must be between 10 and 20 inclusive. The syntax is reminiscent of Pascal's subranges, but in Wuffs, a subsequent assignment like
x = 21 or even
x = y + z is a compile time error unless the right hand side can be proven to be within range.
Types can also provide a default value, such as
u32[10..20] = 16, especially if zero is out of range. If not specified, the implicit default is zero.
Refinement bounds may be omitted, where the base integer type provides the implicit bound.
var x u8[..5] means that
x is between 0 and 5.
var y i8[-7..] means that
y is between -7 and +127.
var z u32[..] is equivalent to
var z u32.
Refinement bounds must be constant expressions.
var x u32[..2+3] is valid, but
var x u32; var y u32[..x] is not. Wuffs does not have dependent types. Relationships such as
y <= x are expressible as assertions (see below), but not by the type system.
Structs are a list of fields, enclosed in parentheses:
struct point(x i32, y i32). The struct name may be followed by a question mark
?, which means that its methods may be coroutines. (See below).
Function signatures read from left to right:
func max(x i32, y i32)(z i32) is a function that takes two
i32s and returns one
i32. Two pairs of parentheses are required: a function that in other languages would return
void in Wuffs returns the empty struct
(), also known as the unit type.
When calling a function, each argument must be named. It is
m = max(x:10, y:20) and not
m = max(10, 20).
The function name, such as
max, may be followed by either an exclamation mark
! or a question mark
? but not both. An exclamation mark means that the function is impure, and may assign to things other than its local variables. A question mark means that the function is impure and furthermore a coroutine: it can return a (recoverable) suspension code, such as needing more input data, or return a (fatal) error code, such as being invalid with respect to a file format. If suspended, calling that function again will resume at the suspension point, not necessarily at the top of the function body. If an error was returned, calling that function again will return the same error.
Some functions are methods, with syntax
func foo.bar(etc)(etc), where
foo names a struct type and
bar is the method name. Within the function body, an implicit
this argument will point to the receiving struct. Methods can also be marked as impure or coroutines.
Variable declarations are hoisted like JavaScript, so that all variables have function scope. Proofs are easier to work with, for both humans and computers, when one variable can't shadow another variable with the same name.
Assertions state a boolean typed, pure expression, such as
assert x >= y, that the compiler must prove. As a consequence, the compiler can then prove that, if
x and
y have type
u32, the expression
x - y will not underflow.
An assertion applies for a particular point in the program. Subsequent assignments or impure function calls, such as
x = z or
f!(), can invalidate previous assertions. See the “Facts” section below for more details.
Arithmetic inside assertions is performed in ideal integer math, working in the integer ring ℤ. An expression like
x + y in an assertion never overflows, even if
x and
y have a realized (non-ideal) integer type like
u32.
The
assert keyword makes an assertion as a statement, and can occur inside a block of code like any other statement, such as an assignment
x = y or an
if statement. The
pre,
inv keywords are similar to
assert, but apply only to
func bodies and
while loops.
pre states a pre-condition: an assertion that must be proven on every function call or on every entry to the loop. Loop entry means the initial execution of the loop, plus every explicit
continue statement that targets that
while loop, plus the implicit
continue at the end of the loop. For
while loops, the pre-condition must be proven before the condition (the
x < y in
while x < y { etc }) executes.
post states a post-condition: an assertion that must be proven on every function return (whether by an explicit
return statement or by an implicit
return at the end of the function body) or on every loop exit (whether by an explicit
break statement or by the implicit
break when the condition evaluates false).
For example, a
while loop that contains no explicit
break statements can always claim the inverse of its condition as a post-condition:
while x < y, post x >= y { etc }.
inv states an invariant, which is simply an assertion that is both a pre-condition and post-condition.
When a
func or
while has multiple assertions, they must be listed in
pre,
inv and then
post order.
Static constraints are expressed in the type system and apply for the lifetime of the variable, struct field or function argument. For example,
var x u32 and
var p ptr u32 constrain
x to be non-negative and
p to be non-null. Furthermore,
var y u32[..20] constrains
y to be less than or equal to
20.
Dynamic constraints, also known as facts, are previously seen assertions, explicit or implicit, that are known to hold at a particular point in the program. The set of known facts can grow and shrink over the analysis of a program's statements. For example, the assignment
x = 7 can both add the implicit assertion
x == 7 to the set of known facts, as well as remove any other facts that mention the variable
x, as
x's value might have changed. TODO: define exactly when facts are dropped or updated.
Similarly, the sequence
assert x < y; z = 3 would result in set of known facts that include both the explicit assertion
x < y and the implicit assertion
z == 3, if none of
x,
y and
z alias another (e.g. they are all local variables).
Wuffs has two forms of non-sequential control flow:
if branches (including
if,
else if,
else if chains) and
while loops.
For an
if statement, such as
if b { etc0 } else { etc1 }, the condition
b is a known fact inside the if-true branch
etc0 and its inverse
not b is a known fact inside the if-false branch
etc1. After that
if statement, the overall set of known facts is the intersection of the set of known facts after each non-terminating branch. A terminating branch is a non-empty block of code whose final statement is a
return,
break,
continue or an
if,
else if chain where the final
else is present and all branches terminate. TODO: also allow ending in
while true?
For a
while statement, such as
while b { etc }, the set of known facts at the start of the body
etc is precisely the condition
b plus all
pre and
inv assertions. No other prior facts carry into the loop body, as the loop can re-start coming from other points in the program (i.e. an explicit or implicit
continue) If the
while loop makes no such
pre or
inv assertions, no facts are known other than
b.
Similarly, the set of known facts after the
while loop exits is precisely its
inv and
while loop must explicitly list its state of the world just before and just after it executes. This includes facts (i.e. invariants) about variables that are not mentioned at all by the
while condition or its body but are proven before the
while loop and assumed after it.
Wuffs' assertion and bounds checking system is a proof checker, not a full SMT solver or automated theorem prover. It verifies explicit annotations instead of the more open-ended task of searching for implicit proof steps. This involves more explicit work by the programmer, but compile times matter, so Wuffs is fast (and dumb) instead of smart (and slow).
Nonetheless, the Wuffs syntax is regular (and unlike C++, does not require a symbol table to parse), so it should be straightforward to transform Wuffs code to and from file formats used by more sophisticated proof engines.
Some rules are applied automatically by the proof checker. For example, if
x <= 10 and
y <= 5 are both known true, whether by a static constraint (the type system) or dynamic constraint (an asserted fact), then the checker knows that the expression
x + y is bounded above by
10 + 5 and therefore will not overflow a
u8 (but would overflow a
u8[..12]).
TODO: rigorously specify these automatic rules, when we have written more Wuffs code and thus have more experience on what rules are needed to implement multiple, real world image codecs.
Other rules are built in to the proof checker but are not applied automatically (see “fast... instead of smart” above). Such rules have double-quote enclosed names that look a little like mathematical statements. They are axiomatic, in that these rules are assumed, not proved, by the Wuffs toolchain. They are typically at a higher level than e.g. Peano axioms, as Wuffs emphasizes practicality over theoretical minimalism. As they are axiomatic, they endeavour to only encode ‘obvious’ mathematical rules. For example, the rule named
"a < b: a < c; c <= b" is one expression of transitivity: the assertion
a < b is proven if both
a < c and
c <= b are provable, for some expression
c. Terms like
a,
b and
c here are all integers in ℤ, they do not encompass floating point concepts like negative zero,
NaNs or rounding.
Such rules are invoked by the
via keyword. For example,
assert n_bits < 12 via "a < b: a < c; c <= b"(c:width) makes the assertion
n_bits < 12 by applying that transitivity rule, where
a is
n_bits,
b is
12 and
c is
width. The trailing
(c:width) syntax is deliberately similar to a function call (recall that when calling a function, each argument must be named), but the
"a < b: a < c; c <= b" named rule is not a function-typed expression.
TODO: specify these built-in
via rules, again after more experience.
Labeled
break and
continue statements enable jumping out of loops that aren‘t the most deeply nested. The syntax for labels is
while:label instead of Java’s
label:while, as the former is slightly easier to parse, and Wuffs does not otherwise use labels for switch cases or goto targets.
TODO: describe the built in
buf1 and
buf2 types: 1- and 2-dimensional buffers of bytes, such as an I/O stream or a table of pixel data.
Updated on April 2018. | https://skia.googlesource.com/external/github.com/google/wuffs/+/HEAD/doc/wuffs-the-language.md | CC-MAIN-2019-47 | refinedweb | 2,123 | 71.04 |
FlexJS Components
Components in the FlexJS framework are bundles of functionality formed by composition, rather than by inheritance. The concept of adding functionality (composition) is different from the current version of Flex which tends to extend (inheritance) functionality resulting in more complex components or adding features (overloading) to existing components.
For example, to have a text input field also include password and prompt features, you might use inheritance to create additional classes and wind up copying code between them. Another option is to add these properties to the text input field and overload it with features. Feature overloading makes it convenient for developers but most of the time only a basic set of features are ever used. This means applications can be very large (byte-wise) because every component has code and properties it rarely needs.
FlexJS solves these problems by allowing developers to add just the features they need when they need them. Instead of every text input field having password and prompt capabilities, only a few text input controls have those features and the application remains lighter as a result.
A component in FlexJS consists of strands onto which beads are added. A strand is the component wrapper while a bead encapsulates a particular bit of functionality. In the example above, the password and prompt features are beads that can be added to any component having a view bead that implements the
ITextFieldView interface; the actual text input control is provided by a view bead and the data (the text itself) is managed by a model bead. In this way, components in FlexJS embody the model-view-controller (MVC) paradigm.
Beads can interact with each either through the strand, with events, or direct manipulation. For example, a bead that makes text red might listen for changes to the component's model and, when it detects a key word, changes the text in the model; the change to the model would get reflected in the view bead. Beads can add visual elements to components (view beads) or just change data or handle events.
A Word About ActionScript and JavaScript
The FlexJS framework is designed to work well with ActionScript and JavaScript. The philosophy is that if it works in ActionScript, it should work in JavaScript, too, and vice-versa. You create a component (or bead) in ActionScript, designating platform-specific functionality or elements, using the COMPILE::SWF and COMPILE::JS compiler directives. See FlexJS Component Source Code Patterns for details about this development pattern for FlexJS.
You want to make things as efficient as possible in both environments. For instance, the TextInput component in ActionScript is comprised of view and model beads. The JavaScript TextInput has neither since HTML has a view and model already (via the HTMLElement); the FlexJS TextInput component is just a thin wrapper for the HTML control. As you begin creating your component, take the time to understand the best way to represent it so the component is as optimal as possible for both SWF and JS execution.
Bead Life Cycle
There are three ways a bead can be used with a component:
- Place an instance of the bead in-line in an MXML file using the component's <js:beads> property.
- Reference a bead's class in a CSS style for the component.
- Create the bead in ActionScript code (using new operator) and place it onto the component's strand using the addBead() function.
When a component is added to the display list via the addElement() function of its parent, the FlexJS framework invokes a function on the component called, addedToParent().
- The addedToParent() function will look at the <js:beads> list and add those beads to the strand. In doing so, each bead's strand setter (see below) is called.
- Once the <js:beads> are handled, addedToParent() then sees if there are model, view, and controller beads that need to be added to the strand. Using the model bead as an example, addedToParent() checks to see if the model is already on the strand (it may have been in the <js:beads> list). If not, then the style for the component is checked to see if iBeadModel was specified and if it is, a new model is created and added to the strand. This sequence applies to the view and controller beads as well.
- Finally, addedToParent() dispatches the "beadsAdded" event on the component.
By first processing the <js:beads>, the FlexJS framework allows a developer to replace default beads set up in CSS. If you write your own components and have custom beads, follow this pattern:
- Override addedToParent() and call super.addedToParent() immediately. This will perform the three steps above. It will also dispatch "beadsAdded".
- Check to see if your custom bead is already on the strand.
- If the bead is not on the strand, create a default bead either by looking in CSS to see if a class has been specified or just create one using the new operator. Then add it to the strand.
- Dispatch a custom event or dispatch "initComplete" (if your component is not subclassing a container class which will dispatch "initComplete" for you) to signal that all beads are now present.
Some tips are where to perform certain tasks are given in the topics below.
Creating a Bead
The first example shows how to make the password bead. You will see how to compose the bead and how to add it to an existing component's strand.
This example already exists in the FlexJS library. You can look at the class files and follow along. (See; flex-js/frameworks/projects/HTML/as/src/org/apache/flex/html/accessories/PasswordInputBead.as)
For this example, the password bead will modify the underlying text control (a TextField for ActionScript and the
<input> element for JavaScript) so that it becomes a password entry field. These are the steps needed:
- Create the bead class (PasswordInputBead).
- Implement the strand setter, which is required. The strand is the component (in this case, TextInput) which may or may not have all of is beads set when the strand setter is called.
- In the strand setter, a listener is set up for the “viewChanged” event which is sent when the strand’s view bead is added. The view bead has access to the underlying text field.
- When the “viewChanged” event is handled, the viewBead is used to get to the text field and the text field is modified to display its entry as a password.
Create the Bead
Create a new ActionScript class called PasswordInputBead and have it implement the IBead interface. Beads do not normally have their own user interface or display; they normally use the strand. Beads can create new UI components, but then they make the strand the parent of those components.
Implement the Strand Setter
Declare a private var called “_strand” and implement the setter function:
The implementation of the bead differs between JavaScript and SWF. In the browser, the underlying component is an input element and all that this bead needs to do is set its type to be "password". For the SWF platform, it is more complicated with events being intercepted and the text being changed to obscure the password. The strand setter function has these additional lines to complete it.
The strand setter is a good place to initialize values and to set up event listeners, such as "viewChanged", "beadsAdded", or "initComplete" (or a custom event dispatched by your component).
The compile directives will have the input element set up for password input with just a few lines when they are cross-compiled into JavaScript. For ActionScript, an event listener is set up to listen for when the standard beads (model, view, controller) have been added to the strand; this code is not needed in JavaScript and so it is isolated to ActionScript using the COMPILE::SWF directive.
Implement the Event Handler
For ActionScript, create the function to handle the “beadsAddedEvent” event (note that the COMPILE::SWF directive is placed above the function definition so all of the function is included only in the ActionScript build).
The first thing the event handler does is retrieve the ITextFieldView bead (an interface, not an actual class) from the strand using the getBeadByType() function. This function will examine the strand and return the first bead that matches the given type.
With an ITextFieldView bead in hand, the next thing to do is get its underlying Flash textField and set it to display as a password. CSSTextField is a FlexJS class that extends the ActionScript TextField to make it easier to apply styles to it using CSS.
A More Complex Bead
The PasswordInputBead is fairly simple: it just changes the type of input control using the built-in input control's property (
displayAsPassword for ActionScript and
type = 'password' for JavaScript). If you want the bead to do more, you can have the bead listen to events and take its own actions. Here is the
beadsAddedHandler for a bead that restricts input to be numeric and makes sure the text being entered is valid.
Like the PasswordInputBead, the ActionScript platform uses a special property of the TextField to restrict the input to numerals and a decimal separator (a property on this bead). While the
restrict property of the TextField does limit input to those characters, it does not prevent those characters from repeating. That is, you can enter "123.45.67.890" which, of course, is not a valid number.
To have the bead act as an input validator, the bead listens for the
TEXT_INPUT event on the TextField using the
handleTextInput() function:
Since the
TEXT_INPUT event is dispatched before the text property of the TextField is changed, you can determine if the combination of the new text in
event.text plus the TextField's current text value, is a valid number. After converting the combined text to a Number, it can be tested to see if the String represents a numeric value and, if not, the default action of the event is prevented: actually adding the new text to the TextField.
When the event's default action is prevented, not only is the input prevented from being added to the TextField, the model for the component is also unchanged.
The JavaScript version of this bead works similarly to the JavaScript PasswordInputBead where you set things up in the strand setter and listen for the appropriate event, a
keypress event in this case as shown in the COMPILE::JS code block.
Unlike ActionScript, JavaScript input elements (prior to HTML 5) do not have any way to restrict input characters, so you have to do that yourself, which is done in the
validateInput() event handler:
The top portion of the function allows special keys to go through unaltered (backspace, tab, return, delete, and arrow keys). The next test determines if the character is '0' through '9' or the period. If the character fails that test, the event is prevented (same as ActionScript). If the character is valid, it is inserted into the input string and that assemblage is tested. If the string now fails a numeric test (
isNaN() can take either a number or a string) the event is also prevented.
Imagine if every text input control had the ability to restrict its input just by providing some options. This more complex bead is a good example of how FlexJS allows you to build an application using only the parts you need. Having only a handful of TextInput components be able to restrict or validate their data makes for a smaller application footprint. Further, by extracting the functionality of numeric validation into a bead, the validation can be added to any text input control, such as a ComboBox, whenever needed.
Using the Bead
Updating the Manifest and Library
If your bead is to become part of the FlexJS framework library, you will need to modify additional files. If your bead is solely for your application use, you can skip this part.
Your bead must be compiled and place into the FlexJS SWC library. To do, find the FlexJSUIClasses.as file and add your bead. For example:
To allow your bead to use the FlexJS namespace, it must be present in the FlexJS manifest file. Find the basic-manifest.xml file and add the bead, such as:
MXML
To make use of the bead, go to your application or initial view MXML file and create a TextInput and add the PasswordInputBead to it:
The FlexJS framework first adds any beads that are declared in MXML. After that, FlexJS adds beads for the component that are declared in a style sheet. FlexJS uses defaults.css as its style sheet where TextInputView is declared as the view bead for TextInput (more on this later). When the TextInputView bead is added, it triggers the “viewChanged” event which allows the PasswordInputBead to make its modifications.
To see how powerful adding beads can be, add another bead to this strand:
When the application is run, not only can you enter text as a password, a prompt will appear as long as the field is empty.
Of course, if you find that you frequently need a set of components, creating a composite, custom component that combines the beads needed is also possible; add the beads in your custom component's addedToParent() override function.
Bead Guidelines
- Most beads use their strand for their UI parent. Beads can make or use other components or visual parts, then they add them to their strand’s display list.
- Try to use interfaces whenever possible. This keeps implementation code separate and lets modules work better.
- Use the paradigm of separation of concerns as much as possible. That is, do not have beads do more than necessary and separate functions into multiple beads. Very often a component will have one bead for the visual display (a view bead), one bead to hold its data (a model bead), and one bead to handle user interactions (a control bead). This allows a developer to swap out beads as necessary. For example, a mobile developer might want to replace the Slider's mouse controller bead with a touch controller bead: the component's other parts (track, thumb, model, etc.) remain the same.
Making a Component
In the previous example, a new bead was created and added to an existing bead. These steps show you how to make a new component. Remember that components are usually made up of a model bead, a view bead, and a control bead, but this depends on what the component does.
The Slider component is a good example of the MVC architecture of FlexJS components. The Slider has a view bead (which manages the track and thumb - also beads), a model bead (the
RangeModel used by other components), and control bead (to handle mouse clicks and drags). Once you've decided what your component will do, break it down into those three parts. In general, your view and controller beads will probably be unique to your component but you might be able to re-use a model bead.
Using Slider as an example, the basic approach to building a FlexJS component is:
- Slider.as (and Slider.js) is the strand and provides the UI display list. The strand part extends UIBase (for ActionScript) or creates the base element (for JavaScript) and defines the public properties and events for the component. In the case of Slider, it has property setters and getters for
minimum,
maximum,
value, and
snapIntervalthat pass through to the model. Slider also dispatches a
valueChangedevent.
- SliderView.as is the view bead and provides the track and thumb, which are also beads; SliderView simply manages them.
- SliderMouseController is the controller bead and watches for mouse events on the SliderView, translating them to model values and updating the view.
The separation of the parts makes it easy for someone to replace them. For example, you could change how the Slider looks or behaves by replacing the view or controller beads.
- RangeModel.as (and RangeModel.js) provide the data model for the component. The model has property setters and getters for
minimum,
maximum,
value, and
snapIntervalwhich are called by the strand (Slider.as and Slider.js). Changes to any of the properties dispatch a corresponding change event.
One thing you will not see in the Slider.as (strand) code is the application or naming of any specific beads. The beads for a component are identified by the style for the bead. If you look at the
defaults.css file, you'll find the Slider has the following style defined:
A very powerful piece of FlexJS is the
ValuesManager which connects components to styles and applies the beads. In this style definition for Slider, you can see which model, view, and controller are being applied. To replace something, just change it in the style. Since the SliderView uses beads for the thumb and track, those are also defined in the style so you can replace those elements, too.
When you make your own components, be sure to think about replacement - what parts of your component do you think someone might want to change or swap out - then place them into a style definition for your component.
Slider (strand)
If you open Slider.as, you'll see that it implements the setters and getters, but all they do is call upon the model's corresponding setters and getters. Your strand really needs to provide the public interface and that's about it. The strand should not create any views or manipulate any values. There are probably going to be exceptions, but this should be the rule: keep functionality as separate as possible and join it together with events.
The Slide extends UIBase, which on the SWF side will be DisplayObject and on the JavaScript side will be a <div> element. That is fine for Slider, but in case you want to use a different HTML element, you can override the createElement() function which is present only for the JavaScript side:
Notice the use of flexjsignorecoercion doc tag in the comment. This tells the cross-compiler not to generate JavaScript for the "as" construct involving WrappedHTMLElement.
SliderView (view bead)
If you open the SliderView.as file and look at the strand setter function, you can see how the track and thumb beads are identified and added.
Both the track and thumb parts of the Slider are Buttons. Since Buttons are also FlexJS components and follow the same pattern, they too have beads. The look of the track and slider are encapsulated in Button-compatible beads so they are fetched from the style definition by the ValuesManager and added to the Button's strand.
Once the pieces of the view are created, event listeners are set up so the view knows what's happening to the strand, especially the size and the value. Changes to the size cause the view to layout out its children. Changes to the value position the thumb over the track.
Be sure to add any sub-components to the strand's display list shortly after creating them. This will fire off those sub-components' life cycles and allow them to trigger their own compositions. This way, when it comes time for your view bead to size and position the sub-elements, they will have dimension.
RangeModel (model bead)
If you open the RangeModel.as (or any of the other model files) you'll see they are a collection of property setters and getters (and their backing variables, of course). Every property has an event dispatched when it changes. Note that the event is dispatched from the model, not its strand. Beads that need to listen for changes to the model should fetch the strand's model and set up listeners for those properties it is interested in. For example, the Slider's mouse controller bead can update the model value which will be picked up the Slider's view bead and the thumb will change position.
This is the typical pattern for getting the strand's model and setting up the listener. Note the use of interfaces instead of concrete classes.
SliderMouseController (control bead)
If you open the SliderMouseController.as file you will see that it uses the strand setter to get the model and view. The controller's job is to coordinate the actions of the user with the model and view. A controller sets up the input event handlers (e.g., mouse events, keyboard events, touch events) to do that. The SliderMouseController sets up mouse events such that when the track is clicked, the controller catches that event, derives the value using the model and the x position of the click. The controller then updates the model with a new value. Because the model dispatches an event when the value changes, the view, listening for this event, changes the position of the thumb.
When you write your own controllers you can follow the same pattern: translate events to model values and update the model. The view bead(s) should be listening for those changes.
If you open SliderMouseController.as, you see that its
strand setter function gets the track and thumb beads from its strand, via
getBeadByType() and adds event listeners to them. Notice that there are differences between the ActionScript and JavaScript platforms, so these are coded accordingly.
The purpose of the controller is to coordinate the input from the mouse with values from the model which are then reflected in the views. Here are the click handlers for the track:
Using JavaScript Component Libraries with FlexJS
Many web applications now use JavaScript component sets, such as jQuery, and it is possible to use those frameworks with FlexJS; it is just a matter of changing how the components are built. The FlexJS package comes with a handful of jQuery-compatible and CreateJS-compatible components to get you started.
Remember that FlexJS works in both the ActionScript and JavaScript worlds. While you do not have to make ActionScript equivalents of your JavaScript components, it is good practice to provide them just so your application can be run in both environments. You will find ActionScript versions of the sample jQuery and CreateJS FlexJS components in the corresponding ActionScript packages:
org/apache/flex/jquery and
org/apache/flex/createjs, respectively.
jQuery for FlexJS
The biggest trick is to pull in the component set definition files. At this time, FlexJS does not have an easy way to do this. It is a manual process at this point:
- Compile your Flex application using Falcon JX.
- Open the index.html file that was generated.
Insert the following lines into the
<head>portion of the file.
In the FlexJS directories you will find a small set of components in the
org/apache/flex/html/jqueryfolder. If you compare these to the standard components in the
htmlpackage, you will see there are few differences, the most obvious being the inclusion of jQuery function calls to modify the components.
Open the TextButton.as file and look for the
createElement() and addedToParent functions in the COMPILE::JS block:
The only difference between the jQuery version of the TextButton and the basic Text button is the jQuery button-making function,
$(element).button(). Your jQuery components may differ greatly from their non-jQuery
Once you've created or converted the components to use jQuery, the JavaScript side of FlexJS can use jQuery functions to manipulate the components and their beads. For example, might want to create a bead that manipulates the styles and provides effects such as fades. Rather than modifying every component to have the ability to fade in and out, you can just add the "FadeBead" to a component strand.
CreateJS for FlexJS
CreateJS is an altogether different way of making components from jQuery. CreateJS is more like ActionScript in that you build things rather manipulate them. As with jQuery, the big trick is to bring in the CreateJS package:
- Compile your Flex application with the Falcon JX compiler.
- Open the JavaScript file that was generated from your main Flex application (e.g., if your Flex application's main file is Main.mxml, open Main.js).
Insert the following lines before the
goog.provide()statements:
- Be sure to put a copy of the CreateJS component files in a sub-directory called,
createjs, next to the other source directories.
If you open the TextButton.js file in the CreateJS package, you will find two definitions for the TextButton class. One in a COMPILE::SWF block and another in a COMPILE::JS block. This was done because the two versions have enough differences that it would be awkward to mingle the compiler directive blocks; it was cleaner to define the classes separately.
In this example, CreateJS functions construct a button-like object rather than use HTML elements. While the basic, jQuery, and CreateJS TextButtons diff in implementation, they are expressed exactly the same in MXML.
Using FlexJS jQuery and CreateJS Components in MXML
Once you've created your jQuery or CreateJS (or other component library) beads and components, you can add them to your Flex application MXML using namespaces. This is the root tag for a version of MyInitialView.mxml:
Once you have declared the namespaces, you use the namespaces to identify the components:
Cross-Compiling
The ability to generate JavaScript code and components from ActionScript sources is built into the FlexJS development patterns. You guide the compilation process through the use of COMPILE::SWF (exclude from cross-compilation, SWF only) and COMPILE::JS (exclude from SWF, cross-compile to JavaScript) directives; any code not in these blocks is cross-compiled to JavaScript and winds up in the SWF. | https://cwiki.apache.org/confluence/display/FLEX/Creating+Components | CC-MAIN-2018-17 | refinedweb | 4,272 | 60.95 |
The magic of python decorators
Posted by Jason Baker on April 25, 2009
Decorators in Python are one of the language’s more “magical” features. Personally, I’ve tended to glaze over decorators in code because they always seemed to be fairly self-explanatory. But how do you make your own? Personally, I think understanding the uses of decorators and being able to write your own is one of the points where a python newbie transitions to a knowledgeable pythonista.
But what is a decorator?
In actuality, there’s not an actual language construct to define decorators. Any function that takes a function as a parameter and returns one as a result may be used as a decorator. These are known as “higher-order functions” in functional programming circles.
Chances are, you’ve already seen decorators in use and maybe even used them. I’ll give you a common example of decorator usage:
class SomeClass(object): @property def x(self): return 5 >>> var = SomeClass() >>> var.x 5
For those of you familiar with the concept of properties, it should be pretty straight-forward what’s going on here. But where the heck did property come from? I’ll give you a hint. The above code works identically to this code:
class SomeClass(object): def x(self): return 5 x = property(x)
I can write my own?!
Yes you can. A lot of well-written libraries make very good use of decorators. And given the right situation, the little bit of syntactic sugar they provide can do a lot of good. But decorators aren’t just there for others to define. Once you wrap your head around decorators, they can save you a lot of copy-and-pasting (which you’re not doing anyway, right?) when used in your own code. To illustrate this, I want to show you a couple of very much real-world cases that I’ve found decorators to be useful.
Those pesky connection objects
I have a library that needs to call a few particular stored procedures in a SQL Server database. Because my ORM doesn’t support stored procedures, I have to use straight adodbapi. The calls look something like this:
import adodbapi def LookupPerson(): conn = adodbapi.connect(CONNECTION_STRING) try: #do stuff here finally: conn.close()
This is all well and good for just one function. But what happens when you need 4 or 5 of these? And what about the visual cruft that the try finally block is adding to the function (adodbapi doesn’t support with blocks before you ask)? I’m sure you’ve already guessed the solution by now. Here’s how you can solve this problem:
import adodbapi def with_connection(func): def _exec(*args, **argd): conn = adodbapi.connect(CONNECTION_STRING) try: func(conn, *args, **argd) finally: conn.close return _exec @with_connection def LookupPerson(conn): #do stuff here LookupPerson() #conn argument is passed by the decorator
I think that the simplification that happens with LookupPerson here should be obvious. But what is the purpose of the *args and **argd shenanigans? The documentation covers arbitrary argument lists in depth, so I won’t go into too much detail. But what happens if I want to lookup a person by name? The LookupPerson function would be transformed to this:
@with_connection def LookupPerson(conn, name): #do stuff here LookupPerson('Bob') #conn argument is passed by the decorator LookupPerson(name='Jill')
In fact, I can decorate any function that takes any number of arguments either by keyword or by position. Pretty neat, eh?
Error handling
When doing web applications, it’s pretty important to have decent error handling. But setting this up can be a pain. For instance, what if I wanted to make my django application print a wonderfully informative traceback to a log file? I could do that like this:
from traceback import format_exc def index(request): try: #do stuff except: logging.log(format_exc()) return HttpResponseServerError('Error!')
But this definitely can become problematic. What happens if you duplicate this code in all of your view functions and you want to make a change to your error handling? The solution is simple:
def handle_errors(func): def _handler(*args, **argd): try: func(*args, **argd) except: logging.log(format_exc()) return HttpResponseServerError('Error!') @handle_errors def index(request): #do stuff here
As you can tell, this allows us to make our views worry about actually doing stuff instead of constantly handling errors. Yes, there are also middlewares for doing this kind of thing. But then I wouldn’t have a reason to make a blog post about python decorators, would I?
Conclusions
Ok, so I’ll admit something. Python’s decorator syntax is ugly. Its Java-like syntax alone may even be enough to scare some off. But as I’ve show, there are at least a few real-world cases where they are useful.
What are some other decorators that you’ve found to be useful?
rubayeet said
Nice article Jason. Thanks! | http://jasonmbaker.wordpress.com/2009/04/25/the-magic-of-python-decorators/ | CC-MAIN-2013-48 | refinedweb | 824 | 65.83 |
.
Thanks for quick reply @philippjfr
but its not working ,
can i do curdoc() by making standalone HTML files
from bokeh.io import curdoc doc=curdoc() # finalplot=finalplot.get_root(doc) # return Markup(file_html(finalplot.get_root(doc),CDN,"myplot")) if __name__=='__main__': app.run(debug=True)
it giving static plot , no zoom function , nothing.
2- by using component method no error is coming same time no plot is showing in webpage ,
i am using
from bokeh.resources import CDN
so there is no mismatch of bokeh cdn version but still no plot showing.
from bokeh.io import curdoc doc = curdoc() script, div = components(finalplot.get_root(doc)) cdn_js = CDN.js_files[1] cdn_css=CDN.css_files return render_template("plot.html", script=script, div=div, cdn_css=cdn_css, cdn_js=cdn_js) #
plot.html
{%extends "layout.html"%} {%block content%} <link rel="stylesheet" href={{cdn_css | safe}} <script type="text/javascript" src={{cdn_js | safe}}></script> <div class="about"> <h1>My about page</h1> <p>This is a test website again</p> </div> {{script1 | safe}} {{div1 | safe}} {%endblock%}
My about page is showing , no error while plotting but plot is not showing in web page :(
sorry for lengthy .
I will really grateful if u guide me on this .
Thank you.. | https://gitter.im/pyviz/pyviz?at=5edbd70e22dd444224020477 | CC-MAIN-2020-34 | refinedweb | 198 | 51.75 |
Agenda
See also: IRC log
AB: Arve had a last minute
cancelation and will not attend
... registered but not here yet: Paddy, Richard Tibbett, Jonathon, Nick and Ivan
AB: all of the minutes will be
Public
... any questions about that?
[ None ]
AB: Agenda:
... we will start with P+C this morning
... talk about high priority issues
... from 13:00-15:00 today we will talk about Security Model vis-a-vis <access> and the WARP document
AB: spec:
... other than feature and L10N are there other hot topics?
MC: no not really
AB: Henri's
... comment about clarifying purpose of feature
... I think the way we have documented feature in P+C is OK
... but there are questions about what a UA will do with the data
... what is our plan to specify the behavior?
<scribe> Scribe: Art, Mike
<MikeSmith> Scribenick: MikeSmith
ArtB: what work remains to be done for <feature>?
Marcos: I don't think anything more needs to be done.. it's specified.
ArtB: Anybody disagree with that?
Marcos: Biggest impact is on
BONDI, so it matters most if it is OK as-is for them.
... I think it meets the BONDI use cases.
Robin: If OMTP is OK with it, I'm
OK with it.
... I'm happier with use cases that don't require it, because that's more Web-like.
David: In the absence of a more
proper security model, we still support this.
... We are happy for [the editors] to take the lead on this.
Marcin: We just want it to be stable.
ArtB: Is OMTP going to extend it after?
Bryan: We may add some semantics, but we are not planning to add additional attributes.
David: If we have a policy mechanism -- some way of regulating access for the user -- then this element is actually redundant.
Marcos: So it really is more of a stop-gap for now
ArtB: Anybody else have anything to add on this topic?
PROPOSED RESOLUTION: The group agrees that the <feature> element as defined in the LC WD is complete.
ArtB: Any objections?
[none]
RESOLUTION: The group agrees that the <feature> element as defined in the LC WD is complete.
Marcos: [discussing issue of case sensitivity in localization system]
[discussion about mailing-list discussions from last couple days]
Marcin: [talking specifically about recent BONDI decisions around requestFeature() and widgets vs. Web pages]
Marcos: as far as requestFeature(), as this point, it does not exist in the Widgets specs.
David: Yeah, we are still just discussing it within OMTP.
Marcin: [explaining background on submission of BONDI specs for review within W3C]
Bryan: One question is: Do we
have the ability to author [a document] as both a Web page and
a Widget.
... Another question is around dynamically loading.
Marcos: I think the DAP WG will be the one that needs to answer that.
timeless_mbp: because of localization and path constraints, currently you won't be able to [drop a widget into a page and have it work]
Marcin: In theory, for this case, the widget UA should be behaving conceptually in the same way as an HTTP server.
ArtB: What I see is that David announced "we are now done, please review"
David: So if it's the view of the WebApps WG that getFeature() is more correctly specified within the DAP WG, then we would follow your lead on that.
Marcos: The problem is that it currently seems to make assumptions about a particular architecture.
Robin: Yes, the feedback you are likely to get from browser vendors is that as currently specified, it does not match with browser architecture, and there are other ways to solve the problem.
Marcin: The whole BONDI
initiative came about because of need for a "fast standard"..
but BONDI operates under many of the same principles as the
W3C.
... The expectation is that everything that has been produced by BONDI will be reviewed within W3C... but none of what BONDI has produced thus far is considered a "must".
David: so to step back, we don't have DAP yet, so we need a stop-gap in the meantime to address the issue
<scribe> Scribenick: Bryan
<ArtB> Jere's comments:
<ArtB> P+C ED:
Jere: comments were mostly editorial
<ArtB> Macros' response to Jere:
Marcos: the main issue was case
sensitivity in localisation
... effectively what we have for localisation is a language list and a list of folders. the algorithm is to do a string match, case sensitively.
... the solution is to match everything in the local part of a path case-insensitively
Josh: forcing failure for
anything other than lowercase is another option
... it is easy to write an algorithm than discards anything that does not match with lower case
Marcos: we need to ensure we don't violate ISO specs re case requirements
Robin: we don't need to follow the ISO specs
Josh: the widgets spec is not defining a language code thus we don't have to follow rules for languages
<Marcos> RESOLUTION: in the spec, we will mandate that language tags for locale folders be in lowercase form (relevant to authors). Only locale folders in lowercase form will be matched by the widget user agent.
Jere: is it possible to have upper-case folders present anyway, and the sensisble thing is to fold it to lower case and continue
Robin: the sensible thing to do is to discard folders that are non-conformant
Jere: compromise, allow any case as long as it's unique and then treat it as lower case
Robin: in a case insensistive file system, how to handle if the language tag folders are not unique - the easiest is just to kill them
Bryan: what is the downside of ensuring uniqueness and case folding?
Josh: it can cause confusion as the author was expecting one behavior and gets another
<timeless_mbp> DRAFT RESOLUTION: any folder as a direct child of the locales folder whose name is not entirely in lowercase will not be reachable by any means.
David: is there any existing requirement mandating lowercase in the specs?
Josh: there is precedent in other specs to require case sensitive matching
No objections.
RESOLUTION: any folder as a direct child of the locales folder whose name is not entirely in lowercase will not be reachable by any means.
Art: are there still some comments on localisation outstanding?
Jere: some editorial comments, the email exchange is ongoing
Marcos: it was proposed to
reshuffle the content which is now done, e.g. the localisation
is now in one area. Need to do a read-thru to ensure good
flow
... there's nothing else that is editorial - the question on xml:lang needs to be resolved
Josh: in 5.3 the locale/folder needs to not reference the folder name - it needs to be called "locale folder" or something that makes it clear what we are referring to
<timeless_mbp> not locale folder since that's taken
<timeless_mbp> but locale-folder-name which might reference BCP47 with a prose restriction to lowercase, or a copy of BCP47 with the BNF restricted to lowercase
Marcos: to fix this, we need to change elements of the ABNF if we were to take the language tag from bcp47
Robin: it is better to restrict it in prose rather than ABNF
<timeless_mbp> ok :)
Jere: the issue raised re xml:lang values being unique, does this come from I18N best practices?
Michael: from HTML5, for authoring we have encouraged people to move away from xml:lang
Robin: that's because HTML4 had a
lang tag and there is thus duplication. in our case we are
starting from scratch
... for widgets, we define the processing model and it will clarify how to handle the set of xml:lang entries
Marcos: the entries are specified to be in document order
Marcin: does this work related to ITS?
Marcos: it relates since the ITS affects to to handle character sequences
Jere: the issue is resolved since the description will define the handling
Marcos: in the 1st example of
step 5, we need to make the language sequence consistent, and
to ensure what is being ilustrated is correct
... the use case is the user has entered the language preferences, and the widget user agent ensures the list of languages is per the spec, and to avoid confusion we need to be clear on how it does that
Benoit: is there a point inthe processing model, how specific the selected language needs to be
Marcos: there are those who want a specific dialect over the generic or another dialect
Josh: there are those that would prefer english for example to an unknown dialect of their language
Marcos: the question is how to eliminate repetitions/ambiguity in the selected list
Josh: the processing should enable e.g. avoidance of random untagged english if another language is preferable
Art: are there any objections to the processing model presented on the screen?
<Marcos> Draft Resolution: treat language tags in the order they appear in the UA Locale list, instead of treating them as recommended by BCP47.
<Marcos> "en-us,en-au,fr,en"
<Marcos> Would become:
<Marcos> "en-us,en-au,fr,en"
<Marcos> "en-us,en-au,fr"
<Marcos> Would become:
<Marcos> "en-us,en-au,en,fr"
Josh: the example does not yet quite meet the draft resolution
Art: it's a question for Josh and Marcos to figure out how to word in the spec
Resolution: treat language tags in the order they appear in the UA Locale list, instead of treating them as recommended by BCP47.
Jere: an outstanding issue is the runtime resolution of the resources, we can discuss that later
<ArtB> Scribe+ DanA
<darobin> do you see me?
<tlr> darobin, if you could dial into the bridge?
<DKA> Scribe: Dan
<DKA> ScribeNick: DKA
[back from lunch]
Art: I'm projecting the June 5
version of the WARP document.
... We want to use this time to go through this document and solicit comments. One question I'd like to pose is - is there consensus to publish the document as FPWD?
<ArtB>
Art: over to Robin for a quick walk-through
Robin: To give some background -
this spec defines the access element which was previously in
PnC and got dropped out to a separate spec rather than delay
PnC.
... It follows typical structure.
... It has a simple model whereby the access grants access within the widget execution scope to certain network resources but anything that is outside the widget executtion scope
... does not have the same levels of access.
... The advantage: it maintains protection to sensitive APIs because you can't communicate across iframe boundaries. etc...
Bryan: clarify?
Robin: if you have a widget with access to the address book (e.g.) and in a separate context you have an access element that grants it to load something from a foreign host then this context will not have access to the address book.
<Zakim> Thomas, you wanted to note that it *can* communicate, but the widget is able to control that access
Thomas: to clarify - a very
limited amount of communication is possible using APIs like
post message... you do have cross-origin communication within a
browser. But this is tightly controlled by the widget. The
important point is that the widget cannot script the iframe and
the iframe cannot script the widget.
... This gives us a very well-defined interface and puts relatively strict limits - doesn't give access from the web to "risky" APIs yet.
Robin: there's no information leakage unless you've trusted an evil widget.
Josh: With an iframe, to a normal
user, you can load a javascript URL that executes arbitrary
code in the context of that web page.... Assuming the widget
will not be allowed to do that.
... That code executes in the context of the iframe. It doesn't have access to the widget but it has total access to the iframe.
Robin: Yes.
Josh: So it's not a very tall wall in that direction.
<Zakim> timeless_mbp, you wanted to verify that the widget can't load javascript:scriptWidget() in the iframe
Robin: The rest of the spec is
the syntax and the processing model.
... There have been two messages so far with editorial comments which I'll apply before we publish.
[discussion of the comments from Thomas from today]
<ArtB> TLR's comments today:
Thomas: Point 3 in my notes - I
continue to not be convinced that it's a good idea to build a
new model within the widget that contains inline content.
... other points raised are editorial in nature.
... [discusses his additional comments]
... To give an example, the document talks about parsing in document order but this doesn't have anything to do with this specification.
... [suggests compressing the parsing instructions]
Robin: WRT point 2. I was thinking that it shouldn't say anything about HTML5 security policy but should just say that it uses the security policy "of the host language being used" which removes the dependency on HTML5.
Josh: there are 2 parts that reference HTML5.
Art: Any objections to that proposal?
Josh: The other HTML5 reference needs to point to some other thing.
Bryan: [clarify web application scope?]
<ArtB> [ Discuss "The widget execution scope is the scope (or set of scopes, seen as a single one for simplicity's sake) being the execution context for code running from documents that are part of the widget package. Note that a script loaded from an external URI into a document that is part of the widget is running in the widget execution scope. " ]
Bryan: If I load a script off of the Web and I run that within a container that is part of the html page that the widget as defined, is that web scope or widget scope?
Robin: If the access has been granted by the access element then it is running in the widget context.
Bryan: if I load further scripts then those have the same permissions?
Robin: Yes.
Bryan: Where do we transition to the Web scope?
Robin: If you have another document - like an iframe - which has an origin that is not inside the widget.
<timeless_mbp> for my reference, CORS is
Robin: The case of bringing in
script from the web relys on the access element having granted
that access [in the widget context] so subject to the access
policy.
... A widget can contain multiple documents... All of those documents run within the widget scope. If one of those runs a script from a URI on the web then that script is running in the widget context.
... We don't want to constrain the security models for others within this spec.
... We don't want to break the Web.
Bryan: Suggests inserting a [zzzt zzzt]
<tlr> [awfully noisy call right now]
<darobin>
Bryan: Suggests inserting a concrete example in the document to clarify.
Frederic: I support having more details in the examples - e.g. the airline flight tracker. If you have a feature that allows access to the camera ...
<timeless_mbp> Zakim: mute [london]
Frederic: it talks about feature-enabled APIs in section 2. I assume feature enabled then that feature applies to anything [in that context].
Thomas: Any script that can control the widget execution context would have access to that feature.
Robin: I will put a specific example in to clarify.
Frederic: This is truly for network access and not for anything else (e.g. a URI to a feature).
Bryan: A local host URI such as a smartcard web server would be covered.
[yes]
Robin: Your definition of a network resource is anything with a URI that is referenced by DNS or IP.
[agreement]
<Zakim> timeless_mbp, you wanted to ask if <access uri=""> and a widget has <iframe src=""> would be
Robin: If access says it's OK to access foo.com and you load foo.com and it redirects to bar.com.
Josh: [advertisement for CORS
Thomas: Don't have an easy answer
to the redirect question. Not clear that CORS is the answer.
The fundamental distinction we have is ...
... just mixing redirects and origin determination could be a huge security hole.
Frederic: We have the asterix which allows access to all assets - could this become a problem?
Robin: this was debated before but not everyone was happy with the solutiuon. But if you want to access something like google maps you get a zillion subdomains...
Steve: There's no way to state that intent more explicitly?
Robin: if you enable foo.com and its subdomains then it could allow access to an IP address in your internal network.
[consensus we need to fix the web or something]
Robin: a user agent would assign an opaque, unique, global identifier to each instance.
Thomas: I suggest we leave this open because there is a proposal to assign the same identifier to different widgets if they have been signed with the same cert.
Robin: We remain silent.
Josh: What about multiple instances?
Robin: Currently undefined.
Thomas: We don't know right now -
probably something we should leave undefined at this
time.
... When it comes to local storage they would have to take care of not stepping on eachother's toes. That's the one [problem area I see with multiple instances]
Art: where are we wrt FPWD?
<lewontin> Possible that device access security model might further restrict access beyond same-origin.
<fjh2> I was the speaker asking about making intent more explicit...
<lewontin> This shouldn't affect anything in this spec explicitly.
Art: What kind of time-frame are you thinking?
Robin: I can do it this week.
Art: I'd like to give Robin the freedom to make those changes.
PROPOSED RESOLUTION: The WARP document modulo the changes Robin's agreed to make is ready for FPWD.
[no objections]
RESOLUTION: The WARP document modulo the changes Robin's agreed to make is ready for FPWD.
Robin: Short name?
Art: My recommendation is widget-access
[discussion on what to cover next]
<ArtB> Spec:
<tlr>;%20charset=iso-8859-1
<darobin>
<tlr>;%20charset=utf-8
Art: Over to Robin.
<Marcos>
Robin: This isn't up to date with
the latest edits.
... I want to propose that the authority is a string that must be ignored in this version. Paves the path forward for use of signatures in future versions.
<Marcos> Scribe+ Marcos
<Marcos> ScribeNick: Marcos
RB: with the issues listed at the begining, plus a few other things, we have enough to run with for version 1
<tlr> works for me
<tlr> certainly ready for FPWD
JS: what does it mean to ignore the authority?
RB: [gives background on
whiteboard]
... we started that the Origin was synthetic opaque with a UUID, then ppl complained about the UUID so we got rid of it. So the authority part could be used for other things, like crypto.
JS: the DOM should not reflect that authority?
RB: in future versions, we might make use of the authority part
TR: so my understanding is that,
when the URI gets dereferenced, the authority part gets
ignored...
... the authority does not carry any semantics right now...
... the idea is just to keep it open for now, so we can do more with it later
RB: Agreed
SL: might need to clarify that in section 4 of the spec
TR: need clarifications or it's going to be hard to parse
<tlr> 3986
RB: it still conforms to the URI specification, and the UUID would still be dropped
<tlr> (thinking about this, I was wrong; ignore)
<tlr> (about the character repertoire, that is)
<lewontin> Maybe we want to drop the word "unique" in section 4 since we left open the possibility that multiple instances or multiple widgets might share the same URI
<tlr> +1 to dropping "unique"
JS: I need to read the spec, will
try to do that now
... have editorial comments
AB: if we look at the issues at the top of the doc. It seems we have closed a few of those issues
RB: a lot of those are
editorial
... so unicode, UUID are dropped. Can reference a bunch of things from P&C. And the thing about dig sig, not sure what I meant.
JS and RB discuss some minor issues
AB: It's highly likely we are going to get some feedback once this goes out. So, I'm inclined to push of a FPWD ASAP.
RB: I can have it ready this week
AB: the question is the, should we agree on a FPWD today?
RB: I think so
MC: I agree
AB: Robin will make the changes, so I propose to the group that we get a resolution to publish
PROPOSED RESOLUTION: The group agrees to publish a FPWD once changes agreed on during this discussion have been spec'd.
RB and BS discuss synthetic origins
<ArtB> BS: I would like to see a definition of synthetic added
<ArtB> RB: yes, I will add a definition
RB: a lot of people were uncomfortable with widget://
<tlr> tlr; think it's a bad idea to have a URI scheme which you can't ever write out in absolute
<tlr> tlr: think it's fine to have authoring guideline that says "relative uri references preferred"
<tlr> tlr: bu also think it's a bad idea to forbid them in the implementation
BS: if I want to call a local resource, can I pass it a parameter?
RB: it should work, the
javascript could access the relevant document property and
access that information
... you would not be able to post to a widget URI
JS: when I talked to TR, we agreed that POST would not work for 1.0, but may be something that gets added later
BS: how does this work with HTTP?
RB: there is no relationship to HTTP, it's just a URI
TR: the only thing we define for the URI scheme is how to retrieve files form a packaged, but nothing else. WRT queries, they are ignored, but is reflected in the DOM... but we don't say that right now, but it should say it in the spec
RB: fragments also
... ppl will be surprised if they are not there
TR: query is part of the resource
identification
... fragment happens after the uri is dereferenced
RESOLUTIONS: The group agrees to publish a FPWD once changes agreed on during this discussion have been spec'd.
<ArtB> Larry:
AB: before we close this topic, I did want to follow up on this topic. Larry sent an email about thismessage
<ArtB> AB: the wiki
AB: at some point we were keeping
track of all the candidates for URI schemes
... in the wiki
RB: on first reading, it seemed very MIME constrained
JS: yes, I found the same thing.
JS reads the abstract
<timeless_mbp>
<timeless_mbp> last paragraph, first sentence
<timeless_mbp> This document a) defines the use of a MIME multipart/related
<timeless_mbp> structure
<timeless_mbp> -- if the abstract is accurate, then the RFC isn't portable for us
RB: I think we need to deconstruct it and see what is good/bad in there
<timeless_mbp> -- if the abstract is not accurate, then the RFC isn't worth reading
<timeless_mbp> oh, *of first page
<scribe> ACTION: Send Larry a proper response about "thismessage" and how it relates to Widget URI scheme [recorded in]
<trackbot> Sorry, couldn't find user - Send
<scribe> ACTION: Robin to send Larry a proper response about "thismessage" and how it relates to Widget URI scheme [recorded in]
<trackbot> Created ACTION-353 - Send Larry a proper response about "thismessage" and how it relates to Widget URI scheme [on Robin Berjon - due 2009-06-16].
RB: from what I read it was _very_ MiME related
BS: what is the context of this discussion?
JS: the TAG is against creating new URI schemes unless one is REALLY needed
AB: the history here is that we decided we needed a new URI scheme for widgets, but we need to explore the whole landscape to make sure nothing fits.
RB: I'm happy to discuss this
with the TAG
... I love the TAG, I'm hoping I will be appointed to it.
<darobin> MC: I want to chair the AB
<Bryan> hello
<darobin> Scribe+ Robin
<ArtB> ScribeNick: darobin
AB: Jere, did we finish your comments?
JK: I think so yes, waiting on an email from MC for formal acknowledgement
MC: will do that
JK: do we need that for the DoC? Do I need to say I'm happy?
MC: yes
JK: not trying to push MC
MC: need to make sure I've addressed everything
AB: from a process & scheduling perspective LC ends on 19/06, so no specific rush
JK: happy to co-ordinate offline
AB: that's done
... anything heard from XML Core?
MC: no
<scribe> ACTION: Art to ping XML Core and the XML CG about reviewing our PC LC [recorded in]
AB: MWBP was also reviewing
<scribe> ACTION: Art to follow up with MWBP chairs for LC comments [recorded in]
AB: Marcin, you've sent several
... do you want to discuss them in the group
MH: I think we're handling it on
the mailing list
... I'm not sure who else would speak up about versioning and interoperability
AB: I wanted to talk about
versioning
... what is the consensus about versioning for PC — emails trail off but that doesn't mean we have consensus and no issues
MC: I think we're fine
... we have made it as future-compatible as possible based on past experience, on other groups' languages, on their recommendations
... we think our processing model is solid enough to handle the future
RB: I agree
MH: I think on the mailing list
we've agreed that versioning is built on the NS, if there's
incompatibility we can change it
... spec grows monotonically
... ensure back-compat of new releases
... two aspects: 1) the versioning of the format, 2) versioning of the APIs
... e.g. Geolocation
MC: the P+C doesn't concern
itself with the APIs
... but in P+C we take the same architectural approach
... future-compatibility without explicity versioning
... because you end up with a situation whereby you need to support previous versions, it's heavy
... lots of legacy crap, like WAP, because there's content out there that uses it
... we want to avoid that
MH: this changes my
understanding
... you want to drop support for some APIs
MC: no, we just want to support one evolving API built to be back-compatilble
MH: you assume there will be no deprecation
MC: yes
RB: and if there are breaking changes we change the name — just like for namespaces
Magnus: at some point you make changes, how do you determine whether that something has changed without versioning?
MC: that approach doesn't work,
it doesn't live up to the lifespan that web content has
... "at least 100 years" is a design principle
... running the same Tetris a century from now
... archive.org should still run
... it's about creating a communication medium that will stay there for a very very long time
... instead of dying after a few years
... pages from 1991 still work
MH: you don't know it's from 1991
MC: and you don't care — which is the point
BS: that works as we have a slow transition from one language to another — but you expect applications to change faster
Josh: no — on the web we expect things to keep working even if the author is long dead
MC: like a dead
Andy: I don't expect Betamax to work today
Josh: as a user, if it has good content — I want to watch
MC: that is a fault in the design
of Betamax
... it's very frustrating
RB: and it's a loss to civilisation
BS: media conversion occurs all the time — valuable content gets converted
MC: we'll still support legacy stuff
BS: you mean if possible
MC: no, actually support
Benoit: a new browser created today would have to be compatible all the way to 19991
MC: that's the point
BS: in the case of APIs you may find a better way to do it
RB: just change the name
BS: but then you don't have to support the old ones
RB: yes you do, there's content out there
MH: versioning helps
Josh, MC, Benoit, RB: no it doesn't
Benoit: versioning only works if
you can decide to support just one version
... or deprecate some versions
MH: it depends on the relationship between v1 and v2
Benoit: if v2 is very different from v1, it's not v2 — it's something different
BS: in principle I agree that
back-compat is important
... but there will be cases when we leave technologies behind
... I think e.g. SMS will be replaced by SIP
MC: people will still want to access them
RB: and it's not a publishing format
BS: but I'm talking about an
API
... there'll be a new API, but still the old SMS API
... what if the device doesn't have the capability?
Benoit: it's a capability issue
RB: that's a capability issue, not a versioning issue
MH: what if a browser doesn't implement all the APIs?
RB: then it's not very useful
AB: can we come back to the P+C spec
MC: the @version is only for authors, it only identifies the version of the widget — it's just a string that humans can interpret
MH: I wanted to change the name of this attribute
MC: it's in line with how it's used
MH: it's different from how it is in other W3C specifications
AB: let's try to get some
closure
... does anybody object to the definition in the P+C?
MC: Marcin, what's your proposal?
MH: @widget-version
... I would like someone from the TAG to review this
... geolocation also define a version attribute on the object
... for the specification version
AB: I don't see a conflict between that and us
MC: I can't find that on the API
MH: it was discussed today, also
with Anne
... if W3C is a spec vendor, then make it consistent
RB: that's already hopeless
<Zakim> MikeSmith, you wanted to comment
MS: the TAG is already having a
discussion about versioning
... co-ordination is not a constraint
... you don't want W3C to attempt to impose coherence at that level of granularity — it would grind everything to a halt
AB: we're not going to find authority in the W3C that will tell us what to do
MS: the one point in the process
where that can happen is during transition
... at that point a formal objection can raise to the Director
... and then the Director steps in, having collected information from the TAG
AB: we don't want TimBL having to step in with the naming of an attribute
Josh: I'm fine with a change to make the text say in its first sentence that @version is the version of the widget, not of anything else
<anne> fwiw, geolocation does not specify version on the object
<anne> it is being considered by some, but that's not the same
<anne> (and I don't think it'll happen)
MH: I think that by doing this we
are breaking the architectural assumption of W3C
specifications
... elsewhere it is version of the specificaiton
... seen it in SVG, SML
thanks anne
MS: that's not true — e.g. HTML
RB: note that those examples do not have the same semantics
Josh: we shouldn't blacklist a word because it didn't work in other semantics — we want to use it for useful semantics
MC: how can we clarify this?
JK: it's already clear, I don't see what the confusion is
Josh: agreed
... I was confused by the attribute type description — can we stick it after boolean, numeric (or alphabetically) so that it doesn't jump out so much?
MC: yup
AB: third time, does anybody object to the way in which the @version attribute has been defined?
[None]
RESOLUTION: @version as defined in P+C LC is acceptable
AB: any other issues to raise today?
MC: thank you Marcin for your feedback, fixed a lot of stuff
AB: +1
... is MaxF going to submit comments?
MC: no, Lachlan and Anne are
<ArtB> AB: this one
AB: one extra topic, Scott Wilson brought up a number of good things, do we want to discuss some of them or is the on-list discussion enough to make progress?
MC: I think we're fine for P+C — a lot of his comments recently have been about A+E
AB: I have a cloudy crystal
ball
... modulo any major issues we should be ready to go to CR
... what's your sense here Marcos?
MC: it's hard to judge, the
commenters I have lined up may bring up issues
... I think people on the WG have gone through it, hopefully we've weeded out issues
... I plan to finish before I go on holiday (18th)
AB: Dan, will MWBP review?
DKA: hasn't MWBP come back?
AB: for LC1
DKA: I don't think there'll be any feedback for LC2
<scribe> ACTION: Josh to go through P+C one more time [recorded in]
AB: I don't want to get a bunch of comments on the 20th — let's not extend the time, it's been in LC since the beginning of the year
<DKA> +1
RB: should we ask the SVG WG to review?
Josh: good idea
<scribe> ACTION: Robin to ask the SVG WG to review (before the 19th) [recorded in]
<shepazu> noted
Benoit: what does vacation mean for the CR timing?
MC: probably July 1st
Benoit: can't decide on the 18th
MC: back on the 25th
... I should be able to ring in for the conf
AB: we could record a decision to
go forward on the 20th
... using a call for consensus
... if there are no objections, I'll then send a transition request
DKA: we could do it on the 25th's call
AB: ok, let's do that
RB: I can fix the spec for pubrules if needed in MC's absence
MC: and it should be set to go anyway
AB: we'll cover testing
tomoroow
... PC, AOB?
Josh: exit criteria?
MS: what's the plan?
MC: I like the XBL2 criteria
AB: I like the DigSig
MC: it says the same thing, but wishy-washy
Josh: I like the second sentence about openness
AB: not sure it's clear enough
MS: we don't need to overanalyse
it, it's just about not getting the spec out based on some
in-house implementation that can't be verified
... needs some degree of distribution and general testing
Josh: the DigSig one requires 2 implementations of each test — not of the whole thing. Let's use the XBL2 version
AB: if the implementation ships as part of a phone, does it count
DKA: yes
RB: yes
... we don't need to overlegalise it, this very same WG will decide when we agree to move out of CR
... this really is process wonking
AB: can we not have the same EC for each spec
RB: how about reusing DigSig, but
changing two implementations of *each* test but two of *all*
tests?
... it's a two word change
[AB summarises the proposal for MC]
<timeless_mbp> ... and demonstrated, according to the test suite, two interoperable implementations.
Dave: we could even drop "each test"
AB: anybody object to replacing " for each test" with nothing?
MC: the XBL2 one is better but I
can live with it
... I have made the change
RESOLUTION: the agreed-upon DigSig CR EC will be applied to P+C and to all subsequent specs in this WG
DKA: do we have a PAG call?
MS: yes
AB: the PAG is having weekly conferences as per process
<trackbot> Sorry... I don't know anything about this channel
<trackbot> If you want to associate this channel with an existing Tracker, please say 'trackbot, associate this channel with #channel' (where #channel is the name of default channel for the group)
BS: but WARP has been moved out into a separate spec
<MikeSmith> trackbot, associate this channel with #webapps
<trackbot> Associating this channel with #webapps...
BS: is it assumed WARP is near LC?
<MikeSmith> trackbot, bye
<trackbot> Sorry... I don't know anything about this channel
<trackbot> If you want to associate this channel with an existing Tracker, please say 'trackbot, associate this channel with #channel' (where #channel is the name of default channel for the group)
AB: when we made that decision,
it was still in PC
... so does the decision move with it?
<MikeSmith> trackbot, associate this channel with #webapps
<trackbot> Associating this channel with #webapps...
<MikeSmith> trackbot, status
<trackbot> This channel is not configured
<MikeSmith> trackbot, status?
<trackbot> This channel is not configured
<MikeSmith> trackbot, init
<MikeSmith> trackbot, status
<trackbot> This channel is not configured
JK: that's a UX killer — if we bring that into <access> where the granularity is a URL, and you have several of these, you're going to get more prompting, and a dreadful UX
<MikeSmith> trackbot. leave
<MikeSmith> trackbot, leave
RT: I agree, you're implying UX with prompting — we don't want to imply UX, that's an implementation thing
MH: consolidation of the prompts?
<MikeSmith> trackbot, associate...
MH: this is an important factor
BS: the purpose is not to mandate
a UI/UX
... obviously apps have to be designed or vetted to access some features
<MikeSmith> trackbot, status?
<trackbot> This channel is not configured
<ArtB> Bryan's email:
BS: the purpose of this disclosure is not to promote a given security model
<MikeSmith> trackbot, status?
<trackbot> This channel is not configured
<MikeSmith> trackbot, leave
BS: we will eventually have a process of alignement
...
BS: we see this process of prompting as essential
<MikeSmith> trackbot, status?
<trackbot> This channel is not configured
<MikeSmith> action-1
errrrr
<scribe> ACTION: RB to send Larry a proper response about "thismessage" and how it relates to Widget URI scheme [recorded in]
<trackbot> Created ACTION-354 - Send Larry a proper response about "thismessage" and how it relates to Widget URI scheme [on Robin Berjon - due 2009-06-16].
<dom> trackbot, associate this channel with #webapps
<trackbot> Associating this channel with #webapps...
BS: some people chage, some people don't
AB: the more we talk about policy, the more I think it's a DAP problem
RB: thank you Art, you'll pay for that
<JereK> +1
<dom> trackbot, status?
<trackbot> This channel is not configured
<dom> ACTION-1?
<trackbot> ACTION-1 -- Doug Schepers to find All Open Issues For DOM3 Events and Update the Specification -- due 2009-03-18 -- OPEN
<trackbot>
This is scribe.perl Revision: 1.135 of Date: 2009/03/02 03:52:20 Check for newer version at Guessing input format: RRSAgent_Text_Format (score 1.00) Succeeded: s/Marcos/OMTP/ Succeeded: s/some way for regulating user access/some way of regulating access for the user/ Succeeded: s/down, please/done, please/ Succeeded: s/[this]/just mixing redirects and origin determination/ Succeeded: s/fix dns/fix the web/ Succeeded: s/Frederic/Steve/ Succeeded: s/Scribe: Marcos/Scribe+ Marcos/ Succeeded: s/BJ/RB/ Succeeded: s/tltr/tlr/ Succeeded: s/MC/MH/ Found Scribe: ArtB Inferring ScribeNick: ArtB Found ScribeNick: ArtB Found Scribe: Art, Bryan Found Scribe: Art, Mike Found ScribeNick: MikeSmith Found ScribeNick: Bryan Found Scribe: Dan Found ScribeNick: DKA Found ScribeNick: Marcos Found ScribeNick: darobin Scribes: ArtB, Art, Bryan, Art, Mike, Dan ScribeNicks: ArtB, MikeSmith, Bryan, DKA, Marcos, darobin Default Present: Thomas, fjh, SteveLewontin, +44.163.567.aaaa, [London] Present: Benoit Mike Josh Jere Art Robin Marcos AndyB DanA David Laura Marcin Bryan Magnus Richard Frederick Thomas SteveL Agenda: Found Date: 09 Jun 2009 Guessing minutes URL: People with action items: art josh rb robin send[End of scribe.perl diagnostic output] | http://www.w3.org/2009/06/09-wam-minutes.html | CC-MAIN-2015-27 | refinedweb | 6,674 | 67.18 |
Grid vs GridLayout vs GridView
Hello all,
I am on my way to implementing a re sizable Grid that houses Items experiencing real time updates.
Before I choose my Type, I am curious to hear from others: Grid vs. GridLayout vs. GridView?
I have used ListView before, so I understand model-view-delegate architecture.
My question is, what do each of these offer, and what are some common setups?
My initial thinking would be to use a GridView, within a GridLayout. Is this correct/feasible?
Thanks!
Edit: If you are just going to post a link to Qt Documentation, you're just wasting both of our time, as that is what I'm reviewing right now. My reason for posting this is to hear what other developers have done and what their experience was like.
First question you probably have to ask yourself is how you get the Elements, which should be displayed.
Grid and GridLayout do position your Elements. So you have already existing Elements, like 4 Rectangles and want them in a grid. It's really easy to say how exactly they should be displayed ... 4 Row, 4 Columns, 2 Rows and 2 Columns ... spacing ...
From my point of view, I consider them for a static number of Elements. Because you either declare all Elements in a qml or in case you have always have the same Element (more or less) you use it together with a Repeater. At least in the first case it's no problem to make changes on the Elements as you can give them all id's. With a Repeater this is probably not that easy.
If you decide to use this approach, you still need to know if you should use Grid or GridLayout:
In General, you should use Grid if you want the Grid to be static. In a Grid you define the width and the height of each Element and therefore the Elements will only take the space they need.
In a GridLayout the Elements usually take as much space as they have. At least if you define your Elements to fillWidth or fillHeight. Of course you can give them also a fixed width or height, but there must be at least one Item, which cover the rest.
For Example:
One dimensional(width, height)
Element1(20,20) Element2(20,20) Item(fillWidth, 20) Element3(20,20)
If you now resize the whole Application, the Item will get resized, whereas the Elements will always have 20,20. If you make all your Elements fillWidth, fillHeight, then every elements gets smaller or bigger if you resize your application.
Use Grid if it has to be static and GridLayout for resizable things.
Or your third option: GridView
GridView is the best approach if you have a model, for example if you want to do a file Manager. You really don't know how many folders there will be the directory you are.
As you have a model, you can also easily to changes in it.
Unconfigured it's in point of resizable better than Grid, as your Elements don't go off the screen. But instead the GridView will become a Flickable, which you can scroll.
As the Grid View it takes as much space as needed, even if there is more space.
But with some configuration you can make it behave like a GridLayout ... for example you can bind the cellWidth and cellHeight to the applications height and width.
Of course this is a little bit more tricky as you may need to do some calculations (how many Elements in one row, in one column, available space, length of the model ....) to get the reigth cellWidth and cellHeight. Furthermore, you also have to calculate spacing by yourself (by making cellWidth/cellHeight bigger than the actual Element).
In conclusion, you have the choice between GridLayout and GridView depending on how you get your Elements (from a model, already defined in qml ...). If you want it to be resizable it's of course much easier to use GridLayout, but if have understand you correctly, you probably need a model and therefore have to go with GridView. (Which is perfectly fine, just a little bit more work to configure).
A GridView within a GridLayout would be a Grid with lots of Grids. I don't think this is what you need?
@Leon_2001 Thanks for the reply! I ended up taking the approach of making a ListView of ListViews.
The first step I took was creating Cell.qml : just a basic Rectangle with a string inside.
Second step was creating CustomRow.qml: Just 3 Cells in a RowLayout.
Third step was creating CustomGrid.qml, which is basically a Rectangle with a ListView inside. The model for this ListView came from my context property, and I used CustomRow as my delegate.
Finally, fourth step was to create a ListView in my Display.qml (the one inside main.qml), where I used context property again for the model, and the delegate was CustomGrid.
Although this seems complicated, It's really just a bunch of components broken down, with the desired functionalities addressed.
Although, while we are here, I do have a question regarding the ListView model property.
Let's say we have registered Model.cpp as a context property of the QML engine. Let's also say that Model.cpp contains a few QVectors that contain important data-related information, including how many items should be visualized.
Logically, for our ListView, we could assign the model property to be something like:
model: ModelContextProperty.getLengthofDataVector()
So my question is, when the length of this data vector is modified (say, we add or remove a data item), how does QML react?
Knowing that the delegate property is Component based, does it recognize that the model has been modified, start at index==0, and reload each delegate Component? My plan is to make another post regarding this topic, but I figured I may as well ask the question here too.
First of all I am glad that you found a solution you're happy with.
Nevertheless, I still recommend to use GridView. On the one hand, it probably reduces your amount of code, on the other hand, and most importantly, it's much more readable to you and every other developer, who might want to help you or needs some Inspiration, because he has the same problems as you have.
To your question:
On of the key features of Qml is property binding. So let's say you have
import QtQuick.Controls 2.3 ApplicationWindow { id: root width: 600; height: 600 visible: true Rectangle { width: parent.width/2; height: parent.height/2 color: "blue" } MouseArea { anchors.fill: parent onClicked: { root.width -= 10; root.height += 10; } } }
If you click the applicationWindow its width will be decreased by 10 and its height increased by 10. At the same time the rectangle's width will be decreased by 5 and its height increased by 5. That's because its size depends on the size of the applicationWindow and will be changed automatically.
Same applies to your case. If the model changes its size, your ListView should notice this and update the list.
Just in case you don't know (or if it's working in your case, didn't know how your model looks like) you can do:
model: yourModelName.length
or if it's a List of Arrays/Vectors
model: yourModelName[index].length
Index should be available through the outer ListView if I did understand you correctly.
ListView { model: yourModel.length delegate: ListView { model: yourModel[index].length } }
Probably there is no need to write an "getLengthOfDataVector" function, if you intended to do it like this. But maybe I missed something as I don't know how you model looks like exactly. | https://forum.qt.io/topic/92959/grid-vs-gridlayout-vs-gridview/4 | CC-MAIN-2019-47 | refinedweb | 1,298 | 65.22 |
create-react-app is the best thing that's happened to the React ecosystem since React 14 gave us functional components. No more messing around with random boilerplates or manual headaches around setting up your project from scratch.
Instead, you run
create-react-app MyThing, and it sets everything up.
If you like MobX, there's a crucial piece missing: decorators. You don't have to use decorators with MobX, but that's like saying you don't have to use JSX with React. You don't "have to”; you "want to". Because that's what the library was designed for.
MobX is a state management competitor to Redux, by the way. I like it because there's almost no boilerplate. We've been using at The Day Job™ and it's been amaze so far.
A React component that reacts to MobX data store changes would use the
@observer decorator. Like this:
import React, { Component } from "react";import { observer } from "mobx-react";@observerclass Hello extends Component {render() {return <h1>Hello {this.props.store.name}</h1>;}}
You can think of decorators as function wrappers. A sort of functional composition, if you will.
The observer decorator automatically runs a component’s
render method when MobX detects a change in a store value that
render references. Yes, MobX circumvents React's own prop and state change detection.
I'm not sure yet how I feel about that, but so far, so good. Can't complain.
It's those decorators that make working with MobX powerful and concise. But
create-react-app doesn't enable them because of some interesting history. They used to be in Babel 5, then Babel 6 removed them because the official spec got pushed back.
There's a Babel plugin you can use, but
create-react-app maintainers have decided not to include it.
How to get decorators in create-react-app
Ok, so here's what you do when setting up a new React app:
1) Run
create-react-app. This creates a new app with the official configuration.
2) Run
npm run eject. This moves files around and makes your app's configuration accessible.
3) Run
npm install --saveDev babel-plugin-transform-decorators-legacy. This installs the Babel plugin for decorators. It's called
legacy even though it's a feature from the far future.
4) Open
package.json, find the
"babel" section (line 78 for me), and add 4 lines so it looks like this:
"babel": {"plugins": [ "transform-decorators-legacy" ], "presets": [ "react-app" ]},
5) Run
npm install --save mobx mobx-react. This installs MobX.
You're ready to go. Happy hacking! ?️ | https://swizec.com/blog/how-to-use-mobx-with-createreactapp/ | CC-MAIN-2022-27 | refinedweb | 436 | 59.3 |
BIO_f_base64.3ossl - Man Page
base64 BIO filter
Synopsis
#include <openssl/bio.h> #include <openssl/evp.h> const BIO_METHOD *BIO_f_base64(void);
Description
BIO_f_base64() returns the base64 BIO method. This is a filter BIO that base64 encodes any data written through it and decodes any data read through it.
Base64 BIOs do not support BIO_gets() or BIO_puts().
For writing, output is by default divided to lines of length 64 characters and there is always a newline at the end of output.
For reading, first line should be at most 1024 characters long. If it is longer then it is ignored completely. Other input lines can be of any length. There must be a newline at the end of input.
This behavior can be changed with BIO_FLAGS_BASE64_NO_NL flag.(). For writing, it causes all data to be written on one line without newline at the end. For reading, it expects the data to be all on one line (with or without a trailing newline).
Notes
Because of the format of base64 encoding the end of the encoded block cannot always be reliably determined.
Return Values
BIO_f_base64() returns the base64 BIO method.
Examples
Base);
Bugs
The ambiguity of EOF in base64 encoded data can cause additional data following the base64 encoded block to be misinterpreted.
There should be some way of specifying a test that the BIO can perform to reliably determine EOF (for example a MIME boundary).
Licensed under the Apache License 2.0 (the “License”). You may not use this file except in compliance with the License. You can obtain a copy in the file LICENSE in the source distribution or at <>.
Referenced By
bio.7ossl(7). | https://www.mankier.com/3/BIO_f_base64.3ossl | CC-MAIN-2022-40 | refinedweb | 274 | 76.22 |
Python library for reporting metrics to Atlas.
Project description
Introduction
Python port of the Spectator library for Java.
See the Spectator documentation for an overview of core concepts and details on usage.
Supports Python >= 3.5, which is the oldest system Python 3 available on our commonly used OSes.
Local Development
- Install pyenv, possibly with Homebrew.
- Install Python versions: 3.5, 3.6, 3.7, and 3.8. Enable all versions globally.
- Make changes and add tests.
tox
Usage
Installing
The
netflix-spectator-py package alone is not sufficient to report data to an Atlas backend -
a configuration package must also be installed.
At Netflix, the internal configuration package is named
netflix-spectator-pyconf and it declares
a dependency on this client package.
pip3 install netflix-spectator-pyconf
Importing
Standard Usage
At Netflix, your initialization script should load the environment, to ensure that the standard variables are available to the Python application.
source /etc/nflx/environment
Importing the
GlobalRegistry configures common tags based on environment variables, sets the
Atlas Aggregator URL, and starts a background thread which reports metrics data every five seconds.
from spectator import GlobalRegistry
Once the
GlobalRegistry is imported, it is used to create and manage Meters.
Concurrent Usage
There is a known issue in Python where forking a process after a thread is started can lead to
deadlocks. This is commonly seen when using the
multiprocessing module with default settings.
The root cause of the deadlocks is that
fork() copies everything in memory, including globals
that have been set in imported modules, but it does not copy threads - any threads started in
the parent process will not exist in the child process. The possibility of deadlocks occurs when
global state sets a lock and it then depends upon a thread to remove the lock.
Under the standard usage model for
spectator-py, it starts a background publishing thread when
the module is imported, which is responsible for manipulating a lock. Below, there are a couple of
options described for working around this issue.
Gunicorn
If you are using
spectator-py while running under Gunicorn, then do not use the
--preload
flag, which loads application code before worker processes are forked. Preloading triggers the
conditions that allow deadlocks to occur in the background publish thread.
At Netflix, you can set the following flag in
/etc/default/ezconfig to achieve this configuration
for Gunicorn:
WSGI_GUNICORN_PRELOAD = undef
Task Worker Forking
For other pre-fork worker processing frameworks, such as huey, you need to be careful about how
and when you start the
GlobalRegistry to avoid deadlocks in the background publish thread. You
should set the
SPECTATOR_PY_DISABLE_AUTO_START_GLOBAL environment variable to disable automatic
startup of the Registry, so that you can plan to start it manually after all of the workers have
been forked.
You can set the variable as a part of your initialization script:
export SPECTATOR_PY_DISABLE_AUTO_START_GLOBAL=1
You can set the variable in Python code, as long as it is at the top of the module where you plan
to use
spectator-py:
import os os.environ["SPECTATOR_PY_DISABLE_AUTO_START_GLOBAL"] = "1"
After your workers have started, you can then start the
GlobalRegistry as follows:
from spectator import GlobalRegistry GlobalRegistry.start()
It is often best to have the
import and
start() within an initialization function for the
workers, to help ensure that it is not started when the module is loaded.
Generic Multiprocessing
In Python 3, you can configure the start method to
spawn for
multiprocessing. This will cause
the module to do a
fork() followed by an
execve() to start a brand new Python process.
To configure this option globally:
from multiprocessing import set_start_method set_start_method("spawn")
To configure thid option within a context:
from multiprocessing import get_context def your_func(): with get_context("spawn").Pool() as pool: pass
Logging
This package provides three loggers:
spectator.init
spectator.HttpClient
spectator.Registry
When troubleshooting metrics collection and reporting, you should set
Registry logging to the
DEBUG level. For example:
import logging # record the human-readable time, name of the logger, logging level, thread id and message logging.basicConfig( level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(thread)d - %(message)s' ) # silence the HttpClient logger output, to minimize confusion while reading logs logging.getLogger('spectator.HttpClient').setLevel(logging.ERROR) # set the Registry logger to INFO or ERROR when done troubleshooting logging.getLogger('spectator.Registry').setLevel(logging.DEBUG)
Detecting Deadlocks
If you need to detect whether or not your application is affected by deadlocks, then you can use sys._current_frames to collect stack frames periodically and check them. A common pattern is to run this on a background thread every 10 seconds.
Working with IDs
The IDs used for looking up a meter in the
GlobalRegistry consist of a name and a set of tags.
IDs will be consumed by users many times after the data has been reported, so they should be
chosen thoughtfully, while considering how they will be used. See the naming conventions page
for general guidelines.
IDs are immutable, so they can be freely passed around and used in a concurrent context. Tags can be added to an ID when it is created, to track the dimensionality of the metric. All tag keys and values must be strings. For example, if you want to keep track of the number of successful requests, you must cast integers to strings.
requests_id = GlobalRegistry.counter('server.numRequests', {'statusCode': str(200)}) requests_id.increment()
Meter Types
Counters
A Counter is used to measure the rate at which an event is occurring. Considering an API endpoint, a Counter could be used to measure the rate at which it is being accessed.
Counters are reported to the backend as a rate-per-second. In Atlas, the
:per-step operator
can be used to convert them back into a value-per-step on a graph.
Call
increment() when an event occurs:
GlobalRegistry.counter('server.numRequests').increment()
You can also pass a value to
increment(). This is useful when a collection of events happens
together:
GlobalRegistry.counter('queue.itemsAdded').increment(10).
Always use base units when recording data, to ensure that the tick labels presented on Atlas graphs
are readable. If you are measuring payload size, then use bytes, not kilobytes (or some other unit).
This means that a
4K tick label will represent 4 kilobytes, rather than 4 kilo-kilobytes.
Call
record() with a value:
GlobalRegistry.distribution_summary('server.requestSize').record(10)
Gauges
A gauge is a value that is sampled at some point in time. Typical examples for gauges would be the size of a queue or number of threads in a running state. Since gauges are not updated inline when a state change occurs, there is no information about what might have occurred between samples.
Consider monitoring the behavior of a queue of tasks. If the data is being collected once a minute, then a gauge for the size will show the size when it was sampled. The size may have been much higher or lower at some point during interval, but that is not known.
Call
set() with a value:
GlobalRegistry.gauge('server.queueSize').set(10)
Gauges are designed to report the last set value for 15 minutes. This done so that updates to the values do not need to be collected on a tight 1-minute schedule to ensure that Atlas shows unbroken lines in graphs.
If you wish to no longer report a Gauge value, then set it to
float('nan'). This is a separate
and distinct value from
'nan' or
'NaN', which are strings.
Timers
A Timer is used to measure how long (in seconds) some event is taking.
Call
record() with a value:
GlobalRegistry.timer('server.requestLatency').record(0.01)
Timers will keep track of the following statistics as they are used:
count
totalTime
totalOfSquares
max
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/netflix-spectator-py/0.1.15/ | CC-MAIN-2021-39 | refinedweb | 1,321 | 54.42 |
Alright, so I am designing a program that contains binary trees to function as a parser. I have encounted a very strange problem that is causing my program to fail while it is running. I have done several tests and narrowed down the incidents.
Ok, so this results in a successful test:
#include <iostream> #include <cstdlib> #include "BinaryTree.cpp" #include "Stack.cpp" using namespace std; int main() { BinaryTree<char> treeL, treeR; Stack< BinaryTree<char> > stack1; BinaryTree<char> tree1('a'); cout << "Test"; return 0; }
Output:
Test RUN SUCCESSFUL (total time: 93ms)
Now, whenever I throw in the push function (the method that causes the program to crash the most):
.push(tree1); return 0; }
I get this output (periods added to show newlines):
. . . RUN FAILED (exit value 1, total time: 271ms)
Notice how it still prints the newlines but fails to print the text. Even stranger is that the push function comes after the cout, it shouldn't affect it.
Lastly, whenever I do the pop function instead:
.pop(); return 0; }
I get this:
. . . Test The stack is already empty. RUN FAILED (exit value 1, total time: 168ms)
With that method, it prints the text correctly and completes the method, but fails immediately after. I can't for the life of me understand why it does these things but maybe you can help. Here is my push and pop functions:
template <class elemType> void Stack<elemType>::push(elemType x) { Stack_Node<elemType> *newNode; newNode = new Stack_Node<elemType>; newNode->value = x; newNode->link = stackTop; stackTop = newNode; } template <class elemType> elemType Stack<elemType>::pop() { Stack_Node<elemType> *temp; if (!IsEmpty()) { temp = stackTop; stackTop = stackTop->link; return temp->value; //Returns the value of the top node. delete temp; //Deletes the top node in the stack. } else cout << endl << "The stack is already empty." << endl; }
here is the BinaryTree constructor being used:
//Constructor #2 template<class Node_Type> BinaryTree<Node_Type>::BinaryTree(Node_Type nodeValue) { root = new Tree_Node; root->Node_Info = nodeValue; //Store value into root node. root->left = NULL; root->right = NULL; }
and stack.h:
#ifndef STACK_H #define STACK_H //Node definition. template<class elemType> struct Stack_Node { elemType value; Stack_Node<elemType> *link; }; template<class elemType> class Stack { public: const Stack<elemType>& operator=(const Stack<elemType>&); //Overloaded assignment operator. void initialize(); //Function to initialize the stack. //Postcondition: stack is empty. void push(elemType x); //Function to add x to the stack. //Precondition: The stack exists and is not full. //Postcondition: x is added to the top of the stack. elemType pop(); //Function to return and remove the top element of the stack. //Precondition: The stack exists and is not empty. //Postcondition: The top element is returned then removed from the stack bool IsEmpty() const; //Function to determine if the stack is empty. //Postcondition: Returns true if stack is empty, else returns // false. Stack(); //Default constructor. //Postcondition: The top of the stack is set to NULL. Stack(const Stack<elemType>& otherStack); //Copy constructor. ~Stack(); //Destructor. //Removes all elements from the stack. //Postcondition: The list is deleted. private: Stack_Node<elemType> *stackTop; //Pointer to the top of the stack. void copyStack(const Stack<elemType>& otherStack); //Function to make a copy of otherStack. //Postcondition: A copy of otherStack is made and assigned to this one. }; #endif /* STACK_H */
The IsEmpty function works fine. If any of you need any of the BinaryTree.h , BinaryTree.cpp , or operation overloading code let me know. I'm trying to keep this post as clean as possible. Thanks. | https://www.daniweb.com/programming/software-development/threads/434374/very-odd-problem-causing-program-to-fail-stacks-and-binary-trees | CC-MAIN-2018-30 | refinedweb | 566 | 59.19 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.